// ==UserScript==
// @name 物理实验助手
// @namespace http://tampermonkey.net/
// @version 1.3.0
// @description 辅助武理物理实验的预习作业学习
// @author 毫厘
// @match http://59.69.101.153/lab/Reports/*
// @match http://59.69.103.147/Reports/*
// @match http://wlsys.whut.edu.cn:8081/SelectiveCoursesSystem/*
// @match https://wlsys.whut.edu.cn:8081/SelectiveCoursesSystem/*
// @grant none
// @run-at document-idle
// @license MIT
// ==/UserScript==
(() => {
'use strict';
const modules = { document, PhysicsLabHelperVersion: "1.3.0" };
(function (root) {
'use strict';
const styles = `
:host([hidden]) { display: none !important; }
:host { all: initial; position: fixed; top: 88px; right: 20px; z-index: 2147483600; width: min(380px, calc(100vw - 24px)); color-scheme: light; }
.uikit-root { --uikit-brand: #1565c0; --uikit-brand-text: #fff; --uikit-bg: #f8f9fc; --uikit-card-bg: #fff; --uikit-text: #4c4f69; --uikit-text-muted: #6c6f85; --uikit-border: #dce0e8; --uikit-soft: #eef2f8; --uikit-danger: #be3340; --uikit-success: #2e8468; --uikit-radius-sm: 6px; --uikit-radius-md: 10px; --uikit-radius-lg: 16px; --uikit-space-1: 4px; --uikit-space-2: 8px; --uikit-space-3: 12px; --uikit-space-4: 16px; --uikit-shadow: 0 12px 40px #1e1e2e24; --uikit-duration: 300ms; --uikit-ease: cubic-bezier(.19,1,.22,1); --uikit-bounce: cubic-bezier(.34,1.56,.64,1.1); color: var(--uikit-text); background: var(--uikit-bg); font: 14px/1.6 system-ui, sans-serif; border: 1px solid var(--uikit-border); border-radius: var(--uikit-radius-lg); box-shadow: var(--uikit-shadow); overflow: hidden; }
.uikit-root[data-theme="dark"] { --uikit-brand: #87b0f9; --uikit-brand-text: #1e1e2e; --uikit-bg: #1e1e2e; --uikit-card-bg: #24243a; --uikit-text: #cdd6f4; --uikit-text-muted: #a6adc8; --uikit-border: #45475a; --uikit-soft: #313244; --uikit-danger: #ffabb7; --uikit-success: #a6e3a1; color-scheme: dark; }
*, *::before, *::after { box-sizing: border-box; }
[hidden] { display: none !important; }
:focus-visible { outline: 2px solid var(--uikit-brand); outline-offset: 3px; }
header { display: flex; align-items: center; gap: 6px; padding: 18px 16px; border-bottom: 1px solid var(--uikit-border); background: linear-gradient(135deg, var(--uikit-card-bg), var(--uikit-soft)); touch-action: none; user-select: none; cursor: move; }
.identity { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; white-space: nowrap; }
.identity > strong { display: block; font-size: clamp(12px, 3.6vw, 15px); font-weight: 750; letter-spacing: .5px; line-height: 1.4; }
.meta { display: flex; align-items: center; gap: 5px; }
.version-badge { padding: 1px 7px; border: 1px solid var(--uikit-border); border-radius: 5px; background: var(--uikit-card-bg); color: var(--uikit-brand); font: 600 10px/1.7 ui-monospace, monospace; letter-spacing: .3px; }
.author { padding: 1px 7px; border: 1px solid var(--uikit-border); border-radius: 5px; background: var(--uikit-soft); font-size: 10px; line-height: 1.7; font-weight: 600; color: var(--uikit-text); }
.body { padding: 14px; max-height: calc(100vh - 128px); max-height: calc(100dvh - 128px); overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: var(--uikit-border) transparent; }
.button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 38px; padding: 8px 12px; border: 1px solid var(--uikit-border); border-radius: 9px; background: var(--uikit-card-bg); color: var(--uikit-text); font: 600 12px/1.5 system-ui, sans-serif; cursor: pointer; transition: background 180ms ease, transform 180ms ease, box-shadow 180ms ease; }
.button:hover:not(:disabled) { background: var(--uikit-soft); border-color: var(--uikit-brand); }
.button.primary { min-height: 42px; background: var(--uikit-brand); color: var(--uikit-brand-text); border-color: transparent; font-size: 13px; box-shadow: 0 3px 9px #1565c01a; }
.button.primary:hover:not(:disabled) { filter: brightness(1.08); transform: translateY(-1px); }
.button:active:not(:disabled) { transform: translateY(1px); }
.button:disabled { opacity: .45; cursor: not-allowed; box-shadow: none; }
.icon-button { flex: 0 0 30px; width: 30px; min-height: 30px; padding: 5px; background: transparent; border-color: transparent; border-radius: 8px; }
svg { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
.section { padding: 14px; background: var(--uikit-card-bg); border: 1px solid var(--uikit-border); border-radius: 12px; }
.section + .section { margin-top: 12px; }
h2, p { margin: 0; } h2 { font-size: 13px; font-weight: 700; letter-spacing: .3px; } p, .muted { font-size: 11px; color: var(--uikit-text-muted); }
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.section-heading .button { min-height: 28px; padding: 3px 8px; font-size: 11px; font-weight: 500; }
.section-note { margin-top: 4px; line-height: 1.7; }
.actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
.actions .primary { flex: 1; }
.setting { display: flex; gap: 14px; align-items: center; justify-content: space-between; min-height: 60px; padding: 12px 0; cursor: pointer; }
.setting + .setting { border-top: 1px solid var(--uikit-border); }
.setting:last-child { padding-bottom: 0; }
.setting-copy { flex: 1; min-width: 0; }
.setting-title { display: block; font-size: 12px; font-weight: 600; line-height: 1.6; }
.setting-hint { display: block; margin-top: 3px; font-size: 11px; line-height: 1.6; color: var(--uikit-text-muted); }
.setting input { appearance: none; -webkit-appearance: none; position: relative; flex: 0 0 36px; width: 36px; height: 21px; margin: 0; border: 1px solid var(--uikit-border); border-radius: 20px; background: var(--uikit-soft); cursor: pointer; transition: background 180ms ease, border-color 180ms ease; }
.setting input::after { content: ''; position: absolute; top: 2px; left: 2px; width: 15px; height: 15px; border-radius: 50%; background: var(--uikit-text-muted); transition: transform 180ms ease, background 180ms ease; }
.setting input:checked { background: var(--uikit-brand); border-color: var(--uikit-brand); }
.setting input:checked::after { transform: translateX(15px); background: var(--uikit-brand-text); }
.setting input:disabled { opacity: .45; cursor: not-allowed; }
.status { font-size: 11px; line-height: 1.8; padding: 11px 12px; margin-top: 12px; background: var(--uikit-soft); border: 1px solid var(--uikit-border); border-radius: 10px; overflow-wrap: anywhere; }
.status[data-tone="error"] { color: var(--uikit-danger); } .status[data-tone="success"] { color: var(--uikit-success); }
.answers { margin-top: 12px; max-height: 280px; overflow: auto; border: 1px solid var(--uikit-border); border-radius: 9px; scrollbar-width: thin; scrollbar-color: var(--uikit-border) transparent; }
.answer-row { display: grid; grid-template-columns: minmax(72px, 1fr) minmax(0, 1fr); align-items: center; gap: 12px; padding: 9px 12px; font-size: 12px; }
.answer-row + .answer-row { border-top: 1px solid var(--uikit-border); }
.answer-row:not(.answer-heading):hover { background: var(--uikit-soft); }
.answer-heading { position: sticky; top: 0; z-index: 1; background: var(--uikit-soft); color: var(--uikit-text-muted); font-size: 11px; }
.answer-value { justify-self: start; padding: 2px 9px; border-radius: 5px; background: var(--uikit-soft); font-size: 13px; font-weight: 800; color: var(--uikit-brand); letter-spacing: 1px; overflow-wrap: anywhere; max-width: 100%; }
.empty-state { padding: 22px 14px; text-align: center; color: var(--uikit-text-muted); font-size: 12px; line-height: 1.9; }
@media (max-width: 360px) { header { padding: 14px 10px; gap: 2px; } .identity { gap: 5px; } .meta { gap: 3px; } .version-badge, .author { padding-inline: 4px; } .icon-button { flex-basis: 26px; width: 26px; } }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
@media (forced-colors: active) { .button, .uikit-root { border: 1px solid ButtonText; } .setting input { appearance: auto; -webkit-appearance: auto; width: 20px; flex-basis: 20px; } .setting input::after { display: none; } }
`;
const icons = {
auto: '',
light: '',
dark: '',
collapse: '', expand: ''
};
function create({ id, title, version }) {
const document = root.document;
const host = document.createElement('div');
host.id = id;
const shadow = host.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = styles;
const controller = new AbortController();
const on = (target, event, callback, options = {}) => target.addEventListener(event, callback, { ...options, signal: controller.signal });
const element = (tag, className = '', text = '') => {
const node = document.createElement(tag);
node.className = className;
node.textContent = text;
return node;
};
const button = (label, action, className = '') => {
const node = element('button', `button ${className}`, label);
node.type = 'button';
on(node, 'click', action);
return node;
};
const read = key => { try { return localStorage.getItem(`${id}:${key}`); } catch { return null; } };
const save = (key, value) => { try { localStorage.setItem(`${id}:${key}`, value); } catch {} };
const shell = element('section', 'uikit-root');
shell.setAttribute('aria-label', title);
const header = element('header');
header.tabIndex = 0;
header.setAttribute('aria-label', '拖动面板,或按 Alt 与方向键调整位置');
const identity = element('div', 'identity');
const meta = element('div', 'meta');
const author = element('span', 'author', '毫厘');
meta.append(author, element('span', 'version-badge', `v${version}`));
identity.append(element('strong', '', title), meta);
header.append(identity);
const body = element('div', 'body');
const system = matchMedia('(prefers-color-scheme: dark)');
let mode = read('theme') || 'auto';
if (!['auto', 'light', 'dark'].includes(mode)) mode = 'auto';
const icon = (node, key, label) => {
node.innerHTML = ``;
node.title = label;
node.setAttribute('aria-label', label);
};
const theme = button('', () => { mode = { auto: 'light', light: 'dark', dark: 'auto' }[mode]; save('theme', mode); applyTheme(); }, 'icon-button');
const applyTheme = () => {
shell.dataset.theme = mode === 'auto' ? system.matches ? 'dark' : 'light' : mode;
const names = { auto: '跟随系统', light: '浅色', dark: '深色' };
theme.dataset.themeMode = mode;
icon(theme, mode, `当前${names[mode]};切换为${names[{ auto: 'light', light: 'dark', dark: 'auto' }[mode]]}`);
};
on(system, 'change', applyTheme);
applyTheme();
let collapsed = read('collapsed') === 'true';
const toggle = button('', () => { collapsed = !collapsed; applyCollapsed(); save('collapsed', String(collapsed)); constrain(); }, 'icon-button');
function applyCollapsed() {
body.hidden = collapsed;
icon(toggle, collapsed ? 'expand' : 'collapse', collapsed ? '展开面板' : '收起面板');
toggle.setAttribute('aria-expanded', String(!collapsed));
}
applyCollapsed();
header.append(theme, toggle);
shell.append(header, body);
shadow.append(style, shell);
document.body.append(host);
function position(x, y) {
host.style.right = 'auto';
host.style.left = `${Math.max(12, Math.min(x, innerWidth - host.offsetWidth - 12))}px`;
host.style.top = `${Math.max(12, Math.min(y, innerHeight - host.offsetHeight - 12))}px`;
}
function constrain() { const box = host.getBoundingClientRect(); position(box.left, box.top); }
function persistPosition() { const box = host.getBoundingClientRect(); save('position', JSON.stringify([box.left, box.top])); }
try {
const stored = JSON.parse(read('position'));
if (Array.isArray(stored) && stored.length === 2 && stored.every(Number.isFinite)) position(...stored);
} catch {}
let drag = null;
on(header, 'pointerdown', event => {
if (event.button !== 0 || event.target.closest('button')) return;
const box = host.getBoundingClientRect();
drag = { id: event.pointerId, dx: event.clientX - box.left, dy: event.clientY - box.top };
header.setPointerCapture(event.pointerId);
});
on(header, 'pointermove', event => { if (drag?.id === event.pointerId) position(event.clientX - drag.dx, event.clientY - drag.dy); });
const endDrag = () => { if (drag) persistPosition(); drag = null; };
on(header, 'pointerup', endDrag);
on(header, 'pointercancel', endDrag);
on(header, 'lostpointercapture', endDrag);
on(header, 'keydown', event => {
const offsets = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
if (event.target !== header || !event.altKey || !offsets) return;
event.preventDefault();
const box = host.getBoundingClientRect(), step = event.shiftKey ? 24 : 8;
position(box.left + offsets[0] * step, box.top + offsets[1] * step);
persistPosition();
});
on(window, 'resize', constrain);
const observer = new ResizeObserver(constrain);
observer.observe(shell);
const destroy = () => { controller.abort(); observer.disconnect(); host.remove(); };
return { host, shadow, body, on, element, button, destroy };
}
root.UserscriptPanel = Object.freeze({ create });
})(modules);
(function (root) {
'use strict';
function start() {
if (document.getElementById('physics-lab-helper-preview')) return;
const ui = root.UserscriptPanel.create({ id: 'physics-lab-helper-preview', title: '物理实验助手', version: root.PhysicsLabHelperVersion || '开发版' });
const { element, button, on } = ui;
const read = key => { try { return localStorage.getItem(key); } catch { return null; } };
const save = (key, value) => { try { localStorage.setItem(key, String(value)); } catch {} };
const status = element('p', 'status', '正在读取当前题目…');
status.setAttribute('role', 'status');
const say = (message, tone = '') => { status.textContent = message; status.dataset.tone = tone; };
// 仅使用当前页提供的有效答案;缺失或不完整时不修改原选项。
function questions() {
const inputs = [...document.querySelectorAll('input[id]')];
const labels = [...document.querySelectorAll('label[for]')];
return inputs.flatMap(hidden => {
const match = hidden.id.match(/^(.*)result_refer_pre(\d+)$/);
const value = hidden.value.trim();
if (!match || !/^[01]+$/.test(value) || !value.includes('1')) return [];
const [, prefix, index] = match;
const options = inputs.filter(node => {
const suffix = node.id.slice(prefix.length).match(/^pre(\d+)_op(\d+)$/);
return node.id.startsWith(prefix) && suffix && suffix[1] === index && /^(checkbox|radio)$/.test(node.type);
});
const validLabels = labels.filter(label => label.textContent.trim() && options.some(option => option.id === label.htmlFor));
const desired = options.filter(option => value[Number(option.id.match(/_op(\d+)$/)[1])] === '1');
if (!options.length || desired.length !== [...value].filter(bit => bit === '1').length) return [];
if (options.some(option => option.type === 'radio') && desired.length !== 1) return [];
const letters = desired.map(option => {
const label = validLabels.find(item => item.htmlFor === option.id);
if (!label) return '选项' + (Number(option.id.match(/_op(\d+)$/)[1]) + 1);
const letter = label.textContent.trim().match(/^([A-Z])(?:[.、.::))\s]|$)/i);
return letter ? letter[1].toUpperCase() : String.fromCharCode(65 + validLabels.indexOf(label));
});
return [{ key: hidden.id + ':' + value + ':' + options.map(option => option.id).join(','), index: Number(index), options, desired, letters: [...new Set(letters)].sort().join('') }];
}).sort((a, b) => a.index - b.index);
}
function selectAnswers(data = questions()) {
if (!data.length) { say('当前页面未识别到预习题。'); return; }
let changed = 0, skipped = 0;
data.forEach(item => item.options.forEach(option => {
const checked = item.desired.includes(option);
if (option.checked === checked) return;
if (option.matches(':disabled')) { skipped++; return; }
if (option.type !== 'radio' || checked) option.click();
if (option.checked !== checked) {
option.checked = checked;
option.dispatchEvent(new Event('input', { bubbles: true }));
option.dispatchEvent(new Event('change', { bubbles: true }));
}
changed++;
}));
say(`已核对 ${data.length} 道预习题,调整 ${changed} 个选项${skipped ? `;${skipped} 个选项不可编辑` : ''}。`, skipped ? '' : 'success');
}
const quizSection = element('section', 'section');
quizSection.dataset.section = 'quiz';
const answerList = element('div', 'answers');
const quizActions = element('div', 'actions');
const quizFill = button('一键勾选预习题', () => selectAnswers(), 'primary');
quizFill.dataset.action = 'fill-quiz';
quizActions.append(quizFill);
const autoLabel = element('label', 'setting');
const auto = element('input');
auto.type = 'checkbox';
auto.setAttribute('role', 'switch');
auto.checked = read('physics_helper_autorun') === 'true';
on(auto, 'change', () => { save('physics_helper_autorun', auto.checked); if (auto.checked) { selectAnswers(); rememberAutomatic(questions()); } });
const autoCopy = element('span', 'setting-copy');
autoCopy.append(element('span', 'setting-title', '自动勾选'), element('span', 'setting-hint', '读取到预习答案后自动填写'));
autoLabel.append(autoCopy, auto);
const refresh = button('刷新题目', () => refreshData(true));
refresh.dataset.action = 'refresh';
refresh.title = '手动重新读取当前题目';
const quizHeading = element('div', 'section-heading');
quizHeading.append(element('h2', '', '预习题'), refresh);
quizSection.append(quizHeading, answerList, quizActions);
const settings = element('section', 'section');
settings.append(element('h2', '', '偏好设置'), autoLabel);
ui.body.append(quizSection, settings, status);
let lastSignature = null;
let autoNodes = new WeakMap();
function rememberAutomatic(data) {
data.forEach(item => item.options.forEach(option => autoNodes.set(option, item.key)));
}
function refreshData(manual = false) {
const data = questions();
quizSection.hidden = false;
ui.host.hidden = false;
quizFill.disabled = !data.length;
const signature = data.map(item => item.key + ':' + item.letters).join('|');
if (manual || signature !== lastSignature) {
if (data.length) {
const heading = element('div', 'answer-row answer-heading');
heading.append(element('span', '', '题号'), element('span', '', '答案'));
answerList.replaceChildren(heading, ...data.map((item, index) => {
const row = element('div', 'answer-row');
row.append(element('span', '', `第 ${index + 1} 题`), element('strong', 'answer-value', item.letters));
return row;
}));
} else {
answerList.replaceChildren(element('div', 'empty-state', '请打开实验预习题页面,答案将自动更新。'));
}
say((data.length ? `已读取 ${data.length} 道预习题。` : '暂未获取到预习答案。'), '');
lastSignature = signature;
}
if (auto.checked) {
const pending = data.filter(item => item.options.some(option => autoNodes.get(option) !== item.key));
if (pending.length) { selectAnswers(pending); rememberAutomatic(pending); }
}
}
refreshData();
// 兼容延迟加载、ASP.NET 局部更新和 iframe 各自加载;不读取跨域框架。
const refreshTimer = window.setInterval(() => refreshData(), 1000);
const destroyPanel = ui.destroy;
const destroy = () => {
window.clearInterval(refreshTimer);
destroyPanel();
};
on(window, 'pagehide', event => { if (!event.persisted) destroy(); });
root.PhysicsLabHelper = Object.freeze({ destroy });
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
else start();
})(modules);
})();