// 共用小工具:數字格式、toast、日期、DOM const SUFFIX = ['', 'K', 'M', 'B', 'T', 'aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'jj']; export function fmt(n, digits = 2) { if (n === null || n === undefined || Number.isNaN(n)) return '0'; if (!Number.isFinite(n)) return '∞'; const neg = n < 0; n = Math.abs(n); let out; if (n < 1000) { const hasDecimal = Math.abs(n - Math.round(n)) > 1e-5; out = hasDecimal ? (Math.round(n * 10) / 10).toFixed(1) : Math.round(n).toString(); } else { const tier = Math.floor(Math.log10(n) / 3); if (tier < SUFFIX.length) { const v = n / Math.pow(1000, tier); out = v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : digits) + SUFFIX[tier]; } else { out = n.toExponential(2).replace('+', ''); } } return (neg ? '-' : '') + out; } export function fmtTime(sec) { sec = Math.max(0, Math.floor(sec)); const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; if (h) return `${h} 小時 ${m} 分`; if (m) return `${m} 分 ${s} 秒`; return `${s} 秒`; } export function todayStr(d = new Date()) { const y = d.getFullYear(); const m = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); return `${y}-${m}-${day}`; } export function addDays(dateStr, days) { const [y, m, d] = dateStr.split('-').map(Number); const dt = new Date(y, m - 1, d); dt.setDate(dt.getDate() + days); return todayStr(dt); } export function fmtDateTime(ts) { if (!ts) return '—'; const d = new Date(ts); return `${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; } export function $(sel, root = document) { return root.querySelector(sel); } export function $$(sel, root = document) { return Array.from(root.querySelectorAll(sel)); } export function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } let toastWrap = null; export function toast(msg, type = 'info', ms = 2600) { if (!toastWrap) { toastWrap = document.createElement('div'); toastWrap.className = 'toast-wrap'; document.body.appendChild(toastWrap); } const el = document.createElement('div'); el.className = `toast toast-${type}`; el.textContent = msg; toastWrap.appendChild(el); requestAnimationFrame(() => el.classList.add('show')); setTimeout(() => { el.classList.remove('show'); setTimeout(() => el.remove(), 300); }, ms); } // 按鈕 loading 狀態包裝:避免重複點擊,並提供視覺回饋 export async function withLoading(btn, fn) { if (!btn || btn.dataset.loading === '1') return; btn.dataset.loading = '1'; btn.classList.add('is-loading'); btn.disabled = true; try { return await fn(); } finally { btn.dataset.loading = '0'; btn.classList.remove('is-loading'); btn.disabled = false; } } // 安全綁定事件:先移除舊的 handler,避免重複觸發(支援傳入 capture / options) const HANDLERS = new WeakMap(); export function bind(el, type, handler, options) { if (!el) return; // 防呆:若只傳入 (el, handler),預設事件為 'click' if (typeof type === 'function' && handler === undefined) { handler = type; type = 'click'; } const captureKey = (options === true || (options && options.capture)) ? `${type}__capture` : type; let map = HANDLERS.get(el); if (!map) { map = {}; HANDLERS.set(el, map); } const prev = map[captureKey]; if (prev) el.removeEventListener(type, prev.handler, prev.options); map[captureKey] = { handler, options }; el.addEventListener(type, handler, options); } export function shuffle(arr) { const a = arr.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } export function openModal(html, { onClose, wide = false, closable = true, className = '' } = {}) { const back = document.createElement('div'); back.className = 'modal-back'; back.innerHTML = ``; document.body.appendChild(back); document.body.classList.add('modal-open'); requestAnimationFrame(() => back.classList.add('show')); let closed = false; const close = () => { if (closed) return; // 防止重複關閉 closed = true; back.classList.remove('show'); setTimeout(() => { back.remove(); // 沒有其他 modal 時才移除 modal-open if (!document.querySelector('.modal-back')) document.body.classList.remove('modal-open'); }, 200); onClose && onClose(); }; if (closable) { back.querySelector('.modal-x').addEventListener('click', close); back.addEventListener('click', (e) => { if (e.target === back) close(); }); } const bodyEl = back.querySelector('.modal-body'); return { el: bodyEl, modalEl: bodyEl, close }; } /** * 格式化 LaTeX 數學式或科學記號指數 * 支援: * 1. $...$ 顯式 LaTeX 語法,例如 `$2.5 \times 10^7$` * 2. 科學記號指數識別,例如 `2.5X105`、`2.5X10^7`、`10^-3`、`2.5*10^6` * 3. 安全降級:若 KaTeX 尚未載入或網路異常,平滑降級為 HTML 標籤 */ export function formatMathInText(rawText) { if (!rawText) return ''; let str = String(rawText); const tokens = []; const saveToken = (html) => { const idx = tokens.length; tokens.push(html); return `___MATH_TOKEN_${idx}___`; }; const renderFormula = (latex) => { if (typeof window !== 'undefined' && window.katex && typeof window.katex.renderToString === 'function') { try { return window.katex.renderToString(latex, { throwOnError: false, displayMode: false }); } catch (e) { console.warn('[KaTeX error]', e); } } // 降級 fallback: 解析 \times, 10^{exp} 等 return latex .replace(/\\times/g, '×') .replace(/10\^\{?([+-]?\d+)\}?/g, '10$1') .replace(/\^\{?([+-]?\d+)\}?/g, '$1'); }; // 1. 先處理顯式 $...$ str = str.replace(/\$([^$]+)\$/g, (_, latex) => saveToken(renderFormula(latex.trim()))); // 2. 處理未包在 $...$ 裡的科學記號(例如 2.5X105, 2.5X10^7, 2.5×10^7) str = str.replace(/(\d+(?:\.\d+)?)\s*[xX*×]\s*10(?:\^([+-]?\d+)|([3-9]))(?!\d)/g, (_, base, exp1, exp2) => { const exp = exp1 || exp2; return saveToken(renderFormula(`${base} \\times 10^{${exp}}`)); }); // 3. 處理單純 10^n 或 10^-n str = str.replace(/(? { return saveToken(renderFormula(`10^{${exp}}`)); }); // 4. 還原所有 tokens str = str.replace(/___MATH_TOKEN_(\d+)___/g, (_, idx) => tokens[Number(idx)] || ''); return str; } /** * 渲染測驗題目與選項富文本: * 1. 保留安全合法之 圖片標籤 * 2. 轉義其餘純文字防範 XSS * 3. 透過 KaTeX 解析渲染指數與數學式 */ export function renderRichQuizText(rawText) { if (!rawText) return ''; let str = String(rawText); // 1. 萃取合法的 標籤 const imgTokens = []; str = str.replace(/]*src=["']([^"']+)["'][^>]*>/gi, (match) => { const token = `___IMG_TOKEN_${imgTokens.length}___`; let cleanImg = match; if (!/class=["']/.test(cleanImg)) { cleanImg = cleanImg.replace('/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); // 3. 解析數學式與 KaTeX 指數 str = formatMathInText(str); // 4. 還原圖片標籤 str = str.replace(/___IMG_TOKEN_(\d+)___/g, (_, idx) => imgTokens[Number(idx)] || ''); return str; }