feat: add opt-in answer selection and global hidden panel
This commit is contained in:
Vendored
+354
-29
@@ -1,10 +1,9 @@
|
||||
// ==UserScript==
|
||||
// @name 华谊题库助手 · CSV导出与划词检索
|
||||
// @namespace local.huayi.question-bank
|
||||
// @version 1.1.0
|
||||
// @description 按题库采集与同名CSV导出,支持多题库批量导入、文字搜索、划词查答案、选择复制与隐藏面板。
|
||||
// @match https://www.shhuayi-elearning.cn/*
|
||||
// @match https://shhuayi-elearning.cn/*
|
||||
// @version 1.2.0
|
||||
// @description 全网页快捷键唤出、本地题库文字检索与自动选择答案,按库导入导出;每页默认完全隐藏。
|
||||
// @match *://*/*
|
||||
// @run-at document-start
|
||||
// @noframes
|
||||
// @grant unsafeWindow
|
||||
@@ -566,7 +565,7 @@ const QBAdapter = (() => {
|
||||
} catch (_) { return ''; }
|
||||
}
|
||||
|
||||
function create({ window: win, document: doc, onQuestions = () => {}, onStatus = () => {}, onBankChange = () => {} }) {
|
||||
function create({ window: win, document: doc, onQuestions = () => {}, onStatus = () => {}, onBankChange = () => {}, observeNetwork = true }) {
|
||||
let active = false;
|
||||
let copyEnabled = false;
|
||||
let observer = null;
|
||||
@@ -593,6 +592,14 @@ const QBAdapter = (() => {
|
||||
const status = message => { try { onStatus(message); } catch (_) { /* UI callbacks must not affect the page. */ } };
|
||||
const locationURL = () => String(win.location && win.location.href || '');
|
||||
|
||||
function isSupportedPage() {
|
||||
try {
|
||||
const host = new URL(locationURL()).hostname;
|
||||
if (host === 'www.shhuayi-elearning.cn' || host === 'shhuayi-elearning.cn') return true;
|
||||
} catch (_) { /* An incomplete location still allows an explicit exercise root. */ }
|
||||
return Boolean(doc.querySelector(ROOT_SELECTOR));
|
||||
}
|
||||
|
||||
function formSnapshot() {
|
||||
const element = [...doc.querySelectorAll(`${ROOT_SELECTOR} .yxtulcdsdk-form`)].find(visible);
|
||||
return element ? { element, text: flat(element.textContent) } : null;
|
||||
@@ -628,6 +635,18 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function syncBank() {
|
||||
if (!isSupportedPage()) {
|
||||
const empty = { bankId: '', bankName: '', taskId: '', loading: false };
|
||||
const changed = !currentBank || JSON.stringify(currentBank) !== JSON.stringify(empty);
|
||||
currentBank = empty;
|
||||
pendingSelection = '';
|
||||
blockedForm = null;
|
||||
lastFormSnapshot = null;
|
||||
if (changed) {
|
||||
try { onBankChange({ ...empty }); } catch (_) { /* The host page remains independent. */ }
|
||||
}
|
||||
return { ...empty };
|
||||
}
|
||||
const state = bankDOM();
|
||||
const identity = JSON.stringify([state.taskId, flat(state.bankName)]);
|
||||
const oldIdentity = currentBank && JSON.stringify([currentBank.taskId, flat(currentBank.bankName)]);
|
||||
@@ -663,7 +682,7 @@ const QBAdapter = (() => {
|
||||
function getCurrentBank() { return syncBank(); }
|
||||
|
||||
function ensureBankListeners() {
|
||||
if (bankListeners) return;
|
||||
if (bankListeners || !isSupportedPage()) return;
|
||||
bankListeners = true;
|
||||
win.addEventListener?.('hashchange', syncBank);
|
||||
win.addEventListener?.('popstate', syncBank);
|
||||
@@ -713,6 +732,7 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function getCurrentQuestion() {
|
||||
if (!isSupportedPage()) return null;
|
||||
const bank = syncBank();
|
||||
if (bankDOM().mismatch) return null;
|
||||
const forms = [...doc.querySelectorAll(`${ROOT_SELECTOR} .yxtulcdsdk-form`)].filter(visible);
|
||||
@@ -774,6 +794,10 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function captureCurrent() {
|
||||
if (!isSupportedPage()) {
|
||||
status('当前为通用网页,可使用本地题库搜索;本站采集未开启。');
|
||||
return null;
|
||||
}
|
||||
const current = getCurrentQuestion();
|
||||
if (current) emit([current]);
|
||||
else status('当前页面未发现可采集的练习题,请进入题目页面。');
|
||||
@@ -796,6 +820,7 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function installNetwork() {
|
||||
if (!observeNetwork || !isSupportedPage()) return;
|
||||
const generation = ++networkGeneration;
|
||||
if (typeof win.fetch === 'function') {
|
||||
const originalFetch = win.fetch;
|
||||
@@ -882,7 +907,7 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function ensureCopyStyle() {
|
||||
if (!copyEnabled || copyStyle?.isConnected) return;
|
||||
if (!copyEnabled || copyStyle?.isConnected || !isSupportedPage()) return;
|
||||
const parent = doc.head || doc.documentElement;
|
||||
if (!parent) return;
|
||||
copyStyle = doc.createElement('style');
|
||||
@@ -892,7 +917,7 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function ensureObserver() {
|
||||
if (observer || !win.MutationObserver) return;
|
||||
if (observer || !win.MutationObserver || !isSupportedPage()) return;
|
||||
observer = new win.MutationObserver(mutations => {
|
||||
const relevant = mutations.some(m => {
|
||||
const node = m.target.nodeType === 1 ? m.target : m.target.parentElement;
|
||||
@@ -914,10 +939,12 @@ const QBAdapter = (() => {
|
||||
}
|
||||
|
||||
function setCopyEnabled(value) {
|
||||
copyEnabled = Boolean(value);
|
||||
const supported = isSupportedPage();
|
||||
if (!supported && !copyEnabled && !copyStyle) return;
|
||||
copyEnabled = Boolean(value) && supported;
|
||||
for (const type of ['copy', 'cut', 'contextmenu', 'selectstart']) {
|
||||
win.removeEventListener(type, copyEvent, true);
|
||||
if (copyEnabled) win.addEventListener(type, copyEvent, true);
|
||||
win.removeEventListener?.(type, copyEvent, true);
|
||||
if (copyEnabled) win.addEventListener?.(type, copyEvent, true);
|
||||
}
|
||||
if (copyEnabled) { ensureCopyStyle(); ensureObserver(); }
|
||||
else if (copyStyle) { copyStyle.remove(); copyStyle = null; }
|
||||
@@ -929,6 +956,11 @@ const QBAdapter = (() => {
|
||||
function start() {
|
||||
if (active) return;
|
||||
active = true;
|
||||
if (!isSupportedPage()) {
|
||||
syncBank();
|
||||
status('当前为通用网页,可使用本地题库搜索;本站采集未开启。');
|
||||
return;
|
||||
}
|
||||
ensureBankListeners();
|
||||
ensureObserver();
|
||||
installNetwork();
|
||||
@@ -943,7 +975,7 @@ const QBAdapter = (() => {
|
||||
status('采集已暂停,已保存题库和选择复制功能仍可使用。');
|
||||
}
|
||||
|
||||
return { start, stop, captureCurrent, getCurrentQuestion, getCurrentBank, setCopyEnabled };
|
||||
return { start, stop, captureCurrent, getCurrentQuestion, getCurrentBank, setCopyEnabled, isSupportedPage };
|
||||
}
|
||||
|
||||
return { create, extractQuestions };
|
||||
@@ -951,12 +983,260 @@ const QBAdapter = (() => {
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
|
||||
|
||||
// ---- src/autofill.js ----
|
||||
/* Select confirmed local answers. This module never submits forms or changes pages. */
|
||||
const QBAuto = (() => {
|
||||
'use strict';
|
||||
const tidy = value => String(value == null ? '' : value).replace(/\u00a0/g, ' ').trim();
|
||||
const flat = value => tidy(value).replace(/\s+/gu, '');
|
||||
const stemKey = value => flat(tidy(value).replace(/^(?:第\s*\d+\s*题[\s、..::]*|\d+\s*[、.]\s*|\d+\.\s+)/u, ''));
|
||||
const judgeText = value => /^(正确|对|是|√|true)$/i.test(tidy(value)) ? '正确' : /^(错误|错|否|×|false)$/i.test(tidy(value)) ? '错误' : tidy(value);
|
||||
const optionKey = (value, type) => flat(type === 'judge' ? judgeText(value) : value);
|
||||
const sorted = values => [...values].sort();
|
||||
const optionSet = question => JSON.stringify(sorted(question.options.map(option => optionKey(option.text, question.type))));
|
||||
const localCore = supplied => supplied || (typeof QBCore !== 'undefined' ? QBCore : typeof require === 'function' ? require('./core.js') : null);
|
||||
|
||||
function planAnswer(records, current, suppliedCore) {
|
||||
const result = (status, message, more = {}) => ({ status, message, labels: [], answerTexts: [], ...more });
|
||||
const core = localCore(suppliedCore);
|
||||
if (!core || !current || !Array.isArray(records)) return result('unsupported', '当前网页未识别到可自动选择的题目。');
|
||||
let question;
|
||||
try { question = core.normalizeRecord({ ...current, answerStatus: 'missing' }); }
|
||||
catch (_) { return result('unsupported', '当前题目结构不完整,已跳过。'); }
|
||||
if (!['single', 'multiple', 'judge'].includes(question.type) || question.options.length < 2 || question.options.length > 100) return result('unsupported', '当前题型暂不支持自动选择。');
|
||||
const contents = question.options.map(option => optionKey(option.text, question.type));
|
||||
if (new Set(contents).size !== contents.length || new Set(question.options.map(option => option.label)).size !== question.options.length) return result('ambiguous', '当前选项文字或标记重复,无法唯一对应,已跳过。');
|
||||
const relevant = [];
|
||||
for (const input of records) {
|
||||
let record;
|
||||
try { record = core.normalizeRecord(input); } catch (_) { continue; }
|
||||
if (record.type !== question.type || stemKey(record.stem) !== stemKey(question.stem) || optionSet(record) !== optionSet(question)) continue;
|
||||
if (question.bankId && record.bankId && question.bankId !== record.bankId) continue;
|
||||
if (!record.bankId && question.bankName && question.bankName !== '未命名题库' && record.bankName !== '未命名题库' && flat(record.bankName) !== flat(question.bankName)) continue;
|
||||
relevant.push(record);
|
||||
}
|
||||
let candidates = relevant;
|
||||
if (question.bankId) {
|
||||
const exactBank = relevant.filter(record => record.bankId === question.bankId);
|
||||
if (exactBank.length) candidates = relevant.filter(record => record.bankId === question.bankId || !record.bankId);
|
||||
} else if (question.bankName && question.bankName !== '未命名题库') {
|
||||
const sameName = relevant.filter(record => flat(record.bankName) === flat(question.bankName));
|
||||
if (sameName.length) candidates = sameName;
|
||||
}
|
||||
if (candidates.some(record => record.answerStatus === 'conflict')) return result('ambiguous', '本地题库存在该题的冲突答案,已跳过。');
|
||||
const confirmed = candidates.filter(record => record.answerStatus === 'confirmed');
|
||||
if (!confirmed.length) return result('missing', '未找到题干、题型和全部选项一致的已确认答案。');
|
||||
const signatures = new Set(confirmed.map(record => JSON.stringify(sorted(record.answerTexts.map(value => optionKey(value, record.type))))));
|
||||
if (signatures.size !== 1) return result('ambiguous', '相同题目对应多个不同标准答案,已跳过。');
|
||||
const mapped = confirmed.map(record => ({ record, mapping: core.mapAnswers(record, question) }));
|
||||
if (mapped.some(item => item.mapping.status !== 'matched' || !item.mapping.labels.length)) return result('ambiguous', '标准答案无法安全对应当前选项,已跳过。');
|
||||
const labelSets = new Set(mapped.map(item => JSON.stringify(sorted(item.mapping.labels))));
|
||||
if (labelSets.size !== 1) return result('ambiguous', '标准答案对应的选项位置不一致,已跳过。');
|
||||
return result('ready', '已找到唯一对应的标准答案。', { labels: [...mapped[0].mapping.labels], answerTexts: [...mapped[0].mapping.answerTexts], record: mapped[0].record });
|
||||
}
|
||||
|
||||
function create({ window: win, document: doc, core: suppliedCore, getRecords = () => [], getQuestion = () => null, getBank = () => null, onStatus = () => {}, onChange = () => {} }) {
|
||||
const core = localCore(suppliedCore);
|
||||
const SITE_FORM = '.yxtulcdsdk-pc-marking-main .yxtulcdsdk-form';
|
||||
const GENERIC = 'fieldset, .question, .question-item, [data-question]';
|
||||
let state = { enabled: false, busy: false, status: 'idle', message: '自动答题未开启。', answeredCount: 0, skippedCount: 0, lastStem: '' };
|
||||
let observer = null, timer = null, interval = null, generation = 0, destroyed = false;
|
||||
let attempts = new WeakMap();
|
||||
const setTimer = (fn, delay) => win.setTimeout(fn, delay);
|
||||
function emit(patch) {
|
||||
const before = state;
|
||||
state = { ...state, ...patch };
|
||||
if (JSON.stringify(before) === JSON.stringify(state)) return;
|
||||
try { onChange({ ...state }); } catch (_) { /* UI failures must not affect a page. */ }
|
||||
if (before.message !== state.message) try { onStatus(state.message); } catch (_) { /* Ignore callback errors. */ }
|
||||
}
|
||||
function visible(element) {
|
||||
if (!element || !element.isConnected || element.closest('#huayi-qb-root')) return false;
|
||||
for (let at = element; at && at.nodeType === 1; at = at.parentElement) {
|
||||
if (at.hidden || at.getAttribute('aria-hidden') === 'true') return false;
|
||||
const style = win.getComputedStyle?.(at);
|
||||
if (style?.display === 'none' || style?.visibility === 'hidden' || style?.visibility === 'collapse') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function labelText(input, container) {
|
||||
let label = input.labels && [...input.labels].find(item => container.contains(item));
|
||||
if (!label) label = input.closest('label');
|
||||
if (label) {
|
||||
const rich = label.querySelector('.yxtf-radio__label [data-rich-text], .yxtf-checkbox__label [data-rich-text]');
|
||||
if (rich) return tidy(rich.textContent);
|
||||
const clone = (label.querySelector('.yxtf-radio__label, .yxtf-checkbox__label') || label).cloneNode(true);
|
||||
clone.querySelectorAll('input,button,script,style').forEach(node => node.remove());
|
||||
return tidy(clone.textContent).replace(/^(?:[A-Z][.、.)::]|\[[A-Z]\])\s*/u, '');
|
||||
}
|
||||
const labelled = tidy(input.getAttribute('aria-labelledby')).split(/\s+/u).filter(Boolean).map(id => doc.getElementById(id)).filter(node => node && container.contains(node));
|
||||
return tidy(labelled.length ? labelled.map(node => node.textContent).join(' ') : input.getAttribute('aria-label'));
|
||||
}
|
||||
function controls(container, site) {
|
||||
const selector = site ? '.yxtulcdsdk-ques-radio input[type="radio"],.yxtulcdsdk-ques-checkbox input[type="checkbox"]' : 'input[type="radio"],input[type="checkbox"]';
|
||||
const inputs = [...container.querySelectorAll(selector)].filter(input => site || input.closest(GENERIC) === container);
|
||||
if (inputs.length < 2 || inputs.length > 100) return null;
|
||||
const types = new Set(inputs.map(input => input.type));
|
||||
if (types.size !== 1 || inputs.some(input => input.disabled || input.matches(':disabled') || input.closest('[aria-disabled="true"]'))) return null;
|
||||
if (inputs.some(input => !visible(input) && !visible(input.closest('label')))) return null;
|
||||
if (!site && inputs[0].type === 'radio' && new Set(inputs.map(input => input.name)).size > 1) return null;
|
||||
const texts = inputs.map(input => labelText(input, container));
|
||||
if (texts.some(value => !value)) return null;
|
||||
return { inputs, texts, type: inputs[0].type === 'checkbox' ? 'multiple' : 'single' };
|
||||
}
|
||||
function readSite(container) {
|
||||
if (!visible(container)) return null;
|
||||
const current = getQuestion();
|
||||
const bank = getBank();
|
||||
if (!current || bank?.loading) return null;
|
||||
const set = controls(container, true);
|
||||
if (!set || set.inputs.length !== current.options?.length || set.texts.some((value, index) => optionKey(value, current.type) !== optionKey(current.options[index].text, current.type))) return null;
|
||||
return { container, inputs: set.inputs, question: current, site: true };
|
||||
}
|
||||
function readGeneric(container) {
|
||||
if (!visible(container)) return null;
|
||||
const set = controls(container, false);
|
||||
if (!set) return null;
|
||||
const titles = [...container.querySelectorAll(':scope > legend, :scope > .question-title, :scope > [data-question-title], :scope > .question-stem, :scope > .stem, :scope > h2, :scope > h3, :scope > p')].filter(node => visible(node) && !node.querySelector('input'));
|
||||
if (titles.length !== 1) return null;
|
||||
const stem = tidy(titles[0].textContent);
|
||||
if (!stem || stem.length > 100000) return null;
|
||||
const judged = set.type === 'single' && set.texts.length === 2 && set.texts.map(judgeText).includes('正确') && set.texts.map(judgeText).includes('错误');
|
||||
const type = judged ? 'judge' : set.type;
|
||||
const question = {
|
||||
bankId: tidy(container.getAttribute('data-bank-id')), bankName: tidy(container.getAttribute('data-bank-name')),
|
||||
questionId: '', stem, type, options: set.inputs.map((input, index) => ({ id: input.value || input.id || '', text: judged ? judgeText(set.texts[index]) : set.texts[index], label: judged ? judgeText(set.texts[index]) : String.fromCharCode(65 + index) })),
|
||||
answerStatus: 'missing', answerTexts: [], correctOptionIds: []
|
||||
};
|
||||
return { container, inputs: set.inputs, question, site: false };
|
||||
}
|
||||
function allCandidates() {
|
||||
const siteForms = [...doc.querySelectorAll(SITE_FORM)].filter(visible);
|
||||
if (siteForms.length) return siteForms.length === 1 ? [readSite(siteForms[0])].filter(Boolean) : [];
|
||||
return [...doc.querySelectorAll(GENERIC)].map(readGeneric).filter(Boolean);
|
||||
}
|
||||
function fingerprint(candidate) {
|
||||
const question = candidate.question;
|
||||
return JSON.stringify([question.bankId || '', question.bankName || '', question.type, stemKey(question.stem), question.options.map(option => [option.label, optionKey(option.text, question.type)])]);
|
||||
}
|
||||
function stillSame(candidate, mark) {
|
||||
if (!candidate.container.isConnected || candidate.inputs.some(input => !input.isConnected || input.disabled)) return false;
|
||||
const current = candidate.site ? readSite(candidate.container) : readGeneric(candidate.container);
|
||||
return current && fingerprint(current) === mark && current.inputs.length === candidate.inputs.length && current.inputs.every((input, index) => input === candidate.inputs[index]);
|
||||
}
|
||||
function attempted(candidate, plan) { return `${fingerprint(candidate)}\u001f${plan.status}\u001f${JSON.stringify(sorted(plan.answerTexts || []))}`; }
|
||||
function desired(candidate, plan) { return candidate.question.options.map(option => plan.labels.includes(option.label)); }
|
||||
function alreadyChosen(candidate, flags) { return candidate.inputs.every((input, index) => Boolean(input.checked) === flags[index]); }
|
||||
function skipped(message, stem = '', count = true) {
|
||||
emit({ busy: false, status: 'skipped', message, lastStem: stem, skippedCount: state.skippedCount + (count ? 1 : 0) });
|
||||
return { status: 'skipped', message };
|
||||
}
|
||||
async function answerCurrent(options = {}) {
|
||||
const continuous = options.continuous === true;
|
||||
if (destroyed) return { status: 'cancelled', message: '自动答题已关闭。' };
|
||||
if (state.busy) return { status: 'busy', message: '正在处理当前题目。' };
|
||||
if (continuous && !state.enabled) return { status: 'cancelled', message: '连续自动选择已暂停。' };
|
||||
const candidates = allCandidates();
|
||||
if (!candidates.length) return continuous ? { status: 'idle', message: '等待可识别的选择题。' } : skipped('当前网页未识别到明确的题干和选项,已跳过。');
|
||||
const prioritized = [...candidates].sort((a, b) => Number(Boolean(b.container.matches('.current,.is-active,[aria-current="true"]'))) - Number(Boolean(a.container.matches('.current,.is-active,[aria-current="true"]'))));
|
||||
let candidate, plan, attempt;
|
||||
for (const item of prioritized) {
|
||||
const proposal = planAnswer(getRecords(), item.question, core);
|
||||
const key = attempted(item, proposal);
|
||||
if (continuous && attempts.get(item.container) === key) continue;
|
||||
candidate = item; plan = proposal; attempt = key; break;
|
||||
}
|
||||
if (!candidate) return { status: 'idle', message: '当前识别的题目已处理。' };
|
||||
const questionStem = candidate.question.stem;
|
||||
attempts.set(candidate.container, attempt);
|
||||
if (plan.status !== 'ready') return skipped(plan.message, questionStem);
|
||||
const flags = desired(candidate, plan);
|
||||
if (candidate.question.type !== 'multiple' && flags.filter(Boolean).length !== 1) return skipped('单选或判断题的目标选项不唯一,已跳过。', questionStem);
|
||||
if (alreadyChosen(candidate, flags)) {
|
||||
emit({ status: 'answered', message: '当前题已选择正确选项。', lastStem: questionStem });
|
||||
return { status: 'answered', alreadySelected: true, labels: plan.labels, answerTexts: plan.answerTexts };
|
||||
}
|
||||
const mark = fingerprint(candidate);
|
||||
const runGeneration = generation;
|
||||
emit({ busy: true, status: 'matched', message: `正在选择:${plan.answerTexts.join(';')}`, lastStem: questionStem });
|
||||
try {
|
||||
const actions = candidate.question.type === 'multiple'
|
||||
? candidate.inputs.map((input, index) => ({ input, index })).filter(({ input, index }) => Boolean(input.checked) !== flags[index])
|
||||
: candidate.inputs.map((input, index) => ({ input, index })).filter(({ index }) => flags[index]);
|
||||
for (const { input } of actions) {
|
||||
if (destroyed || generation !== runGeneration || (continuous && !state.enabled)) {
|
||||
emit({ busy: false, status: 'idle', message: '自动选择已暂停。' });
|
||||
return { status: 'cancelled', message: '自动选择已暂停。' };
|
||||
}
|
||||
if (!stillSame(candidate, mark)) return skipped('点击前题目或选项已变化,已停止本次选择。', questionStem);
|
||||
input.click();
|
||||
await Promise.resolve();
|
||||
if (destroyed || generation !== runGeneration || (continuous && !state.enabled)) {
|
||||
emit({ busy: false, status: 'idle', message: '自动选择已暂停。' });
|
||||
return { status: 'cancelled', message: '自动选择已暂停。' };
|
||||
}
|
||||
if (!stillSame(candidate, mark)) return skipped('页面在选择过程中换题或替换控件,已停止后续点击。', questionStem);
|
||||
}
|
||||
if (!alreadyChosen(candidate, flags)) return skipped('网页未保留预期的选中状态,请人工核对。', questionStem);
|
||||
emit({ busy: false, status: 'answered', message: `已选择正确选项:${plan.labels.join('、')}`, answeredCount: state.answeredCount + 1, lastStem: questionStem });
|
||||
return { status: 'answered', labels: plan.labels, answerTexts: plan.answerTexts };
|
||||
} catch (error) {
|
||||
return skipped(`自动选择未完成:${error.message || '控件操作失败'}`, questionStem);
|
||||
} finally { if (state.busy) emit({ busy: false }); }
|
||||
}
|
||||
function schedule() {
|
||||
if (!state.enabled || destroyed) return;
|
||||
win.clearTimeout(timer);
|
||||
timer = setTimer(() => { timer = null; void answerCurrent({ continuous: true }); }, 160);
|
||||
}
|
||||
function stopObservers() {
|
||||
win.clearTimeout(timer); win.clearInterval(interval); timer = null; interval = null;
|
||||
if (observer) observer.disconnect(); observer = null;
|
||||
}
|
||||
function setEnabled(value) {
|
||||
if (destroyed) return;
|
||||
const enabled = Boolean(value);
|
||||
if (state.enabled === enabled) {
|
||||
// A page can be hidden while a one-shot selection is awaiting a UI
|
||||
// microtask. Calling false must cancel that run even without continuous mode.
|
||||
if (!enabled) {
|
||||
generation++;
|
||||
stopObservers();
|
||||
if (state.busy) emit({ busy: false, status: 'idle', message: '自动选择已暂停。' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
generation++;
|
||||
stopObservers();
|
||||
emit({ enabled, busy: false, status: 'idle', message: enabled ? '连续自动选择已开启,仅处理明确匹配的题目。' : '连续自动选择已暂停。' });
|
||||
if (!enabled) return;
|
||||
attempts = new WeakMap();
|
||||
if (win.MutationObserver) {
|
||||
observer = new win.MutationObserver(mutations => {
|
||||
if (mutations.some(mutation => {
|
||||
const element = mutation.target.nodeType === 1 ? mutation.target : mutation.target.parentElement;
|
||||
return element && !element.closest('#huayi-qb-root');
|
||||
})) schedule();
|
||||
});
|
||||
observer.observe(doc, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['class', 'hidden', 'disabled', 'aria-disabled'] });
|
||||
}
|
||||
interval = win.setInterval(schedule, 1500);
|
||||
schedule();
|
||||
}
|
||||
function destroy() { setEnabled(false); stopObservers(); destroyed = true; generation++; }
|
||||
return { answerCurrent, setEnabled, isEnabled: () => state.enabled, getState: () => ({ ...state }), destroy };
|
||||
}
|
||||
return { planAnswer, create };
|
||||
})();
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = QBAuto;
|
||||
|
||||
|
||||
// ---- src/app.js ----
|
||||
// UI and persistence stay inside the userscript sandbox. Page data is rendered as text.
|
||||
(() => {
|
||||
const CONFIG_KEY = 'huayi-qb.config.v1';
|
||||
const RECORDS_KEY = 'huayi-qb.records.v1';
|
||||
const DEFAULTS = { mode: 'open', keepLauncher: true, copyEnabled: true, collecting: true, tab: 'search' };
|
||||
const DEFAULTS = { mode: 'hidden', keepLauncher: false, copyEnabled: true, collecting: true, tab: 'search' };
|
||||
const pageWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
|
||||
const storage = {
|
||||
get(key, fallback) {
|
||||
@@ -973,9 +1253,13 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
try { rawConfig = storage.get(CONFIG_KEY, {}); } catch (_) { rawConfig = {}; }
|
||||
const config = { ...DEFAULTS, ...(rawConfig && typeof rawConfig === 'object' ? rawConfig : {}) };
|
||||
if (!['open', 'collapsed', 'hidden'].includes(config.mode)) config.mode = 'open';
|
||||
if (!['search', 'library', 'settings'].includes(config.tab)) config.tab = 'search';
|
||||
if (!['search', 'library', 'auto', 'settings'].includes(config.tab)) config.tab = 'search';
|
||||
['keepLauncher', 'copyEnabled', 'collecting'].forEach(key => { if (typeof config[key] !== 'boolean') config[key] = DEFAULTS[key]; });
|
||||
// Every new page starts completely hidden, including upgrades from older settings.
|
||||
config.mode = 'hidden';
|
||||
config.keepLauncher = false;
|
||||
let records = [];
|
||||
let recordsDirty = false;
|
||||
let loadError = '';
|
||||
try {
|
||||
const saved = storage.get(RECORDS_KEY, []);
|
||||
@@ -983,15 +1267,37 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
records = QBCore.upsert([], saved);
|
||||
} catch (error) { loadError = `本地题库读取失败:${error.message}。请先保留已有备份。`; }
|
||||
let root, shadow, panel, launcher, resultBox, statusBox;
|
||||
let saveTimer, searchTimer, query = '', scope = '__current__', searchScope = '__current__', searchField = 'all';
|
||||
let networkEnabled = ['www.shhuayi-elearning.cn', 'shhuayi-elearning.cn'].includes(window.location.hostname);
|
||||
let saveTimer, searchTimer, query = '', scope = networkEnabled ? '__current__' : '', searchScope = scope, searchField = 'all';
|
||||
let activeBank = null, importing = false;
|
||||
let status = loadError || '准备就绪,可输入文字搜索,也可选中题干检索。';
|
||||
let storageError = false;
|
||||
let mounted = false;
|
||||
const adapter = QBAdapter.create({ window: pageWindow, document, onQuestions: receive, onStatus: adapterStatus, onBankChange: bankChanged });
|
||||
const createAdapter = () => QBAdapter.create({ window: pageWindow, document, onQuestions: receive, onStatus: adapterStatus, onBankChange: bankChanged, observeNetwork: networkEnabled });
|
||||
let adapter = createAdapter();
|
||||
const autoAnswer = QBAuto.create({ window: pageWindow, document, core: QBCore, getRecords: () => records, getQuestion: currentQuestion, getBank: currentBank,
|
||||
onStatus: message => { tell(message); }, onChange: () => { renderAuto(); } });
|
||||
|
||||
function activateKnownPage() {
|
||||
if (!networkEnabled && document.querySelector('.yxtulcdsdk-pc-marking-main')) {
|
||||
adapter.stop();
|
||||
adapter.setCopyEnabled(false);
|
||||
networkEnabled = true;
|
||||
scope = '__current__'; searchScope = '__current__';
|
||||
adapter = createAdapter();
|
||||
if (config.collecting) adapter.start();
|
||||
adapter.setCopyEnabled(Boolean(config.copyEnabled));
|
||||
}
|
||||
}
|
||||
|
||||
function bankChanged(bank) {
|
||||
if (!bank || (!bank.bankName && !bank.bankId)) return;
|
||||
if (!bank || (!bank.bankName && !bank.bankId)) {
|
||||
if (activeBank) {
|
||||
activeBank = null; scope = ''; searchScope = '';
|
||||
if (mounted) { refreshScope(); renderStats(); renderCurrent(); renderResults(); }
|
||||
}
|
||||
return;
|
||||
}
|
||||
const previous = activeBank;
|
||||
const sameName = previous && bankNameKey(previous.bankName) === bankNameKey(bank.bankName);
|
||||
const identityChanged = previous && (!sameName || (previous.taskId && bank.taskId && previous.taskId !== bank.taskId) || (previous.bankId && bank.bankId && previous.bankId !== bank.bankId));
|
||||
@@ -1011,13 +1317,14 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
}
|
||||
function persistRecords() {
|
||||
clearTimeout(saveTimer);
|
||||
if (loadError) return;
|
||||
if (loadError || !recordsDirty) return;
|
||||
try {
|
||||
// Merge other tabs before writing; GM change events also refresh an open panel.
|
||||
const stored = storage.get(RECORDS_KEY, []);
|
||||
if (!Array.isArray(stored)) throw new Error('现有题库结构异常,已停止覆盖');
|
||||
records = QBCore.upsert(stored, records);
|
||||
storage.set(RECORDS_KEY, records);
|
||||
recordsDirty = false;
|
||||
storageError = false;
|
||||
} catch (error) {
|
||||
storageError = true;
|
||||
@@ -1040,6 +1347,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
return names?.size === 1 ? QBCore.normalizeRecord({ ...record, bankName: [...names][0] }) : record;
|
||||
});
|
||||
records = QBCore.upsert(records, incoming);
|
||||
recordsDirty = true;
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = setTimeout(persistRecords, 250);
|
||||
if (mounted) { refreshScope(); renderStats(); renderResults(); renderCurrent(); }
|
||||
@@ -1069,7 +1377,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
if (!panel) return;
|
||||
panel.hidden = config.mode === 'hidden';
|
||||
panel.classList.toggle('collapsed', config.mode === 'collapsed');
|
||||
launcher.hidden = config.mode !== 'hidden' || !config.keepLauncher;
|
||||
launcher.hidden = true;
|
||||
const collapse = shadow.querySelector('[data-action="collapse"]');
|
||||
collapse.textContent = config.mode === 'collapsed' ? '展开' : '收起';
|
||||
collapse.setAttribute('aria-expanded', String(config.mode !== 'collapsed'));
|
||||
@@ -1131,7 +1439,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
}
|
||||
function scopeName(selectedScope = scope) {
|
||||
if (selectedScope === '') return '全部题库';
|
||||
if (selectedScope === '__current__') return currentBank()?.bankName || '未识别当前题库';
|
||||
if (selectedScope === '__current__') return currentBank()?.bankName || '当前网页未识别题库';
|
||||
const anchor = records.find(record => bankKey(record) === selectedScope);
|
||||
return anchor?.bankName || '未命名题库';
|
||||
}
|
||||
@@ -1186,14 +1494,23 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
if (!shadow) return;
|
||||
const bank = currentBank();
|
||||
const current = currentQuestion();
|
||||
const name = bank?.bankName || '尚未识别当前题库';
|
||||
const known = Boolean(bank?.bankName || bank?.bankId);
|
||||
const name = bank?.bankName || '通用网页 · 本地题库';
|
||||
shadow.getElementById('qb-context-name').textContent = name;
|
||||
shadow.getElementById('qb-context-name').title = name;
|
||||
const pool = scopedRecords('__current__');
|
||||
shadow.getElementById('qb-context-count').textContent = `${bank?.loading ? '切换中 · ' : ''}本库已采集 ${pool.length} 题 · 已确认 ${pool.filter(record => record.answerStatus === 'confirmed').length} 题`;
|
||||
shadow.getElementById('qb-context-count').textContent = known ? `${bank?.loading ? '切换中 · ' : ''}本库已采集 ${pool.length} 题 · 已确认 ${pool.filter(record => record.answerStatus === 'confirmed').length} 题` : `本地共 ${records.length} 题 · 可划词或输入文字搜索`;
|
||||
shadow.getElementById('qb-current-title').textContent = bank?.loading ? '题库切换中,等待当前题目加载。' : current?.stem || '打开练习题后,这里显示当前题目。';
|
||||
shadow.getElementById('qb-current-bank').textContent = name;
|
||||
}
|
||||
function renderAuto() {
|
||||
if (!shadow) return;
|
||||
const state = autoAnswer.getState();
|
||||
shadow.getElementById('qb-auto-enabled').checked = state.enabled;
|
||||
shadow.getElementById('qb-auto-status').textContent = state.message || '自动答题尚未开启。可先点击“答当前题”。';
|
||||
shadow.getElementById('qb-auto-count').textContent = `本页已选择 ${state.answeredCount || 0} 题 · 已跳过 ${state.skippedCount || 0} 题`;
|
||||
shadow.querySelector('[data-action="auto-answer-current"]').disabled = Boolean(state.busy);
|
||||
}
|
||||
function renderResults() {
|
||||
if (!resultBox) return;
|
||||
resultBox.replaceChildren();
|
||||
@@ -1312,6 +1629,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
const before = records.length;
|
||||
const merged = QBCore.upsert(records, incoming);
|
||||
records = merged;
|
||||
recordsDirty = true;
|
||||
persistRecords();
|
||||
refreshScope(); renderStats(); renderCurrent(); renderResults();
|
||||
const bankCount = new Set(incoming.map(bankKey)).size;
|
||||
@@ -1333,6 +1651,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
|
||||
function mount() {
|
||||
if (mounted || document.getElementById('huayi-qb-root')) return;
|
||||
activateKnownPage();
|
||||
root = node('div'); root.id = 'huayi-qb-root';
|
||||
shadow = root.attachShadow({ mode: 'open' });
|
||||
const style = node('style'); style.textContent = css;
|
||||
@@ -1343,15 +1662,19 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
<header class="header"><div><div class="brand">题库助手</div><div class="subtitle">HUAYI · 本地练习资料</div></div><div class="tools"><button type="button" data-action="collapse" title="收起或展开内容" aria-expanded="true">收起</button><button type="button" data-action="hide" title="隐藏面板,Alt + Shift + Q 恢复">隐藏</button></div></header>
|
||||
<div class="body">
|
||||
<div class="context"><span class="context-label">当前题库</span><strong id="qb-context-name">正在识别题库…</strong><div class="context-count" id="qb-context-count"></div></div>
|
||||
<nav class="tabs" role="tablist" aria-label="助手功能"><button type="button" data-tab="search" role="tab" aria-controls="qb-view-search">文字搜索</button><button type="button" data-tab="library" role="tab" aria-controls="qb-view-library">题库 / 导出</button><button type="button" data-tab="settings" role="tab" aria-controls="qb-view-settings">设置</button></nav>
|
||||
<nav class="tabs" role="tablist" aria-label="助手功能"><button type="button" data-tab="search" role="tab" aria-controls="qb-view-search">文字搜索</button><button type="button" data-tab="library" role="tab" aria-controls="qb-view-library">题库 / 导出</button><button type="button" data-tab="auto" role="tab" aria-controls="qb-view-auto">自动答题</button><button type="button" data-tab="settings" role="tab" aria-controls="qb-view-settings">设置</button></nav>
|
||||
<div class="view" id="qb-view-search" data-view="search" role="tabpanel"><div class="search-label"><label for="qb-search">输入或粘贴文字查答案</label><button type="button" class="text-button" data-action="clear-search">清空</button></div><div class="search-wrap"><input id="qb-search" type="search" maxlength="4000" placeholder="题干、选项或答案关键词…" aria-label="文字搜索"><button type="button" class="btn primary" data-action="search">搜索</button></div><div class="search-filters"><label>搜索题库<select id="qb-search-scope" aria-label="搜索题库"><option value="__current__">当前题库</option><option value="">全部题库</option></select></label><label>搜索内容<select id="qb-search-field" aria-label="搜索内容"><option value="all">全部文字</option><option value="stem">仅题干</option><option value="options">仅选项</option><option value="answer">仅标准答案</option></select></label></div><p class="hint" id="qb-query-state"></p><div id="qb-results" aria-live="polite"></div></div>
|
||||
<div class="view" id="qb-view-library" data-view="library" role="tabpanel" hidden>
|
||||
<div class="section"><h3>统计与导出范围</h3><label class="scope">选择题库<select id="qb-scope" aria-label="题库范围"><option value="__current__">当前题库</option><option value="">全部题库</option></select></label><p class="export-name" id="qb-export-name"></p><div class="stats"><div class="stat"><strong id="qb-stat-total">0</strong><span>范围内题数</span></div><div class="stat"><strong id="qb-stat-confirmed">0</strong><span>答案确认</span></div><div class="stat"><strong id="qb-stat-missing">0</strong><span>待补答案</span></div><div class="stat"><strong id="qb-stat-conflicts">0</strong><span>答案冲突</span></div></div><div class="row"><button type="button" class="btn primary" data-action="export-csv">导出 CSV</button><button type="button" class="btn" data-action="export-json">备份 JSON</button></div><p class="filename" id="qb-export-preview"></p></div>
|
||||
<div class="section"><div class="row spread"><h3>当前练习</h3><span class="state" id="qb-capture-state">采集中</span></div><p id="qb-current-bank"></p><div id="qb-current-title"></div><div class="row"><button type="button" class="btn small primary" data-action="capture-current">采集当前题</button><button type="button" class="btn small" data-action="toggle-capture">暂停采集</button></div><p>记录正常加载的练习题与标准答案。答案尚未返回的题目会标为待补,可在后续练习中继续补齐。</p></div>
|
||||
<div class="section"><div class="row spread"><h3>已保存题库</h3><button type="button" class="btn small" data-action="import">导入多个题库</button></div><input id="qb-import-file" type="file" accept=".csv,.json,text/csv,application/json" multiple hidden><p>可一次选择多个 CSV / JSON,分别保留题库名称。无名称的文件使用文件名作为题库名。</p><p id="qb-library-summary"></p><div class="bank-list" id="qb-bank-list"></div></div>
|
||||
</div>
|
||||
<div class="view" id="qb-view-auto" data-view="auto" role="tabpanel" hidden>
|
||||
<div class="section"><h3>自动选择正确答案</h3><p>根据本地已确认答案核对题干、题型和完整选项,按当前顺序选择。没有答案、答案冲突或无法唯一匹配的题目会跳过。</p><button type="button" class="btn primary" data-action="auto-answer-current">答当前题</button><label class="check"><input id="qb-auto-enabled" type="checkbox"><span>连续自动选择<small>开启后随题目变化自动选择,仅本页有效;刷新或打开新页面后关闭。</small></span></label><p id="qb-auto-status" role="status"></p><p id="qb-auto-count"></p><p>选择后按页面流程检查、提交或换题;部分网站会自动保存作答。</p></div>
|
||||
<div class="section"><h3>适配范围</h3><p>支持华谊练习页面,以及使用标准单选框/复选框和明确题干容器的网页。网页未识别时可继续使用文字搜索。</p></div>
|
||||
</div>
|
||||
<div class="view" id="qb-view-settings" data-view="settings" role="tabpanel" hidden>
|
||||
<div class="section"><h3>面板显示</h3><p>右上角可收起或隐藏,刷新后保持原状态。</p><label class="check"><input id="qb-keep-launcher" type="checkbox"><span>隐藏时保留悬浮按钮<small>取消后可完全隐藏,用快捷键或油猴菜单恢复。</small></span></label><p>显示 / 隐藏快捷键:<kbd class="kbd">Alt + Shift + Q</kbd></p><p>面板隐藏时,划选文字仍可更新检索内容,面板保持隐藏。</p><button type="button" class="btn small" data-action="hide">立即隐藏</button></div>
|
||||
<div class="section"><h3>面板显示</h3><p>每次打开或刷新网页都默认完全隐藏,不显示悬浮按钮。</p><p>显示 / 隐藏快捷键:<kbd class="kbd">Shift + Alt + Q</kbd></p><p>面板隐藏时,划选文字仍可更新检索内容,面板保持隐藏。</p><button type="button" class="btn small" data-action="hide">立即隐藏</button></div>
|
||||
<div class="section"><h3>选择与复制</h3><label class="check"><input id="qb-copy-enabled" type="checkbox"><span>恢复题目区域的选择复制<small>换题后自动适配,关闭后恢复原有处理。</small></span></label></div>
|
||||
<div class="section"><h3>答案规则</h3><p>按标准答案内容保存,再对应当前页面的选项位置。没有标准答案就显示待补;不同答案会保留冲突。所有资料保存在当前浏览器,建议定期导出备份。</p></div>
|
||||
</div>
|
||||
@@ -1363,7 +1686,6 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
panel = shadow.getElementById('qb-panel'); launcher = shadow.getElementById('qb-launcher');
|
||||
resultBox = shadow.getElementById('qb-results'); statusBox = shadow.getElementById('qb-status');
|
||||
mounted = true;
|
||||
shadow.getElementById('qb-keep-launcher').checked = Boolean(config.keepLauncher);
|
||||
shadow.getElementById('qb-copy-enabled').checked = Boolean(config.copyEnabled);
|
||||
shadow.addEventListener('click', event => {
|
||||
const button = event.target.closest('button');
|
||||
@@ -1376,6 +1698,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
case 'collapse': setMode(config.mode === 'collapsed' ? 'open' : 'collapsed'); break;
|
||||
case 'search': runSearch(shadow.getElementById('qb-search').value); break;
|
||||
case 'clear-search': clearTimeout(searchTimer); runSearch(''); shadow.getElementById('qb-search').focus(); break;
|
||||
case 'auto-answer-current': Promise.resolve(autoAnswer.answerCurrent()).catch(error => tell(`自动选择失败:${error.message}`, true)); break;
|
||||
case 'capture-current': {
|
||||
const captured = adapter.captureCurrent();
|
||||
renderCurrent();
|
||||
@@ -1405,7 +1728,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
shadow.getElementById('qb-scope').addEventListener('change', event => { scope = event.target.value; renderStats(); });
|
||||
shadow.getElementById('qb-search-scope').addEventListener('change', event => { searchScope = event.target.value; renderResults(); });
|
||||
shadow.getElementById('qb-search-field').addEventListener('change', event => { searchField = event.target.value; renderResults(); });
|
||||
shadow.getElementById('qb-keep-launcher').addEventListener('change', event => { config.keepLauncher = event.target.checked; persistConfig(); renderMode(); });
|
||||
shadow.getElementById('qb-auto-enabled').addEventListener('change', event => { autoAnswer.setEnabled(event.target.checked); renderAuto(); });
|
||||
shadow.getElementById('qb-copy-enabled').addEventListener('change', event => { config.copyEnabled = event.target.checked; adapter.setCopyEnabled(config.copyEnabled); persistConfig(); });
|
||||
shadow.getElementById('qb-import-file').addEventListener('change', async event => {
|
||||
const input = event.currentTarget;
|
||||
@@ -1418,7 +1741,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
catch (error) { tell(`导入失败,题库未替换:${error.message}`, true); }
|
||||
finally { input.value = ''; importing = false; button.disabled = false; }
|
||||
});
|
||||
refreshScope(); renderStats(); renderCurrent(); renderResults(); renderStatus(); selectTab(config.tab); renderMode();
|
||||
refreshScope(); renderStats(); renderCurrent(); renderResults(); renderAuto(); renderStatus(); selectTab(config.tab); renderMode();
|
||||
setInterval(() => { bankChanged(currentBank()); if (config.mode === 'open') renderCurrent(); }, 1000);
|
||||
}
|
||||
|
||||
@@ -1440,11 +1763,13 @@ if (typeof module !== 'undefined' && module.exports) module.exports = QBAdapter;
|
||||
event.preventDefault(); setMode(config.mode === 'hidden' ? 'open' : 'hidden');
|
||||
}
|
||||
}, true);
|
||||
window.addEventListener('pagehide', persistRecords);
|
||||
window.addEventListener('pagehide', () => { autoAnswer.setEnabled(false); persistRecords(); });
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (event.persisted) { autoAnswer.setEnabled(false); config.mode = 'hidden'; renderMode(); }
|
||||
});
|
||||
if (typeof GM_registerMenuCommand === 'function') {
|
||||
GM_registerMenuCommand('显示题库助手(Alt+Shift+Q)', () => setMode('open'));
|
||||
GM_registerMenuCommand('隐藏题库助手', () => setMode('hidden'));
|
||||
GM_registerMenuCommand('完全隐藏题库助手(快捷键或菜单恢复)', () => { config.keepLauncher = false; if (shadow) shadow.getElementById('qb-keep-launcher').checked = false; setMode('hidden'); });
|
||||
}
|
||||
if (typeof GM_addValueChangeListener === 'function') GM_addValueChangeListener(RECORDS_KEY, (_key, _old, value, remote) => {
|
||||
if (!remote || !Array.isArray(value)) return;
|
||||
|
||||
Reference in New Issue
Block a user