// ==UserScript== // @name JPX-PLUS // @namespace ijpx // @author MeiYongAI // @version 2026.11.20.1 // @description JPX-PLUS // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAGdklEQVR4AeyZW2wUVRjHvxkqiBAFqSigQuoFEiAhEa2GbAUCmijSlIv4oJFwFQn6YqvR6IOJRlpeFBEplGDCA4hAimiiICBL1SomJEACKg2IgJZyMyCCZY7nN2E2ZZjZnZndtrvbbvr1zLl98//958zZzYwpAT/xj+b1ji+bOTVePXvhzuqZn+2qnvVNvHrW9mwItKAprrXZGrXWgFiS0gCddBzJpeC/02IYn1rWlfJzjedLjzc0jT3+28nRWRFaC5rQJlojWtGM9lRG+BoQXzmjiCQiasulC5dL92w7KLWLd8jy8o3G2oVfF2xa8q18vnRnVgRa0IQ2NKIVzWiHARY/IzwNYBmpy8ZeZalJ9Zv3yidvbS6o/2Kf/Hn4lF+erGlHI1ptzVo7DLDA5CXyOgPiy2fNYRnpRDetq9pi7Nn+i9e8nGhDOwywwGSzuZRfY4DtkpJlh/ceE5bV2cbzruG5V4UBFphEs9mMLTASBnCfKCWrTjQ0yVerfmgxJD8OYYINRlgdqoQBqtmoVKK671z3s9OXdyVsMMLqwNkG8HVhiDH5py/3GywZpzPfSthghBVm+GwDlFgv/HvhUjObBo35HDDCCjOcJr/wcORA/eECGjpCwAoz7KZ0uTwO6CP7T1B0iEiwanZTDHOkZVlKf1d2CHggYbUsS8Fu6nvhnr+bLlyhI9eiaNhAqVg23w6Ow+iHGXZTL4HeF89fysn7f+y0mPTq28uOKQsmhOEXmGHXK0BM/Xs51GRn8MRXFkjl7u1S89evGQlykbPPXXc6p0hatrzqGJF08NVOp4BZiegF4LSELBFaWv6SBBUbJD25yDlqWlmQ4RkZY0bNgtCoc1PNa83c7nNHNuDU0T/cuVq1znJnw3t34xvihPuETjslY5njHuOuRzZg15oN7lytWnc2vKAnYU8IsjFGNmDTosVSt2a9tPVKCGoA4043nqNIGpENIOvKl1+TipFjZObt90UO8gSJbWvj0rDvSJCh9pizjWeFOXYlyb+0DEiSN+NdwK94c7W8XvZOItwnadlXOXdJIMNyxgA3bKbqnQZkysn2yMNt4Zy35bHTFqTM6RXAJgd40A3Py5CcNgB4NsagG17eGeAFFLYtp1dAWFiv8Z0GeLmST22pWDpXQCqH8r2/cwXk+xVOxRdpBfA8kAeYBMc8y0t1omztD20AwDyzA5rgOOpDTOa3tzGhDQDYLdqrzT0mTL0tnzKFNsBPXJSrWXj3gDC+tMrY0Ab4qYgCM/iRhzzTHair92xvjcbQBpz8/ZinDj8Yz8FXG/1unaaj3ue4Oi2jRWgDDn7nfXWAGTyqOLA4NlO/wXVrN/p1Zbw9vAHf/+gromLDahn1zOSUr8uAxzCvROwxhFdfa7SFN0Dfn7wP8BMz4/33hMAIVoSzOVInyrVJfvDkrF30IUWbRWgDUIbIZFdpiL4VMIEVwY8l3h5TJ+gjh1ew+SUz12tOum2RDAA+lQlhhZGzatKzYaelPT6SAZyVK7VLvx9EOPV0ghw1+i1TOjmcuWHLyAZwok36/eDCsueEpUs9SjCX12sH9d4SZX66c0xDxDL4HzETV4+lW6mXL8dh0vBukblh5mRqLMywm5aoM917dmtONzFXkCuJEbVVHwjB1XVMoaRep98oM4YXqhyne96o82GGXV9789DNhT26RE3knocR3BoEVxdTgKWkzlVnjHteW9dhNsQ8ZIqydpumadwxqI90lA+sMNvscqXrVsAHDu1H0SEiwarZzdiLS88oUeuHFA9Kex/IFfdghRl2+2vQEPPjG3t0Kxgx5n7J9w+MsBqaWfTHNiA2Z/lWHHnwiaGqV9+eujk//2CDEVaYobQN4MAoUBWGGBdLpj5ANS8DNhhhdQATBsRmrGwwDJner6hQHp/+sNOfNyVMsMEIqwOWMICG2NyadWLI3EHDB8jE+Y8KS4b2XA4YYIEJNpuxBdA1BtAem72iWpR6Wn9X/jO1fLxi06A9FwPtMMACk83mArnOAPpxyeiqhuvfyxuKJwyX59+e0Fz85DDRiejO6kAjWm3NWjsMsMDkJdz0aqSN+6RkTs0UEWN8tx5da0eMHSylC0bL7KoyNe3Vx5pZVk/NK5FsCLSgCW1oRCuaRWuHARbx+fga4IyP6a/IEoxovuFWlpFpdqm6pW/P2v5Fhdv633vbjvYO+/xaC5rQhkbRWtEc09odDr/yfwAAAP//nlygdwAAAAZJREFUAwCEBED17v6rSAAAAABJRU5ErkJggg== // @run-at document-start // @match *://*.hentaiverse.org/* // @exclude *hentaiverse.org/equip/* // @exclude *hentaiverse.org/isekai/equip/* // @grant unsafeWindow // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_listValues // @grant GM_addValueChangeListener // @connect github.com // @connect api.github.com // @connect raw.githubusercontent.com // @connect jpx-plus-downloads.lernsc.workers.dev // @connect hv-monsterdb-data.skk.moe // @homepageURL https://github.com/MeiYongAI/JPX-PLUS // @supportURL https://github.com/MeiYongAI/JPX-PLUS/issues // @updateURL https://raw.githubusercontent.com/MeiYongAI/JPX-PLUS/main/JPX-PLUS.user.js // @downloadURL https://raw.githubusercontent.com/MeiYongAI/JPX-PLUS/main/JPX-PLUS.user.js // ==/UserScript== // BEGIN JPX SHARED DATA // One userscript-owned data store for the primary and alt hosts. Native storage // remains untouched as a migration backup; transient battle logs stay local. function createJpxSharedData({ native, gm, origin, emit = () => {}, now = Date.now, uuid = () => crypto.randomUUID() }) { const root = 'jpx_shared_v1:', settingPrefix = root + 'setting:'; const enabled = !!gm && ['get', 'set', 'list', 'listen'].every(key => typeof gm[key] === 'function'); const setting = key => /^jpx_(cfgBattle(?:_isekai)?|cfgStats|userKeybinds(?:_isekai)?|configLibrary_v1|configApplySignal_v1|theme|stamina(?:_isekai)?|cleanupRequest)(?::.*)?$/.test(key); const config = key => /^jpx_(cfgBattle|cfgStats|userKeybinds|configLibrary_v1)/.test(key); const clone = value => JSON.parse(JSON.stringify(value)); const day = value => new Date(value).toISOString().slice(0, 10); const worldOf = record => record.world === 'Isekai' ? 'Isekai' : 'Persistent'; const idOf = record => JSON.stringify([worldOf(record), record.timestamp]); const encode = value => encodeURIComponent(value); const resultKey = record => root + 'result:' + encode(idOf(record)); let lastStamp = 0; const stamp = () => { const observed = enabled ? Number(String(get(root + 'change')?.nonce || '').split(':')[0]) || 0 : 0; lastStamp = Math.max(now(), lastStamp + 1, observed + 1); return String(lastStamp).padStart(16, '0') + ':' + uuid(); }; const get = (key, fallback = null) => { const value = gm.get(key, fallback); if (value?.then) throw new Error('JPX shared data requires synchronous GM storage'); return value; }; const set = (key, value) => { const result = gm.set(key, value); if (result?.then) throw new Error('JPX shared data requires synchronous GM storage'); }; const keys = () => { const value = gm.list(); if (!Array.isArray(value)) throw new Error('JPX shared data cannot enumerate storage'); return value; }; const notify = key => { try { const nonce = stamp(); if (['records', 'migration'].includes(key)) set(root + 'recordsRevision', nonce); set(root + 'change', { key, nonce }); } catch (error) { console.warn('JPX shared data was saved; notification failed.', error); } }; const legacyKey = root + 'legacy:' + encode(origin); const markerKey = root + 'settingsMigrated:' + encode(origin); const recordMarker = root + 'recordsMigrated:' + encode(origin); const compressedMarker = root + 'recordsCompressed_v1'; let migration = null, compression = null, recordCache = null, recordsMigrated = false, archiveRevision = null; const cache = new Map(); const payloads = new WeakMap(); // Userscript managers preload GM storage before injection. Keep the large // record payload compressed; stamina/ordering metadata stays directly readable. async function pack(value) { const stream = new Blob([JSON.stringify(value)]).stream().pipeThrough(new CompressionStream('gzip')); const bytes = new Uint8Array(await new Response(stream).arrayBuffer()); let binary = ''; for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768)); return 'gzip:' + btoa(binary); } async function unpack(value) { if (typeof value !== 'string') return value; // Existing uncompressed archives. if (!value.startsWith('gzip:')) throw new Error('Unknown JPX archive encoding'); const bytes = Uint8Array.from(atob(value.slice(5)), char => char.charCodeAt(0)); const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')); return JSON.parse(await new Response(stream).text()); } function payload(event) { if (!payloads.has(event)) payloads.set(event, unpack(event.record ?? event.records)); return payloads.get(event); } function checkReset(before) { if (get(root + 'reset') !== before) throw new Error('JPX data was reset while saving records'); } async function compressRecords() { if (get(compressedMarker)) return; if (compression) return compression; compression = (async () => { const reset = get(root + 'reset'); for (const key of keys()) { const field = key.startsWith(root + 'result:') ? 'record' : key.startsWith(root + 'legacyRecords:') || key.startsWith(root + 'batch:') ? 'records' : null; if (!field) continue; const event = get(key); if (!event?.[field] || typeof event[field] === 'string') continue; const packed = await pack(event[field]); checkReset(reset); const current = get(key); if (!current || typeof current[field] === 'string') continue; if (JSON.stringify(current) !== JSON.stringify(event)) throw new Error('JPX archive changed during compression'); set(key, { ...event, [field]: packed }); } set(compressedMarker, true); recordCache = null; notify('records'); })(); try { await compression; } finally { compression = null; } } // Recovery copies and settled results are rarely read, yet the manager loads // them before every page. Pack copies once their host has migrated, and fold // results older than the stamina window into one bundle per pass. // Decide from key names alone: ordinary page loads must not read payloads. const packPending = root + 'packPending', packedMarker = root + 'recoveryPacked_v1', settledDays = 1, bundleMinimum = 20; const packDue = () => !!get(packPending) || !get(packedMarker); const prunePending = root + 'prunePending', prunedMarker = root + 'archivePruned_v1'; const pruneDue = all => !!get(prunePending) || !get(prunedMarker) && all.some(key => key.startsWith(root + 'batch:')); const settledKeys = all => { const cutoff = day(now() - settledDays * 86400000); return all.filter(key => { if (!key.startsWith(root + 'result:')) return false; // Receipt IDs carry the battle timestamp: "YYYY-MM-DD hh:mm:ss" or epoch ms. try { const stamp = JSON.parse(decodeURIComponent(key.slice((root + 'result:').length)))[1]; const date = Number.isFinite(Number(stamp)) && String(stamp).trim() ? day(Number(stamp)) : /^\d{4}-\d{2}-\d{2}/.test(stamp) ? stamp.slice(0, 10) : ''; return !!date && date < cutoff; } catch { return false; } }); }; let compaction = null; async function compactStorage() { if (!enabled) return; if (compaction) return compaction; compaction = (async () => { const all = keys(); if (!packDue() && !pruneDue(all) && settledKeys(all).length < bundleMinimum) return; const lock = get(root + 'compacting'); if (lock && lock.until > now()) return; set(root + 'compacting', { until: now() + 60000 }); try { await compact(); } finally { gm.remove(root + 'compacting'); } })(); try { await compaction; } finally { compaction = null; } } async function compact() { const reset = get(root + 'reset'), all = keys(); // Write only if the value is unchanged since it was read. const replace = (key, before, after) => { checkReset(reset); if (JSON.stringify(get(key)) !== JSON.stringify(before)) return; set(key, after); }; if (packDue()) { // Clear first: a copy written during this pass raises the flag again. gm.remove(packPending); try { for (const key of all.filter(key => key.startsWith(root + 'revision:'))) { const revision = get(key); if (typeof revision?.value !== 'string' || revision.value.length < 1024) continue; const { value, ...rest } = revision; replace(key, revision, { ...rest, packed: await pack(value) }); } for (const key of all.filter(key => key.startsWith(root + 'legacy:'))) { const snapshot = get(key); // The snapshot is read again only until its own host has migrated. if (!snapshot?.values || !get(root + 'settingsMigrated:' + encode(snapshot.origin))) continue; const { values, ...rest } = snapshot; replace(key, snapshot, { ...rest, packed: await pack(values) }); } set(packedMarker, true); } catch (error) { set(packPending, true); throw error; } } if (pruneDue(all)) { gm.remove(prunePending); try { await prune(all, replace); set(prunedMarker, true); } catch (error) { set(prunePending, true); throw error; } recordCache = null; notify('records'); } const settled = []; for (const key of settledKeys(all)) { const event = get(key); if (event?.order) settled.push([key, event]); } if (settled.length >= bundleMinimum) { const events = []; for (const [, event] of settled) events.push({ ...event, record: await unpack(event.record) }); events.sort((a, b) => a.order.localeCompare(b.order)); const packed = await pack(events); checkReset(reset); // Bundle first: an interrupted pass leaves duplicates, which reads // collapse by receipt order, never a missing result. set(root + 'bundle:' + events.at(-1).order, { order: events.at(-1).order, count: events.length, events: packed }); for (const [key, event] of settled) { if (JSON.stringify(get(key)) !== JSON.stringify(event)) continue; gm.remove(key); // Day pointers serve only today's stamina lookup. if (event.stamina) gm.remove(root + 'day:' + event.stamina.world + ':' + event.stamina.date + ':' + encode(event.id)); } recordCache = null; notify('records'); } } // A payload is dead once a later delete names its ID or a later replacing // import clears the archive: replay can never surface it again. Receipts // keep their order and stamina, so daily charges are unchanged; delete // events stay (packed) for legacy archives a host may still migrate. async function prune(all, replace) { const batches = all.filter(key => key.startsWith(root + 'batch:')).map(key => [key, get(key)]).filter(([, event]) => event); let cleared = ''; const removed = new Map(); for (const [, event] of batches) { if (event.type === 'import' && !event.merge) { if (event.order > cleared) cleared = event.order; } else if (event.type === 'delete') for (const id of await unpack(event.ids)) if (!(removed.get(id) > event.order)) removed.set(id, event.order); } if (!cleared && !removed.size) return; const dead = (id, order) => cleared > order || (removed.get(id) ?? '') > order; const strip = ({ record, ...receipt }) => receipt; for (const key of all.filter(key => key.startsWith(root + 'legacyRecords:'))) { const archive = get(key); if (!archive) continue; const records = await unpack(archive.records), kept = records.filter(record => !dead(idOf(record), '')); if (kept.length < records.length) replace(key, archive, { ...archive, records: await pack(kept) }); } for (const [key, event] of batches) { if (event.type === 'import') { const records = await unpack(event.records), kept = records.filter(record => !dead(idOf(record), event.order)); if (kept.length < records.length) replace(key, event, { ...event, records: await pack(kept) }); } else if (event.type === 'delete' && Array.isArray(event.ids)) replace(key, event, { ...event, ids: await pack(event.ids) }); } for (const key of all.filter(key => key.startsWith(root + 'result:'))) { const event = get(key); if (event?.record && dead(event.id, event.order)) replace(key, event, strip(event)); } for (const key of all.filter(key => key.startsWith(root + 'bundle:'))) { const bundle = get(key); if (!bundle) continue; const events = await unpack(bundle.events); if (!events.some(event => event.record && dead(event.id, event.order))) continue; replace(key, bundle, { ...bundle, events: await pack(events.map(event => event.record && dead(event.id, event.order) ? strip(event) : event)) }); } } function baseline(world, date) { const override = get(root + 'staminaBase:' + world + ':' + date); if (override !== null) return override; let value = 0; for (const key of keys()) if (key.startsWith(root + 'legacyStamina:' + world + ':' + date + ':')) value = Math.max(value, get(key, 0)); return value; } function migrateSettings() { if (get(markerKey)) return; let snapshot = get(legacyKey); if (!snapshot) { snapshot = { origin, capturedAt: now(), values: {} }; for (let i = 0; i < native.length; i++) { const key = native.key(i); if (setting(key) || /^jpx_staminaRecords(?:_isekai)?$/.test(key)) snapshot.values[key] = native.getItem(key); } set(legacyKey, snapshot); } for (const [key, raw] of Object.entries(get(root + 'reset') ? {} : snapshot.values)) { if (key.startsWith('jpx_staminaRecords')) { let value; try { value = JSON.parse(raw); } catch { /* Keep the original snapshot, including malformed legacy data. */ } if (Number.isFinite(value?.lastUpdate) && Number.isFinite(value.staminaCost) && value.staminaCost >= 0) set(root + 'legacyStamina:' + (key.endsWith('_isekai') ? 'Isekai' : 'Persistent') + ':' + day(value.lastUpdate) + ':' + encode(origin), value.staminaCost); } else if (key !== 'jpx_cleanupRequest' && get(settingPrefix + key) === null) set(settingPrefix + key, { value: raw, source: origin }); } set(markerKey, true); set(packPending, true); notify('migration'); } function readSetting(key) { if (!cache.has(key)) cache.set(key, get(settingPrefix + key)?.value ?? null); return cache.get(key); } function writeSetting(key, value) { const oldValue = readSetting(key); if (oldValue === value) return; // Retain concurrent/previous configuration revisions independently of the // authoritative value. Never overwrite the other host's legacy snapshot. if (config(key)) { // Save the proposed value too: simultaneous edits from different // domains cannot erase either user's version even without GM CAS. const current = get(settingPrefix + key)?.value ?? null; const revisionKey = root + 'revision:' + encode(key) + ':' + encode(origin); if (current !== null) set(revisionKey + ':previous', { key, value: current, at: now(), source: origin }); set(revisionKey + ':proposed', { key, value, at: now(), source: origin }); set(packPending, true); } set(settingPrefix + key, { value, source: origin }); cache.set(key, value); notify(key); } const facade = { getItem(key) { key = String(key); return enabled && setting(key) ? readSetting(key) : native.getItem(key); }, setItem(key, value) { key = String(key); value = String(value); if (enabled && setting(key)) writeSetting(key, value); else native.setItem(key, value); }, removeItem(key) { key = String(key); if (enabled && setting(key)) writeSetting(key, null); else native.removeItem(key); }, key(index) { return storageKeys()[index] ?? null; }, get length() { return storageKeys().length; } }; function storageKeys() { const all = new Set(Array.from({ length: native.length }, (_, i) => native.key(i))); if (enabled) for (const key of keys()) if (key.startsWith(settingPrefix)) all.add(key.slice(settingPrefix.length)); return [...all].filter(key => facade.getItem(key) !== null); } const storage = enabled ? new Proxy(facade, { get(target, key) { return key in target || typeof key !== 'string' ? Reflect.get(target, key) : target.getItem(key); }, ownKeys: storageKeys, getOwnPropertyDescriptor(target, key) { return typeof key === 'string' && facade.getItem(key) !== null ? { configurable: true, enumerable: true, value: facade.getItem(key) } : undefined; } }) : native; let lastChange = null; function refresh(change) { if (!enabled || !change || lastChange === change.nonce) return; lastChange = change.nonce; lastStamp = Math.max(lastStamp, Number(String(change.nonce || '').split(':')[0]) || 0); const nextRevision = get(root + 'recordsRevision'); const recordsChanged = nextRevision !== archiveRevision; archiveRevision = nextRevision; if (recordsChanged) recordCache = null; // A notification is an invalidation, never the source of truth. // Refresh every cached setting so concurrent notifications coalesce. for (const [key, oldValue] of cache) { const newValue = get(settingPrefix + key)?.value ?? null; cache.set(key, newValue); if (newValue !== oldValue) emit({ key, oldValue, newValue }); } if (setting(change.key) && !cache.has(change.key)) { const newValue = get(settingPrefix + change.key)?.value ?? null; cache.set(change.key, newValue); emit({ key: change.key, oldValue: null, newValue }); } if (recordsChanged) emit({ key: 'jpx_recordsChanged' }); } if (enabled) { migrateSettings(); archiveRevision = get(root + 'recordsRevision'); gm.listen(root + 'change', (_key, _old, change, remote) => { if (remote) refresh(change); }); } async function ensureRecords(readLegacy) { if (!enabled) return; if (!recordsMigrated && !get(recordMarker)) { if (!migration) migration = (async () => { const reset = get(root + 'reset'); const records = await pack(reset ? [] : await readLegacy()); checkReset(reset); // A single committed value makes migration atomic and retryable. set(root + 'legacyRecords:' + encode(origin), { origin, records }); set(recordMarker, true); recordCache = null; notify('records'); })(); try { await migration; } finally { migration = null; } } recordsMigrated = true; await compressRecords(); await compactStorage(); } function operations() { const currentRevision = get(root + 'recordsRevision'); if (currentRevision !== archiveRevision) { archiveRevision = currentRevision; recordCache = null; } if (recordCache) return recordCache; const result = { legacy: [], results: [], bundles: [], batches: [], baselines: new Map(), overrides: new Map() }; for (const key of keys()) { if (key.startsWith(root + 'legacyRecords:')) result.legacy.push(get(key)); else if (key.startsWith(root + 'result:')) result.results.push(get(key)); else if (key.startsWith(root + 'bundle:')) result.bundles.push(get(key)); else if (key.startsWith(root + 'batch:')) result.batches.push(get(key)); else if (key.startsWith(root + 'legacyStamina:')) { const id = key.slice((root + 'legacyStamina:').length).split(':').slice(0, 2).join(':'); result.baselines.set(id, Math.max(result.baselines.get(id) || 0, get(key, 0))); } else if (key.startsWith(root + 'staminaBase:')) result.overrides.set(key.slice((root + 'staminaBase:').length), get(key, 0)); } result.legacy.sort((a, b) => a.origin.localeCompare(b.origin)); recordCache = result; return result; } function stamina(world, date, exclude) { let used = baseline(world, date); // Load only today's receipts, never all historical battle payloads. for (const key of keys()) if (key.startsWith(root + 'day:' + world + ':' + date + ':')) { const item = get(get(key)); if (item?.stamina?.date === date && item.id !== exclude) used += item.stamina.used; } return Math.round(used * 100) / 100; } async function allRecords() { const ops = operations(), map = new Map(), receipts = new Map(); for (const batch of ops.legacy) for (const record of await payload(batch)) { const id = idOf(record); if (!map.has(id)) map.set(id, clone(record)); } // A receipt can briefly exist both loose and bundled; its order is unique. for (const bundle of ops.bundles) { if (!payloads.has(bundle)) payloads.set(bundle, unpack(bundle.events)); for (const event of await payloads.get(bundle)) receipts.set(event.order, event); } for (const event of ops.results) receipts.set(event.order, event); const results = [...receipts.values()]; const events = [...results, ...ops.batches].sort((a, b) => a.order.localeCompare(b.order)); for (const event of events) { if (event.record) map.set(event.id, clone(await payload(event))); else if (event.type === 'import') { if (!event.merge) map.clear(); for (const record of await payload(event)) { const id = idOf(record); if (!event.merge || !map.has(id)) map.set(id, clone(record)); } } else if (event.type === 'delete') for (const id of await unpack(event.ids)) map.delete(id); } // Allocate daily free stamina once in deterministic completion order, // including concurrent results. Archive deletion never erases usage. const totals = new Map(); for (const event of results.sort((a, b) => a.order.localeCompare(b.order))) { const cost = event.stamina; if (!cost) continue; const key = cost.world + ':' + cost.date; const before = totals.has(key) ? totals.get(key) : ops.overrides.get(key) ?? ops.baselines.get(key) ?? 0; const charged = Math.round(Math.max(0, cost.used - Math.max(0, cost.quota - before)) * 10) / 10; totals.set(key, before + cost.used); const record = map.get(event.id); if (record && record.sharedResult === event.order) { record.revenueRecords.staminaCost = charged; record.revenueRecords.finalProfit = Math.round((record.revenueRecords.totalProfit - charged * cost.unitPrice) * 10) / 10; } } return [...map.values()]; } async function saveResult(record, cost) { const key = resultKey(record); if (get(key)) return; const reset = get(root + 'reset'), order = stamp(), saved = clone(record); saved.sharedResult = order; const event = { order, id: idOf(record), record: saved }; if (cost) event.stamina = clone(cost); event.record = await pack(saved); checkReset(reset); if (get(key)) return; // Write the small lookup before the atomic receipt. An interrupted write // leaves an inert pointer, never an unrecorded charge. Stable receipt IDs // also deduplicate two hosts settling the same battle around midnight. if (event.stamina) set(root + 'day:' + event.stamina.world + ':' + event.stamina.date + ':' + encode(event.id), key); set(key, event); recordCache = null; notify('records'); } function batch(value) { const order = stamp(); // Deleted payloads are dropped later, in the idle compaction pass. if (value.type === 'delete' || value.type === 'import' && !value.merge) set(prunePending, true); set(root + 'batch:' + order, { ...value, order }); recordCache = null; notify('records'); } function reset() { // Retain migration markers so another host's old native database cannot // resurrect data after the user explicitly resets the shared store. for (const key of keys()) if (key.startsWith(root) && !key.includes('Migrated:') && key !== settingPrefix + 'jpx_cleanupRequest') gm.remove(key); set(root + 'reset', stamp()); cache.clear(); recordCache = null; notify('records'); } return { enabled, storage, idOf, ensureRecords, allRecords, saveResult, stamina, refresh() { if (enabled) refresh(get(root + 'change')); }, async importRecords(records, merge) { const reset = get(root + 'reset'), packed = await pack(records); checkReset(reset); batch({ type: 'import', records: packed, merge }); }, deleteRecords: ids => batch({ type: 'delete', ids }), reset, usage: world => ({ lastUpdate: now(), staminaCost: stamina(world, day(now())) }), // Recovery copies may be packed; callers receive them restored. backups: () => enabled ? Promise.all(keys().filter(key => key.startsWith(root + 'legacy:')).map(async key => { const { packed, ...snapshot } = get(key); return packed ? { ...snapshot, values: await unpack(packed) } : snapshot; })) : Promise.resolve([]), revisions: () => enabled ? Promise.all(keys().filter(key => key.startsWith(root + 'revision:')).map(async key => { const { packed, ...revision } = get(key); return packed ? { ...revision, value: await unpack(packed) } : revision; })) : Promise.resolve([]), compact: compactStorage, baseline, setBaseline(world, date, value) { if (!Number.isFinite(value) || value < 0) throw new Error('Invalid stamina baseline'); set(root + 'staminaBase:' + world + ':' + date, value); recordCache = null; notify('records'); }, restore(snapshot) { for (const [key, value] of Object.entries(snapshot.values)) if (config(key)) { if (value === null) storage.removeItem(key); else storage.setItem(key, value); } } }; } // END JPX SHARED DATA // The records URL is a local app on the HV origin, not an HV homepage. (function jpxBoot(window) { let started = false, frame, task; const wakeEvents = ['keydown', 'pointerdown', 'click', 'change', 'submit', 'pagehide']; function start() { if (started) return; started = true; cancelAnimationFrame(frame); clearTimeout(task); for (const type of wakeEvents) window.removeEventListener(type, start, true); document.removeEventListener('visibilitychange', onVisibility); jpxMain(); } function onVisibility() { if (document.hidden) start(); } function ready() { // Combat and riddles need their handlers immediately. Hidden tabs cannot // rely on animation frames; their configuration tracking must still run. if (document.hidden || document.querySelector('#textlog, #battle_main, #riddlemaster')) { start(); return; } // Release the userscript injection task before initializing ordinary pages. // rAF alone runs before rendering: the following task gives the browser a // chance to paint first. Input starts us on window capture, before the new // document handlers receive that same event (no synthetic replay). for (const type of wakeEvents) window.addEventListener(type, start, true); document.addEventListener('visibilitychange', onVisibility); frame = requestAnimationFrame(() => { task = setTimeout(start, 0); }); } if (location.hash === '#jpx-records') { window.stop(); const root = document.createElement('html'); root.append(document.createElement('head'), document.createElement('body')); if (document.documentElement) document.documentElement.replaceWith(root); else document.append(root); if (!document.doctype) document.insertBefore(document.implementation.createDocumentType('html', '', ''), root); start(); return; } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready, { once: true }); else ready(); // Keep the existing Battle API, confirmation handler and language pack in the page window. function jpxMain() { const jpxShared = createJpxSharedData({ native: window.localStorage, origin: location.origin, gm: typeof GM_getValue === 'function' && typeof GM_listValues === 'function' && typeof GM_addValueChangeListener === 'function' ? { get: GM_getValue, set: GM_setValue, remove: GM_deleteValue, list: GM_listValues, listen: GM_addValueChangeListener } : null, emit: change => queueMicrotask(() => onJpxSharedChange(change)) }); // Only JPX accesses this facade. HVUT and translation retain their own storage. const localStorage = jpxShared.storage; if (jpxShared.enabled) { window.addEventListener('focus', () => jpxShared.refresh()); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') jpxShared.refresh(); }); } let cfgBattle = {}; const settingsPlugins = new Map(); // Generic extension tabs remain supported. Store credentials stay in this sandbox. window.JPXPlus = Object.freeze({ apiVersion: 1, version: '2026.11.20.1', features: Object.freeze({ configManagement: true, monsterDatabase: true }), getBattleTiming: () => Object.freeze({ ...jpxBattleTiming }), migrateLegacyConfigs: entries => migrateJpxLegacyConfigs(entries), registerSettingsTab(plugin) { if (!plugin || !/^[a-z][a-zA-Z0-9-]{0,39}$/.test(plugin.id) || ['battle', 'battleRules', 'keyBindings', 'stats', 'configManager', 'configStore'].includes(plugin.id) || typeof plugin.render !== 'function' || typeof plugin.title !== 'function') return false; if (settingsPlugins.has(plugin.id)) return false; settingsPlugins.set(plugin.id, plugin); window.dispatchEvent(new Event('jpx:settings-plugin')); return true; } }); function createDefaultRecoveryRules(spiritPotion = 0.5, spiritElixir = 0.4) { return [ {"type":"item","name":"Spirit Gem","conditions":[{"key":"pSP","value":[0,0.9]}]}, {"type":"item","name":"Spirit Potion","conditions":[{"key":"pSP","value":[0,spiritPotion]}]}, {"type":"item","name":"Last Elixir","conditions":[{"key":"pSP","value":[0,spiritElixir]}]}, {"type":"item","name":"Spirit Elixir","conditions":[{"key":"pSP","value":[0,spiritElixir]}]}, {"type":"stop","customMessage":"Can't use Spirit Elixir","conditions":[{"key":"pSP","value":[0,spiritElixir]}]}, {"type":"item","name":"Health Gem","conditions":[]}, {"type":"spellSupport","name":"Cure","conditions":[{"key":"pHP","value":[0,0.4]}]}, {"type":"item","name":"Health Potion","conditions":[{"key":"pHP","value":[0,0.4]}]}, {"type":"spellSupport","name":"Full-Cure","conditions":[{"key":"pHP","value":[0,0.4]}]}, {"type":"item","name":"Health Elixir","conditions":[{"key":"pHP","value":[0,0.4]}]}, {"type":"stop","customMessage":"Can't use Health Elixir","conditions":[{"key":"pHP","value":[0,0.4]}]}, {"type":"item","name":"Mana Gem","conditions":[{"key":"pMP","value":[0,0.8]}]}, {"type":"item","name":"Mana Potion","conditions":[{"key":"pMP","value":[0,0.4]}]}, {"type":"item","name":"Mana Elixir","conditions":[{"key":"pMP","value":[0,0.2]}]}, {"type":"stop","customMessage":"Can't use Mana Elixir","conditions":[{"key":"pMP","value":[0,0.2]}]}, {"type":"item","name":"Mystic Gem","conditions":[{"key":"pIgnoredEffects","value":[0,9999,"Channeling"]}]}, ]; } let defaultCfgBattle = { "battleVersion": 20251216, "advanceToNextRound": false, "autoFinishBattle": false, "ajaxRound": false, "hideRoundPopup": false, "showCooldowns": false, "quickbarExtend": [], "showDurations": false, "showRealTimeProficiency": false, "showMonsterIndex": false, "showMonsterInfo": false, "showMonsterHP": false, "recordBattleLog": false, "dailyStaminaQuotaPlus": 0, "ctrlWidgetStyleText": [], "ctrlWidgetMouseEnter": false, "ctrlWidgetMouseEnterPause": false, "ctrlWidgetRows": [ {"id":"isActiveBattle"}, {"id":"readyNext"}, {"id":"networkDelay"}, {"id":"battleStyle"}, {"id":"battleType"}, {"id":"round"} ], "OneHanded_General": { "rules": [ ...createDefaultRecoveryRules(), {"type":"spellSupport","name":"Heartseeker","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,100,"Heartseeker"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,50,"Regen"]}]}, {"type":"toggle","name":"Spirit","toggled":true,"conditions":[{"key":"pOC","value":[6,10]}]}, {"type":"spellSupport","name":"Heartseeker","conditions":[{"key":"pEffects","value":[-1,0,"Heartseeker"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[-1,0,"Regen"]}]}, {"type":"item","name":"Health Draught","conditions":[{"key":"pEffects","value":[-1,0,"Regeneration"]},{"key":"monsters","value":[4,10]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"item","name":"Mana Draught","conditions":[{"key":"pEffects","value":[-1,0,"Replenishment"]},{"key":"pMP","value":[0,0.85]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"item","name":"Spirit Draught","conditions":[{"key":"pEffects","value":[-1,0,"Refreshment"]},{"key":"pSP","value":[0,0.9]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"smartDebuff","name":"Weaken","targetCount":3,"tailSkip":0,"bottomUp":false,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tTypes","value":["Arena400","Arena500"],"offset":[0,0],"matched":[1,1]},{"key":"tIgnoredEffects","value":[1,9999,"Weakened"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"world","value":["Persistent"]},{"key":"tDaysSinceUpdate","value":[46,9999],"offset":[0,0],"matched":[1,1]},{"key":"tIgnoredEffects","value":[0,9999,"Imperiled","Searing Skin","Freezing Limbs","Turbulent Air","Deep Burns","Breached Defense","Blunted Attack"],"offset":[0,0],"matched":[1,1]}]}, {"type":"skill","name":"Scan","conditions":[{"key":"pActionCounts","value":[0,0,"Scan"]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tName","value":"Yggdrasil","offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tTypes","value":["Rare","Legendary","Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[]}, {"type":"skill","name":"Orbital Friendship Cannon","conditions":[{"key":"activeMonsters","value":[6,10]},{"key":"pOC","value":[9,10]},{"key":"pSpiritStatus","value":true}]}, {"type":"smartDebuff","name":"Imperil","targetCount":3,"bottomUp":false,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Imperiled"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Rare","Legendary","Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"smartDebuff","name":"Imperil","targetCount":3,"bottomUp":false,"tailSkip":-1,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Imperiled"],"offset":[0,0],"matched":[1,1]},{"key":"activeBosses","value":[0,0]}]}, {"type":"skill","name":"Merciful Blow","conditions":[{"key":"tTypes","value":["Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]},{"key":"tEffects","value":[0,9999,"Bleeding Wound"],"offset":[0,0],"matched":[1,1]},{"key":"tHP","value":[0.04,0.22],"offset":[0,0],"matched":[1,1]},{"key":"pOC","value":[4.5,10]}]}, {"type":"skill","name":"Vital Strike","conditions":[{"key":"tTypes","value":["Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]},{"key":"tEffects","value":[0,9999,"Stunned"],"offset":[0,0],"matched":[1,1]},{"key":"tHP","value":[0.05,1],"offset":[0,0],"matched":[1,1]},{"key":"pOC","value":[2.5,10]}]}, {"type":"normalAttack","conditions":[]} ] }, "OneHanded_Tower": { "rules": [ ...createDefaultRecoveryRules(0.6, 0.6), {"type":"spellSupport","name":"Heartseeker","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,100,"Heartseeker"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,50,"Regen"]}]}, {"type":"toggle","name":"Spirit","toggled":true,"conditions":[{"key":"pOC","value":[6,10]},{"key":"defeatedMonsters","value":[1,10]}]}, {"type":"spellSupport","name":"Heartseeker","conditions":[{"key":"pEffects","value":[-1,0,"Heartseeker"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[-1,0,"Regen"]}]}, {"type":"item","name":"Health Draught","conditions":[{"key":"pEffects","value":[-1,0,"Regeneration"]},{"key":"monsters","value":[4,10]}]}, {"type":"item","name":"Mana Draught","conditions":[{"key":"pEffects","value":[-1,0,"Replenishment"]},{"key":"pMP","value":[0,0.85]}]}, {"type":"item","name":"Spirit Draught","conditions":[{"key":"pEffects","value":[-1,0,"Refreshment"]},{"key":"pSP","value":[0,0.9]}]}, {"type":"smartDebuff","targetCount":3,"name":"Sleep","bottomUp":true,"tailSkip":1,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Asleep"],"offset":[0,0],"matched":[1,1]},{"key":"roundCurrent","value":[0,9999]},{"key":"floor","value":[36,9999]}]}, {"type":"smartDebuff","targetCount":3,"name":"Weaken","bottomUp":false,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Weakened","Asleep"],"offset":[0,0],"matched":[1,1]},{"key":"roundCurrent","value":[10,9999]},{"key":"floor","value":[40,9999]}]}, {"type":"smartDebuff","targetCount":3,"name":"Silence","bottomUp":true,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Asleep","Silenced"],"offset":[0,0],"matched":[1,1]},{"key":"roundCurrent","value":[15,9999]},{"key":"floor","value":[40,9999]}]}, {"type":"smartDebuff","targetCount":3,"name":"Imperil","bottomUp":false,"tailSkip":-1,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Imperiled"],"offset":[0,0],"matched":[1,1]},{"key":"roundCurrent","value":[0,9999]},{"key":"floor","value":[40,9999]}]}, {"type":"target","priorityRule":"Top Down","conditions":[]}, {"type":"toggle","name":"Spirit","toggled":true,"conditions":[{"key":"pOC","value":[6,10]}]}, {"type":"skill","name":"Merciful Blow","conditions":[{"key":"tEffects","value":[0,9999,"Bleeding Wound"],"offset":[0,0],"matched":[1,1]},{"key":"tHP","value":[0.04,0.22],"offset":[0,0],"matched":[1,1]},{"key":"pOC","value":[4.5,10]},{"key":"roundCurrent","value":[0,9999]},{"key":"floor","value":[95,9999]}]}, {"type":"skill","name":"Vital Strike","conditions":[{"key":"tEffects","value":[0,9999,"Stunned"],"offset":[0,0],"matched":[1,1]},{"key":"tHP","value":[0.05,1],"offset":[0,0],"matched":[1,1]},{"key":"pOC","value":[2.5,10]},{"key":"pSpiritStatus","value":true},{"key":"roundCurrent","value":[0,9999]},{"key":"floor","value":[60,9999]}]}, {"type":"normalAttack","conditions":[]} ] }, "1H_Mage_General": { "rules": [ ] }, "TwoHanded_General": { "rules": [ ...createDefaultRecoveryRules(), {"type":"spellSupport","name":"Heartseeker","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,100,"Heartseeker"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,50,"Regen"]}]}, {"type":"spellSupport","name":"Heartseeker","conditions":[{"key":"pEffects","value":[-1,0,"Heartseeker"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[-1,0,"Regen"]}]}, {"type":"item","name":"Health Draught","conditions":[{"key":"pEffects","value":[-1,0,"Regeneration"]},{"key":"monsters","value":[4,10]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"item","name":"Mana Draught","conditions":[{"key":"pEffects","value":[-1,0,"Replenishment"]},{"key":"pMP","value":[0,0.85]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"item","name":"Spirit Draught","conditions":[{"key":"pEffects","value":[-1,0,"Refreshment"]},{"key":"pSP","value":[0,0.9]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"smartDebuff","name":"Weaken","targetCount":3,"bottomUp":false,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Weakened"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"smartDebuff","name":"Silence","targetCount":3,"bottomUp":false,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Silenced"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"smartDebuff","name":"Imperil","targetCount":3,"bottomUp":false,"tailSkip":0,"maxAtFirst":4,"minMonstersLeft":5,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Imperiled"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"kamisamaniNattaHi","code":"let{prefix:e,isekaiSuffix:n,battleType:t,towerFloor:r,roundInfo:i,vitals:o,spiritStatus:a,actionCounts:l,spellCooldowns:s,monsterData:g,monstersObj:{monsters:c,activeMonsters:f,bosses:u,activeBosses:d},actionHandlers:h,doSpellsDebuffGoNext:m,doSpellGoNext:P,doAttackGoNext:p,doToggleGoNext:B}=jpx,w=parseInt(localStorage.getItem(e+\"playerLevel\"+n)||1),x=(f[0].index,f.at(-1).index,l[\"Rending Blow\"]??0),v=\"-\"===s[\"Rending Blow\"]?9999:s[\"Rending Blow\"],R=(\"-\"===s[\"Shatter Strike\"]||s[\"Shatter Strike\"],d.reduce((e,n)=>!e||n.hpPercentage>e.hpPercentage?n:e,null)),S=f.reduce((e,n)=>!e||n.hpPercentage>e.hpPercentage?n:e,null),A=f.reduce((e,n)=>!e||T(n)>T(e)?n:e,null),G=w<300;function T(e){return g[e.index].maxHP*e.hpPercentage}function b({minTargets:e=1,minBossTargets:n=0,minNormalHP:t=.2,minBossHP:r=.1,minUnPA:i=0,minBossUnPA:o=0,bossPriority:a=!0}={}){let l=-1,s=0,g=0,f=0,u=0;for(let d=0;d0||o>0?a?p>u||p===u&&(m>g||m===g&&h>s):P>f||P===f&&(h>s||h===s&&m>g):a?m>g||m===g&&h>s:h>s||h===s&&m>g)&&(l=d,s=h,g=m,f=P,u=p)}return l}let C=f.find(e=>\"Yggdrasil\"===e.name);if(C){if(o.oc>=2.5&&P(\"Great Cleave\",C))return!0;if(p(C))return!0}if(G)if(0===x){if((c.length>=3||f.length>=4)&&o.oc>=2.5&&P(\"Rending Blow\",c[b({minTargets:3,bossPriority:!1})]))return!0}else{if(f.length>=4&&o.oc>=3&&S.hpPercentage>.9&&P(\"Rending Blow\",c[b({minTargets:3})]))return!0;if(f.length>=6&&o.oc>=2.5&&S.hpPercentage>.7&&P(\"Rending Blow\",c[b({minTargets:3})]))return!0}if(!G&&f.length>=3){if(o.oc>=2.5&&P(\"Rending Blow\",c[b({minBossHP:.4,minBossUnPA:1})]))return!0;if(!a){if(o.oc>=2.5&&0===d.length&&P(\"Rending Blow\",c[b({minTargets:3,minNormalHP:.4})]))return!0;if(o.oc>=4.5&&R?.hpPercentage>.3&&P(\"Great Cleave\",A))return!0;if(o.oc>=6&&R?.hpPercentage<.3&&P(\"Rending Blow\",c[b({minTargets:3,minNormalHP:.4,minBossHP:.1})]))return!0;if(o.oc>=9&&S.hpPercentage>.7&&P(\"Great Cleave\",A))return!0}}if(i.current===i.total&&!a){if(o.oc>=2.5&&P(\"Great Cleave\",A))return!0;if(o.oc>=4&&P(\"Rending Blow\",c[b()]))return!0}if((!G||v<=1)&&f.length<=2&&o.oc>=(G?8:a?10:6)&&R?.hpPercentage>.4&&P(\"Great Cleave\",A))return!0;if(!G&&o.oc>=10&&S.hpPercentage>.7&&P(\"Rending Blow\",c[b({minTargets:2})]))return!0;if(!G&&o.oc>=10&&!a&&B(\"Spirit\"))return!0;if((!G||v<=1)&&o.oc>=10&&P(\"Great Cleave\",S))return!0;if(!G&&o.oc>=10&&P(\"Rending Blow\",c[b()]))return!0;if((!G||v<=1)&&o.oc>=10&&P(\"Shatter Strike\",c[b()]))return!0;if(!G&&R?.hpPercentage>.1&&p(A))return!0;let H=f.filter(e=>\"Normal\"===e.type),[N,y]=G&&H.length>0?H:f;return!(y&&1===Math.abs(N.index-y.index)||!p(N))||!!p(y.hpPercentage-N.hpPercentage>.2&&T(y)>T(N)?y:N)"} ] }, "2H_Mage_General": { "rules": [ ] }, "DualWielding_General": { "rules": [ ] }, "DW_Mage_General": { "rules": [ ] }, "NitenIchiryu_General": { "rules": [ ] }, "NI_Mage_General": { "rules": [ ] }, "Staff_General": { "rules": [ ...createDefaultRecoveryRules(), {"type":"spellSupport","name":"Arcane Focus","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,100,"Arcane Focus"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[0,9999,"Channeling"]},{"key":"pEffects","value":[-1,50,"Regen"]}]}, {"type":"spellSupport","name":"Arcane Focus","conditions":[{"key":"pEffects","value":[-1,0,"Arcane Focus"]}]}, {"type":"spellSupport","name":"Regen","conditions":[{"key":"pEffects","value":[-1,0,"Regen"]}]}, {"type":"item","name":"Health Draught","conditions":[{"key":"pEffects","value":[-1,0,"Regeneration"]},{"key":"monsters","value":[4,10]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"item","name":"Mana Draught","conditions":[{"key":"pEffects","value":[-1,0,"Replenishment"]},{"key":"pMP","value":[0,0.85]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"item","name":"Spirit Draught","conditions":[{"key":"pEffects","value":[-1,0,"Refreshment"]},{"key":"pSP","value":[0,0.9]},{"key":"battleTypes","value":["Arena","Colosseum","Battle1000","Tower","Item"]}]}, {"type":"smartDebuff","targetCount":3,"name":"Weaken","bottomUp":false,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Weakened"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"smartDebuff","targetCount":3,"name":"Silence","bottomUp":false,"tailSkip":0,"maxAtFirst":10,"minMonstersLeft":10,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Silenced"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"smartDebuff","targetCount":3,"name":"Imperil","bottomUp":false,"tailSkip":0,"maxAtFirst":3,"minMonstersLeft":5,"conditions":[{"key":"tIgnoredEffects","value":[1,9999,"Imperiled"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tDaysSinceUpdate","value":[46,9999],"offset":[0,0],"matched":[1,1]},{"key":"tIgnoredEffects","value":[0,9999,"Imperiled","Searing Skin","Freezing Limbs","Turbulent Air","Deep Burns","Breached Defense","Blunted Attack"],"offset":[0,0],"matched":[1,1]}]}, {"type":"skill","name":"Scan","conditions":[{"key":"pActionCounts","value":[0,0,"Scan"]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tName","value":"Yggdrasil","offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tEffects","value":[0,9999,"Imperiled","Coalesced Mana"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Rare","Legendary","Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tEffects","value":[0,9999,"Coalesced Mana"],"offset":[0,0],"matched":[1,1]},{"key":"tTypes","value":["Rare","Legendary","Ultimate","Arena300","Arena400","Arena500"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tEffects","value":[0,9999,"Imperiled","Coalesced Mana"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[{"key":"tEffects","value":[0,9999,"Imperiled"],"offset":[0,0],"matched":[1,1]}]}, {"type":"target","priorityRule":"Top Down","conditions":[]}, {"type":"spellDamage","name":"T3","conditions":[{"key":"activeMonsters","value":[2,10]}]}, {"type":"spellDamage","name":"T2","conditions":[{"key":"activeMonsters","value":[2,10]}]}, {"type":"spellDamage","name":"T1","conditions":[{"key":"activeMonsters","value":[2,10]}]}, {"type":"spellDamage","name":"T3","conditions":[{"key":"pMP","value":[0.2,1]}]}, {"type":"spellDamage","name":"T2","conditions":[{"key":"pMP","value":[0.2,1]}]}, {"type":"spellDamage","name":"T1","conditions":[{"key":"pMP","value":[0.2,1]}]}, {"type":"normalAttack","conditions":[]} ] }, "Unarmed_General": { "rules": [ ] }, }; let cfgStats = {}; let defaultCfgStats = { "statsVersion": 20260109, "columnGroups": {}, "combatRows": [ {"id":"fire"}, {"id":"cold"}, {"id":"wind"}, {"id":"elec"}, {"id":"holy"}, {"id":"dark"}, {"id":"crushing","s_pt":"background-color: #ff6a6a;"}, {"id":"slashing","s_pt":"background-color: #ff6a6a;"}, {"id":"piercing","s_pt":"background-color: #ff6a6a;"}, {"id":"void"}, {"id":"damagePlus"}, {"id":"damageTotal"}, {"id":"glance","s_pt":"background-color: #e58a8a;"}, {"id":"hit","s_pt":"background-color: #e58a8a;"}, {"id":"crit","s_pt":"background-color: #e58a8a;"}, {"id":"miss","s_pt":"background-color: #66cc33;"}, {"id":"evade","s_pt":"background-color: #66cc33;"}, {"id":"parry","s_pt":"background-color: #66cc33;"}, {"id":"resist","s_md":"background-color: #8f7ee6;"}, {"id":"block","s_pt":"background-color: #66cc33;"}, {"id":"resultTotal"}, {"id":"parryPartially","s_pt":"background-color: #9fd67a;"}, {"id":"resistPartially","s_md":"background-color: #b5a8f2;"}, {"id":"blockPartially","s_pt":"background-color: #9fd67a;"} ], "revenueRows": [ {"id":"exp"}, {"id":"proficiency"}, {"id":"credit","styleText":"color: #a89000;"}, {"id":"equipment","styleText":"color: #f00;"}, {"id":"material","styleText":"color: #f00;"}, {"id":"consumable","styleText":"color: #00b000;"}, {"id":"token","styleText":"color: #3a7540;"}, {"id":"food","styleText":"color: #489eff;"}, {"id":"figurine","styleText":"color: #25f;"}, {"id":"artifact","styleText":"color: #25f;"}, {"id":"trophy","styleText":"color: #7c4bff;"}, {"id":"crystal","styleText":"color: #ba05b4;"}, {"id":"crystalTotal","styleText":"color: #ba05b4;"}, {"id":"totalProfit"}, {"id":"stamina"}, {"id":"finalProfit"} ], "statsColumns": [ {"id":"date"}, {"id":"world"}, {"id":"level"}, {"id":"persona"}, {"id":"battleType"}, {"id":"round"}, {"id":"deltaTime"}, {"id":"turns"}, {"id":"tps"}, {"id":"exp"}, {"id":"finalProfit"}, {"id":"credit"}, {"id":"eqP"}, {"id":"eqL"}, {"id":"eqM"}, {"id":"cha"}, {"id":"blo"}, {"id":"food"}, {"id":"fig"}, {"id":"arti"}, {"id":"crys"}, {"id":"t2"}, {"id":"t36"}, {"id":"lCharm"}, {"id":"gCharm"}, {"id":"seed"}, {"id":"hd"}, {"id":"md"}, {"id":"sd"}, {"id":"hp"}, {"id":"mp"}, {"id":"sp"}, {"id":"he"}, {"id":"me"}, {"id":"se"}, {"id":"le"}, {"id":"swif"}, {"id":"prot"}, {"id":"avat"}, {"id":"abso"}, {"id":"shad"}, {"id":"life"}, {"id":"gods"}, {"id":"staminaCost"}, {"id":"totalProfit"} ] }; const JPX_DARK_COLORS = Object.freeze({ background: '#202226', surface: '#292c31', field: '#24272b', text: '#e5e0d8', muted: '#bbb2a6', accent: '#e2bc8c', border: '#5a534c', header: '#453b30', selected: '#514434', hover: '#3d3933' }); // Only transform built-in styles. User-supplied metric and panel colors keep priority. function jpxThemeCSS(css) { const roles = { '#edebdf': 'background', '#e3e0d1': 'background', '#ece6d8': 'background', '#f9f6ec': 'surface', '#f4f1e5': 'surface', '#f5f1e7': 'surface', '#eee': 'surface', '#fffdf7': 'field', '#fff': 'field', '#ffffff': 'field', '#392d25': 'text', '#333': 'text', '#71634f': 'muted', '#79604f': 'muted', '#8c6551': 'muted', '#777': 'muted', '#666': 'muted', '#5c0d11': 'accent', '#9b4e03': 'accent', '#c8b49b': 'border', '#bda68e': 'border', '#ddd0bd': 'border', '#d3c5b2': 'border', '#b49369': 'border', '#baa080': 'border', '#e1d7c7': 'border', '#c1ab8c': 'border', '#ccc': 'border', '#888': 'border', '#444': 'border', '#e9d5ae': 'header', '#f2e6ce': 'header', '#ead9b8': 'selected', '#eddbb2': 'selected', '#e0e0e0': 'selected', '#f1e2c5': 'hover', '#eee2c9': 'hover', '#f0eadf': 'hover', '#f4e5c4': 'hover' }; return css.replace(/#[\da-f]{3,8}\b|rgb\((?:92 13 17|155 78 3|244 229 196|237 235 223) \/ [\d.]+%\)/gi, color => { const role = roles[color.toLowerCase()]; if (role) return 'var(--jpx-theme-' + role + ', ' + color + ')'; const alpha = color.match(/^rgb\(([\d ]+) \/ ([\d.]+)%\)$/i); if (!alpha) return color; const [alphaRole, fallback] = { '92 13 17': ['accent', '#5c0d11'], '155 78 3': ['accent', '#9b4e03'], '244 229 196': ['hover', '#f4e5c4'], '237 235 223': ['background', '#edebdf'] }[alpha[1]]; return 'color-mix(in srgb, var(--jpx-theme-' + alphaRole + ', ' + fallback + ') ' + alpha[2] + '%, transparent)'; }); } // Reuse the same converted styles in settings and temporary detail windows. function ensureJpxStyle(doc = document, entryOnly = false) { let style = doc.getElementById('jpx'); if (!style) { style = doc.createElement('style'); style.id = 'jpx'; doc.head.appendChild(style); } if (entryOnly && style.textContent === ensureJpxStyle.css) return style; const css = entryOnly ? jpxThemeCSS(JPX_ENTRY_CSS) : (ensureJpxStyle.css ??= jpxThemeCSS(fullJpxStyle())); if (style.textContent !== css) style.textContent = css; return style; } const JPX_SCROLLBAR_TARGETS = ':is(#settings-container .settings-tab-header, #settings-container [role=tabpanel], #settings-container .multiSelect-popup-panel, .jpx-records-table-scroll, .jpx-records-sheet-body)'; const JPX_SCROLLBAR_CSS = ` ${JPX_SCROLLBAR_TARGETS} { scrollbar-width: var(--jpx-scrollbar-width, thin); scrollbar-color: #5c0d11 #e3e0d1; } ${JPX_SCROLLBAR_TARGETS}::-webkit-scrollbar { width: 9px; height: 9px; } ${JPX_SCROLLBAR_TARGETS}::-webkit-scrollbar-track { background: #e3e0d1; } ${JPX_SCROLLBAR_TARGETS}::-webkit-scrollbar-thumb { border: 2px solid #e3e0d1; background: #5c0d11; } `; const JPX_RECORD_IMAGE_CSS = ` .jpx-record-image-actions { position: relative; z-index: 5; flex: none; color: #5c0d11; font: 13px/1.45 Arial, Helvetica, sans-serif; } .jpx-record-image-actions > summary, .jpx-record-image-actions button { box-sizing: border-box; min-height: 28px; padding: 3px 8px; border: 1px solid #c8b49b; border-radius: 4px; background: #fffdf7; color: inherit; font: inherit; cursor: pointer; } .jpx-record-image-actions > summary { display: none; list-style: none; } .jpx-record-image-actions > summary::after { content: ' ▾'; } .jpx-record-image-actions > summary::-webkit-details-marker { display: none; } .jpx-record-image-actions > div { display: grid; gap: 4px; } .jpx-record-image-actions button { text-align: center; white-space: nowrap; } html .jpx-record-image-actions button:is(:hover, :focus, :active) { background: #eee2c9; color: inherit; border-color: #c8b49b; } .jpx-record-image-actions button:disabled { cursor: wait; opacity: .6; } .jpx-record-image-toast { max-width: min(280px, calc(100vw - 32px)); box-sizing: border-box; padding: 8px 12px; border: 1px solid #c8b49b; border-radius: 4px; background: #f9f6ec; color: #5c0d11; box-shadow: 0 2px 6px #0002; font: 13px/1.45 Arial, Helvetica, sans-serif; overflow-wrap: anywhere; } .jpx-record-image-actions :focus-visible { outline: 1px solid #9b4e03; outline-offset: -1px; box-shadow: 0 0 0 2px rgb(155 78 3 / 12%); } @media (max-width: 650px), (pointer: coarse) { .jpx-record-image-actions > summary, .jpx-record-image-actions button { min-height: 40px; } } @media (max-width: 650px), (pointer: coarse) and (orientation: landscape) and (max-height: 600px) { .jpx-record-image-toast { position: fixed; top: max(12px, env(safe-area-inset-top, 0px)); left: 50%; transform: translateX(-50%); width: max-content; max-width: min(320px, calc(100vw - 24px)); min-height: 44px; padding: 10px 14px; font-size: 14px; text-align: center; } .jpx-record-image-actions { position: fixed; right: 14px; bottom: max(14px, env(safe-area-inset-bottom, 0px)); } .jpx-record-image-actions > summary { display: flex; align-items: center; justify-content: center; gap: 4px; min-width: 80px; padding: 6px 10px; background: #f9f6ec; } .jpx-record-image-actions > summary::after { content: ' ▴'; } .jpx-record-image-actions > div { position: absolute; right: 0; bottom: calc(100% + 6px); display: grid; gap: 4px; width: max-content; max-width: calc(100vw - 28px); padding: 4px; border: 1px solid #c8b49b; border-radius: 6px; background: #f9f6ec; box-shadow: 0 2px 6px #0002; } .jpx-record-image-actions button { border-color: transparent; } } `; const JPX_ENTRY_CSS = ` #jpx-mobile-entry { display: none; position: fixed; z-index: 110; margin: 0; color: #5c0d11; font: 14px/1.4 Verdana, Arial, sans-serif; transform-origin: top left; } #jpx-mobile-entry > summary, #jpx-mobile-entry button { box-sizing: border-box; min-height: 44px; margin: 0; padding: 10px 12px; border: 1px solid #bda68e; border-radius: 3px; background: #edebdf; color: inherit; font: inherit; cursor: pointer; touch-action: manipulation; } #jpx-mobile-entry > summary { min-width: 72px; list-style-position: inside; user-select: none; } #jpx-mobile-entry > nav { position: absolute; bottom: calc(100% + 6px); left: 0; display: grid; gap: 4px; min-width: 116px; } #jpx-mobile-entry button { display: flex; align-items: center; gap: 10px; width: 100%; text-align: left; white-space: nowrap; } #jpx-mobile-entry svg { flex: none; width: 17px; height: 17px; } #jpx-mobile-entry :focus-visible { outline: 2px solid #9b4e03; outline-offset: 2px; } @media (pointer: coarse) { #jpx-mobile-entry { display: block; } } body:has(#hvut-top-config-icon, #textlog, #battle_main, #riddlemaster) #jpx-mobile-entry { display: none; } #hvut-top .jpx-hvut-config > .hvut-top-config { visibility: hidden; } #hvut-top .jpx-hvut-config[data-jpx-open=true] > .hvut-top-config { visibility: visible; } body:has(#settings-container[open]) #jpx-mobile-entry { visibility: hidden; } html[data-jpx-theme=dark] #jpx-mobile-entry { color-scheme: dark; color: var(--jpx-theme-text); } `; function fullJpxStyle() { const JPX_RECORD_DETAIL_CSS = ` ${JPX_RECORD_IMAGE_CSS} body.jpx-record-detail { margin: 0; background: #edebdf; } .jpx-record-detail { color: #392d25; font: 13px/1.45 Arial, Helvetica, sans-serif; } .jpx-record-detail * { box-sizing: border-box; } .jpx-record-detail-page { width: fit-content; max-width: min(1240px, 100%); margin: 0 auto; padding: 12px; } .jpx-record-detail-summary { display: grid; gap: 8px; margin-bottom: 12px; padding: 8px 10px; border: 1px solid #c8b49b; background: #f9f6ec; } .jpx-record-detail-summary:has(> .jpx-record-image-actions) { grid-template-columns: minmax(0, 1fr) auto; } .jpx-record-detail-summary > .jpx-record-image-actions { grid-column: 2; grid-row: 1 / 3; align-self: center; padding-left: 12px; border-left: 1px solid #ddd0bd; } .jpx-record-detail-summary > :not(.jpx-record-image-actions) { grid-column: 1; } .jpx-record-detail #info-records-div, .jpx-record-detail #time-records-div { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 16px; text-align: left; white-space: normal; overflow-wrap: anywhere; } .jpx-record-detail #info-records-div { color: #5c0d11; font-weight: 600; } .jpx-record-detail #info-records-div > span { max-width: 100%; } .jpx-record-detail #time-records-div { font-size: 12px; color: #71634f; } .jpx-record-detail .jpx-record-metric { display: inline-flex; align-items: baseline; gap: 4px; white-space: nowrap; } .jpx-record-detail .jpx-record-metric strong { color: #392d25; font-weight: 600; font-variant-numeric: tabular-nums; } .jpx-record-detail-grid { display: grid; grid-template-columns: minmax(0, max-content) minmax(0, max-content); align-items: start; gap: 12px; } .jpx-record-detail-column { display: grid; align-content: start; gap: 12px; width: fit-content; min-width: 0; max-width: 100%; } .jpx-record-detail-scroll { width: fit-content; min-width: 0; max-width: 100%; overflow: auto; overscroll-behavior-x: contain; border: 1px solid #bda68e; background: #fffdf7; scrollbar-color: #5c0d11 #e3e0d1; } .jpx-record-detail-scroll:focus-visible { outline: 2px solid #9b4e03; outline-offset: 2px; } .jpx-record-detail table { width: auto; margin: 0 !important; border: 0; border-collapse: collapse; background: #fffdf7; font-size: 12px; font-variant-numeric: tabular-nums; } .jpx-record-detail td, .jpx-record-detail th { padding: 2px 4px; line-height: 1.5; vertical-align: middle; border: 1px solid #e1d7c7; } .jpx-record-detail tr:nth-child(even) { background-color: #f5f1e7; } .jpx-record-detail .records-table tr:nth-child(-n+2), .jpx-record-detail #combat-records-use-table tr:first-child { background: #e9d5ae; color: #5c0d11; font-weight: 700; } .jpx-record-detail .records-table tr:nth-child(2) { background: #f2e6ce; font-weight: 600; } .jpx-record-detail #combat-records-table { min-width: 0; } .jpx-record-detail #combat-records-table td { white-space: nowrap; } .jpx-record-detail #combat-records-table tr:nth-child(-n+2) > td { border-bottom-color: #e1d7c7; } .jpx-record-detail-scroll:has(> #combat-records-use-table) { width: 100%; contain: inline-size; } .jpx-record-detail #combat-records-use-table { width: 100%; table-layout: fixed; } .jpx-record-detail #combat-records-use-table td, .jpx-record-detail #combat-records-use-table th { border-color: #e1d7c7; } .jpx-record-detail #combat-records-use-table td { white-space: normal; overflow-wrap: anywhere; } .jpx-record-detail #combat-records-use-table td:first-child { width: 96px; vertical-align: top; } .jpx-record-detail #revenue-records-table { width: 500px; table-layout: auto; } .jpx-record-detail #revenue-records-table td { overflow-wrap: anywhere; } .jpx-record-detail #revenue-records-table tr:nth-child(n+3) > td:first-child:not([colspan]) { white-space: nowrap; } .jpx-record-detail #revenue-records-table tr:nth-child(n+3) > td:not(:first-child):not([colspan]) { text-align: right; white-space: nowrap; } @media (max-width: 1099px) { .jpx-record-detail-grid { grid-template-columns: minmax(0, 1fr); } .jpx-record-detail-page > .jpx-record-detail-summary { contain: inline-size; } .jpx-record-detail-page .jpx-record-detail-column, .jpx-record-detail-page .jpx-record-detail-scroll, .jpx-record-detail-page #combat-records-table { width: 100%; } } @media (max-width: 650px) { .jpx-record-detail-page { padding: 6px 6px 58px; } .jpx-record-detail-summary { padding: 6px 8px; } } @media (max-width: 650px), (pointer: coarse) and (orientation: landscape) and (max-height: 600px) { .jpx-record-detail-page { padding-bottom: 58px; } .jpx-record-detail-summary:has(> .jpx-record-image-actions) { grid-template-columns: minmax(0, 1fr); } .jpx-record-detail-summary > .jpx-record-image-actions { padding-left: 0; border-left: 0; } } .jpx-record-final { display: grid; gap: 6px; min-width: 0; max-width: 100%; margin: 6px 0; text-align: left; } .jpx-record-final .jpx-record-detail-summary { margin: 0; } .jpx-record-final > a { margin: 0 !important; font-size: 12px !important; color: #5c0d11; } .jpx-record-final td, .jpx-record-final th { line-height: 1.4; } #btcp.jpx-final-result { box-sizing: border-box; display: block; width: 530px; min-width: 0; max-width: 530px; height: auto; min-height: 120px; max-height: 621px; overflow: auto; } /* Native result-panel div rules must not size or position the statistics. */ #btcp.jpx-final-result #jpx-final-revenue, #btcp.jpx-final-result #jpx-final-revenue div { position: static; inset: auto; width: auto; min-width: 0; max-width: 100%; height: auto; min-height: 0; max-height: none; } #btcp.jpx-final-result #jpx-final-revenue { display: block; margin: 8px 0 0; } #btcp.jpx-final-result #jpx-final-revenue .jpx-record-detail-summary { margin: 0 0 6px; padding: 6px 8px; } #btcp.jpx-final-result #revenue-records-table { width: 100%; min-width: 480px; } `; return ` ${JPX_SCROLLBAR_CSS} html.jpx-hide-round-popup #btcp:not(:has(img[src$="finishbattle.png"])) { display: none !important; } #ctrl-widget { position: fixed; inset: auto 12px 12px auto; opacity: 1; z-index: 100; } ${JPX_ENTRY_CSS} .jpx-widget-card { --jpx-state-header: var(--jpx-manual-header, #b49c8e); --jpx-state-ink: var(--jpx-manual-ink, #3d2b22); --jpx-state-border: var(--jpx-manual-border, #896f60); --jpx-state-accent: var(--jpx-manual-border, #72513d); box-sizing: border-box; width: 196px; max-width: calc(100vw - 16px); height: auto; padding: 0; border: 1px solid var(--jpx-state-border); border-radius: 4px; background: #edebdf; color: var(--jpx-theme-text, #000); font: 12px/1.45 Arial, Helvetica, sans-serif; text-align: left; box-shadow: 0 2px 8px rgb(45 32 20 / 16%); overflow: hidden; } .jpx-widget-card[data-battle-state=auto] { --jpx-state-header: var(--jpx-auto-header, #86b16f); --jpx-state-ink: var(--jpx-auto-ink, #19351e); --jpx-state-border: var(--jpx-auto-border, #5c8248); --jpx-state-accent: var(--jpx-auto-border, #3c662c); } .jpx-widget-card[data-battle-state=waiting] { --jpx-state-header: var(--jpx-waiting-header, #d5ac4e); --jpx-state-ink: var(--jpx-waiting-ink, #49330b); --jpx-state-border: var(--jpx-waiting-border, #9a7625); --jpx-state-accent: var(--jpx-waiting-border, #805d0d); } /* Theme defaults also apply to the preview; inline custom colors keep priority. */ html[data-jpx-theme=dark] .jpx-widget-card { --jpx-auto-header: #344d31; --jpx-auto-surface: #252d24; --jpx-auto-border: #6e925e; --jpx-auto-ink: #def0d3; --jpx-manual-header: #51443a; --jpx-manual-surface: #2b2927; --jpx-manual-border: #9a8270; --jpx-manual-ink: #f0e0d1; --jpx-waiting-header: #5c491f; --jpx-waiting-surface: #302c22; --jpx-waiting-border: #b2934c; --jpx-waiting-ink: #ffebb7; --jpx-widget-info-hover: rgb(255 255 255 / 6%); } /* Outrank native button hover/focus/active rules without overriding custom palette values. */ #ctrl-widget .jpx-widget-drag, .jpx-widget-card .jpx-widget-drag { display: flex; box-sizing: border-box; align-items: center; gap: 6px; width: 100%; margin: 0; padding: 5px 8px; min-height: 28px; border: 0; border-bottom: 1px solid var(--jpx-state-border); border-radius: 0; background: var(--jpx-state-header); color: var(--jpx-state-ink); font: inherit; line-height: 1.2; text-align: left; cursor: grab; touch-action: none; user-select: none; } .jpx-widget-card .jpx-widget-drag > strong { font-size: 11px; letter-spacing: .3px; } .jpx-widget-card .jpx-widget-drag > svg { width: 12px; height: 12px; flex: none; margin-left: auto; opacity: .65; } .jpx-widget-card .jpx-widget-info { padding: 6px 8px; min-height: 20px; color: inherit; white-space: pre-line; cursor: pointer; } .jpx-widget-card .jpx-widget-info:empty { min-height: 24px; } .jpx-widget-card .jpx-widget-info:hover { background: var(--jpx-widget-info-hover, rgb(255 255 255 / 35%)); } .jpx-widget-card .jpx-widget-info-row { display: flex; align-items: baseline; gap: 8px; padding: 1px 0; } .jpx-widget-card .jpx-widget-info-label { flex: none; opacity: .75; } .jpx-widget-card .jpx-widget-info-value { margin-left: auto; min-width: 0; text-align: right; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } .jpx-widget-card [data-row-id=isActiveBattle] .jpx-widget-info-value { box-sizing: border-box; min-width: 36px; padding-left: 6px; border-left: 3px solid var(--jpx-state-accent); font-weight: 700; } .jpx-widget-card .jpx-widget-actions { display: grid; grid-template-columns: 1fr 1fr; border-top: 1px solid var(--jpx-theme-border, #c9b7a2); } #ctrl-widget .jpx-widget-action, .jpx-widget-card .jpx-widget-action { display: inline-flex; align-items: center; justify-content: center; gap: 4px; box-sizing: border-box; width: 100%; min-height: 28px; padding: 4px; margin: 0; border: 0; border-radius: 0; background: transparent; color: inherit; font: inherit; cursor: pointer; } .jpx-widget-card .jpx-widget-action + .jpx-widget-action { border-left: 1px solid var(--jpx-theme-border, #c9b7a2); } .jpx-widget-card .jpx-widget-action svg { width: 13px; height: 13px; flex: none; } #ctrl-widget .jpx-widget-action:is(:hover, :focus-visible, :active), .jpx-widget-card .jpx-widget-action:is(:hover, :focus-visible, :active) { background: #f4e5c4; } .jpx-widget-card :focus-visible { outline: 2px solid #9b4e03; outline-offset: -2px; } #ctrl-widget.is-dragging, #ctrl-widget.is-dragging .jpx-widget-drag { cursor: grabbing; user-select: none; } #ctrl-widget.is-dragging { box-shadow: 0 4px 12px rgb(45 32 20 / 22%); } #proficiency-record { position: absolute; top: 752px; left: 50px; white-space: nowrap; text-align: left; } @media (min-width: 600px) and (orientation:landscape) { #proficiency-record { top: 50px; left: 1240px; } } #battle_right { position: absolute; top: 42px; left: 681px; width: 364px; overflow: visible; .btm6 { min-width: 200px; } } .effect-duration { display: inline-block; width: 30px; margin-right: -30px; position: relative; text-align: center; z-index: 1; div { display: inline-block; min-width: 16px; padding: 0 2px; background: #edebdf; color: black; font-weight: bold; border: 1px solid black; } } .cooldown { width: 37px; margin-top: 7px; position: relative; z-index: 3; color: black; font-size: 20px; font-weight: bold; } .monster-hp { display: inline-block; position: relative; top: -20px; left: 204px; } #info-records-div { font-weight: bold; } #info-records-div, #time-records-div { text-align: center; white-space: pre; } .records-table { border-top: 1px solid; border-bottom: 1px solid; border-collapse: collapse; background-color: #fff; & tr:nth-child(1) > td, & tr:nth-child(2) > td { text-align: center; } & tr:not(:nth-child(1), :nth-child(2)) > td:nth-child(1) { text-align: left; } & td { min-width: 40px; padding: 2px 4px; border-left: 1px solid; border-right: 1px solid; text-align: right; } } #combat-records-table { margin: 10px 0px; } #combat-records-table tr:nth-child(1) > td:not(:nth-child(1)), #combat-records-table tr:nth-child(2) > td { border-bottom: 1px solid; } #combat-records-use-table { border-collapse: collapse; background-color: #fff; & th, & td { border: 1px solid; min-width: 40px; padding: 2px 4px; } & th { text-align: center; } & td { text-align: left; } } #revenue-records-table { margin: 10px auto; } #revenue-records-table .surplus { color: #000; !important; background-color: #a5f779 !important; } #revenue-records-table .deficit { color: #000 !important; background-color: #ff6a6a !important; } #revenue-records-table .noData { color: #000 !important; background-color: #a796fa !important; } .heading { font-weight: bold; margin: 8px 0; border-bottom: 1px solid #ccc; padding-bottom: 2px; } .array-row:not(.array-row .array-row) { border: 1px solid #888; background: #eee; padding: 4px; margin: 4px 0; position: relative; } .drag-handle { cursor: grab; user-select: none; } .drag-handle:active { cursor: grabbing; } #settings-container.jpx-settings-dialog { --jpx-motion: 160ms; --jpx-motion-fast: 120ms; position: fixed; box-sizing: border-box; inset: 0; width: min(820px, calc(100vw - 48px)); height: min(780px, calc(100dvh - 112px)); max-width: calc(100vw - 48px); max-height: calc(100dvh - 112px); margin: auto; padding: 3px; overflow: hidden; border: 2px solid #5c0d11; background: #edebdf; box-shadow: 0 12px 30px rgb(0 0 0 / 28%); color: #5c0d11; font: 13px/1.45 Verdana, Arial, sans-serif; text-align: left; } #settings-container.jpx-settings-dialog:focus { outline: none; } #settings-container.jpx-settings-dialog::backdrop { background: rgb(24 18 14 / 62%); } #settings-container .jpx-settings-window { display: flex; container: jpx-settings / inline-size; box-sizing: border-box; width: 100%; height: 100%; min-width: 0; flex-direction: column; border: 1px solid #5c0d11; background: #edebdf; text-align: left; } /* Layout gaps own button spacing; host margins overflow full-width list rows. */ #settings-container button { margin: 0; } #settings-container button:not(.settings-tab-btn) { min-height: 29px; padding: 4px 8px; border: 1px solid rgb(92 13 17 / 30%); border-radius: 2px; background: #edebdf; color: #5c0d11; cursor: pointer; } #settings-container button:not(.settings-tab-btn):hover { background: #fff; } #settings-container button:not(.settings-tab-btn):disabled { opacity: .5; cursor: not-allowed; } #settings-container button, #settings-container .jpx-rule-item > summary, #settings-container .heading, #settings-container .jpx-settings-title { user-select: none; -webkit-user-select: none; } #settings-container input, #settings-container textarea, #settings-container [contenteditable=true] { user-select: text; -webkit-user-select: text; } #settings-container .jpx-settings-titlebar { display: flex; min-height: 46px; align-items: center; justify-content: space-between; padding: 0 12px; border-bottom: 1px solid #5c0d11; background: #edebdf; } #settings-container .jpx-settings-title { font-size: 15px; font-weight: 700; } #settings-container .jpx-settings-titlebar button { width: 34px; height: 34px; padding: 0; border: 1px solid transparent; background: transparent; color: #5c0d11; font-size: 20px; } #settings-container .jpx-settings-titlebar button:hover { border-color: #5c0d11; background: var(--jpx-theme-hover, #fff9); } #settings-container .jpx-settings-sidebar { display: flex; flex: none; width: 154px; flex-direction: column; min-width: 0; overflow: hidden; border-right: 1px solid #5c0d11; background: #e3e0d1; transition: width var(--jpx-motion) ease-out; } #settings-container .jpx-settings-sidebar-toggle { display: flex; width: 56px; min-width: 0 !important; min-height: 38px; align-items: center; justify-content: center; padding: 0; margin: 0; box-sizing: border-box; border: 0 !important; border-radius: 0 !important; border-bottom: 1px solid rgb(92 13 17 / 20%); background: transparent !important; color: #5c0d11; box-shadow: none !important; appearance: none; } #settings-container .jpx-settings-sidebar-toggle svg, #settings-container .settings-tab-btn svg { width: 18px; height: 18px; flex: none; } #settings-container .settings-tab-header { display: flex; min-height: 0; flex: 1; flex-direction: column; overflow-x: hidden; overflow-y: auto; margin: 0; background: #e3e0d1; scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } #settings-container .jpx-settings-workspace { display: flex; min-width: 0; min-height: 0; flex: 1; } #settings-container .jpx-settings-panels { display: flex; min-width: 0; min-height: 0; flex: 1; flex-direction: column; } #settings-container .settings-tab-btn { display: grid; width: 100%; min-height: 42px; flex: none; grid-template-columns: 56px minmax(0, 1fr); align-items: center; gap: 0; padding: 0 !important; border: 0 !important; border-radius: 0 !important; border-bottom: 1px solid rgb(92 13 17 / 20%) !important; background: transparent !important; color: #5c0d11 !important; text-align: left; white-space: normal; box-shadow: none !important; appearance: none; } #settings-container .settings-tab-btn > svg { justify-self: center; } #settings-container .settings-tab-btn[aria-selected=true] { background: #edebdf !important; box-shadow: inset -3px 0 #5c0d11; } #settings-container .settings-tab-btn:hover, #settings-container .jpx-settings-sidebar-toggle:hover { background: rgb(237 235 223 / 72%) !important; } #settings-container .jpx-tab-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: 1; translate: 0; visibility: visible; transition: opacity var(--jpx-motion-fast) ease-out, translate var(--jpx-motion) ease-out, visibility 0s; } #settings-container .jpx-settings-workspace.sidebar-collapsed .jpx-settings-sidebar { width: 56px; } #settings-container .jpx-settings-workspace.sidebar-collapsed .settings-tab-btn[aria-selected=true] { box-shadow: inset -3px 0 #5c0d11; } #settings-container .jpx-settings-workspace.sidebar-collapsed .jpx-tab-label { opacity: 0; translate: -4px 0; visibility: hidden; transition-delay: 0s, 0s, var(--jpx-motion); } #settings-container [role=tabpanel] { display: flex; min-height: 0; flex: 1; flex-direction: column; overflow: auto; padding: 14px 18px 12px; scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } #settings-container #cfgBattle-ui, #settings-container #cfgStats-ui { display: grid; min-width: 0; grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: 18px; align-content: start; } #settings-container #cfgBattle-ui > .field-block, #settings-container #cfgStats-ui > .field-block { min-width: 0; } #settings-container #cfgBattle-ui > .field-block[data-field-type=heading], #settings-container #cfgBattle-ui > .field-block[data-field-key=ctrlWidgetRows], #settings-container #cfgStats-ui > .field-block[data-field-type=heading], #settings-container #cfgStats-ui > .field-block[data-field-type=fieldPicker] { grid-column: 1 / -1; } #settings-container .jpx-battle-mode-selects { display: flex !important; align-items: center; flex-wrap: wrap; gap: 8px; } #settings-container .jpx-battle-mode-selects > div { margin-right: 0 !important; } #settings-container .jpx-rule-sections, #settings-container .jpx-rule-section:not([hidden]) { display: flex; flex: 1; flex-direction: column; min-height: 0; min-width: 0; } #settings-container .jpx-rule-section[hidden], #settings-container .jpx-rule-section > .heading[hidden] { display: none; } #settings-container .jpx-battle-mode-selects { flex: none; padding-bottom: 10px; } #settings-container .jpx-rule-navigation { display: flex; flex: none; align-items: center; gap: 4px; border-bottom: 1px solid rgb(92 13 17 / 30%); margin-bottom: 6px; } #settings-container .jpx-rule-section-tabs { display: flex; flex-wrap: wrap; min-width: 0; gap: 0; } #settings-container .jpx-rule-section-tabs > button { padding: 6px 8px; min-height: 32px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: #71634f; } #settings-container .jpx-rule-section-tabs > button[aria-pressed=true] { border-bottom-color: #5c0d11; color: #5c0d11; } #settings-container .jpx-rule-section-tabs > button[data-change-state] { box-shadow: inset 0 2px var(--jpx-change-color); } #settings-container .jpx-rule-section-controls { flex: none; margin-left: auto; } #settings-container .jpx-rule-section-controls .jpx-rule-list-toggle { padding: 3px 4px; border-color: transparent; background: transparent; } #settings-container .jpx-rule-section { margin: 0; } #settings-container .jpx-rule-context-menu { box-sizing:border-box; min-width:176px; margin:0; padding:4px; border:1px solid var(--jpx-theme-border,#c8b49b); border-radius:0; background:var(--jpx-theme-surface,#edebdf); color:var(--jpx-theme-text,#5c0d11); overflow:hidden; box-shadow:0 4px 12px rgb(0 0 0 / 18%); } #settings-container .jpx-rule-context-menu:popover-open { display:grid; grid-template:minmax(0,1fr) / minmax(0,1fr); } #settings-container .jpx-rule-menu-page { grid-area:1 / 1; display:flex; flex-direction:column; min-height:0; min-width:0; } /* Inactive pages reserve their size, so navigation never moves the popover. */ #settings-container .jpx-rule-menu-page[inert] { visibility:hidden; pointer-events:none; } #settings-container .jpx-rule-menu-items { min-height:0; overflow:auto; overscroll-behavior:contain; scrollbar-width:thin; scrollbar-gutter:stable; } #settings-container .jpx-rule-context-menu button { display:block; width:100%; min-height:32px; text-align:left; border:0; border-radius:0; background:transparent; padding:6px 12px; } #settings-container .jpx-rule-context-menu :is(.jpx-rule-menu-next,.jpx-rule-menu-back) { display:flex; align-items:center; gap:8px; } #settings-container .jpx-rule-context-menu svg { width:14px; height:14px; flex:none; } #settings-container .jpx-rule-menu-next svg { margin-left:auto; } #settings-container .jpx-rule-context-menu .jpx-rule-menu-back { flex:none; border-bottom:1px solid var(--jpx-theme-border,#c8b49b); margin-bottom:4px; } #settings-container .jpx-rule-context-menu .jpx-rule-menu-separator { border-top:1px solid var(--jpx-theme-border,#c8b49b); margin:4px 0; } #settings-container .jpx-rule-context-menu button:hover:not(:disabled) { background:var(--jpx-theme-hover,#f1e2c5); } #settings-container .jpx-rule-context-menu .jpx-rule-menu-delete { color:#a1282f; } html[data-jpx-theme=dark] #settings-container .jpx-rule-context-menu .jpx-rule-menu-delete { color:#ffb4b6; } #settings-container .jpx-rule-context-menu button:focus-visible { outline:2px solid var(--jpx-theme-accent,#5c0d11); outline-offset:-2px; background:var(--jpx-theme-hover,#f1e2c5); } #settings-container.jpx-settings-mobile .jpx-rule-context-menu button { min-height:44px; } #settings-container .jpx-rule-scroll { flex: 1; min-height: 0; min-width: 0; overflow: auto; padding-right: 4px; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } #settings-container .jpx-rule-add-actions { display: flex; flex: none; flex-wrap: wrap; gap: 4px; padding: 8px 0 6px; border-top: 1px solid rgb(92 13 17 / 30%); background: #edebdf; } #settings-container .jpx-rule-add-actions button { min-height: 28px; padding: 3px 6px; } #settings-container .jpx-rule-add-actions > .jpx-rule-add { display:inline-flex; align-items:center; gap:8px; min-height:34px; padding:6px 12px; border-radius:0; } #settings-container .jpx-rule-add svg { width:14px; height:14px; } #settings-container.jpx-settings-mobile .jpx-rule-add-actions > .jpx-rule-add { min-height:44px; } #settings-container .jpx-keybinding-rule-group .jpx-rule-add-actions { position: sticky; bottom: 0; z-index: 2; } #settings-container .jpx-keybindings-settings { display: grid; min-width: 0; grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)); gap: 6px 12px; margin-bottom: 8px; } #settings-container .jpx-keybindings-settings > div { display: grid; min-width: 0; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; } #settings-container .jpx-keybindings-settings > div > span { overflow-wrap: anywhere; } #settings-container .jpx-keybindings-settings button { max-width: 100%; white-space: normal; overflow-wrap: anywhere; } #settings-container .jpx-settings-footer { display: flex; flex-wrap: wrap; min-height: 48px; flex: none; align-items: center; justify-content: flex-end; gap: 6px; margin: 0 !important; padding: 7px 10px; border-top: 1px solid #5c0d11; background: #e3e0d1; } #settings-container .jpx-settings-file-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; min-width: 0; } #settings-container .jpx-settings-footer button { min-height: 30px; padding: 4px 10px; border: 1px solid #5c0d11; background: transparent; color: #5c0d11; } #settings-container .jpx-settings-footer button:hover { background: #fff; } #settings-container .jpx-settings-footer #save-button { background: #5c0d11; color: #fff; } #settings-container .jpx-settings-footer #save-button:hover { background: #9b4e03; } #settings-container button, #settings-container input, #settings-container select, #settings-container textarea { box-sizing: border-box; font: inherit; } #settings-container button, #settings-container select, #settings-container input, #settings-container textarea { accent-color: #5c0d11; } #settings-container button:focus-visible, #settings-container input:focus-visible, #settings-container select:focus-visible, #settings-container textarea:focus-visible { outline: 1px solid #9b4e03; outline-offset: -1px; box-shadow: 0 0 0 2px rgb(155 78 3 / 12%); } #settings-container .settings-tab-btn:focus-visible { outline: none; box-shadow: inset 0 0 0 1px #9b4e03, inset -3px 0 #5c0d11 !important; } #settings-container select { width: auto; max-width: min(100%, 320px); min-height: 30px; padding: 4px 7px; border: 1px solid rgb(92 13 17 / 32%); border-radius: 2px; background-color: #fff; color: #5c0d11; } #settings-container select:not([multiple]) { field-sizing: content; min-width: 0; } #settings-container select, #settings-container textarea { scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } /* Host option rules do not inherit the themed select's colors. */ #settings-container select :is(option,optgroup) { color: var(--jpx-theme-text, #5c0d11); background: #fffdf7; } #settings-container select option:checked { background: #eddbb2; } @supports (appearance: base-select) { #settings-container select:not([multiple]), #settings-container select:not([multiple])::picker(select) { appearance: base-select; } #settings-container select:not([multiple]) { gap: 8px; cursor: pointer; background: #f9f6ec; } #settings-container select:not([multiple])::picker-icon { color: #5c0d11; } #settings-container select:not([multiple])::picker(select) { width: max-content; min-width: anchor-size(width); max-width: min(560px, calc(100vw - 32px)); max-height: min(280px, 50dvh); box-sizing: border-box; padding: 3px; overflow: auto; border: 1px solid #5c0d11; border-radius: 2px; background: #edebdf; color: #5c0d11; box-shadow: 0 4px 12px rgb(36 18 15 / 18%); scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } #settings-container.jpx-settings-mobile select:not([multiple])::picker(select) { /* The native top layer escapes dialog transforms; zoom keeps anchor collision handling. */ zoom: var(--settings-scale); min-width: calc(anchor-size(width) / var(--settings-scale)); max-width: calc(var(--settings-width) - 24px); max-height: min(280px, calc(var(--settings-height) * .5)); } #settings-container select:not([multiple]) option { box-sizing: border-box; min-height: 30px; margin: 0; padding: 5px 8px; gap: 8px; white-space: normal; overflow-wrap: anywhere; border: 0; border-radius: 0; background: transparent; color: var(--jpx-theme-text, #5c0d11); border-bottom: 1px solid rgb(92 13 17 / 12%); } #settings-container select:not([multiple]) option:checked { background: #eddbb2; } #settings-container select:not([multiple]) option:hover, #settings-container select:not([multiple]) option:focus { background: #f4e5c4; outline: 1px solid #9b4e03; outline-offset: -1px; } #settings-container select:open::picker(select) { animation: jpx-settings-fade var(--jpx-motion-fast) ease-out; } } #settings-container input:not([type=checkbox]):not([type=radio]), #settings-container textarea { max-width: 100%; min-height: 30px; padding: 4px 7px; border: 1px solid rgb(92 13 17 / 28%); border-radius: 2px; background: #fff; color: #5c0d11; } #settings-container textarea { width: min(100%, 780px); } #settings-container input[type=number] { field-sizing: content; width: 8ch; min-width: 7ch; max-width: min(18ch, 100%); } #settings-container input[type=text] { field-sizing: content; width: 20ch; min-width: min(16ch, 100%); max-width: min(48ch, 100%); } @supports (field-sizing: content) { #settings-container input[type=number], #settings-container input[type=text] { width: auto; } } #settings-container [data-field-key=ctrlWidgetStyleText] input { min-width: min(30ch, 100%); } #settings-container [data-field-key=controlPanel] { container-type: inline-size; } #settings-container .jpx-control-panel-editor { --stats-border: rgb(92 13 17 / 24%); --stats-surface: #f9f6ec; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.7fr); gap: 12px; align-items: start; } #settings-container .jpx-control-panel-editor > div { min-width: 0; } #settings-container .jpx-control-appearance-body { display: grid; grid-template-columns: minmax(0, 1fr) 214px; gap: 12px; align-items: start; } #settings-container .jpx-control-appearance-body > div { min-width: 0; } #settings-container .jpx-control-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 28px; margin-bottom: 6px; border-bottom: 1px solid rgb(92 13 17 / 24%); } #settings-container .jpx-control-appearance > .jpx-control-heading { flex-wrap: wrap; } #settings-container .jpx-control-count { font-size: 11px; color: #71634f; } #settings-container .jpx-control-panel-editor .jpx-control-list { max-height: none; } #settings-container .jpx-control-list .jpx-stats-row { min-height: 32px; } #settings-container .jpx-control-list .jpx-stats-select { min-height: 32px; padding-right: 94px; cursor: default; } #settings-container .jpx-control-panel-editor .jpx-control-list .jpx-stats-select[aria-pressed=true] { background: transparent; box-shadow: none; font-weight: normal; } #settings-container .jpx-control-list .jpx-stats-select:hover { background: #fff; } #settings-container .jpx-control-style { display: grid; gap: 6px; } #settings-container .jpx-control-style-row { display: grid; grid-template-columns: minmax(0, 1fr) 32px 28px; min-width: 0; align-items: center; gap: 8px; min-height: 28px; } #settings-container .jpx-control-preview { display: grid; gap: 8px; min-width: 0; } #settings-container .jpx-control-preview-states { justify-content: center; } #settings-container button.jpx-appearance-reset { display: inline-flex; flex: none; justify-content: center; align-items: center; width: 28px; min-width: 28px; height: 28px; min-height: 28px; margin: 0; padding: 4px; border: 1px solid var(--jpx-theme-border, #c8b49b); border-radius: 0; color: var(--jpx-theme-accent, #5c0d11); background: transparent; } #settings-container button.jpx-appearance-reset svg { width: 14px; height: 14px; } #settings-container button.jpx-appearance-reset:focus-visible { outline: 2px solid var(--jpx-theme-accent, #5c0d11); outline-offset: 2px; } #settings-container button.jpx-appearance-reset-all { width: auto; height: auto; padding: 4px 8px; margin-left: auto; white-space: nowrap; font: inherit; } #settings-container .jpx-control-style input[type=color] { margin: 0; } #settings-container .jpx-control-style-row > label { flex: none; } #settings-container .jpx-control-style input[type=color] { width: 32px; height: 28px; min-width: 32px; padding: 1px; background: #fff; border: 1px solid rgb(92 13 17 / 24%); cursor: pointer; } #settings-container .jpx-control-opacity-row { grid-template-columns: minmax(0, 1fr) auto 28px; gap: 4px 8px; margin-top: 2px; padding-top: 8px; border-top: 1px solid var(--stats-border); } #settings-container .jpx-control-opacity-row input { grid-column: 1 / -1; grid-row: 2; } #settings-container input[data-control-opacity] { flex: 1; width: 0; min-width: 44px; height: 28px; padding: 0; } #settings-container .jpx-control-opacity-row input[data-control-opacity] { width: 100%; min-width: 0; margin: 0; padding: 0; border: 0; background: transparent; } #settings-container [data-control-opacity-value] { min-width: 4ch; font-variant-numeric: tabular-nums; text-align: right; } #settings-container .jpx-control-preview-states { display: flex; gap: 4px; } #settings-container .jpx-control-preview-states button { min-height: 24px; padding: 2px 6px; margin: 0; font-size: 11px; border-color: transparent; } #settings-container .jpx-control-preview-states button[aria-pressed=true] { border-color: rgb(92 13 17 / 30%); background: #eddbb2; } #settings-container .jpx-control-preview-stage { display: flex; justify-content: center; padding: 8px; border: 1px solid rgb(92 13 17 / 18%); background: #f9f6ec; } #settings-container .jpx-control-preview-sample { max-width: 100%; opacity: 1; } #settings-container .jpx-control-preview-content { white-space: pre-line; overflow-wrap: anywhere; } #settings-container .jpx-control-preview-sample .jpx-widget-drag, #settings-container .jpx-control-preview-sample .jpx-widget-info, #settings-container .jpx-control-preview-sample .jpx-widget-action { cursor: default; } @container (max-width: 579px) { #settings-container .jpx-control-panel-editor { grid-template-columns: repeat(2, minmax(0, 1fr)); } #settings-container .jpx-control-appearance-body { grid-template-columns: minmax(0, 1fr); } } @container (max-width: 479px) { #settings-container .jpx-control-panel-editor { grid-template-columns: minmax(0, 1fr); gap: 12px; } } #settings-container .jpx-settings-group { grid-column: 1 / -1; } #settings-container .jpx-settings-group-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 18px; } #settings-container .jpx-settings-group-fields > .field-block { min-width: 0; margin: 0; } #settings-container .jpx-settings-group-fields > [data-field-type=array], #settings-container .jpx-settings-group-fields > [data-field-type=fieldPicker], #settings-container .jpx-settings-group-fields > [data-field-key=ctrlWidgetStyleText] { grid-column: 1 / -1; } #settings-container .field-block[data-field-type=boolean] > label { display: inline-flex; align-items: flex-start; gap: 4px; max-width: 100%; } #settings-container .field-block[data-field-type=boolean] > label > input { flex: none; margin: 3px 0 0; } #settings-container .jpx-field-help { margin: 3px 0 0 24px; color: #79604f; font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; } #settings-container .jpx-settings-group .heading { margin-top: 12px; font-size: inherit; } #settings-container .jpx-settings-group:first-child .heading { margin-top: 0; } #settings-container button.jpx-delete-button { color: #b42328; } #settings-container button.jpx-delete-button:hover { color: #8f151b; background: #f7ddd6; border-color: #b42328; } #settings-container .jpx-delete-button svg, #settings-container .jpx-history-buttons svg { width: 14px; height: 14px; vertical-align: middle; flex: none; } #settings-container .jpx-history-buttons { display: flex; gap: 6px; margin-right: auto; } #settings-container .jpx-history-buttons button { display: inline-flex; gap: 5px; align-items: center; min-height: 30px; padding: 4px 8px; } #settings-container .jpx-history-buttons button:disabled { opacity: .45; cursor: default; } #settings-container .field-block { margin: 0 0 7px; } #settings-container .heading { margin: 14px 0 6px; padding: 5px 8px; border-bottom: 1px solid rgb(92 13 17 / 28%); background: #eddbb2; color: #5c0d11; font-weight: 700; text-align: left; } #settings-container .array-row:not(.array-row .array-row) { margin: 5px 0; padding: 6px 4px; border: 0; border-bottom: 1px solid rgb(92 13 17 / 18%); background: transparent; } #settings-container .jpx-rule-array-item { display: block; min-width: 0; content-visibility:auto; contain-intrinsic-block-size:auto 44px; } #settings-container .jpx-rule-array-item:has(.jpx-rule-item[open]) { contain-intrinsic-block-size:auto 224px; } #settings-container .jpx-rule-array-item:has(.multiSelect-summary[aria-expanded=true]), #settings-container .jpx-rule-item-body:has(.multiSelect-summary[aria-expanded=true]) { content-visibility:visible; } #settings-container .array-row.jpx-rule-array-item:not(.array-row .array-row) { margin:0; padding:2px 4px; } #settings-container .jpx-rule-item { min-width: 0; } #settings-container .jpx-rule-item > summary { display: grid; grid-template-columns: 26px 5px minmax(0, 1fr) auto; min-width: 0; min-height: 44px; align-items: center; gap: 4px 6px; cursor: pointer; list-style: none; } #settings-container .jpx-rule-item > summary::-webkit-details-marker { display: none; } #settings-container .jpx-rule-item > summary::before { grid-column: 2; grid-row: 1; width: 0; height: 0; flex: none; border-top: 4px solid transparent; border-bottom: 4px solid transparent; border-left: 5px solid #5c0d11; transition: transform var(--jpx-motion) ease-out; content: ''; } #settings-container .jpx-rule-item[open] > summary::before { transform: rotate(90deg); } #settings-container .jpx-rule-summary-text { grid-column: 3; grid-row: 1; min-width: 0; } #settings-container .jpx-rule-item > summary > .drag-handle { grid-column: 1; grid-row: 1; } #settings-container .jpx-rule-item > summary > .jpx-array-item-actions { grid-column: 4; grid-row: 1; } #settings-container .jpx-rule-summary-heading { display: flex; min-width: 0; align-items: center; gap: 8px; } /* Keep the summary and actions stationary throughout disclosure. */ ${jpxDisclosureCSS('#settings-container .jpx-rule-item')} @supports (interpolate-size: allow-keywords) and selector(details::details-content) { #settings-container .jpx-rule-item:has(.multiSelect-summary[aria-expanded=true])::details-content { overflow: visible; } } #settings-container .jpx-rule-item-name { min-width: 0; overflow-wrap: anywhere; font-weight: 700; line-height:1.5; } #settings-container .jpx-rule-item-preview { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #71634f; font-size: 11px; line-height: 18px; } #settings-container .jpx-rule-item-preview:empty { display:none; } #settings-container .jpx-rule-item[open] > summary { background:var(--jpx-theme-hover,#f1e2c5); } #settings-container .jpx-keybinding-header { flex-wrap: wrap; gap: 6px; } #settings-container .jpx-rule-list-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding-top: 2px; padding-bottom: 2px; } #settings-container .jpx-rule-list-toolbar { display: flex; flex: none; align-items: center; justify-content: flex-end; margin: 0 0 0 auto; padding: 0; border: 0; } #settings-container .jpx-keybinding-header > .jpx-rule-list-toolbar { margin: 0 0 0 auto; padding: 0; border-bottom: 0; } #settings-container .jpx-rule-list-heading .jpx-rule-list-toggle { min-height: 25px; padding: 2px 6px; border-color: transparent; background: transparent; } #settings-container .jpx-rule-list-heading .jpx-rule-list-toggle:hover { border-color: rgb(92 13 17 / 25%); background: #f4e5c4; } #settings-container .jpx-rule-list-toggle { display: inline-flex; min-height: 30px; align-items: center; gap: 5px; padding: 3px 8px; font-size: 11px; } #settings-container .jpx-rule-list-toggle svg { width: 14px; height: 14px; } #settings-container .jpx-sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; } #settings-container .jpx-rule-item > summary:focus-visible { outline: none; box-shadow: inset 0 0 0 1px #9b4e03; background: rgb(244 229 196 / 70%); } #settings-container .jpx-rule-array-item.is-disabled .jpx-rule-summary-text { opacity: .65; } #settings-container .jpx-rule-array-item.is-disabled .jpx-rule-item-name { text-decoration:line-through; } #settings-container .jpx-rule-array-item.is-dragging { z-index: 2; opacity: .25; outline: 1px dashed #9b4e03; background: #f4e5c4; box-shadow: inset 0 0 0 1px rgb(155 78 3 / 25%); } #settings-container .jpx-rule-array-item.is-drop-before { box-shadow: inset 0 3px #9b4e03; background: #f4e5c4; } #settings-container .jpx-rule-array-item.is-drop-after { box-shadow: inset 0 -3px #9b4e03; background: #f4e5c4; } #settings-container .jpx-rule-drag-layer { position: fixed; z-index: 10000; overflow: hidden; pointer-events: none; } #settings-container .jpx-rule-drop-marker { position: absolute; z-index: 2; height: 3px; background: #9b4e03; box-shadow: 0 0 0 1px rgb(244 229 196 / 75%); pointer-events: none; } #settings-container .jpx-rule-drop-marker.over-preview { background: transparent; box-shadow: none; } #settings-container .jpx-rule-drop-marker::before, #settings-container .jpx-rule-drop-marker::after { content: ''; position: absolute; top: -3px; border-top: 4px solid transparent; border-bottom: 4px solid transparent; } #settings-container .jpx-rule-drop-marker::before { left: 0; border-left: 6px solid #9b4e03; } #settings-container .jpx-rule-drop-marker::after { right: 0; border-right: 6px solid #9b4e03; } #settings-container .jpx-rule-drag-image { position: absolute; top: 0; left: 0; z-index: 1; display: block; box-sizing: border-box; margin: 0; padding: 6px 10px; border: 1px solid #9b4e03; background: #f4e5c4; box-shadow: 0 4px 10px rgb(36 18 15 / 20%); opacity: 1; pointer-events: none; } #settings-container .jpx-rule-drag-label { display: block; width: min(calc(100% - var(--jpx-drag-label-x)), var(--jpx-drag-label-width)); margin-left: calc(var(--jpx-drag-label-x) - 11px); } #settings-container .jpx-rule-drag-grip { position: absolute; top: calc(var(--jpx-drag-handle-y) - 16px); left: calc(var(--jpx-drag-handle-x) - 14px); } #settings-container button.jpx-drag-grip, #settings-container .jpx-drag-grip { display: inline-flex; box-sizing: border-box; flex: none; align-items: center; justify-content: center; width: 26px; min-width: 26px; height: 30px; min-height: 30px; padding: 0; border: 1px solid transparent; border-radius: 2px; background: transparent; color: #8c6551; cursor: grab; touch-action: none; user-select: none; } #settings-container .jpx-drag-grip svg { width: 18px; height: 18px; } #settings-container button.jpx-drag-grip:hover, #settings-container .jpx-drag-grip:hover, #settings-container .jpx-drag-grip:focus-visible { color: #5c0d11; border-color: rgb(92 13 17 / 28%); background: #f4e5c4; } #settings-container .jpx-drag-grip:active { cursor: grabbing; } #settings-container .jpx-rule-array-item .drag-handle { cursor: grab; touch-action: none; user-select: none; } #settings-container .jpx-rule-array-item.is-dragging .drag-handle { cursor: grabbing; } #settings-container .jpx-rule-item-body { padding: 5px 0 3px 13px; border-top: 1px solid rgb(92 13 17 / 15%); content-visibility:auto; contain-intrinsic-block-size:auto 180px; } #settings-container .jpx-rule-item-body > .field-block:first-child[data-field-type=constant] { display: none; } #settings-container .jpx-array-item-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 2px; } #settings-container .jpx-array-item-actions svg { width: 14px; height: 14px; vertical-align: middle; } #settings-container .jpx-rule-state-toggle { display: inline-flex; align-items: center; justify-content: center; } #settings-container .jpx-rule-state-toggle[data-enabled=false] { color: #71634f; } #settings-container .jpx-rule-state-toggle svg { width: 16px; height: 16px; } #settings-container [data-change-state] { --jpx-change-color: #975000; --jpx-change-bg: #f5ebd5; } #settings-container [data-change-state=added] { --jpx-change-color: #39633b; --jpx-change-bg: #e7eddf; } html[data-jpx-theme=dark] #settings-container [data-change-state] { --jpx-change-color: var(--jpx-theme-accent); --jpx-change-bg: var(--jpx-theme-selected); } html[data-jpx-theme=dark] #settings-container [data-change-state=added] { --jpx-change-color: #a4cfaa; --jpx-change-bg: #293a2d; } #settings-container .field-block[data-change-state], #settings-container .array-row[data-change-state]:not(.is-drop-before, .is-drop-after, .is-dragging), #settings-container .dynamic-array-row[data-change-state], #settings-container .jpx-keybindings-settings > [data-change-state], #settings-container .jpx-stats-edit-field[data-change-state] { background-color: var(--jpx-change-bg); box-shadow: inset 3px 0 var(--jpx-change-color); } #settings-container .field-block[data-change-state], #settings-container .jpx-keybindings-settings > [data-change-state], #settings-container .jpx-stats-edit-field[data-change-state] { border-radius: 2px; box-shadow: none; } #settings-container .field-block[data-field-type=array][data-change-state], #settings-container .field-block[data-field-type=conditionsArray][data-change-state], #settings-container .field-block[data-field-type=keyBasedObjectArray][data-change-state] { background: transparent; box-shadow: none; } #settings-container .jpx-stats-list .jpx-stats-row[data-change-state]:not(.is-drop-before, .is-drop-after, .is-dragging) > .jpx-stats-select { box-shadow: inset 3px 0 var(--jpx-change-color); } #settings-container .field-block[data-field-type=array][data-change-state] > div:first-child, #settings-container .field-block[data-field-type=keyBasedObjectArray][data-change-state] > div:first-child, #settings-container [data-change-state] > .jpx-keybinding-header { color: var(--jpx-change-color); border-bottom-color: var(--jpx-change-color); background-color: var(--jpx-change-bg); } #settings-container .field-block[data-field-type=conditionsArray][data-change-state] > button, #settings-container .jpx-stats-nav button[data-change-state] { color: var(--jpx-change-color); border-bottom-color: var(--jpx-change-color); } #settings-container .jpx-stats-row-label { flex: 1; } #settings-container .jpx-rule-array-item .jpx-array-item-actions button, #settings-container .jpx-stats-row .jpx-array-item-actions button { width: 27px; min-width: 27px; min-height: 27px; padding: 2px; } #settings-container .jpx-rule-item > summary > .jpx-array-item-actions { flex-wrap:nowrap; gap:0; } #settings-container .jpx-rule-item > summary > .jpx-array-item-actions > button { width:32px; min-width:32px; min-height:32px; border:0; border-radius:0; background:transparent; } #settings-container .jpx-rule-item > summary > .jpx-array-item-actions > button:hover { background:var(--jpx-theme-selected,#ead8b4); } #settings-container.jpx-settings-mobile .jpx-rule-item > summary { grid-template-columns:44px 5px minmax(0,1fr) auto; gap:4px; } #settings-container.jpx-settings-mobile .jpx-rule-item > summary > .drag-handle { width:44px; min-width:44px; min-height:44px; } #settings-container.jpx-settings-mobile .jpx-rule-item > summary > .jpx-array-item-actions > button { width:44px; min-width:44px; min-height:44px; } #settings-container .jpx-rule-sort-actions { display: inline-flex; gap: 0; margin-right: 5px; } #settings-container .jpx-rule-sort-actions > button { border-radius: 0; } #settings-container .jpx-rule-sort-actions > button + button { margin-left: -1px; } #settings-container .jpx-rule-sort-actions > button:first-child { border-radius: 2px 0 0 2px; } #settings-container .jpx-rule-sort-actions > button:last-child { border-radius: 0 2px 2px 0; } #settings-container .jpx-rule-sort-popover { position: fixed; inset: auto; box-sizing: border-box; margin: 0; padding: 10px; width: max-content; max-width: calc(100vw - 24px); border: 1px solid #5c0d11; background: #edebdf; color: #5c0d11; box-shadow: 0 4px 12px rgb(36 18 15 / 18%); } #settings-container .jpx-rule-sort-popover label { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; } #settings-container .jpx-rule-sort-popover input { width: 7ch; min-width: 7ch; } #settings-container .jpx-rule-sort-presets { display: flex; gap: 6px; margin-top: 8px; } #settings-container .dynamic-array-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: start; gap: 6px 8px; margin: 8px 0 !important; padding: 8px; border: 1px solid rgb(92 13 17 / 22%); border-left: 2px solid #9b4e03; background: #f4f1e5; } #settings-container .dynamic-array-row > div { min-width: 0; max-width: 100%; margin-left: 0 !important; } #settings-container .dynamic-array-row > select { grid-column: 1; grid-row: 1; justify-self: start; max-width: 100%; } #settings-container .dynamic-array-row > button { grid-column: 2; grid-row: 1; min-width: 28px; min-height: 28px; margin: 0 !important; } #settings-container .dynamic-array-row > .jpx-condition-value, #settings-container .dynamic-array-row > .jpx-condition-extra { grid-column: 1 / -1; } #settings-container .jpx-condition-value { display: flex; flex-wrap: wrap; align-items: center; } #settings-container .jpx-condition-extra { display: flex; flex-wrap: wrap; gap: 6px 12px; padding-top: 6px; border-top: 1px solid rgb(92 13 17 / 16%); } #settings-container .jpx-condition-extra:empty { display: none; } #settings-container .jpx-range { display: inline-flex; max-width: 100%; align-items: center; flex-wrap: wrap; gap: 4px 6px; } #settings-container .jpx-range-inputs { display: inline-flex; align-items: center; gap: 4px; min-width: 0; max-width: 100%; } #settings-container .jpx-range-inputs input { min-width: 7ch; max-width: min(18ch, calc((100% - 24px) / 2)); } #settings-container .multiSelect-popup { position: relative; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; width: 100%; min-width: 0; max-width: 100%; } #settings-container .multiSelect-summary { display: inline-flex; align-items: center; gap: 8px; width: max-content; min-width: 0; max-width: 100%; background: #f9f6ec; text-align: left; } #settings-container .multiSelect-value { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #settings-container .multiSelect-summary::after { content: ''; flex: none; width: 5px; height: 5px; margin: -3px 2px 0; border-right: 1px solid currentColor; border-bottom: 1px solid currentColor; transform: rotate(45deg); } #settings-container .multiSelect-popup-panel { position: absolute; top: 100%; left: 0; z-index: 20; box-sizing: border-box; width: max-content; min-width: min(180px, 100%); max-width: 100%; max-height: min(280px, 50dvh); padding: 4px; overflow: auto; border: 1px solid #5c0d11; border-radius: 2px; background: #edebdf; box-shadow: 0 5px 14px rgb(36 18 15 / 18%); scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } #settings-container .multiSelect-popup-panel > span { display: flex !important; align-items: center; gap: 6px; margin: 0 !important; padding: 5px 6px; border-bottom: 1px solid rgb(92 13 17 / 12%); } #settings-container .multiSelect-popup-panel > span:has(input:checked) { background: #eddbb2; } #settings-container .multiSelect-popup-panel > span:hover { background: #f4e5c4; } #settings-container #cfgStats-ui, #settings-container .jpx-config-stats-editor { --stats-ink: #5c0d11; --stats-muted: #71634f; --stats-border: rgb(92 13 17 / 24%); --stats-surface: #f9f6ec; } #settings-container #cfgStats-ui { display: block; } #settings-container #cfgStats-ui [hidden] { display: none !important; } #settings-container .jpx-stats-nav { display: flex; flex-wrap: wrap; gap: 0; margin: 0 0 14px; border-bottom: 1px solid rgb(92 13 17 / 28%); } #settings-container .jpx-stats-nav button { min-height: 32px; margin: 0; padding: 6px 12px 7px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: #71634f; } #settings-container .jpx-stats-nav button[aria-pressed=true] { border-bottom-color: #5c0d11; background: transparent; color: #5c0d11; } #settings-container .jpx-stats-help { margin: 4px 0 10px; color: #71634f; font-size: 12px; overflow-wrap: anywhere; } #settings-container #panel_stats, #settings-container .jpx-config-stats-editor { container: jpx-stats / inline-size; } #settings-container .jpx-stats-picker { display: grid; grid-template-columns: minmax(240px, .9fr) minmax(0, 1.1fr); grid-template-areas: 'selected editor'; gap: 12px 16px; align-items: start; } #settings-container .jpx-stats-picker > div { min-width: 0; align-self: start; } #settings-container .jpx-stats-selected-pane { grid-area: selected; } #settings-container .jpx-stats-pane { min-width: 0; } #settings-container .jpx-stats-pane-heading { display: flex; min-height: 31px; align-items: center; gap: 8px; border-bottom: 1px solid rgb(92 13 17 / 24%); } #settings-container .jpx-stats-pane-heading > strong:first-child { color: #5c0d11; } #settings-container .jpx-stats-pane-count { margin-left: auto; color: #71634f; font-size: 11px; } #settings-container .jpx-stats-row > .jpx-array-item-actions, #settings-container .jpx-stats-drag-preview > .jpx-array-item-actions { position: absolute; inset: 0 4px 0 auto; flex-wrap: nowrap; pointer-events: none; } #settings-container .jpx-stats-row > .jpx-array-item-actions button { pointer-events: auto; } #settings-container .jpx-stats-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin: 6px 0; } #settings-container .jpx-stats-list { max-height: clamp(240px, calc(100dvh - 360px), 440px); overflow: auto; overscroll-behavior: contain; border: 1px solid var(--stats-border); background: var(--stats-surface); scrollbar-width: thin; scrollbar-color: #5c0d11 #e3e0d1; } #settings-container .jpx-stats-row { position: relative; display: flex; align-items: center; gap: 4px; min-height: 38px; border-bottom: 1px solid rgb(92 13 17 / 12%); } #settings-container button.jpx-stats-select { display: flex; flex: 1; min-width: 0; align-items: center; gap: 4px; align-self: stretch; padding: 3px 95px 3px 3px; border: 0; border-radius: 0; background: transparent; text-align: left; } #settings-container .jpx-stats-row:hover > button.jpx-stats-select { background: #fff; } #settings-container .jpx-stats-row > button.jpx-stats-select[aria-pressed=true] { background: #eddbb2; box-shadow: inset 3px 0 #5c0d11; } #settings-container .jpx-stats-row-label { min-width: 0; overflow-wrap: anywhere; } #settings-container .jpx-stats-row[data-enabled=false] .jpx-stats-row-label { opacity: .55; } #settings-container .jpx-stats-list .is-dragging { opacity: .35; cursor: grabbing; } #settings-container .jpx-stats-list .is-drop-before { box-shadow: inset 0 3px #9b4e03; } #settings-container .jpx-stats-list .is-drop-after { box-shadow: inset 0 -3px #9b4e03; } #settings-container .jpx-stats-drag-layer { position: fixed; z-index: 10000; overflow: hidden; pointer-events: none; } #settings-container .jpx-stats-drag-preview { position: absolute; box-sizing: border-box; display: flex; align-items: center; gap: 4px; background: #f4e5c4; border-bottom: 1px solid transparent; box-shadow: inset 0 0 0 1px #9b4e03, 0 3px 8px rgb(36 18 15 / 20%); } #settings-container .jpx-stats-drop-marker { position: absolute; z-index: 1; left: 0; right: 0; height: 3px; background: #9b4e03; } #settings-container .jpx-stats-drop-marker.over-preview { background: transparent; border-left: 5px solid #9b4e03; border-right: 5px solid #9b4e03; } #settings-container .jpx-stats-list button:focus-visible { outline: 1px solid #9b4e03; outline-offset: -1px; } #settings-container .jpx-stats-edit { grid-area: editor; position: sticky; top: 0; min-width: 0; padding-left: 16px; border-left: 1px solid var(--stats-border); } #settings-container .jpx-stats-edit-title { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin: 0 0 10px; padding: 5px 0 7px; border-bottom: 1px solid var(--stats-border); color: #5c0d11; overflow-wrap: anywhere; } #settings-container .jpx-stats-edit-title:has(.jpx-stats-name-edit) { flex-wrap: nowrap; gap: 4px; } #settings-container .jpx-stats-edit-title > strong { min-width: 0; } #settings-container .jpx-stats-edit-title input.jpx-stats-name-input { flex: 1; width: 0; min-height: 28px; } #settings-container button.jpx-stats-name-edit { display: inline-flex; flex: none; align-items: center; justify-content: center; width: 20px; min-height: 22px; padding: 3px; border: 0; border-radius: 2px; background: transparent; color: var(--stats-muted); } #settings-container button.jpx-stats-name-edit:hover, #settings-container button.jpx-stats-name-edit[aria-expanded=true] { background: #e3e0d1; color: var(--stats-ink); } #settings-container .jpx-stats-name-edit svg { width: 12px; height: 12px; } #settings-container .jpx-stats-name-edit:focus-visible { outline: 2px solid var(--stats-ink); outline-offset: 2px; } #settings-container .jpx-stats-edit-field { display: grid; grid-template-columns: 8.5em minmax(0, 1fr); align-items: center; gap: 4px; margin: 0; } #settings-container .jpx-stats-edit-field > label { white-space: nowrap; } #settings-container .jpx-stats-edit input { width: 100%; field-sizing: fixed; min-width: 0; max-width: 100%; } #settings-container .jpx-stats-style-fields { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; } #settings-container .jpx-stats-edit-group { display: grid; min-width: 0; gap: 6px; margin: 0; padding: 0 0 12px; border: 0; border-bottom: 1px solid var(--stats-border); } #settings-container .jpx-stats-edit-group legend { padding: 0 0 6px; color: #71634f; font-weight: 700; } #settings-container .jpx-stats-edit input[data-style-field] { font: 12px/1.5 Consolas, monospace; } #settings-container .jpx-stats-style-control { display: flex; align-items: center; gap: 4px; min-width: 0; } #settings-container .jpx-stats-style-control > input[type=text] { flex: 1; width: 0; } #settings-container .jpx-stats-edit-field:has(.jpx-stats-palette), #settings-container .jpx-stats-color-heading { display: grid; grid-template-columns: minmax(0, 1fr) minmax(196px, 2fr); align-items: center; gap: 4px; } #settings-container .jpx-stats-edit-field:has(.jpx-stats-palette) > label { white-space: normal; overflow-wrap: anywhere; } #settings-container .jpx-stats-style-control:has(.jpx-stats-palette) { display: block; } #settings-container .jpx-stats-palette { display: grid; grid-template-columns: 68px 68px minmax(44px, 1fr); align-items: center; gap: 8px; min-width: 0; } /* Align column headings with the editable rows at every width. */ #settings-container .jpx-stats-color-heading { margin-bottom: 6px; color: var(--stats-muted); } #settings-container .jpx-stats-color-heading > div { display: grid; grid-template-columns: 68px 68px minmax(44px, 1fr); gap: 8px; text-align: center; font-size: 11px; } #settings-container .jpx-stats-color { display: flex; align-items: center; gap: 8px; min-width: 0; } #settings-container .jpx-stats-color input[type=color] { margin: 0; } #settings-container .jpx-stats-color input[type=color] { width: 32px; height: 26px; min-height: 26px; padding: 1px; border: 1px solid var(--stats-border); background: #fff; cursor: pointer; } #settings-container .jpx-stats-color input[data-default=true] { border-style: dashed; } #settings-container .jpx-stats-preview { min-width: 0; } #settings-container .jpx-stats-preview-sample { display: block; min-width: 44px; padding: 3px 4px; box-sizing: border-box; border: 1px solid var(--stats-border); background: #edebdf; color: #5c0d11; font: 12px/18px Verdana, sans-serif; text-align: center; } #settings-container .jpx-stats-thresholds { margin-top: 12px; } #settings-container .jpx-stats-threshold-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; } #settings-container .jpx-stats-threshold-heading button { min-height: 26px; padding: 2px 6px; } #settings-container .jpx-stats-threshold-list { display: grid; gap: 6px; max-height: 200px; overflow: auto; margin-top: 6px; } #settings-container .jpx-stats-threshold-row { display: grid; grid-template-columns: auto minmax(52px, 1fr) auto 32px 24px; align-items: center; gap: 6px; } #settings-container .jpx-stats-threshold-row > label { font-size: 12px; } #settings-container .jpx-stats-threshold-row input[type=color] { width: 32px; height: 28px; min-height: 28px; padding: 1px; border: 1px solid var(--stats-border); background: #fff; cursor: pointer; } #settings-container .jpx-stats-threshold-row button { min-height: 28px; min-width: 24px; padding: 0; border: 0; background: transparent; } #settings-container .jpx-stats-threshold-row:has(.jpx-stats-threshold-legacy) { grid-template-columns: minmax(0, 1fr) 24px; } #settings-container .jpx-stats-threshold-legacy { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 12px/1.5 Consolas, monospace; } #settings-container .jpx-stats-threshold-note { margin: 6px 0; font-size: 11px; color: var(--stats-muted); } #settings-container .jpx-stats-threshold-preview { margin-top: 8px; font-size: 12px; } #settings-container .jpx-stats-threshold-preview summary { cursor: pointer; color: var(--stats-muted); } #settings-container .jpx-stats-threshold-preview-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 6px; } #settings-container .jpx-stats-threshold-preview input { width: 80px; } #settings-container .jpx-stats-threshold-match { flex-basis: 100%; font-size: 11px; color: var(--stats-muted); } #settings-container .jpx-stats-color input:focus-visible, #settings-container .jpx-stats-style-control button:focus-visible { outline: 2px solid var(--stats-ink); outline-offset: 2px; } #settings-container .jpx-stats-transfer { margin-top: 12px; padding: 12px; border: 1px solid rgb(92 13 17 / 28%); background: #f4f1e5; overflow-wrap: anywhere; } #settings-container .jpx-stats-transfer select { max-width: 100%; } @container jpx-stats (max-width: 540px) { #settings-container .jpx-stats-nav { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-bottom: 10px; } #settings-container .jpx-stats-nav button { min-width: 0; padding: 8px 2px; line-height: 1.35; white-space: normal; overflow-wrap: anywhere; } #settings-container .jpx-stats-picker { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'selected' 'editor'; } #settings-container .jpx-stats-edit { position: static; padding-left: 0; border-top: 1px solid var(--stats-border); border-left: 0; padding-top: 8px; } #settings-container .jpx-stats-list { max-height: 220px; } #settings-container .jpx-stats-style-fields { grid-template-columns: minmax(0, 1fr); } } @container jpx-stats (max-width: 360px) { #settings-container .jpx-stats-nav button { font-size: 13px; } } @container jpx-settings (max-width: 600px) { #settings-container .jpx-rule-section-tabs > button { padding: 5px 6px; font-size: 12px; } #settings-container .jpx-rule-section-controls .jpx-rule-list-toggle { font-size: 11px; gap: 4px; } #settings-container #cfgBattle-ui, #settings-container #cfgStats-ui { grid-template-columns: minmax(0, 1fr); } #settings-container #cfgBattle-ui > .field-block, #settings-container #cfgStats-ui > .field-block { grid-column: 1; } #settings-container #cfgBattle-ui > [data-role=battleMode], #settings-container #cfgBattle-ui > .field-block[data-field-key=ctrlWidgetRows], #settings-container #cfgStats-ui > .field-block[data-field-type=fieldPicker] { grid-column: 1; } #settings-container .jpx-settings-group-fields { grid-template-columns: minmax(0, 1fr); } } #settings-container.jpx-settings-mobile { inset: var(--settings-top) auto auto var(--settings-left); width: var(--settings-width); height: var(--settings-height); max-width: none; max-height: none; margin: 0; padding: 0; border: 0; border-radius: 0; box-shadow: none; transform: scale(var(--settings-scale)); transform-origin: top left; font-size: 14px; } #settings-container.jpx-settings-mobile .jpx-settings-window { border: 0; } #settings-container.jpx-settings-mobile .jpx-settings-titlebar { flex: none; min-height: 44px; justify-content: flex-start; gap: 12px; padding: env(safe-area-inset-top, 0px) 10px 0; } #settings-container #jpx-theme-toggle { display: inline-flex; align-items: center; justify-content: center; gap: 6px; width: auto; min-width: 64px; height: 32px; margin-left: auto; margin-right: 8px; padding: 4px 8px; border: 1px solid #c8b49b; border-radius: 6px; background: #f9f6ec; font: 13px/1.4 Arial, sans-serif; } #settings-container #jpx-theme-toggle::before { content: ''; width: 12px; height: 12px; border: 1px solid currentColor; border-radius: 50%; background: linear-gradient(90deg, currentColor 50%, transparent 50%); } #settings-container.jpx-settings-mobile #jpx-theme-toggle { height: 40px; } html[data-jpx-theme=dark] :is(#settings-container, .jpx-records-page, .jpx-record-detail, .jpx-record-final) { color-scheme: dark; color: var(--jpx-theme-text); } html[data-jpx-theme=dark] #settings-container :is(input:not([type=color]):not([type=checkbox]):not([type=range]), select, textarea) { background-color: var(--jpx-theme-field); color: var(--jpx-theme-text); border-color: var(--jpx-theme-border); } html[data-jpx-theme=dark] #settings-container .jpx-rule-item { color: var(--jpx-theme-text); } html[data-jpx-theme=dark] #settings-container button.jpx-delete-button { color: #ff9295; } html[data-jpx-theme=dark] #settings-container button.jpx-delete-button:hover { color: #ffb4b6; background: #493034; border-color: #bb6c71; } html[data-jpx-theme=dark] .effect-duration > div { color: var(--jpx-theme-text); border-color: var(--jpx-theme-border); } html[data-jpx-theme=dark] .effect-duration > div[style*="aquamarine"] { background: #25483d !important; color: #b4efd4; } html[data-jpx-theme=dark] .effect-duration > div[style*="lavender"] { background: #3e3555 !important; color: #e3d4ff; } html[data-jpx-theme=dark] #settings-container .settings-tab-btn:hover, html[data-jpx-theme=dark] #settings-container .jpx-settings-sidebar-toggle:hover { background: var(--jpx-theme-hover) !important; } #settings-container #jpx-settings-menu-button { display: none; } #settings-container.jpx-settings-mobile #close-button { order: -1; width: auto; min-width: 64px; height: 40px; padding: 0 6px; font-size: 14px; } #settings-container.jpx-settings-mobile #jpx-settings-menu-button { display: inline-flex; margin-left: 0; width: 40px; height: 40px; align-items: center; justify-content: center; } #settings-container #jpx-settings-menu-button svg { width: 20px; height: 20px; } #settings-container.jpx-settings-mobile .jpx-settings-workspace { position: relative; flex-direction: column; } #settings-container.jpx-settings-mobile .jpx-settings-workspace .jpx-settings-sidebar { display: flex; position: absolute; z-index: 2; inset: 6px 10px auto auto; box-sizing: border-box; width: max-content; max-width: calc(100% - 20px); max-height: calc(100% - 12px); padding: 3px; border: 1px solid #bda68e; border-radius: 3px; box-shadow: 0 3px 8px #0002; opacity: 0; visibility: hidden; pointer-events: none; transition: opacity var(--jpx-motion-fast) ease-out, visibility 0s var(--jpx-motion-fast); } #settings-container.jpx-settings-mobile.jpx-settings-navigation-open .jpx-settings-sidebar { opacity: 1; visibility: visible; pointer-events: auto; transition-delay: 0s; } #settings-container.jpx-settings-mobile .jpx-settings-sidebar-toggle { display: none; } #settings-container.jpx-settings-mobile .settings-tab-header { display: flex; flex-direction: column; overflow: auto; border: 0; } #settings-container.jpx-settings-mobile .settings-tab-btn { display: flex; width: 100%; min-width: 0; min-height: 40px; justify-content: flex-start; gap: 8px; padding: 6px 10px !important; border: 0 !important; text-align: left; font-size: 14px; line-height: 1.4; } #settings-container.jpx-settings-mobile .settings-tab-btn > svg { display: block; } #settings-container.jpx-settings-mobile .settings-tab-btn .jpx-tab-label { display: block; overflow: visible; opacity: 1; translate: 0; visibility: visible; transition: none; } #settings-container.jpx-settings-mobile .settings-tab-btn[aria-selected=true] { box-shadow: inset 3px 0 #5c0d11 !important; } #settings-container.jpx-settings-mobile [role=tabpanel] { padding: 12px 10px; overscroll-behavior-y: contain; } #settings-container.jpx-settings-mobile .jpx-settings-footer { flex-wrap: nowrap; min-height: 0; gap: 8px; padding: 6px 10px max(6px, env(safe-area-inset-bottom, 0px)); } #settings-container.jpx-settings-mobile .jpx-settings-file-actions { flex: 1; flex-wrap: nowrap; gap: 6px; } #settings-container.jpx-settings-mobile .jpx-settings-footer button { min-width: 40px; min-height: 40px; padding: 5px 6px; white-space: nowrap; } #settings-container.jpx-settings-mobile .jpx-settings-file-actions button { min-width: 64px; padding-inline: 4px; font-size: 12px; } #settings-container.jpx-settings-mobile .jpx-history-buttons { gap: 4px; } #settings-container.jpx-settings-mobile .jpx-history-buttons button { justify-content: center; } #settings-container.jpx-settings-mobile .jpx-history-label { display: none; } #settings-container.jpx-settings-mobile .jpx-history-buttons svg { width: 18px; height: 18px; } #settings-container.jpx-settings-mobile :is(input:where(:not([type=checkbox]):not([type=radio]):not([type=color]):not([type=range])), select, textarea) { font-size: inherit; min-height: 30px; padding: 3px 6px; } #settings-container.jpx-settings-mobile .jpx-rule-item-body .dynamic-array-row { margin: 6px 0 !important; padding: 6px; gap: 4px 8px; } #settings-container.jpx-settings-mobile .jpx-rule-item-body .dynamic-array-row > button { width: 30px; min-width: 30px; min-height: 30px; padding: 3px; } #settings-container.jpx-settings-mobile .jpx-rule-item-body .field-block[data-field-type=conditionsArray] > button { min-height: 30px; padding: 3px 6px; } #settings-container.jpx-settings-mobile .jpx-rule-item-body .multiSelect-summary { min-height: 30px; padding: 3px 6px; } /* Firefox uses touch-action to opt out of focus autozoom (Mozilla bug 1746126). Keep native scrolling and pinch zoom available on editable fields. */ #settings-container.jpx-settings-mobile input:is(:not([type]), [type=text], [type=number], [type=search], [type=email], [type=url], [type=tel], [type=password]), #settings-container.jpx-settings-mobile textarea { touch-action: manipulation; } #settings-container.jpx-settings-mobile input[type=color] { min-width: 32px; } #settings-container.jpx-settings-mobile .jpx-stats-edit-field:has(.jpx-stats-palette), #settings-container.jpx-settings-mobile .jpx-stats-color-heading { grid-template-columns: minmax(0, 1fr) minmax(188px, 2fr); align-items: center; } #settings-container.jpx-settings-mobile .jpx-stats-edit-field:has(.jpx-stats-palette) > label { padding-top: 0; white-space: normal; overflow-wrap: anywhere; } #settings-container.jpx-settings-mobile .jpx-stats-palette, #settings-container.jpx-settings-mobile .jpx-stats-color-heading > div { grid-template-columns: 64px 64px minmax(44px, 1fr); } #settings-container.jpx-settings-mobile .jpx-stats-color { gap: 4px; } #settings-container.jpx-settings-mobile .jpx-stats-color input[type=color], #settings-container.jpx-settings-mobile .jpx-control-style input[type=color], #settings-container.jpx-settings-mobile button.jpx-appearance-reset { width: 32px; min-width: 32px; min-height: 32px; height: 32px; } #settings-container.jpx-settings-mobile .jpx-stats-color button.jpx-appearance-reset { width: 28px; min-width: 28px; padding: 4px; border: 0; } #settings-container.jpx-settings-mobile .jpx-stats-preview-sample { display: flex; align-items: center; justify-content: center; min-height: 32px; } #settings-container.jpx-settings-mobile .jpx-stats-edit-group { gap: 8px; padding-bottom: 8px; } #settings-container.jpx-settings-mobile button.jpx-appearance-reset-all { width: auto; height: auto; } #settings-container.jpx-settings-mobile .jpx-control-style-row { grid-template-columns: minmax(0, 1fr) 32px 32px; } #settings-container.jpx-settings-mobile .jpx-control-opacity-row { grid-template-columns: minmax(0, 1fr) auto 32px; } #settings-container.jpx-settings-mobile .jpx-control-preview-states button { min-height: 30px; min-width: 40px; } #settings-container.jpx-settings-mobile .jpx-stats-threshold-row { grid-template-columns: auto minmax(52px, 1fr) auto 32px 28px; } #settings-container.jpx-settings-mobile .jpx-stats-threshold-row:has(.jpx-stats-threshold-legacy) { grid-template-columns: minmax(0, 1fr) 24px; } #settings-container.jpx-settings-mobile .jpx-stats-transfer { padding: 8px; margin-top: 8px; } @keyframes jpx-settings-reveal { from { opacity: 0; translate: 0 -4px; } to { opacity: 1; translate: 0; } } @keyframes jpx-settings-fade { from { opacity: 0; } to { opacity: 1; } } #settings-container .jpx-config-confirm { animation: jpx-settings-reveal var(--jpx-motion-fast) ease-out; } #settings-container :is(.jpx-rule-context-menu:popover-open,.jpx-config-menu:popover-open,.jpx-rule-sort-popover:popover-open,.multiSelect-popup-panel) { animation: jpx-settings-fade var(--jpx-motion-fast) ease-out; } #settings-container :is(.jpx-config-overlay,.jpx-config-notice:not(:empty)) { animation: jpx-settings-fade var(--jpx-motion-fast) ease-out; } #settings-container :is(.settings-tab-btn,.jpx-config-nav>button,.jpx-rule-section-tabs>button) { transition: background-color var(--jpx-motion-fast), color var(--jpx-motion-fast), border-color var(--jpx-motion-fast); } @media (prefers-reduced-motion: reduce) { #settings-container.jpx-settings-dialog { --jpx-motion: 0ms; --jpx-motion-fast: 0ms; } } ${JPX_RECORD_DETAIL_CSS} `; } jpxPanelManager(); jpxMarket(); jpxUtils(); let doInitDoBattle = false; let isActiveBattle = false; // Weak keys release decorations when the game replaces an element on AJAX updates. const jpxBattleDecorations = new WeakMap(); const jpxHiddenEffectImages = new WeakSet(); function getBattleDecoration(owner, key, create) { let parts = jpxBattleDecorations.get(owner); if (!parts) jpxBattleDecorations.set(owner, parts = {}); return parts[key] ??= create(); } function setBattleText(node, value) { const text = String(value); if (node.textContent !== text) node.textContent = text; } function setBattleAttribute(node, name, value) { if (value == null) { if (node.hasAttribute(name)) node.removeAttribute(name); } else if (node.getAttribute(name) !== String(value)) node.setAttribute(name, String(value)); } let readyNext = 0; let lastActionTimestamp = Date.now(); let lastLogTimestamp = Date.now(); let battleLogObservedAt = null; let jpxBattleTiming = { samples: 0, intervalMs: null, queueMs: null, processingMs: null, visibility: null }; let prefix = 'jpx_'; let themeMode = readJpxTheme(); const themeDocuments = new Set(); const themeWindows = new WeakSet(); const cleanupKey = prefix + 'cleanupRequest'; const cleanupOwnerKey = prefix + 'cleanupOwner'; const cleanupHoldKey = prefix + 'cleanupHold'; let cleanupInProgress = false; let isekaiSuffix = document.URL.includes('isekai') ? '_isekai' : ''; let regExp = { locationQueries: /\w+=\w+/g, playerInfo: /(\w+) Lv\.(\d+)/, staminaInfo: /Stamina:\s(\d+)/, spellInfo: /\('([\w\s-]+)'.*, '(\w+)', (\d+), (\d+), (\d+)\)/, //Name, iconID, MP, OC, CD itemInfo: /set_infopane_item\((\d+)/, battleTypeLog: /Initializing (.*) \.\.\./, floor: /Floor (\d+)/, round: /Round (\d+) \/ (\d+)/, monster: /MID=(\d+) \(([^<>]+)\) \LV=(\d+) HP=(\d+)/g, effectGain: /([\w\s-]+) gains the effect ([\w\s-]+)\./g, effectExpired: /The effect ([\w\s-]+) on ([\w\s-]+) has expired\./g, effectWear: /The effect ([\w\s-]+) on ([\w\s-]+) has worn off\./g, effectWearAsleep: /([^<>]+) has been roused from its sleep\./g, effectWearConfused: /([^<>]+) got knocked out of confuse\./g, oc: /div/g, ocHalf: /vcr/g, spellMatch: /\('(?[\w\s-]+)(?:\s\(x(?\d+)\))?',\s?(?.*),\s?'?(?[\w\s-]+)'?\)/, //battleRecorder turnLog: /([^]+?)/, //timeRecorder action: />([^<>]+)<\/td><\/tr>(Spirit Stance Exhausted<\/td><\/tr>)*([^<>]+)<\/td><\/tr>[^<>]+<\/td><\/tr>(Spirit Stance Exhausted<\/td><\/tr>)*]+damage/g, damageTaken1: /(?glances|hits|crits) you.*?(?\d+).*?(?\w+) damage/, damageTaken2: /which (?glances|hits|crits).*?(?\d+).*?(?\w+) damage/, spiritShield: /absorbs (\d+)/, damageDealt1: /(?:You|Your offhand attack|Arcane Blow) (?:(?\d)x-)*(?glance|hit|crit).*?(?\d+).*?(?\w+) damage/, damageDealt2: /(?:(?\d)x-)*(?glanced|hit|crit|eviscerated) for (?\d+) (?\w+) damage/, strike: /(Fire|Cold|Wind|Elec|Holy|Dark|Void) Strike hits.*?(\d+).*?(\w+) damage/, explode: /explodes for (\d+) (\w+) damage/, damagePlus: /for (\d+) damage/, damagePhysicalPlus: /(Bleeding Wound|Spreading Poison)/, damagePoints: /for (\d+) points of (\w+) damage/, debuffLog: /(?:[^<>]+(?: gains the effect | partially resists the effects of your spell\.| shrugs off the effects of your spell\.)+[^<>]*<\/td><\/tr>)+You cast [a-zA-Z]+\.<\/td><\/tr>/, debuffResist0: / gains the effect (?!Coalesced Mana)/g, debuffResist1: / partially resists the effects of your spell\./g, debuffResist3: / shrugs off the effects of your spell\./g, counter: />You counter/g, // dealt magical magicalDealtMiss: / to connect\./g, magicalDealtEvade: / evades your spell\./g, magicalDealtResistPartially: / resists, and was/g, magicalDealtResist: / resists your spell\./g, // dealt physical physicalDealtMiss: / its mark\./g, physicalDealtEvade: / dodges your attack\./g, physicalDealtParryPartially: / parries[^<>]+?(\d+)[^<>]+?(\w+) damage/g, physicalDealtParry: / parries your attack\./g, // taken magical magicalTakenMiss: /(?:casts[^<>]+, but misses the attack\.|casts[^<>]+, missing you completely\.)/g, magicalTakenEvade: />You evade the attack\./g, magicalTakenResistPartially: / resist the attack/g, magicalTakenBlockPartially: /casts[^<>]+partially block (?:and|resist| )*the attack/g, magicalTakenBlock: /(?]+, but misses the attack\.|(?:vigorously whiffs at a shadow|uses[^<>]+), missing you completely\.)/g, physicalTakenEvade: />You evade the attack from/g, physicalTakenParryPartially: /partially parry the attack/g, physicalTakenParry: /(?]+|>)You|you) partially block (?:and|partially|parry| )*the attack/g, physicalTakenBlock: /(?]+ proficiency/g, proficiency: /(\d+\.\d+) points of ([^<>]+) proficiency/, dropsLogs: /\S+ \[[^<>]+\](<\/span><\/td><\/tr>A traveling)*/g, drop: /(\S+) \<.*#(.{6}).*\[(.*)\](.)*/, quality: /(Crude|Fair|Average|Superior|Exquisite|Magnificent|Legendary|Peerless)/, credit: /(\d+) Credit/, crystal: /(?:(\d+)x )?(Crystal of \w+)/, } const COMBAT_LOG_COUNTERS = Object.entries({ magicalDealt: ['miss', 'evade', 'resistPartially', 'resist'], physicalDealt: ['miss', 'evade', 'parryPartially', 'parry'], magicalTaken: ['miss', 'evade', 'blockPartially', 'block', 'resistPartially'], physicalTaken: ['miss', 'evade', 'parryPartially', 'parry', 'blockPartially', 'block'], }).flatMap(([category, keys]) => keys.map(key => [regExp[category + key[0].toUpperCase() + key.slice(1)], category, key])) .concat([[regExp.counter, 'use', 'Counter']]); let log; let battleStyle = ''; let battleType = ''; let worldLevel = 0; let towerFloor = 0; let roundInfo = { current: 0, total: 0 }; let monsterData = []; let allMonsterInfo = {}; let prevMonsterIds = ''; let prevMonsterInfoSignature = ''; let battleUpdateGeneration = 0; let battleLogObserver = null; let battleLogUpdate = null; let battleLogPending = false; let monsterInfoRequest = null; let battleDecisionTimer = null; let monstersEffects = {}; let actionCounts = { history: [] }; let battleLogRecord = []; let battleLogRecordCurrent = []; // Private append-only history: retain one serialized prefix for same-format saves. // Array replacement or truncation invalidates the prefix; nothing is discarded. let battleLogCheckpoint = null; let timeRecords = {}; let combatRecords = {}; let revenueRecords = {}; let spellDamageBonus = readJpxSpellDamageBonus(); let dummy = document.createElement('div'); let newWindow; const difficultyMap = { Normal: 1, Hard: 2, Nightmare: 4, Hell: 7, Nintendo: 10, IWBTH: 15, PFUDOR: 20 }; const itemMap = { 10005: 'Health Gem', 10006: 'Mana Gem', 10007: 'Spirit Gem', 10008: 'Mystic Gem', 11191: 'Health Draught', 11195: 'Health Potion', 11199: 'Health Elixir', 11291: 'Mana Draught', 11295: 'Mana Potion', 11299: 'Mana Elixir', 11391: 'Spirit Draught', 11395: 'Spirit Potion', 11399: 'Spirit Elixir', 11401: 'Energy Drink', 11402: 'Caffeinated Candy', 11501: 'Last Elixir', 12101: 'Infusion of Flames', 12201: 'Infusion of Frost', 12301: 'Infusion of Lightning', 12401: 'Infusion of Storms', 12501: 'Infusion of Divinity', 12601: 'Infusion of Darkness', 13101: 'Scroll of Swiftness', 13111: 'Scroll of Protection', 13199: 'Scroll of the Avatar', 13201: 'Scroll of Absorption', 13211: 'Scroll of Shadows', 13221: 'Scroll of Life', 13299: 'Scroll of the Gods', 19111: 'Flower Vase', 19131: 'Bubble-Gum', }; const itemSrc = [ { keys: ['Health', 'Last Elixir'], src: '/y/e/healthpot.png' }, { keys: ['Mana'], src: '/y/e/manapot.png' }, { keys: ['Spirit'], src: '/y/e/spiritpot.png' }, { keys: ['Drink', 'Candy'], src: '/y/e/soulstone.png' }, { keys: ['Flames'], src: '/y/e/fireinfusion.png' }, { keys: ['Frost'], src: '/y/e/coldinfusion.png' }, { keys: ['Storms'], src: '/y/e/windinfusion.png' }, { keys: ['Lightning'], src: '/y/e/elecinfusion.png' }, { keys: ['Divinity'], src: '/y/e/holyinfusion.png' }, { keys: ['Darkness'], src: '/y/e/darkinfusion.png' }, { keys: ['Protection','vatar'], src: '/y/e/protection_scroll.png' }, { keys: ['Swiftness'], src: '/y/e/haste_scroll.png' }, { keys: ['Absorption'], src: '/y/e/absorb_scroll.png' }, { keys: ['Shadows'], src: '/y/e/shadowveil_scroll.png' }, { keys: ['Life','Gods'], src: '/y/e/sparklife_scroll.png' }, { keys: ['Vase'], src: '/y/e/flowers.png' }, { keys: ['Gum'], src: '/y/e/gum.png' } ]; const effectSrc = { 'Vital Theft': { scr: '/y/e/drainhp.png' }, 'Ether Theft': { scr: '/y/e/drainmp.png' }, 'Spirit Theft': { scr: '/y/e/drainsp.png' }, 'Weakened': { scr: '/y/e/weaken.png' }, 'Imperiled': { scr: '/y/e/imperil.png' }, 'Slowed': { scr: '/y/e/slow.png' }, 'Asleep': { scr: '/y/e/sleep.png' }, 'Confused': { scr: '/y/e/confuse.png' }, 'Blinded': { scr: '/y/e/blind.png' }, 'Silenced': { scr: '/y/e/silence.png' }, 'Immobilized': { scr: '/y/e/magnet.png' }, 'Stunned': { scr: '/y/e/wpn_stun.png' }, 'Penetrated Armor': { scr: '/y/e/wpn_ap.png' }, 'Bleeding Wound': { scr: '/y/e/wpn_bleed.png' }, 'Spreading Poison': { scr: '/y/e/poison.png' }, 'Coalesced Mana': { scr: '/y/e/coalescemana.png' }, 'Searing Skin': { scr: '/y/e/firedot.png' }, 'Freezing Limbs': { scr: '/y/e/coldslow.png' }, 'Turbulent Air': { scr: '/y/e/windmiss.png' }, 'Deep Burns': { scr: '/y/e/elecweak.png' }, 'Breached Defense': { scr: '/y/e/holybreach.png' }, 'Blunted Attack': { scr: '/y/e/darknerf.png' }, 'Burning Soul': { scr: '/y/e/soulfire.png' }, 'Ripened Soul': { scr: '/y/e/ripesoul.png' }, 'Fury of the Sisters': { scr: '/y/e/trio_furyofthesisters.png' }, 'Lamentations of the Future': { scr: '/y/e/trio_skuld.png' }, 'Screams of the Past': { scr: '/y/e/trio_urd.png' }, 'Wails of the Present': { scr: '/y/e/trio_verdandi.png' }, 'Absorbing Ward': { scr: '/y/e/absorb.png' }, }; const spellsDamageObj = { fire: ['Fiery Blast', 'Inferno', 'Flames of Loki'], cold: ['Freeze', 'Blizzard', 'Fimbulvetr'], wind: ['Gale', 'Downburst', 'Storms of Njord'], elec: ['Shockblast', 'Chained Lightning', 'Wrath of Thor'], holy: ['Smite', 'Banishment', 'Paradise Lost'], dark: ['Corruption', 'Disintegrate', 'Ragnarok'], }; const bossTypes = new Map(Object.entries({ Rare: ['Manbearpig', 'White Bunneh', 'Mithra', 'Dalek'], Legendary: ['Konata', 'Mikuru Asahina', 'Ryouko Asakura', 'Yuki Nagato'], Ultimate: ['Skuld', 'Urd', 'Verdandi', 'Yggdrasil', 'Real Life', 'Invisible Pink Unicorn', 'Flying Spaghetti Monster'], Arena300: ['Drogon', 'Rhaegal', 'Viserion'], Arena400: ['New Game +', 'Bottomless Dungeon', 'Recycled Boss Rush', 'Time Trial Mode', 'Achievement Grind', 'Hardcore Mode'], Arena500: ['Angel Bunny', 'Applejack', 'Fluttershy', 'Gummy', 'Pinkie Pie', 'Rarity', 'Spike', 'Rainbow Dash', 'Twilight Sparkle'], }).flatMap(([type, names]) => names.map(name => [name, type]))); const BATTLE_STYLES = ['OneHanded', '1H_Mage', 'TwoHanded', '2H_Mage', 'DualWielding', 'DW_Mage', 'NitenIchiryu', 'NI_Mage', 'Staff', 'Unarmed']; const BATTLE_TYPES = ['Arena', 'Encounter', 'Colosseum', 'Battle1000', 'Item', 'Tower']; const BATTLE_MODES = BATTLE_STYLES.flatMap(style => ['General', ...BATTLE_TYPES].map(type => `${style}_${type}`)); const PRIORITY_RULES = ['Top Down', 'Bottom Up', 'Current HP Low to High', 'Current HP High to Low', 'Current HP Percent Low to High', 'Current HP Percent High to Low']; const MONSTER_TYPES = ['Normal', 'Rare', 'Legendary', 'Ultimate', 'Arena300', 'Arena400', 'Arena500']; const MONSTER_CLASSES = ['Arthropod', 'Avion', 'Beast', 'Celestial', 'Daimon', 'Dragonkin', 'Elemental', 'Giant', 'Humanoid', 'Mechanoid', 'Reptilian', 'Sprite', 'Undead']; const PLAYER_EFFECTS = ['Channeling', 'Regeneration', 'Replenishment', 'Refreshment', 'Regen', 'Heartseeker', 'Arcane Focus', 'Hastened', 'Protection', 'Absorbing Ward', 'Shadow Veil', 'Spark of Life', 'Spirit Shield', 'Infused Flames', 'Infused Frost', 'Infused Storm', 'Infused Lightning', 'Infused Divinity', 'Infused Darkness', 'Energized', 'Sleeper Imprint', 'Kicking Ass', 'Overwhelming Strikes', 'Ether Tap', 'Cloak of the Fallen', 'Blessing of the RiddleMaster', 'Defending', 'Focusing']; const TOGGLE = ['Spirit', 'Defend', 'Focus']; const SKILLS = ['Shield Bash', 'Vital Strike', 'Merciful Blow', 'Iris Strike', 'Backstab', 'Frenzied Blows', 'Great Cleave', 'Rending Blow', 'Shatter Strike', 'Skyward Sword', 'Concussive Strike', 'Flee', 'Scan', 'FUS RO DAH', 'Orbital Friendship Cannon']; const SPELLS_SUPPORT = ['Cure', 'Full-Cure', 'Regen', 'Haste', 'Protection', 'Absorb', 'Shadow Veil', 'Spark of Life', 'Spirit Shield', 'Heartseeker', 'Arcane Focus']; const ITEMS = ['Mystic Gem', 'Health Gem', 'Health Draught', 'Health Potion', 'Health Elixir', 'Mana Gem', 'Mana Draught', 'Mana Potion', 'Mana Elixir', 'Spirit Gem', 'Spirit Draught', 'Spirit Potion', 'Spirit Elixir', 'Last Elixir', 'Infusion of Flames', 'Infusion of Frost', 'Infusion of Storms', 'Infusion of Lightning', 'Infusion of Divinity', 'Infusion of Darkness', 'Scroll of Swiftness', 'Scroll of Protection', 'Scroll of the Avatar', 'Scroll of Absorption', 'Scroll of Shadows', 'Scroll of Life', 'Scroll of the Gods', 'Caffeinated Candy', 'Energy Drink', 'Flower Vase', 'Bubble-Gum']; const SPELLS_DAMAGE = ['T1', 'T2', 'T3', 'Fiery Blast', 'Inferno', 'Flames of Loki', 'Freeze', 'Blizzard', 'Fimbulvetr', 'Gale', 'Downburst', 'Storms of Njord', 'Shockblast', 'Chained Lightning', 'Wrath of Thor', 'Smite', 'Banishment', 'Paradise Lost', 'Corruption', 'Disintegrate', 'Ragnarok']; const SPELLS_DEBUFF = ['Drain', 'Weaken', 'Imperil', 'Slow', 'Sleep', 'Confuse', 'Blind', 'Silence', 'Immobilize']; const CTRLWIDGET_FIELDS = [ { id: 'isActiveBattle', get: () => isActiveBattle ? t('cW.auto') : t('cW.manual') }, { id: 'readyNext', get: () => readyNext }, { id: 'networkDelay', get: () => (lastLogTimestamp > lastActionTimestamp ? lastLogTimestamp - lastActionTimestamp : '-') }, { id: 'battleStyle', get: () => { const style = getManagedBattleStyle(battleStyle), element = getManagedSpellType(); return style ? t('cW.' + style) + (/Staff|Mage/.test(style) && element ? ' (' + t('cW.' + element) + ')' : '') : '—'; } }, { id: 'battleType', get: () => t(`cW.${battleType}`) + (worldLevel ? ` (WL${worldLevel})` : '') + (towerFloor ? ` (${towerFloor}F)` : '') }, { id: 'battleMode', get: () => getBattleMode() }, { id: 'round', get: () => roundInfo.total ? `${roundInfo.current} / ${roundInfo.total}` : '-' }, ].map(f => ({ ...f, label: `cW.${f.id}` })); const COMBAT_FIELDS = [ { id: 'fire', type: 'damage' }, { id: 'cold', type: 'damage' }, { id: 'wind', type: 'damage' }, { id: 'elec', type: 'damage' }, { id: 'holy', type: 'damage' }, { id: 'dark', type: 'damage' }, { id: 'crushing', type: 'damage' }, { id: 'slashing', type: 'damage' }, { id: 'piercing', type: 'damage' }, { id: 'void', type: 'damage' }, { id: 'damagePlus', type: 'damage' }, { id: 'damageTotal', type: 'damage', isTotal: true }, { id: 'glance', type: 'result' }, { id: 'hit', type: 'result' }, { id: 'crit', type: 'result' }, { id: 'miss', type: 'result' }, { id: 'evade', type: 'result' }, { id: 'parry', type: 'result' }, { id: 'resist', type: 'result' }, { id: 'block', type: 'result' }, { id: 'resultTotal', type: 'result', isTotal: true }, { id: 'parryPartially', type: 'resultPartially' }, { id: 'resistPartially', type: 'resultPartially' }, { id: 'blockPartially', type: 'resultPartially' }, { id: 'resultPartiallyTotal', type: 'resultPartially', isTotal: true }, ].map(f => ({ ...f, label: `cP.${f.id}` })); const COMBAT_USE_FIELDS = [ { id: 'action', keys: ['Attack', ...TOGGLE] }, { id: 'item', keys: ['Mystic Gem', 'Health Gem', 'Mana Gem', 'Spirit Gem', 'Caffeinated Candy', 'Energy Drink'] }, { id: 'skill', keys: SKILLS }, { id: 'spellSupport', keys: SPELLS_SUPPORT }, { id: 'spellDamage', keys: SPELLS_DAMAGE }, { id: 'spellDebuff', keys: SPELLS_DEBUFF }, ].map(f => ({ ...f, label: `cP.${f.id}`, keys: f.keys.map(key => ({ key, label: `cB.${key}`})) })); const REVENUE_FIELDS = [ { id: 'exp', type: 'simple' }, { id: 'proficiency', type: 'list_paired', order: [ 'one-handed weapon', 'two-handed weapon', /*legacy901*/'dual wielding'/*legacy902*/, 'dual-wielding', 'staff', 'cloth armor', 'light armor', 'heavy armor', 'elemental magic', 'divine magic', 'forbidden magic', 'supportive magic', 'deprecating magic' ] }, { id: 'credit', type: 'simple' }, { id: 'equipment', type: 'list_flat', order: ['Peerless', 'Legendary', 'Magnificent', 'Exquisite', 'Superior', 'Average', 'Fair', 'Crude'] }, { id: 'material', type: 'grid', order: [ 'Low-Grade Cloth', 'Mid-Grade Cloth', 'High-Grade Cloth', 'Low-Grade Leather', 'Mid-Grade Leather', 'High-Grade Leather', 'Low-Grade Metals', 'Mid-Grade Metals', 'High-Grade Metals', 'Low-Grade Wood', 'Mid-Grade Wood', 'High-Grade Wood', 'Scrap Cloth', 'Scrap Leather', 'Scrap Metal', 'Scrap Wood', 'Energy Cell', ] }, { id: 'consumable', type: 'grid_detailed', order: [ 'Health Draught', 'Health Potion', 'Health Elixir', 'Mana Draught', 'Mana Potion', 'Mana Elixir', 'Spirit Draught', 'Spirit Potion', 'Spirit Elixir', 'Last Elixir', 'Infusion of Flames', 'Infusion of Frost', 'Infusion of Storms', 'Infusion of Lightning', 'Infusion of Divinity', 'Infusion of Darkness', 'Scroll of Swiftness', 'Scroll of Protection', 'Scroll of the Avatar', 'Scroll of Absorption', 'Scroll of Shadows', 'Scroll of Life', 'Scroll of the Gods', 'Voidseeker Shard', 'Aether Shard', 'Featherweight Shard', 'Amnesia Shard', 'World Seed', 'Flower Vase', 'Bubble-Gum' ] }, { id: 'consumableProfit', type: 'simple', source: 'consumable', key: 'profit' }, { id: 'token', type: 'grid', order: ['Token of Blood', 'Chaos Token', 'Soul Fragment'] }, { id: 'tokenProfit', type: 'simple', source: 'token', key: 'profit' }, { id: 'food', type: 'grid', order: ['Monster Chow', 'Monster Edibles', 'Monster Cuisine', 'Happy Pills'] }, { id: 'foodProfit', type: 'simple', source: 'food', key: 'profit' }, { id: 'figurine', type: 'grid', order: [ 'Twilight Sparkle Figurine', 'Rainbow Dash Figurine', 'Applejack Figurine', 'Fluttershy Figurine', 'Pinkie Pie Figurine', 'Rarity Figurine', 'Trixie Figurine', 'Princess Celestia Figurine', 'Princess Luna Figurine', 'Apple Bloom Figurine', 'Scootaloo Figurine', 'Sweetie Belle Figurine', 'Big Macintosh Figurine', 'Spitfire Figurine', 'Derpy Hooves Figurine', 'Lyra Heartstrings Figurine', 'Octavia Figurine', 'Zecora Figurine', 'Cheerilee Figurine', 'Vinyl Scratch Figurine', 'Daring Do Figurine', 'Doctor Whooves Figurine', 'Berry Punch Figurine', 'Bon-Bon Figurine', 'Fluffle Puff Figurine', 'Angel Bunny Figurine', 'Gummy Figurine', ] }, { id: 'figurineProfit', type: 'simple', source: 'figurine', key: 'profit' }, { id: 'artifact', type: 'grid', order: ['Precursor Artifact'] }, { id: 'artifactProfit', type: 'simple', source: 'artifact', key: 'profit' }, { id: 'trophy', type: 'grid', order: [ 'ManBearPig Tail', 'Holy Hand Grenade of Antioch', "Mithra's Flower", 'Dalek Voicebox', 'Lock of Blue Hair', 'Bunny-Girl Costume', 'Hinamatsuri Doll', 'Broken Glasses', 'Black T-Shirt', 'Sapling', 'Unicorn Horn', 'Noodly Appendage', ] }, { id: 'trophyProfit', type: 'simple', source: 'trophy', key: 'profit' }, { id: 'crystal', type: 'grid', order: [ 'Crystal of Vigor', 'Crystal of Finesse', 'Crystal of Swiftness', 'Crystal of Fortitude', 'Crystal of Cunning', 'Crystal of Knowledge', 'Crystal of Flames', 'Crystal of Frost', 'Crystal of Tempest', 'Crystal of Lightning', 'Crystal of Devotion', 'Crystal of Corruption', ] }, { id: 'crystalTotal', type: 'total', source: 'crystal' }, { id: 'totalProfit', type: 'summary' }, { id: 'stamina', type: 'stamina' }, { id: 'finalProfit', type: 'summary' } ].map(f => ({ ...f, label: `rP.${f.id}` })); const STATS_FILTERS = [ { id: 'filter-aggregate', key: 'aggregate', type: 'checkbox', options: ['Aggregate by Day'] }, { id: 'filter-world', key: 'world', type: 'checkbox', options: ['Persistent', 'Isekai'] }, { id: 'filter-battleType', key: 'battleType', type: 'checkbox', options: ['Arena', 'Encounter', 'Colosseum', 'Battle1000', 'Item', 'Tower'] }, { id: 'filter-difficulties', key: 'difficulties', type: 'checkbox', options: ['20', '15', '10', '7', '4', '2', '1'] }, { id: 'filter-result', key: 'result', type: 'checkbox', options: ['Victory', 'Defeat', 'Flee'] }, { id: 'filter-roundTotal', key: 'roundTotal', type: 'rangeNumber', value: [0, 1000] }, { id: 'filter-rows', key: 'rows', type: 'number', value: 50 } ].map(f => ({ ...f, label: `sP.${f.key}` })); const sumRevenueCategory = (record, category) => { let data = record.revenueRecords?.[category]; if (!data) return '0'; let total = 0; for (const [key, value] of Object.entries(data)) { if (key !== 'total' && key !== 'profit') total += value; } return Math.round(total * 100) / 100; }; const sumTrophies = (record, type) => { let data = record.revenueRecords?.trophy; if (!data) return '0'; const TROPHIES_T2 = ['ManBearPig Tail', 'Holy Hand Grenade of Antioch', "Mithra's Flower", 'Dalek Voicebox', 'Lock of Blue Hair']; let total = 0; for (const [key, value] of Object.entries(data)) { if (key === 'total' || key === 'profit') continue; let isLesser = key.match(/Lesser .+ Charm/); let isGreater = key.match(/Greater .+ Charm/); let isT2 = TROPHIES_T2.includes(key); switch (type) { case 'lesserCharm': if (isLesser) total += value; break; case 'greaterCharm': if (isGreater) total += value; break; case 'T2': if (isT2) total += value; break; case 'T36': if (!isT2 && !isLesser && !isGreater) total += value; break; } } return total; }; const getConsumable = (record, field) => { let item = record.revenueRecords?.consumable?.[field]; if (!item) return { drop: 0, use: 0, balance: 0 }; return { drop: item.drop || 0, use: item.use || 0, balance: item.balance || 0 }; }; const STATS_FIELDS = [ { id: 'date', get: d => d.date || '' }, { id: 'world', style: 'min-width: 60px;', get: d => d.world || '', doI18n: true }, { id: 'level', get: d => d.playerLevel || '' }, { id: 'persona', style: 'min-width: 150px;', get: d => d.persona || '' }, { id: 'battleType', get: d => (d.battleType || '') + (d.worldLevel ? ` (WL${d.worldLevel})` : '') + (d.towerFloor ? ` (${d.towerFloor}F)` : ''), doI18n: true }, { id: 'round', get: d => d.roundInfo?.current || '' }, { id: 'deltaTime', get: d => d.deltaTime || '' }, { id: 'turns', style: 'min-width: 60px;', get: d => d.turns || '' }, { id: 'tps', get: d => d.tps || '' }, { id: 'exp', get: d => d.revenueRecords?.exp || 0 }, { id: 'finalProfit', get: d => d.revenueRecords?.finalProfit || 0 }, { id: 'credit', get: d => d.revenueRecords?.credit || 0 }, { id: 'staminaCost', get: d => d.revenueRecords?.staminaCost || 0 }, { id: 'totalProfit', get: d => d.revenueRecords?.totalProfit || 0 }, { id: 'pDGlance', get: d => d.combatRecords?.physicalDealt?.glance || 0 }, { id: 'pDHit', get: d => d.combatRecords?.physicalDealt?.hit || 0 }, { id: 'pDCrit', get: d => d.combatRecords?.physicalDealt?.crit || 0 }, { id: 'mDGlance', get: d => d.combatRecords?.magicalDealt?.glance || 0 }, { id: 'mDHit', get: d => d.combatRecords?.magicalDealt?.hit || 0 }, { id: 'mDCrit', get: d => d.combatRecords?.magicalDealt?.crit || 0 }, { id: 'mDRes', get: d => d.combatRecords?.magicalDealt?.resist || 0 }, { id: 'mDRes50', get: d => d.combatRecords?.magicalDealt?.resist50 || 0 }, { id: 'mDRes75', get: d => d.combatRecords?.magicalDealt?.resist75 || 0 }, { id: 'mDRes90', get: d => d.combatRecords?.magicalDealt?.resist90 || 0 }, { id: 'mDResP', get: d => d.combatRecords?.magicalDealt?.resistPartially || 0 }, { id: 'mDDRes0', get: d => d.combatRecords?.magicalDealt?.debuffResist0 || 0 }, { id: 'mDDRes12', get: d => d.combatRecords?.magicalDealt?.debuffResist1 || 0 }, { id: 'mDDRes3', get: d => d.combatRecords?.magicalDealt?.debuffResist3 || 0 }, { id: 'uCure', get: d => d.combatRecords?.use?.Cure || 0 }, { id: 'uFullCure', get: d => d.combatRecords?.use?.['Full-Cure'] || 0 }, { id: 'uCloakOfTheFallen', get: d => d.combatRecords?.use?.['Cloak of the Fallen'] || 0 }, { id: 'uImperil', get: d => d.combatRecords?.use?.Imperil || 0 }, { id: 'eqP', equipmentQuality: 'Peerless', get: d => d.revenueRecords?.equipment?.Peerless_Avg ?? d.revenueRecords?.equipment?.Peerless?.length ?? 0 }, { id: 'eqL', equipmentQuality: 'Legendary', get: d => d.revenueRecords?.equipment?.Legendary_Avg ?? d.revenueRecords?.equipment?.Legendary?.length ?? 0 }, { id: 'eqM', equipmentQuality: 'Magnificent', get: d => d.revenueRecords?.equipment?.Magnificent_Avg ?? d.revenueRecords?.equipment?.Magnificent?.length ?? 0 }, { id: 'cha', get: d => d.revenueRecords?.token?.['Chaos Token'] || 0 }, { id: 'blo', get: d => d.revenueRecords?.token?.['Token of Blood'] || 0 }, { id: 'food', get: d => sumRevenueCategory(d, 'food') }, { id: 'fig', get: d => sumRevenueCategory(d, 'figurine') }, { id: 'arti', get: d => sumRevenueCategory(d, 'artifact') }, { id: 'crys', get: d => sumRevenueCategory(d, 'crystal') }, { id: 't2', get: d => sumTrophies(d, 'T2') }, { id: 't36', get: d => sumTrophies(d, 'T36') }, { id: 'lCharm', get: d => sumTrophies(d, 'lesserCharm') }, { id: 'gCharm', get: d => sumTrophies(d, 'greaterCharm') }, { id: 'seed', get: d => getConsumable(d, 'World Seed') }, { id: 'hd', get: d => getConsumable(d, 'Health Draught') }, { id: 'md', get: d => getConsumable(d, 'Mana Draught') }, { id: 'sd', get: d => getConsumable(d, 'Spirit Draught') }, { id: 'hp', get: d => getConsumable(d, 'Health Potion') }, { id: 'mp', get: d => getConsumable(d, 'Mana Potion') }, { id: 'sp', get: d => getConsumable(d, 'Spirit Potion') }, { id: 'he', get: d => getConsumable(d, 'Health Elixir') }, { id: 'me', get: d => getConsumable(d, 'Mana Elixir') }, { id: 'se', get: d => getConsumable(d, 'Spirit Elixir') }, { id: 'le', get: d => getConsumable(d, 'Last Elixir') }, { id: 'swif', get: d => getConsumable(d, 'Scroll of Swiftness') }, { id: 'prot', get: d => getConsumable(d, 'Scroll of Protection') }, { id: 'avat', get: d => getConsumable(d, 'Scroll of the Avatar') }, { id: 'abso', get: d => getConsumable(d, 'Scroll of Absorption') }, { id: 'shad', get: d => getConsumable(d, 'Scroll of Shadows') }, { id: 'life', get: d => getConsumable(d, 'Scroll of Life') }, { id: 'gods', get: d => getConsumable(d, 'Scroll of the Gods') }, { id: 'vase', get: d => getConsumable(d, 'Flower Vase') }, { id: 'gum', get: d => getConsumable(d, 'Bubble-Gum') }, { id: 'caff', get: d => -d.combatRecords?.use?.['Caffeinated Candy'] || 0 }, { id: 'ed', get: d => -d.combatRecords?.use?.['Energy Drink'] || 0 }, ].map(f => ({ ...f, label: `sP.${f.id}` })); // UI capability only. The original table still decides by the actual value's type. // Consumable balances are objects and formatted duration is text in the original renderer. const STATS_THRESHOLD_FIELDS = new Set([ 'level', 'round', 'turns', 'tps', 'finalProfit', 'credit', 'staminaCost', 'totalProfit', 'pDGlance', 'pDHit', 'pDCrit', 'mDGlance', 'mDHit', 'mDCrit', 'mDRes', 'mDRes50', 'mDRes75', 'mDRes90', 'mDResP', 'mDDRes0', 'mDDRes12', 'mDDRes3', 'uCure', 'uFullCure', 'uCloakOfTheFallen', 'uImperil', 'eqP', 'eqL', 'eqM', 'cha', 'blo', 'food', 'fig', 'arti', 'crys', 't2', 't36', 'lCharm', 'gCharm', 'caff', 'ed', ]); const STATS_COLUMN_GROUPS = [ { id: 'basic', fields: ['date','world','level','persona','battleType','round','deltaTime','turns','tps'] }, { id: 'earnings', fields: ['exp','finalProfit','credit','staminaCost','totalProfit'] }, { id: 'drops', fields: ['eqP','eqL','eqM','cha','blo','food','fig','arti','crys','t2','t36','lCharm','gCharm'] }, { id: 'potions', fields: ['hd','md','sd','hp','mp','sp','he','me','se','le'] }, { id: 'scrolls', fields: ['swif','prot','avat','abso','shad','life','gods'] }, { id: 'special', fields: ['seed','vase','gum','caff','ed'] }, { id: 'skills', fields: ['uCure','uFullCure','uCloakOfTheFallen','uImperil'] }, { id: 'combat', fields: ['pDGlance','pDHit','pDCrit','mDGlance','mDHit','mDCrit','mDRes','mDRes50','mDRes75','mDRes90','mDResP','mDDRes0','mDDRes12','mDDRes3'] }, ]; const STATS_COLUMN_GROUP_BY_ID = new Map(STATS_COLUMN_GROUPS.flatMap(group => group.fields.map(id => [id, group.id]))); const statsColumnGroupVisible = (groups, id) => groups?.[id] !== false; const KEYBINDS = { openBattleRecords: { key: 'z', ctrl: false, alt: false, shift: false }, toggleActive: { key: 'm', ctrl: false, alt: false, shift: false }, openSettings: { key: ',', ctrl: false, alt: false, shift: false } }; let userKeybinds = JSON.parse(localStorage.getItem(prefix + 'userKeybinds' + isekaiSuffix)) || { ...KEYBINDS }; let idCounter = 0; let settingsSchemas; function getSettingsSchemas() { return settingsSchemas ??= buildSettingsSchemas(); } function buildSettingsSchemas() { const mkF = (key, type, extra = {}) => { const { prefix = 'cB.', label, ...otherExtra } = extra; const field = { key, type, label: label || (type === 'constant' ? `${prefix}${extra.value || key}` : `${prefix}${key}`), ...otherExtra }; ['options', 'multiSelectOptions'].forEach(opts => { if (type !== 'conditionsArray' && Array.isArray(field[opts])) field[opts] = field[opts].map(opt => ({ value: opt, label: `${prefix}${opt}` })); }); return field; }; const mkItem = (type, nameList = null, extra = [], useGeneral = true, useTarget = false) => { const properties = [mkF('type', 'constant', { value: type, class: 'heading' })]; if (nameList) properties.push(mkF('name', 'dropdown', { options: nameList })); if (extra.length > 0) properties.push(...extra.map(item => mkF(item.key, item.type, { ...item }))); let conds = []; if (useGeneral) conds = conds.concat(conditionsGeneral); if (useTarget) conds = conds.concat(conditionsTarget); if (conds.length > 0) properties.push(mkF('conditions', 'conditionsArray', { options: conds })); return { type: 'object', properties }; }; const conditionsGeneral = [ mkF('world', 'array', { multiSelectOptions: ['Persistent', 'Isekai'], itemSchema: { type: 'text' } }), mkF('pLevel', 'rangeNumber'), mkF('pMaxSpellType', 'array', { multiSelectOptions: Object.keys(spellsDamageObj), popup: true, itemSchema: { type: 'text' } }), mkF('battleTypes', 'array', { multiSelectOptions: BATTLE_TYPES, popup: true, itemSchema: { type: 'text' } }), mkF('difficulty', 'array', { multiSelectOptions: Object.keys(difficultyMap), popup: true, itemSchema: { type: 'text' } }), mkF('roundCurrent', 'rangeNumber'), mkF('roundLeft', 'rangeNumber'), mkF('roundTotal', 'rangeNumber'), mkF('floor', 'rangeNumber'), mkF('pActionCooldown', 'array', { multiSelectOptions: [ ...SKILLS, ...SPELLS_SUPPORT, ...ITEMS, ...SPELLS_DAMAGE, ...SPELLS_DEBUFF, ], hasRange: 'cB.cooldownRange', popup: true, itemSchema: { type: 'text' } }), mkF('pActionHistory', 'array', { multiSelectOptions: [ 'Attack', ...TOGGLE, ...SKILLS, ...SPELLS_SUPPORT, ...ITEMS, ...SPELLS_DAMAGE, ...SPELLS_DEBUFF, ], hasRange: 'cB.actionIndexRange', popup: true, itemSchema: { type: 'text' }, defaultValue: [1, 1] }), mkF('pActionCounts', 'array', { multiSelectOptions: [ 'Attack', ...TOGGLE, ...SKILLS, ...SPELLS_SUPPORT, ...ITEMS, ...SPELLS_DAMAGE, ...SPELLS_DEBUFF, ], hasRange: 'cB.usesPerRoundRange', popup: true, itemSchema: { type: 'text' } }), mkF('pTotalActionCounts', 'array', { multiSelectOptions: [ 'Attack', ...TOGGLE, ...SKILLS, ...SPELLS_SUPPORT, ...ITEMS, ...SPELLS_DAMAGE, ...SPELLS_DEBUFF, ], hasRange: 'cB.usesRange', popup: true, itemSchema: { type: 'text' } }), mkF('pHP', 'rangeNumber'), mkF('pMP', 'rangeNumber'), mkF('pSP', 'rangeNumber'), mkF('pOC', 'rangeNumber'), mkF('pSpiritStatus', 'boolean'), mkF('pEffects', 'array', { multiSelectOptions: PLAYER_EFFECTS, hasRange: 'cB.remainingTurnsRange', popup: true, itemSchema: { type: 'text' } }), mkF('pIgnoredEffects', 'array', { multiSelectOptions: PLAYER_EFFECTS, hasRange: 'cB.remainingTurnsRange', popup: true, itemSchema: { type: 'text' } }), mkF('pEffectStacks', 'array', { multiSelectOptions: PLAYER_EFFECTS, hasRange: 'cB.stacksRange', popup: true, itemSchema: { type: 'text' } }), mkF('monsters', 'rangeNumber'), mkF('activeMonsters', 'rangeNumber'), mkF('defeatedMonsters', 'rangeNumber'), mkF('bosses', 'rangeNumber'), mkF('activeBosses', 'rangeNumber'), mkF('defeatedBosses', 'rangeNumber'), mkF('mLevel', 'rangeNumber'), mkF('mWithoutEffects', 'array', { multiSelectOptions: Object.keys(effectSrc), hasRange: 'cB.monsterCountRange', popup: true, itemSchema: { type: 'text' } }), ]; const conditionsTarget = [ mkF('tName', 'text'), mkF('tTypes', 'array', { multiSelectOptions: MONSTER_TYPES, popup: true, itemSchema: { type: 'text' } }), mkF('tClasses', 'array', { multiSelectOptions: MONSTER_CLASSES, popup: true, itemSchema: { type: 'text' } }), mkF('tPowerLevel', 'rangeNumber'), mkF('tIndex', 'rangeNumber'), mkF('tHP', 'rangeNumber'), mkF('tMP', 'rangeNumber'), mkF('tSP', 'rangeNumber'), mkF('tEffects', 'array', { multiSelectOptions: Object.keys(effectSrc), hasRange: 'cB.remainingTurnsRange', popup: true, itemSchema: { type: 'text' } }), mkF('tIgnoredEffects', 'array', { multiSelectOptions: Object.keys(effectSrc), hasRange: 'cB.remainingTurnsRange', popup: true, itemSchema: { type: 'text' } }), mkF('tEffectStacks', 'array', { multiSelectOptions: Object.keys(effectSrc), hasRange: 'cB.stacksRange', popup: true, itemSchema: { type: 'text' } }), mkF('tDaysSinceUpdate', 'rangeNumber'), ].map(f => ({ ...f, extraFields: [ { key: 'offset', type: 'rangeNumber' }, { key: 'matched', type: 'rangeNumber', defaultValue: [1, 1] }, ].map(ef => ({ ...ef, label: `cB.${ef.key}` })) })); const mkBattleRuleSchema = () => ({ type: 'object', discriminator: 'type', oneOf: { target: mkItem('target', null, [{ key: 'priorityRule', type: 'dropdown', options: PRIORITY_RULES }], true, true), spellSupport: mkItem('spellSupport', SPELLS_SUPPORT, [], true, true), item: mkItem('item', ITEMS, [], true, true), toggle: mkItem('toggle', TOGGLE, [{ key: 'toggled', type: 'boolean' }], true, true), stop: mkItem('stop', null, [{ key: 'customMessage', type: 'text' }], true, true), smartDebuff: mkItem('smartDebuff', SPELLS_DEBUFF, [ { key: 'targetCount', type: 'dropdown', options: [3, 2, 1] }, { key: 'bottomUp', type: 'boolean' }, { key: 'tailSkip', type: 'number' }, { key: 'maxAtFirst', type: 'number' }, { key: 'minMonstersLeft', type: 'number' } ], true, true), spellDebuff: mkItem('spellDebuff', SPELLS_DEBUFF, [], true, true), spellDamage: mkItem('spellDamage', SPELLS_DAMAGE, [], true, true), skill: mkItem('skill', SKILLS, [], true, true), normalAttack: mkItem('normalAttack', null, [], true, true), kamisamaniNattaHi: mkItem('kamisamaniNattaHi', null, [ { key: 'code', skipLabel: true, type: 'textarea' } ], false, false), } }); const cfgBattleSchema = { type: 'object', properties: [ mkF('battleControls', 'group', { properties: [ mkF('advanceToNextRound', 'boolean'), mkF('autoFinishBattle', 'boolean'), mkF('ctrlWidgetMouseEnter', 'boolean', { label: 'cB.panelMouseEnter' }), mkF('ctrlWidgetMouseEnterPause', 'boolean', { help: 'cB.ctrlWidgetMouseEnterPauseHelp' }), mkF('ajaxRound', 'boolean', { label: 'cB.ajaxRoundShort', help: 'cB.ajaxRound' }), mkF('hideRoundPopup', 'boolean'), mkF('dailyStaminaQuotaPlus', 'number'), ] }), mkF('battleDisplay', 'group', { properties: [ mkF('showCooldowns', 'boolean'), mkF('showDurations', 'boolean'), mkF('showRealTimeProficiency', 'boolean'), mkF('showMonsterIndex', 'boolean'), mkF('showMonsterInfo', 'boolean'), mkF('showMonsterHP', 'boolean'), mkF('recordBattleLog', 'boolean'), mkF('quickbarExtend', 'array', { itemSchema: { type: 'text' } }), ] }), mkF('controlPanel', 'group', { controlPanelEditor: true, properties: [ mkF('ctrlWidgetStyleText', 'text', { placeholder: 'opacity: 1;' }), mkF('ctrlWidgetRows', 'fieldPicker', { prefix: 'cW.', size: 8, allFields: CTRLWIDGET_FIELDS }), ] }), mkF('battleModeSettings', 'heading', { class: 'heading' }), { key: 'modes', type: 'dropdown', label: 'cB.modes', hasModeDropdown: 'battleMode', options: { battleStyle: BATTLE_STYLES.map(key => ({ value: key, label: `cB.${key}` })), battleType: ['General', ...BATTLE_TYPES].map(key => ({ value: key, label: `cB.${key}` })), }, flatten: '_', itemSchema: { type: 'object', properties: [ mkF('keyBindings', 'keyBasedObjectArray', { class: 'heading', collapsibleItems: true, canDisable: true, flatten: true, itemSchema: mkBattleRuleSchema() }), mkF('rules', 'array', { class: 'heading', collapsibleItems: true, canDisable: true, itemSchema: mkBattleRuleSchema() }) ] } } ] }; const BATTLE_RULE_SCHEMA_KEYS = new Set(['battleModeSettings', 'modes']); const cfgBattleSettingsSchema = { type: 'object', properties: cfgBattleSchema.properties.filter(field => !BATTLE_RULE_SCHEMA_KEYS.has(field.key)) }; const cfgStatsSchema = { type: 'object', properties: [ mkF('basic', 'heading', { class: 'heading', prefix: 'cS.' }), mkF('combatRows', 'fieldPicker', { prefix: 'cS.', statsEditor: true, size: 16, allFields: COMBAT_FIELDS, editFields: [ { key: 's_pd', group: 'outputDisplay' }, { key: 's_md', group: 'outputDisplay' }, { key: 's_td', group: 'outputDisplay' }, { key: 's_pt', group: 'takenDisplay' }, { key: 's_ps', group: 'takenDisplay' }, { key: 's_mt', group: 'takenDisplay' }, { key: 's_ms', group: 'takenDisplay' }, { key: 's_tt', group: 'takenDisplay' }, ].map(f => ({ ...f, label: `cS.${f.key}`, placeholder: 'background-color: red' })), }), mkF('revenueRows', 'fieldPicker', { prefix: 'cS.', statsEditor: true, size: 16, allFields: REVENUE_FIELDS, editFields: [ { key: 'styleText', label: 'cS.styleText', placeholder: 'color: red;' }, ], }), mkF('statsColumns', 'fieldPicker', { prefix: 'cS.', statsEditor: true, size: 16, allFields: STATS_FIELDS, editFields: [ { key: 'customName', label: 'cS.customName' }, { key: 'styleText', label: 'cS.styleText', placeholder: 'color: red;' }, { key: 'colorThresholds', label: 'cS.colorThresholds', placeholder: '500:#c31dcf, 1000:red' }, ], }), ] }; return { cfgBattleSchema, cfgBattleSettingsSchema, cfgStatsSchema, mkBattleRuleSchema, conditionsGeneral, conditionsTarget }; } let spellCooldowns; let itemCooldowns; let vitals; let spiritStatus = false; let playerEffectsObj; let monstersObj; let conditionsObj; const I18N = { cGen: { settings: 'Settings', back: 'Back', save: 'Save', import: 'Import', export: 'Export', menu: 'Menu', statistics: 'Stats', lightTheme: 'Light', darkTheme: 'Dark', switchTheme: 'Switch light / dark theme', undo: 'Undo', redo: 'Redo', undoEmpty: 'Nothing to undo', redoEmpty: 'Nothing to redo', undoAction: 'Undo: ${label}', redoAction: 'Redo: ${label}', restoreDefault: 'Restore default', restoreDefaults: 'Restore defaults', configEdit: 'Config', shortcutConfig: 'Shortcuts', importConfig: 'Import config', reorderRules: 'Reorder rules', rangeTo: 'to', rangeMin: 'Minimum', rangeMax: 'Maximum', on: 'On', off: 'Off', deleteCondition: 'Delete condition', collapseSidebar: 'Collapse sidebar', expandSidebar: 'Expand sidebar', settingsSections: 'Settings sections', expandAllRules: 'Expand all', collapseAllRules: 'Collapse all', dragRule: 'Drag to reorder', draggingRule: 'Dragging: ${label}', dropBefore: 'Insert before ${label}', dropAfter: 'Insert after ${label}', ruleMoved: 'Moved ${label} to position ${index}', dragCancelled: 'Drag canceled.', moveTop: 'Move to top', moveUp: 'Move up', moveToPosition: 'Move to', rulePosition: 'Position', moveApply: 'Move', moveDown: 'Move down', moveBottom: 'Move to bottom', duplicateRule: 'Duplicate rule', disableRule: 'Disable rule', enableRule: 'Enable rule', ruleDisabled: 'Disabled', ruleEnabled: 'Enabled', unsavedAdded: '+ New', unsavedModified: 'Edited', unsavedChange: 'Unsaved change', cancel: 'Cancel', }, cW: { "noAvailableAction": "No available action.", "ruleStopped": "Stop: ${message}", movePanel: 'Drag to move; arrow keys adjust; Home resets position', toggleBattle: 'Toggle automatic battle', waiting: 'Waiting', elementUnknown: 'Spell element unavailable. Open Character outside battle to refresh.', ctrlWidgetRows: 'Panel items', openStats: 'Stats', openSettings: 'Settings', isActiveBattle: 'Status', readyNext: 'Ready', networkDelay: 'Turn interval', battleStyle: 'Style', battleType: 'Battle', battleMode: 'Ruleset', OneHanded: 'One-handed', '1H_Mage': '1H Mage', TwoHanded: 'Two-handed', '2H_Mage': '2H Mage', DualWielding: 'Dual wield', DW_Mage: 'DW Mage', NitenIchiryu: 'Niten Ichiryu', NI_Mage: 'NI Mage', }, sGen: { downloadBattleLog: 'Download log', }, cB: { "riddleSubmitFailed": "Could not submit the answer: ${reason}", "customCodeFailed": "Custom code failed: ${reason}", "emptyRulesRemoved": "Removed empty rules: ${name}", rules: "Rules", addRule: "Add rule", ruleActions: "Rule actions", insertBefore: "Insert above", insertAfter: "Insert below", panelFields: 'Show in panel', panelTextColor: 'Text', panelOpacity: 'Panel opacity', panelPreview: 'Preview', panelMouseEnter: 'Hover panel to start auto battle', panelAppearance: 'Appearance', panelHeaderColor: 'Title bar', panelSurfaceColor: 'Background', panelBorderColor: 'Border', panelReorder: 'Reorder panel items', basicSettings: "General", keyRules: "Key rules", supports: "Support", battleControls: 'Battle controls', battleDisplay: 'Battle display', controlPanel: 'Control panel', ajaxRoundShort: 'Next round without reloading', advanceToNextRound: 'Auto next round', autoFinishBattle: 'Auto finish battle', hideRoundPopup: 'Hide the round victory popup', battleRecordWarning: 'Could not finish the battle stats. Keep this page open to check what happened.', ajaxRound: 'Switch rounds without reloading. Turn this off if it conflicts with another script.', showCooldowns: 'Quickbar cooldowns', quickbarExtend: 'Extra quickbar slots (e.g. ikey_p, Health Draught)', showDurations: 'Effect turns left', showRealTimeProficiency: 'Live proficiency gains', showMonsterIndex: 'Monster numbers', showMonsterInfo: 'Monster class, attack & power', showMonsterHP: 'Monster HP (current / max)', recordBattleLog: 'Record full battle log', dailyStaminaQuotaPlus: 'Extra daily stamina', ctrlWidgetStyleText: 'Panel CSS', ctrlWidgetMouseEnter: 'Hover panel to start auto battle', ctrlWidgetMouseEnterPause: 'Hover again to pause auto battle', ctrlWidgetMouseEnterPauseHelp: 'Requires hover to start auto battle.', battleModeSettings: 'Rulesets', battleRules: 'Battle rules', saveBattleConfig: 'Save battle settings', exportBattleConfig: 'Export battle settings', importBattleConfig: 'Import battle settings', openBattleRecords: 'Battle stats', openSettings: 'Settings', toggleActive: 'Toggle auto battle', keyBindings: 'Shortcuts', saveKeyBindings: 'Save shortcuts', duplicateKeys: 'Key already in use', addNewKeyBinding: 'Add shortcut', actionIndexRange: 'History position (1 = latest)', usesRange: 'Uses this battle', cooldownRange: 'Turns until ready', usesPerRoundRange: 'Uses this round', remainingTurnsRange: 'Turns left', stacksRange: 'Stacks', monsterCountRange: 'Monster count', spellSupport: 'Support spell', customMessage: 'Stop message', priorityRule: 'Target priority', smartDebuff: 'Smart debuff', targetCount: 'Targets', bottomUp: 'Bottom to top (J → A)', tailSkip: 'Trim targets (+N: skip last N; −N: keep first N)', maxAtFirst: 'Cast limit before 2 defeats', minMonstersLeft: 'Unlimited casts at ≤ N monsters left (after 2 defeats)', spellDebuff: 'Debuff spell', spellDamage: 'Damage spell', normalAttack: 'Normal attack', kamisamaniNattaHi: 'Kamisama ni Natta Hi', pLevel: 'Player level', pMaxSpellType: 'Strongest spell type', battleTypes: 'Battle types', roundCurrent: 'Current round', roundLeft: 'Rounds left', roundTotal: 'Total rounds', floor: 'Tower floor', pActionCooldown: 'Action cooldowns', pActionHistory: 'Recent actions', pActionCounts: 'Uses this round', pTotalActionCounts: 'Uses this battle', pHP: 'Player HP %', pMP: 'Player MP %', pSP: 'Player SP %', pOC: 'Player OC', pSpiritStatus: 'Spirit stance', pEffects: 'Player effects', pIgnoredEffects: 'Excluded player effects', pEffectStacks: 'Player effect stacks', monsters: 'Total monsters', activeMonsters: 'Monsters left', defeatedMonsters: 'Monsters defeated', bosses: 'Total bosses', activeBosses: 'Bosses left', defeatedBosses: 'Bosses defeated', mLevel: 'Monster level', mWithoutEffects: 'Monsters missing effects', offset: 'Target offset', matched: 'Matching targets', tName: 'Monster name', tTypes: 'Monster types', tClasses: 'Monster classes', tPowerLevel: 'Monster power level', tIndex: 'Monster position', tHP: 'Monster HP', tMP: 'Monster MP', tSP: 'Monster SP', tEffects: 'Monster effects', tIgnoredEffects: 'Excluded monster effects', tEffectStacks: 'Monster effect stacks', tDaysSinceUpdate: 'Days since monster update', OneHanded: 'One-handed', '1H_Mage': '1H Mage', TwoHanded: 'Two-handed', '2H_Mage': '2H Mage', DualWielding: 'Dual wield', DW_Mage: 'DW Mage', NitenIchiryu: 'Niten Ichiryu', NI_Mage: 'NI Mage', reloadWarning: 'Reload this page? Save your changes first.', importCustomCodeWarning: 'This configuration contains custom JavaScript code that will be executed as part of the battle automation.\n\nOnly import configurations from trusted sources. Malicious code may access or modify data available to this page or perform actions on your behalf.\n\nDo you want to continue?', }, cS: { s_pd: 'Physical', s_md: 'Magical', s_td: 'Total', s_pt: 'Physical', s_ps: 'Physical (spirit)', s_mt: 'Magical', s_ms: 'Magical (spirit)', s_tt: 'Total', styleText: 'CSS style', displaySettings: 'Display settings', outputDisplay: 'Damage dealt', takenDisplay: 'Damage taken', dataRecords: 'Battle records', resetStatsSettings: 'Reset statistics settings', exportDB: 'Export records', importDB: 'Import records', clearRecords: 'Clear records', recordsAllWorlds: 'All worlds', recordsAllBattles: 'All battles', recordsPeriod: 'Dates', recordsAllDates: 'All dates', recordsDateRange: 'Date range', recordsFrom: 'From', recordsTo: 'To', recordsDateHint: 'Use the dates shown in your records. Leave a date blank for no limit.', recordsScopeHint: 'Deletes saved records only. Your settings and current battle stay unchanged.', recordsPreview: '${count} records selected', recordsRangeInvalid: 'Enter a valid date range.', recordsClearConfirm: 'Permanently delete ${count} battle records? This cannot be undone.', recordsCleared: 'Deleted ${count} records.', recordsClearFailed: 'Records could not be cleared. No records were deleted.', statsSettings: 'Stats', saveStatsConfig: 'Save stats settings', exportStatsConfig: 'Export stats settings', importStatsConfig: 'Import stats settings', cleanup: 'Clear all JPX-PLUS data', cleanupScope: 'Deletes settings, shortcuts, temporary data and all battle records for both worlds on this site. Export anything you need first. This cannot be undone.', cleanupConfirm: 'Permanently clear all JPX-PLUS data? Close other game tabs first. This page will reload to perform cleanup. This cannot be undone.', cleanupBattle: 'Leave the battle or puzzle page before clearing data.', cleanupRun: 'Clear permanently', cleanupRunning: 'Clearing local data…', cleanupBlocked: 'Close other game and stats tabs so cleanup can continue.', cleanupFailed: 'Cleanup did not finish. Reload this page to retry.', cleanupDone: 'JPX-PLUS local data cleared. Reload to start with default settings.', cleanupOther: 'Another tab is clearing data. Close this tab or reload when it finishes.', cleanupReload: 'Reload page', importConfirm: 'Do you want to merge the imported data?\nPress OK to only add new records (Merge), or Cancel to overwrite existing data (Overwrite).', section_combatRows: 'Combat', section_revenueRows: 'Earnings', section_statsColumns: 'Columns', section_data: 'Data', help_combatRows: 'Choose combat stats to show. Select one to change its colors.', help_revenueRows: 'Choose loot and earnings to show. Select one to change its colors.', help_statsColumns: 'Choose columns for the stats table.', help_data: 'Import, export or clear battle records, or reset all local data.', allFields: 'Items', enabledCount: '${count} / ${total} enabled', reorderFields: 'Reorder stats', enableField: 'Enable item', disableField: 'Disable item', reorderHint: 'Drag to reorder · Alt + ↑ / ↓ also works', styleHelp: 'Leave blank for defaults. Save to apply.', textColor: 'Text', backgroundColor: 'Fill', defaultColor: 'Default', livePreview: 'Preview', appearance: 'Colors', renameColumn: 'Rename column', confirmName: 'Confirm name', renameHelp: 'Enter to save, Esc to cancel. Leave blank to restore the original name.', previewValue: 'Sample value', thresholdTitle: 'Color by value', thresholdAdd: 'Add rule', thresholdAtLeast: 'At least', thresholdDelete: 'Delete color rule', thresholdEmpty: 'No rules. Uses the color above.', thresholdOrder: 'Uses the rule with the highest matching value.', thresholdTry: 'Try a value', thresholdMatched: 'Uses ≥ ${value}', thresholdBase: 'Uses the color above', thresholdLegacy: 'Saved rule', thresholdLegacyHelp: 'Kept as saved. This rule cannot be edited here.', thresholdHelp: 'Threshold format: 500:#c31dcf, 1000:red', invalidConfig: 'This file is not a valid stats config.', invalidBackup: 'This file is not a valid records backup.', importPreview: 'Import preview', importSummary: '${count} battle records', importMode: 'Import mode', importMerge: 'Add new records only', importReplace: 'Replace all records', importConfirmAction: 'Import', }, tP: { 't/s': 't/s', }, cP: { damageDealt: 'Damage dealt', damageTaken: 'Damage taken', damagePlus: 'Bonus damage', damageTotal: 'Total damage', resultTotal: 'Total', resist50: 'Resist 50', resist75: 'Resist 75', resist90: 'Resist 90', parryPartially: 'Partial Parry', resistPartially: 'Partial Resist', blockPartially: 'Partial Block', resultPartiallyTotal: 'Partial Total', critStack: 'Crit Stacks', debuffResist: 'Debuff Resists', debuffResist0: 'Resist 0', 'debuffResist1-2': 'Resist 1-2', debuffResist3: 'Resist 3', spellSupport: 'Supportive', spellDamage: 'Offensive', spellDebuff: 'Deprecating', }, rP: { unitPrice: 'Unit price', drop: 'Drops', use: 'Used', balance: 'Net', finalProfit: 'Net profit', 'dual-wielding': 'dual-wielding', 'staff': 'staff', }, sP: { "displayGroups": "Show categories", "displayColumns": "Choose columns", "displayHelp": "Changes save automatically. Hidden categories keep their column selections. Stats settings control column names, colors and order within each category.", "displaySaved": "Display preferences saved.", "columnsSelected": "${count} / ${total} selected", "groupHidden": "Category hidden · ${count} / ${total} selected", "group_basic": "Basic", "group_earnings": "Earnings", "group_drops": "Drops", "group_potions": "Potions", "group_scrolls": "Scrolls", "group_special": "Special consumables", "group_skills": "Skill use", "group_combat": "Combat", image: 'Image', downloadImage: 'Download image', copyImage: 'Copy image', imageWorking: 'Creating image…', imageCopied: 'Image copied', imageDownloaded: 'Image downloaded', imageUnavailable: 'Records are still loading.', imageCopyUnavailable: 'Copy unavailable. Download instead.', imageCopyFailed: 'Copy failed. Allow clipboard access or download instead.', imageFailed: 'Image failed. Try fewer rows or columns.', imageTooLarge: 'Image too large. Use fewer rows or columns.', 'jpxStats': 'Battle stats', 'battleDetails': 'Battle details', filters: 'Filters', difficulties: 'Difficulty', result: 'Result', rows: 'Rows', refreshRecords: 'Refresh', recordCount: '${count} records', dayCount: '${count} days', noRecords: 'No matching records', noColumns: 'Choose columns in Stats settings.', loadingRecords: 'Loading records…', recordsError: 'Could not load records', openRecord: 'View details', rangeMin: 'Minimum rounds', rangeMax: 'Maximum rounds', roundTotal: 'Total rounds', deltaTime: 'Duration', tps: 'Turns/s', exp: 'EXP', finalProfit: 'Net profit', 'Aggregate by Day': 'Group by day', pDGlance: 'PDGlance', pDHit: 'PDHit', pDCrit: 'PDCrit', mDGlance: 'MDGlance', mDHit: 'MDHit', mDCrit: 'MDCrit', mDRes: 'MDRes', mDRes50: 'MDRes50', mDRes75: 'MDRes75', mDRes90: 'MDRes90', mDResP: 'MDResP', mDDRes0: 'MDDRes0', mDDRes12: 'MDDRes12', mDDRes3: 'MDDRes3', uCure: 'Cure', uFullCure: 'FCure', uCloakOfTheFallen: 'Spark', uImperil: 'Imp', eqP: 'EqP', eqL: 'EqL', eqM: 'EqM', lCharm: 'LCh', gCharm: 'GCh', hd: 'HD', md: 'MD', sd: 'SD', hp: 'HP', mp: 'MP', sp: 'SP', he: 'HE', me: 'ME', se: 'SE', le: 'LE', ed: 'ED', } }; const mergedI18N = {}; function initHvutEntry() { if (window.top !== window.self || initHvutEntry.refresh) return; let active; const setOpen = (host, open) => { host.dataset.jpxOpen = String(open); host.querySelector('#hvut-top-config-icon')?.setAttribute('aria-expanded', String(open)); active = open ? host : active === host ? null : active; }; const attach = top => { const gear = top?.querySelector('#hvut-top-config-icon'), host = gear?.parentElement; if (!host) return; if (!host.classList.contains('jpx-hvut-config')) { host.classList.add('jpx-hvut-config'); gear.tabIndex = 0; gear.setAttribute('role', 'button'); gear.setAttribute('aria-label', t('cGen.menu')); setOpen(host, false); host.addEventListener('pointerenter', event => { if (event.pointerType === 'mouse' && prepare(top)) setOpen(host, true); }); host.addEventListener('pointerleave', event => { if (event.pointerType === 'mouse') setOpen(host, false); }); } const menu = host.querySelector('.hvut-top-config'); if (!menu) return; for (const [key, action] of [['settings', renderSettings], ['statistics', openBattleRecords]]) { if (menu.querySelector(`[data-jpx-hvut-action="${key}"]`)) continue; // HVUT styles its menu's direct div children; reuse them without a second theme. const item = document.createElement('div'); item.id = `jpx-hvut-${key}`; item.dataset.jpxHvutAction = key; item.setAttribute('role', 'button'); item.tabIndex = 0; item.textContent = `JPX+ ${t('cGen.' + key)}`; item.addEventListener('click', () => { setOpen(host, false); action(); }); item.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); item.click(); } }); menu.append(item); } return menu; }; const prepare = top => { // HVUT creates this submenu on the first mouseenter, including on touch devices. if (top && !top.querySelector('.hvut-top-config')) top.dispatchEvent(new MouseEvent('mouseenter')); return attach(top); }; const discover = event => attach(event.target.closest?.('#hvut-top')); document.addEventListener('pointerover', discover, { passive: true }); document.addEventListener('focusin', discover); document.addEventListener('click', event => { const gear = event.target.closest?.('#hvut-top-config-icon'); if (gear && prepare(gear.closest('#hvut-top'))) { event.preventDefault(); event.stopImmediatePropagation(); setOpen(gear.parentElement, gear.parentElement.dataset.jpxOpen !== 'true'); } else if (active) setOpen(active, false); }, true); document.addEventListener('pointerdown', event => { if (active && !active.contains(event.target)) setOpen(active, false); }, { passive: true }); document.addEventListener('keydown', event => { const gear = event.target.closest?.('#hvut-top-config-icon'); if (gear && (event.key === 'Enter' || event.key === ' ')) { event.preventDefault(); gear.click(); } if (event.key === 'Escape' && active) { const trigger = active.querySelector('#hvut-top-config-icon'); setOpen(active, false); trigger?.focus(); event.stopPropagation(); } }); initHvutEntry.refresh = () => { document.querySelectorAll('[data-jpx-hvut-action]').forEach(item => { item.textContent = `JPX+ ${t('cGen.' + item.dataset.jpxHvutAction)}`; }); document.querySelector('.jpx-hvut-config #hvut-top-config-icon')?.setAttribute('aria-label', t('cGen.menu')); }; attach(document.getElementById('hvut-top')); } function initMobileEntry() { if (window.top !== window.self || location.hash === '#jpx-records' || document.querySelector('#textlog, #battle_main, #riddlemaster')) return; if (document.getElementById('jpx-mobile-entry')) { initMobileEntry.refresh?.(); return; } const entry = document.createElement('details'); entry.id = 'jpx-mobile-entry'; const summary = document.createElement('summary'); summary.textContent = 'JPX-PLUS'; const menu = document.createElement('nav'); const labels = []; for (const [key, icon, action] of [['settings', 'battle', renderSettings], ['statistics', 'stats', openBattleRecords]]) { const button = document.createElement('button'); button.type = 'button'; button.dataset.mobileAction = key; const label = document.createElement('span'); labels.push([label, key]); button.append(createSettingsIcon(icon), label); button.addEventListener('click', event => { event.stopPropagation(); entry.open = false; summary.focus({ preventScroll: true }); action(); }); menu.append(button); } entry.append(summary, menu); document.body.append(entry); const coarse = window.matchMedia('(pointer: coarse)'); const place = () => { if (!coarse.matches) { entry.open = false; return; } const view = window.visualViewport, scale = 1 / (view?.scale || 1); entry.style.transform = `scale(${scale})`; entry.style.left = `${(view?.offsetLeft || 0) + 8 * scale}px`; entry.style.top = `${(view?.offsetTop || 0) + (view?.height || innerHeight) - 52 * scale}px`; }; initMobileEntry.refresh = () => { labels.forEach(([element, key]) => { element.textContent = t('cGen.' + key); }); menu.setAttribute('aria-label', t('cGen.menu')); place(); }; document.addEventListener('pointerdown', event => { if (entry.open && !entry.contains(event.target)) entry.open = false; }); entry.addEventListener('keydown', event => { if (event.key === 'Escape') { entry.open = false; summary.focus(); event.stopPropagation(); } }); window.addEventListener('resize', place); window.visualViewport?.addEventListener('resize', place); window.visualViewport?.addEventListener('scroll', place); coarse.addEventListener('change', place); initMobileEntry.refresh(); } function readJpxTheme() { try { return localStorage.getItem('jpx_theme') === 'dark' ? 'dark' : 'light'; } catch { return 'light'; } } function applyJpxTheme(doc = document) { const root = doc.documentElement; root.dataset.jpxTheme = themeMode; for (const [key, color] of Object.entries(JPX_DARK_COLORS)) { if (themeMode === 'dark') root.style.setProperty('--jpx-theme-' + key, color); else root.style.removeProperty('--jpx-theme-' + key); } doc.querySelectorAll('.jpx-control-appearance, .jpx-stats-palette').forEach(panel => panel._jpxRefreshTheme?.()); const toggle = doc.getElementById('jpx-theme-toggle'); if (toggle) { toggle.textContent = t(themeMode === 'dark' ? 'cGen.darkTheme' : 'cGen.lightTheme'); toggle.setAttribute('aria-checked', String(themeMode === 'dark')); toggle.setAttribute('aria-label', t('cGen.darkTheme')); toggle.title = t('cGen.switchTheme'); } themeDocuments.add(doc); const win = doc.defaultView; if (win && !themeWindows.has(win)) { themeWindows.add(win); win.addEventListener('storage', event => { if (event.storageArea !== win.localStorage || (event.key !== 'jpx_theme' && event.key !== null)) return; themeMode = readJpxTheme(); refreshJpxTheme(); }); win.addEventListener('pagehide', () => themeDocuments.delete(doc)); } } function refreshJpxTheme() { for (const doc of themeDocuments) { try { if (doc.defaultView?.closed) themeDocuments.delete(doc); else applyJpxTheme(doc); } catch { themeDocuments.delete(doc); } } } function toggleJpxTheme() { const next = themeMode === 'dark' ? 'light' : 'dark'; try { localStorage.setItem('jpx_theme', next); } catch { return t('cGen.error!'); } themeMode = next; refreshJpxTheme(); } function requestJpxCleanup() { if (document.querySelector('#textlog, #riddlemaster')) { window.alert(t('cS.cleanupBattle')); return; } if (!window.confirm(t('cS.cleanupScope') + (jpxShared.enabled ? '\n\n' + sharedText('resetScope') : '') + '\n\n' + t('cS.cleanupConfirm'))) return; const token = crypto.randomUUID(); sessionStorage.setItem(cleanupOwnerKey, token); localStorage.setItem(cleanupKey, token); cleanupInProgress = true; isActiveBattle = false; window.removeEventListener('beforeunload', storeTmp); window.location.reload(); } // Reload before deleting so old timers, drafts and unload saves cannot restore data. function renderJpxCleanup(owner) { cleanupInProgress = true; const panel = document.createElement('main'), title = document.createElement('h2'); const status = document.createElement('p'), actions = document.createElement('div'); panel.id = 'jpx-cleanup-page'; panel.style.cssText = jpxThemeCSS('box-sizing:border-box;max-width:520px;margin:24px auto;padding:16px;border:1px solid #c8b49b;background:#f9f6ec;color:#5c0d11;font:14px/1.6 Arial,sans-serif;'); document.body.style.cssText = jpxThemeCSS('margin:12px;background:#edebdf;'); actions.style.cssText = 'display:flex;flex-wrap:wrap;gap:8px;'; status.setAttribute('role', 'status'); let message = owner ? 'cleanupRunning' : 'cleanupOther'; let finished = false; const reload = jpxUtils.createButton(actions, { history: false, onClick: () => { sessionStorage.removeItem(cleanupHoldKey); if (!localStorage.getItem(cleanupKey)) { Object.keys(sessionStorage).filter(key => key.startsWith(prefix)).forEach(key => sessionStorage.removeItem(key)); } window.location.reload(); } }); const retry = jpxUtils.createButton(actions, { history: false, onClick: requestJpxCleanup }); for (const button of [reload, retry]) button.style.cssText = jpxThemeCSS('min-height:40px;padding:6px 12px;border:1px solid #c8b49b;border-radius:4px;background:#fffdf7;color:inherit;font:inherit;cursor:pointer;'); const update = () => { title.textContent = t('cS.cleanup'); status.textContent = t('cS.' + message); reload.textContent = t('cS.cleanupReload'); retry.textContent = t('cS.cleanupRun'); reload.hidden = owner && !finished && message !== 'cleanupFailed'; retry.hidden = owner; }; initDoI18n(update); update(); if (!document.querySelector('meta[name=viewport]')) { const viewport = document.createElement('meta'); viewport.name = 'viewport'; viewport.content = 'width=device-width, initial-scale=1'; document.head.append(viewport); } panel.append(title, status, actions); document.body.replaceChildren(panel); if (!owner) return; const fail = error => { console.error('JPX cleanup failed:', error); message = 'cleanupFailed'; update(); }; try { const removeDatabase = name => new Promise((resolve, reject) => { const request = indexedDB.deleteDatabase(name); request.onblocked = () => { message = 'cleanupBlocked'; update(); }; request.onerror = () => reject(request.error); request.onsuccess = resolve; }); Promise.all(['jpx', 'jpx-monster-database-v1'].map(removeDatabase)).then(() => { try { if (jpxShared.enabled) jpxShared.reset(); for (const storage of [window.localStorage, localStorage, sessionStorage]) { const keys = Array.from({ length: storage.length }, (_, index) => storage.key(index)); keys.filter(key => key?.startsWith(prefix) && key !== cleanupKey && key !== cleanupOwnerKey) .forEach(key => storage.removeItem(key)); } localStorage.removeItem(cleanupKey); sessionStorage.removeItem(cleanupOwnerKey); finished = true; message = 'cleanupDone'; update(); } catch (error) { fail(error); } }).catch(fail); } catch (error) { fail(error); } } // Detection is separate from the selected configuration. Cached magic stats are // useful only for the same world/persona; legacy cache values remain a runtime // fallback until a character page supplies a verified snapshot. function getJpxDetectionContext(root = document) { // After an AJAX swap or another tab's switch, this page can still contain // the previous persona selector. Explicitly fetched documents stay usable. const select = root === document && jpxDetectionSourceIgnored ? null : root.querySelector('#persona_form select'); const selected = select?.selectedOptions?.[0] || select?.options?.[select.selectedIndex]; return { world: isekaiSuffix ? 'Isekai' : 'Persistent', persona: selected?.textContent?.trim() || localStorage.getItem(prefix + 'persona' + isekaiSuffix) || '', personaId: select?.value || localStorage.getItem(prefix + 'personaId' + isekaiSuffix) || '' }; } // Hoisted because initial spell-stat loading also reads the persona context. var jpxDetectionSourceIgnored = false; let jpxDetectionGeneration = 0; let jpxDetectionRequest = null; let jpxDetectionController = null, jpxDetectionRequestGeneration = -1; let jpxDetectionReadLoadout = false, jpxDetectionReadMode = false; let jpxDetectionRetryAt = 0; let jpxBattleDetectedStyle; // This key contains equipment observations only. Old skill-derived caches are ignored. const jpxDetectedFamilyKey = () => prefix + 'equipmentFamily_v1' + isekaiSuffix; const jpxDetectedFamilyValid = family => ['OneHanded', 'TwoHanded', 'DualWielding', 'NitenIchiryu', 'Staff', 'Unarmed'].includes(family); function getJpxEquipmentContext(root = document) { const context = getJpxDetectionContext(root); const active = root === document && jpxDetectionSourceIgnored ? null : root.querySelector('#eqsl img[src*="_on.png"]'); const observedSet = active?.getAttribute('src')?.match(/(?:^|\/)set(\d+)_on\.png(?:[?#]|$)/)?.[1]; const confirmed = readJpxLoadoutCatalog().current; return { ...context, setId: observedSet || (confirmed?.world === context.world && confirmed.personaId === context.personaId ? confirmed.setId : '') }; } function readJpxDetectedFamily(fresh = false) { try { const saved = JSON.parse(localStorage.getItem(jpxDetectedFamilyKey())), current = getJpxEquipmentContext(); if (saved?.version === 1 && jpxDetectedFamilyValid(saved.family) && current.personaId && current.setId && saved.world === current.world && saved.personaId === current.personaId && saved.setId === current.setId && Number.isFinite(saved.verifiedAt) && Date.now() >= saved.verifiedAt && (!fresh || Date.now() - saved.verifiedAt < 60000)) return saved.family; } catch { /* A missing or corrupt observation is not a detected style. */ } return ''; } function rememberJpxDetectedFamily(family, context = getJpxEquipmentContext(), weapons = getJpxEquippedWeapons()) { if (!jpxDetectedFamilyValid(family) || !context.personaId || !context.setId) return; try { const key = jpxDetectedFamilyKey(); let saved; try { saved = JSON.parse(localStorage.getItem(key)); } catch { /* Replace corrupt cached evidence with the live observation. */ } const weaponKey = JSON.stringify(weapons); if (saved?.family === family && saved.weapons === weaponKey && saved.world === context.world && saved.persona === context.persona && saved.personaId === context.personaId && saved.setId === context.setId && Date.now() >= saved.verifiedAt && Date.now() - saved.verifiedAt < 30000) return; localStorage.setItem(key, JSON.stringify({ version: 1, ...context, family, weapons: weaponKey, verifiedAt: Date.now() })); } catch { /* Live evidence remains usable even when browser storage is full. */ } } function getJpxSpellDamageFromPage(root = document) { const label = Array.from(root.querySelectorAll('.spc')).find(node => { if ((node.textContent || '').includes('Spell Damage Bonus')) return true; const glyphs = node.querySelector('div'); return !!glyphs && jpxUtils.parseHVClasses(glyphs).includes('Spell Damage Bonus'); }); let maximum = null; for (const row of label?.nextElementSibling?.querySelectorAll('tr') || []) { const cells = row.querySelectorAll('td'); if (cells.length < 2) continue; const maxValue = parseFloat(cells[0].textContent.trim()); // Display-only translations may append Chinese to the native element. // Match its leading English token, never another stat table or tooltip. const maxType = cells[1].textContent.trim().match(/^(fire|cold|wind|elec|holy|dark)(?![a-z])/i)?.[1].toLowerCase(); if (!Number.isFinite(maxValue) || maxValue < 0 || !maxType) continue; if (!maximum || maxValue > maximum.maxValue) maximum = { maxType: maxValue > 0 ? maxType : '', maxValue }; else if (maxValue === maximum.maxValue && maxType !== maximum.maxType) maximum.maxType = ''; } return maximum; } function readJpxSpellDamageBonus(verifiedOnly = false) { const fallback = () => verifiedOnly ? null : { maxType: '', maxValue: 0 }; try { const key = prefix + 'spellDamageBonus' + isekaiSuffix; const value = JSON.parse(localStorage.getItem(key)); if (!value || !['', 'fire', 'cold', 'wind', 'elec', 'holy', 'dark'].includes(value.maxType) || !Number.isFinite(value.maxValue) || value.maxValue < 0) return fallback(); const result = { maxType: value.maxValue > 0 ? value.maxType : '', maxValue: value.maxValue }; const saved = JSON.parse(localStorage.getItem(key + ':context')); if (!saved) return verifiedOnly ? null : result; const current = getJpxDetectionContext(); if (saved.version !== 1 || saved.world !== current.world || saved.persona !== current.persona || saved.personaId !== current.personaId || !current.persona) return fallback(); return result; } catch { return fallback(); } } function refreshJpxModeDetection() { const key = prefix + 'spellDamageBonus' + isekaiSuffix; const snapshot = () => localStorage.getItem(key) + localStorage.getItem(key + ':context') + localStorage.getItem(jpxDetectedFamilyKey()); const before = snapshot(); const context = getJpxDetectionContext(); const previous = localStorage.getItem(prefix + 'persona' + isekaiSuffix) || ''; const previousId = localStorage.getItem(prefix + 'personaId' + isekaiSuffix) || ''; if (context.persona && (context.persona !== previous || (previousId && context.personaId && context.personaId !== previousId))) { localStorage.removeItem(key); localStorage.removeItem(key + ':context'); localStorage.removeItem(jpxDetectedFamilyKey()); } if (context.persona) { localStorage.setItem(prefix + 'persona' + isekaiSuffix, context.persona); if (context.personaId) localStorage.setItem(prefix + 'personaId' + isekaiSuffix, context.personaId); } const maximum = !jpxDetectionSourceIgnored ? getJpxSpellDamageFromPage() : null; if (maximum && context.persona) { localStorage.setItem(key, JSON.stringify(maximum)); localStorage.setItem(key + ':context', JSON.stringify({ version: 1, ...context })); } spellDamageBonus = maximum || readJpxSpellDamageBonus(); getDetectedJpxBattleStyle(); if (before !== snapshot()) window.dispatchEvent(new Event('jpx:mode-detected')); } function isJpxLoadoutSubmission(form, submitter) { if (form.matches?.('#persona_form')) return true; if (!form.matches?.('#equipform')) return false; // The forge's Item World confirmation submits this same form with a // button-level destination. The visible forge URL is not the action. try { const action = submitter?.getAttribute('formaction') ?? form.getAttribute('action'); const destination = new URL(action || location.href, location.href); const query = destination.searchParams; return destination.origin !== location.origin || query.get('s') !== 'Battle' || query.get('ss') !== 'iw'; } catch { return true; } } function initJpxModeDetection() { refreshJpxModeDetection(); const key = prefix + 'spellDamageBonus' + isekaiSuffix; const invalidate = () => { jpxDetectionSourceIgnored = true; jpxDetectionGeneration++; jpxDetectionRetryAt = 0; localStorage.removeItem(key); localStorage.removeItem(key + ':context'); localStorage.removeItem(jpxDetectedFamilyKey()); spellDamageBonus = readJpxSpellDamageBonus(); window.dispatchEvent(new Event('jpx:mode-detected')); }; document.addEventListener('change', event => { if (event.target.closest?.('#persona_form, [name=equip_set]')) invalidate(); }, true); document.addEventListener('submit', event => { if (isJpxLoadoutSubmission(event.target, event.submitter)) invalidate(); }, true); document.addEventListener('click', event => { if (event.target.closest?.('#eqsl')) invalidate(); }, true); window.addEventListener('storage', event => { if (![key, key + ':context', jpxDetectedFamilyKey(), prefix + 'persona' + isekaiSuffix, prefix + 'personaId' + isekaiSuffix].includes(event.key)) return; jpxDetectionGeneration++; if (event.key === jpxDetectedFamilyKey() || event.key.startsWith(prefix + 'persona')) jpxDetectionSourceIgnored = true; if (!log) spellDamageBonus = readJpxSpellDamageBonus(); window.dispatchEvent(new Event('jpx:mode-detected')); }); // A confirmed AJAX loadout switch needs new equipment/stat observations. window.addEventListener('jpx:loadout-detected', () => queueMicrotask(() => ensureJpxModeDetection())); } function getJpxEquippedWeapons(root = document, metadata = window.dynjs_equip) { // Only read equipped slot metadata. Inventory names and translated labels // cannot establish which weapons are currently equipped. const slots = Array.from(root.querySelectorAll('#eqsb > .eqb')); const slot = number => slots.find(node => node.getAttribute('onclick')?.match(/equip_slot=(\d+)(?:[^0-9]|$)/)?.[1] === String(number)); const read = node => { const item = node?.children?.[1]; if (!item) return null; if (item.matches('.eqempty')) return { id: '', name: '' }; const id = item.dataset?.eid || item.getAttribute('onmouseover')?.match(/(?:hover_equip|equips\.set)\((\d+)/)?.[1]; if (!id) return null; const data = metadata?.[id]; const name = typeof data?.n === 'string' && data.n.trim() ? data.n : typeof data?.t === 'string' ? data.t : ''; return name.trim() ? { id, name } : null; }; const mainSlot = slot(1), next = mainSlot?.nextElementSibling; // Staff/two-handed equipment disables the adjacent offhand slot and removes // its navigation handler. This is explicit emptiness, not missing evidence. const offSlot = slot(2) || (next?.matches('.eqb.eqdisabled') && next.children[1]?.matches('.eqempty') ? next : null); const main = read(mainSlot), off = read(offSlot); return main && off ? [main, off] : null; } function getJpxEquippedStyleFamily(root = document, metadata = window.dynjs_equip) { const weapons = getJpxEquippedWeapons(root, metadata); if (!weapons) return ''; const [main, off] = weapons.map(item => item.name); if (!main && !off) return 'Unarmed'; const has = (name, types) => new RegExp('\\b(?:' + types.join('|') + ')\\b').test(name); const oneHanded = ['Axe', 'Club', 'Rapier', 'Shortsword', 'Wakizashi', 'Dagger']; if (has(main, ['Katana']) && has(off, ['Wakizashi'])) return 'NitenIchiryu'; if (has(main, oneHanded) && has(off, oneHanded)) return 'DualWielding'; if (has(main, oneHanded) && (!off || has(off, ['Buckler', 'Kite Shield', 'Tower Shield', 'Force Shield']))) return 'OneHanded'; if (!off && has(main, ['Longsword', 'Estoc', 'Mace', 'Katana', 'Scythe', 'Swordchucks'])) return 'TwoHanded'; if (!off && has(main, ['Staff'])) return 'Staff'; return ''; } function getJpxStyleFromFamily(family, magic) { if (family === 'Staff' || family === 'Unarmed') return family; const mages = { OneHanded: '1H_Mage', TwoHanded: '2H_Mage', DualWielding: 'DW_Mage', NitenIchiryu: 'NI_Mage' }; if (!mages[family] || !magic) return ''; return magic.maxValue > (family === 'OneHanded' ? 70 : 100) ? mages[family] : family; } function getDetectedJpxBattleStyle() { try { const battle = log || document.querySelector('#textlog, #battle_main'); // Freeze the pre-battle observation for this document, including AJAX rounds. // Refreshes can reuse it without an expiry that would interrupt long battles. if (battle) return jpxBattleDetectedStyle ??= getJpxStyleFromFamily(readJpxDetectedFamily(), readJpxSpellDamageBonus(true)); const equipped = !jpxDetectionSourceIgnored && document.querySelector('#eqsb'); const family = equipped ? getJpxEquippedStyleFamily() : readJpxDetectedFamily(); if (equipped) { if (family) { const weapons = getJpxEquippedWeapons(); let previous; try { previous = JSON.parse(localStorage.getItem(jpxDetectedFamilyKey())); } catch { /* Replace corrupt evidence below. */ } if (previous?.weapons && previous.weapons !== JSON.stringify(weapons)) { // Replacing a weapon within the same set also changes its stats. const key = prefix + 'spellDamageBonus' + isekaiSuffix; localStorage.removeItem(key); localStorage.removeItem(key + ':context'); spellDamageBonus = { maxType: '', maxValue: 0 }; } rememberJpxDetectedFamily(family, getJpxEquipmentContext(), weapons); } else localStorage.removeItem(jpxDetectedFamilyKey()); } return getJpxStyleFromFamily(family, readJpxSpellDamageBonus(true)); } catch { return ''; } } function parseJpxEquipmentMetadata(text) { // Extract only the native JSON assignment; never execute fetched scripts. const match = /\bdynjs_equip\s*=\s*\{/.exec(text); if (!match) return null; const start = match.index + match[0].length - 1; let depth = 0, quoted = false, escaped = false; for (let i = start; i < text.length; i++) { const char = text[i]; if (quoted) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === '"') quoted = false; } else if (char === '"') quoted = true; else if (char === '{') depth++; else if (char === '}' && --depth === 0) { try { return JSON.parse(text.slice(start, i + 1)); } catch { return null; } } } return null; } async function readJpxEquipmentMetadata(root, base, signal) { for (const script of root.scripts) { const data = parseJpxEquipmentMetadata(script.textContent); if (data) return data; } // Native equipment pages normally keep names in a separate dynjs resource. // Follow only the current world's equipment-data URL, not other page scripts. for (const script of root.querySelectorAll('script[src]')) { const url = new URL(script.getAttribute('src'), new URL(base, location.origin)); if (url.origin !== location.origin || url.username || url.password || !url.pathname.startsWith(base + 'dynjs/') || !/\/equip-\d+\.js$/.test(url.pathname)) continue; const response = await fetch(url.href, { method: 'GET', credentials: 'same-origin', cache: 'no-store', redirect: 'error', signal }); return response.ok ? parseJpxEquipmentMetadata(await response.text()) : null; } return null; } function ensureJpxModeDetection(loadout = false) { // Character pages are unavailable during battle. Never probe them in combat, // and never mistake a battle/verification response for a character snapshot. if (jpxLoadoutBusy || log || document.querySelector('#textlog, #battle_main, #riddlemaster') || !/(^|\.)hentaiverse\.org$/.test(location.hostname)) return Promise.resolve(); if (!loadout && getDetectedJpxBattleStyle() && readJpxDetectedFamily(true) && readJpxSpellDamageBonus(true)) return Promise.resolve(); if (jpxDetectionRequest) { if (jpxDetectionRequestGeneration === jpxDetectionGeneration) { jpxDetectionReadLoadout ||= loadout; jpxDetectionReadMode ||= !loadout; return jpxDetectionRequest; } jpxDetectionController?.abort(); } if (Date.now() < jpxDetectionRetryAt) return Promise.resolve(); const generation = jpxDetectionGeneration; let initial = JSON.stringify(getJpxDetectionContext()); const isCurrent = () => generation === jpxDetectionGeneration && initial === JSON.stringify(getJpxDetectionContext()) && !log && !document.querySelector('#textlog, #battle_main, #riddlemaster'); const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 8000); jpxDetectionController = controller; jpxDetectionRequestGeneration = generation; jpxDetectionReadLoadout = loadout; jpxDetectionReadMode = !loadout; jpxDetectionRetryAt = Date.now() + 10000; jpxDetectionRequest = (async () => { try { const base = isekaiSuffix ? '/isekai/' : '/'; const readPage = async page => { const response = await fetch(base + '?s=Character&ss=' + page, { method: 'GET', credentials: 'same-origin', cache: 'no-store', signal: controller.signal }); if (!response.ok) throw new Error('Character lookup failed'); const root = new DOMParser().parseFromString(await response.text(), 'text/html'); if (root.querySelector('#textlog, #battle_main, #riddlemaster')) throw new Error('Character pages are unavailable during battle'); return root; }; // Binding needs only a confirmed persona/set pair. The equipment // response normally supplies both, without an extra character GET. let character, equipment; if (loadout) { equipment = await readPage('eq'); if (!isCurrent()) return; character = equipment.querySelector('#persona_form select') ? equipment : await readPage('ch'); if (!isCurrent()) return; rememberJpxLoadout(character, equipment); initial = JSON.stringify(getJpxDetectionContext()); if (!jpxDetectionReadMode) { jpxDetectionRetryAt = 0; return; } // An open manager can request style detection while binding is // in flight. Reuse the equipment response for that request too. if (character === equipment) character = await readPage('ch'); } else [character, equipment] = await Promise.all(['ch', 'eq'].map(readPage)); if (!isCurrent()) return; const characterPersona = character.querySelector('#persona_form select'); const equipmentPersona = equipment.querySelector('#persona_form select'); if (characterPersona && equipmentPersona && characterPersona.value !== equipmentPersona.value) return; if (!jpxLoadoutPending || jpxDetectionReadLoadout) rememberJpxLoadout(character, equipment); initial = JSON.stringify(getJpxDetectionContext()); if (!character.querySelector('#persona_form select') || !equipment.querySelector('#eqsb')) return; const metadata = await readJpxEquipmentMetadata(equipment, base, controller.signal); if (!isCurrent()) return; const context = getJpxEquipmentContext(equipment), family = getJpxEquippedStyleFamily(equipment, metadata); const magic = getJpxSpellDamageFromPage(character); if (!context.persona || !context.personaId || !context.setId) return; localStorage.setItem(prefix + 'persona' + isekaiSuffix, context.persona); localStorage.setItem(prefix + 'personaId' + isekaiSuffix, context.personaId); const key = prefix + 'spellDamageBonus' + isekaiSuffix; if (magic) { localStorage.setItem(key, JSON.stringify(magic)); localStorage.setItem(key + ':context', JSON.stringify({ version: 1, ...context })); spellDamageBonus = magic; } if (family) rememberJpxDetectedFamily(family, context, getJpxEquippedWeapons(equipment, metadata)); else localStorage.removeItem(jpxDetectedFamilyKey()); jpxDetectionSourceIgnored = true; if (family) jpxDetectionRetryAt = 0; window.dispatchEvent(new Event('jpx:mode-detected')); } catch { /* Retry on a later visit; no modal or false detection on failure. */ } finally { clearTimeout(timeout); controller.abort(); if (jpxDetectionController === controller) { jpxDetectionRequest = null; jpxDetectionController = null; } } })(); return jpxDetectionRequest; } function initDo() { applyJpxTheme(); const cleanupRequest = localStorage.getItem(cleanupKey); if (cleanupRequest || sessionStorage.getItem(cleanupHoldKey) || sessionStorage.getItem(cleanupOwnerKey)) { renderJpxCleanup(!!cleanupRequest && sessionStorage.getItem(cleanupOwnerKey) === cleanupRequest); return; } if (jpxShared.enabled && !document.querySelector('#textlog, #riddlemaster')) { const migrate = () => ensureJpxSharedRecords().catch(error => { console.error('JPX shared archive migration failed:', error); jpxUtils.createToast(sharedText('fail'), 8000); }); if (window.requestIdleCallback) window.requestIdleCallback(migrate, { timeout: 3000 }); else setTimeout(migrate, 0); } if (location.hash === '#jpx-records') { initDoI18n(() => renderBattleRecordsPage(window)); renderBattleRecordsPage(window); return; } ensureJpxStyle(document, !document.querySelector('#textlog, #battle_main, #riddlemaster')); window.addEventListener('beforeunload', storeTmp); document.addEventListener('pointerdown', (e) => { if (!e.target.closest('.multiSelect-popup-panel, .multiSelect-summary')) { document.querySelectorAll('.multiSelect-popup-panel').forEach(p => p.style.display = 'none'); document.querySelectorAll('.multiSelect-summary').forEach(summary => summary.setAttribute('aria-expanded', 'false')); } }); const throttledActionManager = jpxUtils.throttle(actionManager, 75); document.addEventListener('keydown', (e) => onKeyDown(e, throttledActionManager), true); initDoI18n(); initHvutEntry(); initMobileEntry(); let queries = location.search.match(regExp.locationQueries) || []; let queriesObj = Object.fromEntries(queries.map( (query) => { return query.split('=', 2); } )); log = document.querySelector('#textlog'); loadBattleConfig(); initJpxModeDetection(); initJpxLoadoutBindings(); //Battle if (log && !doInitDoBattle) { initDoBattle(); return; } //Riddle if (document.querySelector('#riddlemaster')) { riddleRecorder(); return; } //Lobby if (!log) { ensureJpxModeDetection(); // Checking the rules validates the whole configuration library; keep it // off the first paint, together with the refresh it decides. const refresh = () => { if (needsJpxMonsterDatabase()) getJpxMonsterDatabase().refresh(jpxMonsterWorld()).catch(error => console.warn('JPX monster database update failed.', error)); }; if (window.requestIdleCallback) window.requestIdleCallback(refresh, { timeout: 5000 }); else setTimeout(refresh, 0); if ( (queriesObj.s === 'Bazaar' && queriesObj.ss === 'am' && queriesObj.screen === 'modify') || (queriesObj.s === 'Battle' && queriesObj.ss === 'iw') ) { let equipForm = document.querySelector('#equipform'); if (!equipForm) return; let observer = new MutationObserver(() => { let iwinfo = document.getElementById('iwinfo'); if (!iwinfo) return; let info = {}; iwinfo.querySelectorAll('tr').forEach(tr => { let [keyTd, valueTd] = tr.querySelectorAll('td'); info[keyTd.textContent.slice(0, -1)] = valueTd.textContent; }); localStorage.setItem(prefix + 'worldLevel' + isekaiSuffix, info['World Level']); localStorage.setItem(prefix + 'difficulty' + isekaiSuffix, info['Difficulty'].split(' ')[0]); }); observer.observe(equipForm, { childList: true, subtree: true }); } if (queriesObj.s === 'Battle') { let levelReadout = document.querySelector('#level_readout > div > div')?.innerText; let playerInfo = levelReadout?.match(regExp.playerInfo); if (playerInfo) { let difficulty = localStorage.getItem(prefix + 'difficulty' + isekaiSuffix) || 'undefined'; let playerLevel = parseInt(localStorage.getItem(prefix + 'playerLevel' + isekaiSuffix)) || 0; if (difficulty != playerInfo[1]) localStorage.setItem(prefix + 'difficulty' + isekaiSuffix, playerInfo[1]); if (playerLevel != playerInfo[1]) localStorage.setItem(prefix + 'playerLevel' + isekaiSuffix, playerInfo[2]); } let staminaReadout = document.querySelector('#stamina_readout > div > div')?.innerText; let staminaInfo = staminaReadout?.match(regExp.staminaInfo)?.[1]; if (staminaInfo) { let stamina = parseFloat(localStorage.getItem(prefix + 'stamina' + isekaiSuffix)) || 80; if (stamina != staminaInfo) localStorage.setItem(prefix + 'stamina' + isekaiSuffix, staminaInfo); } } return; } } function loadBattleConfig() { let storedCfgBattle = {}; try { storedCfgBattle = JSON.parse(localStorage.getItem(prefix + 'cfgBattle' + isekaiSuffix) || '{}'); } catch (err) { console.error('Failed to load cfgBattle. Using default cfgBattle.'); console.error(err); storedCfgBattle = {}; } mergeCfg(storedCfgBattle, defaultCfgBattle, cfgBattle, 'battle'); } // The translator keeps English in light DOM and renders Chinese in closed shadow roots. // Remove only its transparent wrappers from a read-only snapshot: jpx's log patterns // depend on native td/strong boundaries. Leave both the live DOM and game markup intact. function getBattleLogHTML(element = log, currentTurnOnly = false) { let html = ''; if (currentTurnOnly) { // Native logs prepend the latest action. Stop at its separator instead // of serializing the whole round; keep nested Scan markup unchanged. const body = element?.tBodies?.[0] || element; for (let row = body?.firstElementChild; row; row = row.nextElementSibling) { html += row.outerHTML; if (row.firstElementChild?.className === 'tls') break; } } else html = element?.innerHTML || ''; return html.replace(/<\/?hv-battle-text\b[^>]*>/gi, ''); } function initDoBattle() { doInitDoBattle = true; window.addEventListener('mousemove', () => { if (!jpxPanelManager.ready) jpxPanelManager.ready = true; }); document.addEventListener('DOMContentLoaded', reDoBattle); if (cfgBattle.recordBattleLog) { const rawBattleLog = localStorage.getItem(prefix + 'battleLogRecord' + isekaiSuffix) || '[]'; battleLogRecord = JSON.parse(rawBattleLog); battleLogCheckpoint = Array.isArray(battleLogRecord) ? { record: battleLogRecord, length: battleLogRecord.length, json: rawBattleLog.trimEnd() } : null; } timeRecords = JSON.parse(localStorage.getItem(prefix + 'timeRecords' + isekaiSuffix) || '{}'); if (jpxUtils.isEmpty(timeRecords)) timeRecords = jpxUtils.createTimeRecords(); combatRecords = JSON.parse(localStorage.getItem(prefix + 'combatRecords' + isekaiSuffix) || '{}'); if (jpxUtils.isEmpty(combatRecords)) combatRecords = jpxUtils.createCombatRecords(); revenueRecords = JSON.parse(localStorage.getItem(prefix + 'revenueRecords' + isekaiSuffix) || '{}'); if (jpxUtils.isEmpty(revenueRecords)) revenueRecords = jpxUtils.createRevenueRecords(); //Battle Style battleStyle = getDetectedJpxBattleStyle(); //Battle Type const initialLog = getBattleLogHTML(); let battleTypeLog = initialLog.match(regExp.battleTypeLog); if (battleTypeLog) { if (battleTypeLog[1].includes('arena challenge') && !battleTypeLog[1].includes('Round 1 / 1)')) { battleType = 'Arena'; } else if (battleTypeLog[1].includes('random encounter')) { battleType = 'Encounter'; } else if (battleTypeLog[1].includes('arena challenge') && battleTypeLog[1].includes('Round 1 / 1)')) { battleType = 'Colosseum'; } else if (battleTypeLog[1].includes('Grindfest')) { battleType = 'Battle1000'; } else if (battleTypeLog[1].includes('Item World')) { battleType = 'Item'; } else if (battleTypeLog[1].includes('The Tower')) { battleType = 'Tower'; let floor = battleTypeLog[1].match(regExp.floor); if (floor) towerFloor = floor[1]; } } if (battleType)localStorage.setItem(prefix + 'battleType' + isekaiSuffix, battleType); else battleType = localStorage.getItem(prefix + 'battleType' + isekaiSuffix) || ''; //World Level if (battleType === 'Item') { worldLevel = parseInt(localStorage.getItem(prefix + 'worldLevel' + isekaiSuffix)) || 0; //Tower Floor } else if (battleType === 'Tower') { if (towerFloor) localStorage.setItem(prefix + 'towerFloor' + isekaiSuffix, towerFloor); else towerFloor = parseInt(localStorage.getItem(prefix + 'towerFloor' + isekaiSuffix)) || 0; let difficulty = 'PFUDOR';; if (jpxUtils.inRange(towerFloor, [1, 6])) difficulty = 'Normal'; else if (jpxUtils.inRange(towerFloor, [7, 13])) difficulty = 'Hard'; else if (jpxUtils.inRange(towerFloor, [14, 19])) difficulty = 'Nightmare'; else if (jpxUtils.inRange(towerFloor, [20, 26])) difficulty = 'Hell'; else if (jpxUtils.inRange(towerFloor, [27, 33])) difficulty = 'Nintendo'; else if (jpxUtils.inRange(towerFloor, [34, 39])) difficulty = 'IWBTH'; localStorage.setItem(prefix + 'difficulty' + isekaiSuffix, difficulty); } preDoBattle(initialLog); if (battleType === 'Arena' && roundInfo.total >= 90) { localStorage.setItem(prefix + 'difficulty' + isekaiSuffix, 'PFUDOR'); } } function stopBattleUpdates() { battleUpdateGeneration++; cancelBattleDecision(); battleLogObserver?.disconnect(); battleLogObserver = null; battleLogUpdate?.cancel(); battleLogUpdate = null; battleLogPending = false; battleLogObservedAt = null; monsterInfoRequest?.cancel(); monsterInfoRequest = null; } function isCurrentBattleUpdate(generation, battleLog) { return generation === battleUpdateGeneration && battleLog === log && battleLog?.isConnected && !document.getElementById('riddlemaster'); } function cancelBattleDecision() { clearTimeout(battleDecisionTimer); battleDecisionTimer = null; } function reDoBattle(e) { if (e?.isTrusted) return; stopBattleUpdates(); if (document.querySelector('#riddlemaster')) { riddleRecorder(); return; } isActiveBattle = false; if (cfgBattle.ctrlWidgetMouseEnter) jpxPanelManager.ready = false; // AJAX keeps the floating panel under the cursor, so no new mouseenter fires. // Require a fresh mouse movement, and consume this only for this round reset. jpxPanelManager.roundHoverResume = cfgBattle.ctrlWidgetMouseEnter ? { pointer: jpxPanelManager.lastPointer } : null; monsterData = []; localStorage.removeItem(prefix + 'monsterData' + isekaiSuffix); allMonsterInfo = {}; actionCounts = { history: [] }; monstersEffects = {}; log = document.querySelector('#textlog'); log && preDoBattle(); jpxPanelManager.setBackground('#fef'); jpxPanelManager.dispatchState(); } function preDoBattle(initialLog) { // Reinitialization can target the same DOM, not just a newly fetched round. stopBattleUpdates(); if (!log?.isConnected || document.getElementById('riddlemaster')) return; //Round // One synchronous snapshot serves all initial parsing. Never retain it for // later updates, another document, or an AJAX round replacement. const initialLogHTML = typeof initialLog === 'string' ? initialLog : getBattleLogHTML(); let round = initialLogHTML.match(regExp.round); let storedRoundInfo = JSON.parse(localStorage.getItem(prefix + 'roundInfo' + isekaiSuffix) || '{}'); const changedRound = round && storedRoundInfo.current && (+round[1] !== +storedRoundInfo.current || +round[2] !== +storedRoundInfo.total); if (changedRound) { monsterData = []; localStorage.removeItem(prefix + 'monsterData' + isekaiSuffix); } if (battleType !== 'Encounter') { if (round) { roundInfo.current = +round[1]; roundInfo.total = +round[2]; localStorage.setItem(prefix + 'roundInfo' + isekaiSuffix, JSON.stringify(roundInfo)); } else { roundInfo.current = storedRoundInfo.current || 0; roundInfo.total = storedRoundInfo.total || 0; } } //Proficiency Record if (cfgBattle.showRealTimeProficiency) { let proficiencyRecord = document.querySelector('#proficiency-record'); if (!proficiencyRecord) { proficiencyRecord = document.createElement('table'); proficiencyRecord.id = 'proficiency-record'; document.querySelector('#csp').appendChild(proficiencyRecord); } let proficiencyKeys = Object.keys(revenueRecords.proficiency); if (proficiencyKeys.length) { let innerHTMLTemp = ''; let order = REVENUE_FIELDS.find(f => f.id === 'proficiency').order; let sortedKeys = jpxUtils.getSortedKeys(order, proficiencyKeys); for (const sortedKey of sortedKeys) { let value = revenueRecords.proficiency[sortedKey]; if (value) innerHTMLTemp += `${Math.round(value * 1000) / 1000}${t(`rP.${sortedKey}`)}`; } proficiencyRecord.innerHTML = `${innerHTMLTemp}`; } } //Monster Data let matches; const monsterLogHTML = initialLogHTML; const parsedMonsters = []; while ((matches = regExp.monster.exec(monsterLogHTML)) !== null) { parsedMonsters.unshift({ id: +matches[1], name: matches[2], level: +matches[3], maxHP: +matches[4], }); } let storedMonsterData = JSON.parse(localStorage[prefix + 'monsterData' + isekaiSuffix] || '[]'); if (parsedMonsters.length) { monsterData = parsedMonsters; } if (monsterData.length) { localStorage.setItem(prefix + 'monsterData' + isekaiSuffix, JSON.stringify(monsterData)); } else if (storedMonsterData.length) { monsterData = storedMonsterData; } else { [...document.getElementsByClassName('btm1')].forEach((monster_btm1, index) => { let levelContainer = monster_btm1.querySelector('.btm2 div:last-child'); monsterData.push({ id: 0, name: monster_btm1.id, level: parseInt(levelContainer.textContent.trim() || jpxUtils.parseHVClasses(levelContainer)), maxHP: 100, }); }); } updateMonsterInfo(); //Riddle if (log.textContent.includes('You gain the effect Blessing of the RiddleMaster.') && timeRecords.riddle.lastTurn !== timeRecords.turn) { timeRecords.riddle.lastTurn = timeRecords.turn; timeRecords.riddle.total += 1; } jpxPanelManager.createCtrlWidget('battle'); const generation = battleUpdateGeneration, battleLog = log; battleLogUpdate = jpxUtils.throttle(() => { battleLogPending = false; if (isCurrentBattleUpdate(generation, battleLog)) preProcessLog(); }, 200, true); battleLogObserver = new MutationObserver(() => { if (!isCurrentBattleUpdate(generation, battleLog)) return; battleLogObservedAt = performance.now(); battleLogPending = true; battleLogUpdate(); }); battleLogObserver.observe(log.firstElementChild || (log.prepend(document.createElement('tbody')), log.firstElementChild), { childList: true }); if (cfgBattle.autoFinishBattle === true && document.querySelector('#btcp img[src$="finishbattle.png"]')) preProcessLog(); else preRender(initialLogHTML.match(regExp.turnLog)?.[0]); } // A final log may be observed more than once; share the same recording operation. function recordFinalBattle() { if (!recordFinalBattle.pending) { const finishBattle = document.querySelector('#btcp img[src$="finishbattle.png"]'); recordFinalBattle.pending = Promise.resolve().then(async () => { await battleRecordPlayer(); for (const key of ['battleLogRecord', 'timeRecords', 'combatRecords', 'revenueRecords']) { localStorage.removeItem(prefix + key + isekaiSuffix); } // Use the game's own exit handler only after the record transaction commits. if (cfgBattle.autoFinishBattle === true && finishBattle?.isConnected && !document.querySelector('#riddlemaster')) { finishBattle.click(); } return true; }).catch(error => { console.error('Battle statistics could not finish:', error); jpxUtils.createToast(t('cB.battleRecordWarning'), 10000); return false; }); } return recordFinalBattle.pending; } function preProcessLog() { const started = performance.now(); const queueMs = battleLogObservedAt === null ? null : Math.max(0, started - battleLogObservedAt); battleLogObservedAt = null; lastActionTimestamp = lastLogTimestamp; lastLogTimestamp = Date.now(); try { processBattleLog(); } finally { // Last sample only: no polling, network hooks, persistent log or upload. // Queue time starts at the MutationObserver callback, not response arrival. jpxBattleTiming = { samples: jpxBattleTiming.samples + 1, intervalMs: lastLogTimestamp - lastActionTimestamp, queueMs, processingMs: performance.now() - started, visibility: document.visibilityState }; } } function processBattleLog() { const separator = log.querySelector('td[class="tls"]'); if (separator && separator.innerHTML !== '
') separator.innerHTML = '
'; // Share this update's snapshot only within this synchronous pass; AJAX and // later log mutations must always be read again on the next update. const turnLog = getBattleLogHTML(log, true).match(regExp.turnLog)?.[0]; battleRecorder(turnLog); let btcp = document.querySelector('#btcp'); let finishBattle = document.querySelector('img[src$="finishbattle.png"]'); if (btcp) { localStorage.removeItem(prefix + 'monsterData' + isekaiSuffix); if (finishBattle) { btcp.setAttribute('style', 'display: block; width: max-content; min-width: 380px; max-width: 530px; height: auto; min-height: 120px; max-height: 621px; overflow: auto;'); btcp.classList.add('jpx-final-result'); recordFinalBattle(); return; } } preRender(turnLog); } function preRender(turnLog) { ({ spellCooldowns, itemCooldowns } = getActionCooldowns(true)); vitals = getVitals(); spiritStatus = getSpiritStatus(); monstersObj = getMonsters(true); conditionsObj = null; let { monsters, activeMonsters } = monstersObj; //Monster Effects if (arguments.length) updateMonsterEffects(turnLog); else updateMonsterEffects(); //Player Effects and Render All playerEffectsObj = getEffectDuration(cfgBattle.showDurations); //Monster HP if (cfgBattle.showMonsterHP) { for (let i = 0; i < monsters.length; i++) { if (!monsterData[i]) break; if (monsters[i].hpPercentage) { let maxHP = monsterData[i].maxHP; const owner = monsters[i].monster_btm1; const hpDiv = getBattleDecoration(owner, 'hp', () => { const node = document.createElement('div'); node.className = 'monster-hp'; return node; }); setBattleText(hpDiv, 'HP: ' + Math.round(maxHP * monsters[i].hpPercentage).toLocaleString() + ' / ' + maxHP.toLocaleString()); if (hpDiv.parentNode !== owner) owner.appendChild(hpDiv); } else { jpxBattleDecorations.get(monsters[i].monster_btm1)?.hp?.remove(); } } } else { for (const monster of monsters) jpxBattleDecorations.get(monster.monster_btm1)?.hp?.remove(); } jpxPanelManager.updateContent('battle'); goNext(); } function goNext() { if (document.querySelector('#riddlemaster')) return; if (isActiveBattle) { jpxPanelManager.setBackground('#4f4'); //End of Round let btcp = document.querySelector('#btcp'); let finishBattle = document.querySelector('img[src$="finishbattle.png"]'); if (finishBattle) return; if (!monstersObj.activeMonsters[0]) { if (btcp) { if (cfgBattle.ajaxRound) { btcp.onclick = async function() { if (btcp.style.visibility === 'hidden') return; btcp.style.visibility = 'hidden'; function bindRiddleForm(riddleform) { let submitting = false; let timer; riddleform.addEventListener('submit', e => { e.preventDefault(); if (submitting) return; submitting = true; timer = setTimeout(() => { submitting = false; }, 10000); let formData = new FormData(riddleform); let submitBtn = document.querySelector('#riddlesubmit'); if (submitBtn?.name) formData.append(submitBtn.name, submitBtn.value); fetch(riddleform.action || location.href, { method: 'POST', body: new URLSearchParams(formData), headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Cache-Control': 'max-age=0', }, }) .then(response => response.redirected ? location.href = response.url : response.text()) .then(html => updateBattleMain(new DOMParser().parseFromString(html, 'text/html'))) .catch(err => { console.error('Submission failed: ', err); jpxUtils.createToast(t('cB.riddleSubmitFailed', { reason: String(err) })); }) .finally(() => { submitting = false; clearTimeout(timer); }); }); } function updateBattleMain(doc) { let main = document.querySelector('#battle_main'); let mainNew = doc.querySelector('#battle_main'); document.querySelector('#riddle-panel')?.remove(); clearInterval(window.timer); if (main && mainNew) { main.replaceWith(mainNew); } else { document.body.innerHTML = doc.body.innerHTML; } let t = setTimeout(() => {}, 0); for (let i = t; i > 0 && i > t - 100; clearInterval(i--)); window.battle = new window.Battle(); document.dispatchEvent(new Event('DOMContentLoaded')); } await jpxUtils.xhrGet([location.href]).then((results) => { for (let result of results) { if (result.status === 'rejected') { console.error(result.reason); break; } try { let parser = new DOMParser(); let doc = parser.parseFromString(result.value.responseText, 'text/html'); if (doc.querySelector('#riddlemaster')) { let riddlePanel = document.createElement('div'); riddlePanel.id = 'riddle-panel'; riddlePanel.style.cssText = 'position:fixed; top:0; left:0; z-index:9999; border:2px solid black; overflow:auto;'; riddlePanel.appendChild(document.importNode(doc.body, true)); document.body.appendChild(riddlePanel); bindRiddleForm(riddlePanel.querySelector('#riddleform')); let script = document.createElement('script'); script.type = 'text/javascript'; script.innerHTML = doc.getElementsByTagName('script')[2]?.innerHTML.replace('e("riddleform").submit();', 'e("riddleform")?.requestSubmit();'); riddlePanel.querySelector('#mainpane').appendChild(script); document.dispatchEvent(new Event('DOMContentLoaded')); } else { updateBattleMain(doc); } } catch (e) { console.error('Parsing error for url:', result.value.url); } } }); } } if (cfgBattle.advanceToNextRound && btcp.style.visibility !== 'hidden') { btcp.click(); btcp.style.visibility = 'hidden'; } } return; } switch (readyNext) { case -1: break; default: readyNext = -1; cancelBattleDecision(); const generation = battleUpdateGeneration, battleLog = log; battleDecisionTimer = setTimeout(() => { battleDecisionTimer = null; if (isActiveBattle && isCurrentBattleUpdate(generation, battleLog)) smartBattle(); }, 0); break; } } } const keybindHandlers = { openBattleRecords, toggleActive, openSettings: renderSettings, }; function onKeyDown(e, throttledActionManager) { if (jpxUtils.keyCaptureController) return; let target = e.target; if (target.closest?.('#jpx-records-cleanup-dialog')) return; // Focused panel controls own their arrows, Home, Enter and Space keys. if (target.closest?.('#ctrl-widget') && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'Enter', ' ', 'Escape'].includes(e.key)) return; if ( e.isComposing || (target instanceof HTMLInputElement && !['checkbox', 'radio', 'button', 'submit', 'reset', 'range', 'color', 'file'].includes(target.type) && !target.readOnly && !target.disabled) || (target instanceof HTMLTextAreaElement && !target.readOnly && !target.disabled) || target.isContentEditable ) return; let currentKB = 'kb_' + jpxUtils.formatKeyCombo({ key: e.key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey }, '+'); if (document.getElementById('settings-container')?.open) { if (!e.repeat && userKeybinds.openSettings && currentKB === 'kb_' + jpxUtils.formatKeyCombo(userKeybinds.openSettings, '+')) { e.preventDefault(); e.stopPropagation(); renderSettings(); } return; } if (!e.repeat) { for (const [action, bind] of Object.entries(userKeybinds)) { if (currentKB === ('kb_' + jpxUtils.formatKeyCombo(bind, '+'))) { e.preventDefault(); keybindHandlers[action]?.(); return; } } } if (!log || isActiveBattle || !monstersObj.activeMonsters[0]) return; let actions = getJpxBattleRules()?.[currentKB]; if (actions) { e.preventDefault(); (e.repeat ? throttledActionManager : actionManager)(actions); } } function toggleActive() { if (!log) return; cancelBattleDecision(); jpxPanelManager.roundHoverResume = null; isActiveBattle = !isActiveBattle; if (isActiveBattle) readyNext = 0; jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground(isActiveBattle ? '#4f4' : '#fef'); if (isActiveBattle) goNext(); jpxPanelManager.dispatchState(); } //Battle Smart function smartBattle() { const rules = getJpxBattleRules(); if (!jpxConfigHasContent(rules)) { isActiveBattle = false; readyNext = '\n' + t('cM.noSceneRules'); jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground('#ff5'); return true; } if (actionManager(rules.rules)) return true; isActiveBattle = false; readyNext = "\n" + t('cW.noAvailableAction'); jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground('#ff5'); return false; } //Battle Utils function doSpellsDebuffGoNext({name, targetCount = 3, tailSkip = 0, bottomUp = false, maxAtFirst = Infinity, minMonstersLeft = 10, conditions}) { let { monsters, activeMonsters } = monstersObj; if (spellCooldowns[name] !== 0) return false; let maxDo = 0; if (monsters.length - activeMonsters.length <= 1) { maxDo = maxAtFirst; } else if (activeMonsters.length <= minMonstersLeft) { maxDo = Infinity; } if ((actionCounts[name] ?? 0) >= maxDo) return false; let firstIndex = activeMonsters[0].index; let lastIndex = activeMonsters.at(-1).index; let dir = !bottomUp ? 1 : -1; const startIndex = bottomUp ? monsters.length - 1 - lastIndex : firstIndex; const limit = bottomUp ? monsters.length - firstIndex : lastIndex + 1; const endIndex = Math.min(tailSkip >= 0 ? limit - tailSkip : startIndex + Math.abs(tailSkip), monsters.length); if (endIndex <= 0) return false; let undebuffedObj = {}; const isUnDebuffed = (i) => { return undebuffedObj[i] ??= ( !!monsters[i]?.isAlive && checkConditions(conditions, monsters[i], false) ); }; const getIndex = (j) => !bottomUp ? j : monsters.length - 1 - j; const castAtEdge = (i, j) => { if ((targetCount === 2 && !bottomUp || targetCount === 3) && i === startIndex && monsters[j + dir]?.isAlive) j += dir; else if ((targetCount === 2 && bottomUp || targetCount === 3) && i === endIndex - 1 && monsters[j - dir]?.isAlive) j -= dir; doSpellGoNext(name, monsters[j]); return true; }; if (targetCount >= 3) { for (let i = startIndex + 1; i < endIndex - 1; i++) { let j = getIndex(i); if (!isUnDebuffed(j - 1) || !isUnDebuffed(j) || !isUnDebuffed(j + 1)) continue; doSpellGoNext(name, monsters[j]); return true; } } if (targetCount >= 2) { for (let i = startIndex; i < endIndex; i++) { let j = getIndex(i); if (!isUnDebuffed(j - 1) || !isUnDebuffed(j)) continue; return castAtEdge(i, j); } } if (targetCount >= 3) { for (let i = startIndex + 1; i < endIndex - 1; i++) { let j = getIndex(i); if (!isUnDebuffed(j - 1) || !monsters[j]?.isAlive || !isUnDebuffed(j + 1)) continue; doSpellGoNext(name, monsters[j]); return true; } } for (let i = startIndex; i < endIndex; i++) { let j = getIndex(i); if (!isUnDebuffed(j)) continue; return castAtEdge(i, j); } return false; } function doSpellGoNext(spell, monster) { readyNext = 0; if (monster?.isAlive && spellCooldowns[spell] === 0) { cast(spell); monster.click(); return true; } return false; } function doAttackGoNext(monster) { readyNext = 0; if (monster?.isAlive) { monster.click(); return true; } return false; } function doToggleGoNext(name) { readyNext = 0; let state = document.querySelector('#ckey_' + name.toLowerCase()); if (state) { dummy.setAttribute('onclick', state.getAttribute('onmouseover')); dummy.click(); state.click(); return true; } return false; } function cast(name) { let spell = document.querySelector('.bts > div[onclick][onmouseover*="\'' + name + '\'"]'); if (document.getElementsByClassName('btii')[0].textContent != name && spell) { dummy.setAttribute('onclick', spell.getAttribute('onmouseover')); dummy.click(); spell.click(); } } function use(name) { let id = Object.entries(itemMap).find(([id, _name]) => _name === name)?.[0]; if (!id) return; let itemArray = Array.from(document.querySelectorAll('.bti3 > div[onclick][onmouseover]')); let item = itemArray.find(div => div.outerHTML.includes(id)); if (item) { dummy.setAttribute('onclick', item.getAttribute('onmouseover')); dummy.click(); item.click(); } } function getActionCooldowns(render = false) { let quickbarObj = {}; function scan({selector, regexp, getName, getInitlCooldown}) { let result = {}; for (const slot of document.querySelectorAll(selector)) { let tooltip = slot.getAttribute('onmouseover'); let matches = tooltip?.match(regexp); const name = matches ? getName(matches) : slot.textContent?.trim() || jpxUtils.parseHVClasses(slot.querySelector('div'), true); if (!name) continue; let cooldown; let onClick = slot.getAttribute('onclick'); if (onClick) { cooldown = 0; result[name] = 0; } else { let lastUse = timeRecords.lastUse[name] ?? -Infinity; let initCooldown = getInitlCooldown(matches); cooldown = lastUse + initCooldown - timeRecords.turn; result[name] = cooldown > 0 ? cooldown : '-'; } if (!render) continue; const info = { tooltip, onClick, cooldown }; if (slot.id === 'ikey_p') { info.name = name; quickbarObj.ikey_p = info; } else quickbarObj[name] = info; } return result; } function getQuickName(quick) { if (quick.id?.startsWith('extend_')) return quick.id.slice(7); let tooltip = quick.getAttribute('onmouseover'); if (!tooltip) return; return tooltip.match(regExp.spellInfo)?.[1]; } function renderQuickbar() { let quickbar = document.querySelector('#quickbar'); if (!quickbar) return; const state = getBattleDecoration(quickbar, 'extensions', () => ({ slots: [] })); cfgBattle.quickbarExtend.forEach((name, index) => { let slot = state.slots[index]; if (!slot || slot.name !== name) { slot?.root.remove(); const root = document.createElement('div'), inner = document.createElement('img'), outer = document.createElement('img'); root.id = 'extend_' + name; root.className = 'btqs extend'; inner.className = 'btqi'; outer.className = 'btqb'; outer.src = '/y/ab/b.png'; root.appendChild(outer); state.slots[index] = slot = { name, root, inner, outer }; } const quickDiv = slot.root, innerImg = slot.inner; if (quickbarObj[name]) { let tooltip = quickbarObj[name].tooltip; setBattleAttribute(quickDiv, 'onmouseover', tooltip || ''); let onClick = quickbarObj[name].onClick; setBattleAttribute(quickDiv, 'onclick', onClick || null); const opacity = onClick ? '' : '0.5'; if (innerImg.style.opacity !== opacity) innerImg.style.opacity = opacity; let spellIconID = tooltip?.match(regExp.spellInfo)?.[2]; const src = spellIconID ? '/y/a/' + spellIconID + '.png' : itemSrc.find(rule => rule.keys.some(key => { if (name === 'ikey_p') return quickbarObj[name].name.includes(key); return name.includes(key); }))?.src ?? '/y/e/channeling.png'; setBattleAttribute(innerImg, 'src', src); if (innerImg.parentNode !== quickDiv) quickDiv.insertBefore(innerImg, slot.outer); } else { setBattleAttribute(quickDiv, 'onmouseover', null); setBattleAttribute(quickDiv, 'onclick', null); innerImg.remove(); } }); for (const slot of state.slots.splice(cfgBattle.quickbarExtend.length)) slot.root.remove(); // Keep configured order and native slots; unchanged DOM needs no moves. let next = null; for (let i = state.slots.length - 1; i >= 0; i--) { const root = state.slots[i].root; if (root.parentNode !== quickbar || root.nextSibling !== next) quickbar.insertBefore(root, next); next = root; } showCooldowns(quickbar); } function showCooldowns(quickbar) { for (const quick of quickbar.querySelectorAll('.btqs')) { let name = getQuickName(quick); let cooldown = quickbarObj[name]?.cooldown; if (!cfgBattle.showCooldowns || quick.hasAttribute('onclick') || !(cooldown > 0)) { jpxBattleDecorations.get(quick)?.cooldown?.remove(); continue; } const cooldownDiv = getBattleDecoration(quick, 'cooldown', () => { const node = document.createElement('div'); node.className = 'cooldown'; return node; }); setBattleText(cooldownDiv, cooldown); if (cooldownDiv.parentNode !== quick) quick.appendChild(cooldownDiv); } } let spellCooldowns = scan({ selector: '.bts > div[onmouseover]', regexp: regExp.spellInfo, getName: m => m[1], getInitlCooldown: m => m ? +m[5] : 0 }); let itemCooldowns = scan({ selector: '.bti3 > div', regexp: regExp.itemInfo, getName: m => itemMap[+m[1]], getInitlCooldown: () => 40 }); if (render) renderQuickbar(); return { spellCooldowns, itemCooldowns }; } function getVitals() { let ocBar = document.querySelector('img[src$="bar_orange.png"]'); let vitalCfg = ocBar ? { widthHP: 414, widthMP: 414, widthSP: 414, widthOC: 414, idHP: ['#dvrhb', '#dvrhd'], idMP: '#dvrm', idSP: '#dvrs', } : { widthHP: 496, widthMP: 207, widthSP: 207, idHP: ['#vrhb', '#vrhd'], idMP: '#vrm', idSP: '#vrs', }; let oc = 0; if (ocBar) { oc = Math.round(10 * parseInt(ocBar.style.width, 10) / vitalCfg.widthOC * 1000) / 1000; } else { let vcp = document.querySelector('#vcp')?.innerHTML; if (vcp) { let matches = vcp.match(regExp.oc); if (matches) { oc = matches.length / 2 - 1; if (vcp.match(regExp.ocHalf)) { oc -= 0.5; } } } } let hpPercentage = Math.round(parseInt(document.querySelector('img[src$="green.png"]').style.width, 10) / vitalCfg.widthHP * 1000) / 1000; let mpPercentage = Math.round(parseInt(document.querySelector('img[src$="bar_blue.png"]').style.width, 10) / vitalCfg.widthMP * 1000) / 1000; let spPercentage = Math.round(parseInt(document.querySelector('img[src$="bar_red.png"]').style.width, 10) / vitalCfg.widthSP * 1000) / 1000; // Native counters are plain text. Avoid forcing layout after quickbar writes; // retain rendered-text semantics when another script adds child elements. const readVital = id => { const node = document.querySelector(id); return node?.childElementCount === 0 ? node.textContent : node?.innerText; }; let hpCurrentText = vitalCfg.idHP.map(readVital).find(Boolean) || "0"; let hpCurrent = parseInt(hpCurrentText, 10) || 0; let mpCurrent = parseInt(readVital(vitalCfg.idMP), 10); let spCurrent = parseInt(readVital(vitalCfg.idSP), 10); let hpMax = Math.round(hpCurrent / hpPercentage * 10) / 10; let mpMax = Math.round(mpCurrent / mpPercentage * 10) / 10; let spMax = Math.round(spCurrent / spPercentage * 10) / 10; return { oc, hpPercentage, mpPercentage, spPercentage, hpCurrent, mpCurrent, spCurrent, hpMax, mpMax, spMax, } } function getSpiritStatus() { let ckey_spirit = document.querySelector('#ckey_spirit'); let spiritStatus = ckey_spirit.outerHTML.includes('spirit_a.png'); return spiritStatus; } function getEffectDuration(render = false) { let playerEffectObj = {}; let effectsPane = document.querySelector('#pane_effects'); let effects = Array.from(effectsPane.getElementsByTagName('img')); let playerEffectsLength = effects.length; effects.push(...document.querySelectorAll('.btm6 > img[onmouseover]')); effects.forEach((effect, index) => { let tooltip = effect.getAttribute('onmouseover'); if (index >= playerEffectsLength && !render) { jpxBattleDecorations.get(effect)?.duration?.root.remove(); return; } if (!tooltip) { jpxBattleDecorations.get(effect)?.duration?.root.remove(); return; } let matches = tooltip.match(regExp.spellMatch); if (!matches?.groups) { jpxBattleDecorations.get(effect)?.duration?.root.remove(); return; } let { name, stack, description, turns } = matches.groups; if (index < playerEffectsLength && name) playerEffectObj[name] = { turns, stack: stack ?? 1 }; if (render) { let displayTurns = turns; const duration = getBattleDecoration(effect, 'duration', () => { const root = document.createElement('div'), value = document.createElement('div'); root.className = 'effect-duration'; root.appendChild(value); return { root, value, background: '' }; }); const durationContainer = duration.root, durationDiv = duration.value; let background = ''; if (turns < 9) { background = turns < 4 ? 'aquamarine' : 'lavender'; } else if (turns === 'autocast') { displayTurns = 'auto'; } else if (turns === 'permanent') { displayTurns = decodeURIComponent('%E2%88%9E'); } else if (turns === 'decaying') { displayTurns = ''; } else if (turns === '-') { displayTurns = '-'; } if (duration.background !== background) { durationDiv.style.background = background; duration.background = background; } setBattleText(durationDiv, displayTurns + (stack ? (turns !== 'decaying' ? '\u00a0' : '') + 'x' + stack : '')); if (durationContainer.nextSibling !== effect || durationContainer.parentNode !== effect.parentNode) effect.before(durationContainer); } else { jpxBattleDecorations.get(effect)?.duration?.root.remove(); } }); return playerEffectObj; } function getMonsters(render = false) { let monsters = []; let activeMonsters = []; let bosses = []; let activeBosses = []; [...document.getElementsByClassName('btm1')].forEach((monster_btm1, index) => { let monsterInfo = allMonsterInfo?.[`mkey_${(index + 1) % 10}`]; let monster = { index: index, click: function() { monster_btm1.click(); }, level: 0, name: 'Unknown', type: 'Normal', hpPercentage: 0, mpPercentage: 0, spPercentage: 0, isAlive: monster_btm1.hasAttribute('onclick'), effectObj: {}, monster_btm1: monster_btm1, }; //level let monster_btm2 = monster_btm1.querySelector('.btm2'); let levelContainer = monster_btm2.querySelector(':scope > div:last-child'); monster.level = parseInt(levelContainer.textContent.trim() || jpxUtils.parseHVClasses(levelContainer)); const indexContainer = monster_btm2.querySelector('div'); //index if (render && (cfgBattle.showMonsterIndex || cfgBattle.showMonsterInfo)) { const image = monster_btm2.querySelector('img'); if (image.style.display !== 'none') image.style.display = 'none'; const monIndex = getBattleDecoration(indexContainer, 'index', () => { const node = document.createElement('div'); node.style.fontWeight = 'bold'; return node; }); setBattleText(monIndex, index + 1); const size = cfgBattle.showMonsterInfo ? '17px' : '28px'; if (monIndex.style.fontSize !== size) monIndex.style.fontSize = size; if (monIndex.parentNode !== indexContainer) indexContainer.appendChild(monIndex); } else if (render) { const monIndex = jpxBattleDecorations.get(indexContainer)?.index; if (monIndex?.parentNode === indexContainer) { monIndex.remove(); monster_btm2.querySelector('img').style.display = ''; } } //info: monsterClass if (render && cfgBattle.showMonsterInfo) { const monClass = getBattleDecoration(indexContainer, 'monsterClass', () => { const node = document.createElement('div'); node.dataset.field = 'monClass'; node.style.cssText = 'font-size: 10px; font-weight: bold; overflow: hidden;'; return node; }); setBattleText(monClass, monsterInfo?.monsterClass ?? '?'); if (monClass.parentNode !== indexContainer) indexContainer.prepend(monClass); } else if (render) { jpxBattleDecorations.get(indexContainer)?.monsterClass?.remove(); } //name let monster_btm3 = monster_btm1.querySelector('.btm3'); let nameContainer = monster_btm3.querySelector('div'); const previousInfo = jpxBattleDecorations.get(nameContainer)?.info; const nameText = previousInfo?.parentNode === nameContainer ? Array.from(nameContainer.childNodes, node => node === previousInfo ? '' : node.textContent).join('') : nameContainer.textContent; monster.name = nameText.trim() || jpxUtils.parseHVClasses(nameContainer); //type monster.type = bossTypes.get(monster.name) || 'Normal'; if (monster.type !== 'Normal') { monster.isAlive && activeBosses.push(monster); bosses.push(monster); } //info: attackType, powerLevel, trainer if (render && cfgBattle.showMonsterInfo) { const name = monster_btm3.querySelector(':scope > div > div'); if (name.style.display !== 'inline') name.style.display = 'inline'; const monTrAtkPl = getBattleDecoration(nameContainer, 'info', () => { const node = document.createElement('span'); node.dataset.field = 'monTrAtkPl'; node.style.cssText = 'font-weight: bold; position: absolute; right: 2px;'; return node; }); setBattleText(monTrAtkPl, jpxUtils.isEmpty(monsterInfo) ? '' : `${monsterInfo?.attack ?? '?'}, ${monsterInfo?.plvl ?? '?'}`); if (monTrAtkPl.parentNode !== nameContainer) nameContainer.appendChild(monTrAtkPl); } else if (render) { previousInfo?.remove(); } //hpPercentage, mpPercentage, spPercentage let monster_btm4 = monster_btm1.querySelector('.btm4'); let healthBar = monster_btm4.querySelector('img[src$="nbargreen.png"]'); monster.hpPercentage = Math.round((parseInt(healthBar?.style.width, 10) / 120) * 100) / 100 || 0; let manaBar = monster_btm4.querySelector('img[src$="nbarblue.png"]'); monster.mpPercentage = Math.round((parseInt(manaBar?.style.width, 10) / 120) * 100) / 100 || 0; let spiritBar = monster_btm4.querySelector('img[src$="nbarred.png"]'); monster.spPercentage = Math.round((parseInt(spiritBar?.style.width, 10) / 120) * 100) / 100 || 0; //status let monster_btm6 = monster_btm1.querySelector('.btm6'); monster_btm6.querySelectorAll('img').forEach((effect) => { if (jpxHiddenEffectImages.has(effect)) return; let tooltip = effect.getAttribute('onmouseover'); if (!tooltip) return; let matches = tooltip.match(regExp.spellMatch); if (!matches?.groups) return; let { name, stack, description, turns } = matches.groups; if (name) monster.effectObj[name] = { turns, stack: stack ?? 1 }; }); monsters.push(monster); monster.isAlive && activeMonsters.push(monster); }); return { monsters, activeMonsters, bosses, activeBosses, } } function updateMonsterEffects(turnLog) { let { monsters, activeMonsters } = monstersObj; function getEffectChanges(turnLog) { let effectsAdded = turnLog.matchAll(regExp.effectGain); let effectsRemoved = [...turnLog.matchAll(regExp.effectExpired), ...turnLog.matchAll(regExp.effectWear)]; let asleepRemoved = turnLog.matchAll(regExp.effectWearAsleep); let confusedRemoved = turnLog.matchAll(regExp.effectWearConfused); let effectChanges = {}; for (const match of effectsAdded) (effectChanges[match[1]] ??= { add: [], remove: [] }).add.push(match[2]); for (const match of effectsRemoved) (effectChanges[match[2]] ??= { add: [], remove: [] }).remove.push(match[1]); for (const match of asleepRemoved) (effectChanges[match[1]] ??= { add: [], remove: [] }).remove.push('Asleep'); for (const match of confusedRemoved) (effectChanges[match[1]] ??= { add: [], remove: [] }).remove.push('Confused'); return effectChanges; } function calcHiddenDelta(name, effectObj) { let savedEffects = monstersEffects[name]; if (!savedEffects) return; let maxDecrease = 0; for (const effect in effectObj) { let savedTurns = +savedEffects[effect]?.turns; let effectTurns = +effectObj[effect]?.turns; if (!isNaN(savedTurns) && !isNaN(effectTurns)) { let delta = savedTurns - effectTurns; if (delta > 0) maxDecrease = Math.max(maxDecrease, delta); } } return maxDecrease; } function applyHiddenDelta(name, effectObj, delta) { let savedEffects = monstersEffects[name]; if (!savedEffects) return; let elementEffects = ['Searing Skin', 'Freezing Limbs', 'Turbulent Air', 'Deep Burns', 'Breached Defense', 'Blunted Attack']; let effects = Object.keys(effectObj); let elementCount = effects.filter(effect => elementEffects.includes(effect)).length; for (const savedEffect in savedEffects) { if (effects.includes(savedEffect)) continue; if ( (elementCount < 3 && elementEffects.includes(savedEffect)) || savedEffect === 'Coalesced Mana' ) { delete savedEffects[savedEffect]; continue; } if (!delta || delta <= 0) continue; let savedTurns = +savedEffects[savedEffect]?.turns; if (isNaN(savedTurns)) continue; if (savedTurns - delta < 0 && elementEffects.includes(savedEffect)) { delete savedEffects[savedEffect]; continue; } savedEffects[savedEffect].turns = Math.max(0, savedTurns - delta); } } if (!arguments.length) turnLog = getBattleLogHTML(log, true).match(regExp.turnLog)?.[0]; let effectChanges = turnLog ? getEffectChanges(turnLog) : {}; for (const activeMonster of activeMonsters) { let name = activeMonster.name; let savedEffects = monstersEffects[name] ??= {}; let effectObj = activeMonster.effectObj; let effects = Object.keys(effectObj); const hiddenNames = new Set(); const monster_btm6 = activeMonster.monster_btm1.querySelector('.btm6'); if (effects.length < 5) { for (const effect in savedEffects) delete savedEffects[effect]; } else if (effects.length === 5) { for (const effect in savedEffects) delete savedEffects[effect]; for (const effect of effects) savedEffects[effect] = { ...effectObj[effect] }; } else if (effects.length === 6) { let delta = calcHiddenDelta(name, effectObj); for (const effect of effects) savedEffects[effect] = { ...effectObj[effect] }; if (effectChanges[name]) { for (const effect of effectChanges[name].add) !effects.includes(effect) && (savedEffects[effect] = { turns: '-', stack: '-' }); for (const effect of effectChanges[name].remove) (!effects.includes(effect) && (effect in savedEffects)) && delete savedEffects[effect]; } applyHiddenDelta(name, effectObj, delta); if (monster_btm6.style.width !== 'max-content') monster_btm6.style.width = 'max-content'; const hidden = getBattleDecoration(monster_btm6, 'hiddenEffects', () => new Map()); for (const effect in savedEffects) { if (!(effect in effectObj)) { hiddenNames.add(effect); let { turns, stack } = savedEffects[effect]; effectObj[effect] = { turns, stack }; if (isNaN(+turns)) turns = `'${String(turns).replace(/'/g, "\\'")}'`; let img = hidden.get(effect); if (!img) { img = document.createElement('img'); hidden.set(effect, img); jpxHiddenEffectImages.add(img); img.src = (isekaiSuffix ? '/isekai' : '') + (effectSrc[effect]?.scr || '/y/e/channeling.png'); img.setAttribute('onmouseout', 'battle.clear_infopane()'); } setBattleAttribute(img, 'onmouseover', `battle.set_infopane_effect('${effect}', 'jpx Hidden Effects', ${turns})`); if (img.parentNode !== monster_btm6) monster_btm6.appendChild(img); } } } const hidden = jpxBattleDecorations.get(monster_btm6)?.hiddenEffects; if (hidden) for (const [effect, img] of hidden) { if (hiddenNames.has(effect)) continue; jpxBattleDecorations.get(img)?.duration?.root.remove(); img.remove(); hidden.delete(effect); } } } let jpxMonsterDatabase; const jpxMonsterWorld = () => isekaiSuffix ? 'isekai' : 'persistent'; function needsJpxMonsterDatabase() { if (cfgBattle.showMonsterInfo) return true; const keys = new Set(['tClasses', 'tPowerLevel', 'tDaysSinceUpdate']); const uses = item => { if (!item || typeof item !== 'object' || item.disabled) return false; return keys.has(item.key) || Object.values(item).some(uses); }; return uses(getJpxBattleRules()); } function getJpxMonsterDatabase() { return jpxMonsterDatabase ||= createJpxMonsterDatabase({ indexedDB: window.indexedDB, request: world => new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { reject(new Error('Userscript HTTP API unavailable')); return; } GM_xmlhttpRequest({ method: 'GET', url: 'https://hv-monsterdb-data.skk.moe/' + world + '.json', anonymous: true, timeout: 30000, onload: response => { if (response.status !== 200) { reject(new Error('Monster database HTTP ' + response.status)); return; } try { resolve(JSON.parse(response.responseText)); } catch (error) { reject(error); } }, onerror: () => reject(new Error('Monster database network error')), ontimeout: () => reject(new Error('Monster database request timed out')), onabort: () => reject(new Error('Monster database request aborted')) }); }), changed: () => { if (log?.isConnected) updateJpxBuiltinMonsterInfo(false); } }); } function getJpxMonsterTargets() { const decoder = document.createElement('textarea'); const spawned = new Map(monsterData.filter(row => row.id > 0).map(row => { decoder.innerHTML = row.name; return [decoder.value, row.id]; })); return Array.from(document.querySelectorAll('#battle_right .btm1'), node => { const nameNode = node.querySelector('.btm3 > div') || node.querySelector('.btm3'); const text = nameNode ? Array.from(nameNode.childNodes, child => child.dataset?.field === 'monTrAtkPl' ? '' : child.textContent).join('').trim() : ''; const name = text || (nameNode ? jpxUtils.parseHVClasses(nameNode) : ''); return { key: node.id, name, id: spawned.get(name) || 0 }; }).filter(row => row.key && row.name); } function renderJpxMonsterInfo() { if (!cfgBattle.showMonsterInfo) return; for (const monster of monstersObj.monsters) { if (!monster.monster_btm1.isConnected) continue; const info = allMonsterInfo?.[monster.monster_btm1.id]; const monClass = monster.monster_btm1.querySelector('[data-field="monClass"]'); if (monClass) setBattleText(monClass, info?.monsterClass ?? '?'); const details = monster.monster_btm1.querySelector('[data-field="monTrAtkPl"]'); if (details) setBattleText(details, info ? `${info.attack ?? '?'}, ${info.plvl ?? '?'}` : ''); } } async function updateJpxBuiltinMonsterInfo(download = true) { if (!needsJpxMonsterDatabase()) return; const generation = battleUpdateGeneration, battleLog = log, targets = getJpxMonsterTargets(); if (!targets.length || !isCurrentBattleUpdate(generation, battleLog)) return; try { const info = await getJpxMonsterDatabase().lookup(jpxMonsterWorld(), targets, download); if (!isCurrentBattleUpdate(generation, battleLog)) return; for (const [key, row] of Object.entries(info)) { const current = allMonsterInfo[key]; if (!current || current.monsterId !== row.monsterId || !(Date.parse(current.lastUpdate) > Date.parse(row.lastUpdate))) allMonsterInfo[key] = row; } renderJpxMonsterInfo(); } catch (error) { console.warn('JPX monster cache unavailable.', error); } } function recordJpxMonsterScan(html) { if (!html?.includes('Scanning')) return; const targets = getJpxMonsterTargets(); const row = parseJpxMonsterScan(html, targets, document); if (!row || !getJpxMonsterDatabase().normalize(row)) return; const target = targets.find(item => item.id === row.monsterId); allMonsterInfo[target.key] = row; renderJpxMonsterInfo(); getJpxMonsterDatabase().scan(jpxMonsterWorld(), row).catch(error => console.warn('JPX monster scan could not be cached.', error)); } // BEGIN JPX MONSTER DATABASE // Public data: https://hv-monster.skk.moe/ (Sukka Monster Database). // Store only the fields JPX consumes. IndexedDB avoids reading a full database // on navigation or putting megabytes into the synchronous settings store. function createJpxMonsterDatabase({ indexedDB, request, now = Date.now, changed = () => {} }) { const classes = new Set('Arthropod Avion Beast Celestial Daimon Dragonkin Elemental Giant Humanoid Mechanoid Reptilian Sprite Undead Common Rare Legendary Ultimate'.split(' ')); const attacks = new Set('Piercing Crushing Slashing Fire Cold Wind Elec Holy Dark Void'.split(' ')); const pending = new Map(); let opening; const day = () => new Date(now()).toISOString().slice(0, 10); function normalize(row) { if (!row || !Number.isSafeInteger(row.monsterId) || row.monsterId <= 0 || typeof row.monsterName !== 'string' || !row.monsterName.trim() || row.monsterName.length > 256 || !classes.has(row.monsterClass) || !attacks.has(row.attack) || !Number.isSafeInteger(row.plvl) || row.plvl < 0 || typeof row.lastUpdate !== 'string' || !Number.isFinite(Date.parse(row.lastUpdate))) return null; return { monsterId: row.monsterId, monsterName: row.monsterName, monsterClass: row.monsterClass, attack: row.attack, plvl: row.plvl, lastUpdate: row.lastUpdate }; } function open() { if (!opening) opening = new Promise((resolve, reject) => { const req = indexedDB.open('jpx-monster-database-v1', 1); req.onupgradeneeded = () => { const db = req.result; const records = db.createObjectStore('monsters', { keyPath: ['world', 'monsterId'] }); records.createIndex('name', ['world', 'monsterName']); db.createObjectStore('meta'); db.createObjectStore('scans', { keyPath: ['world', 'monsterId'] }).createIndex('name', ['world', 'monsterName']); }; req.onerror = () => reject(req.error); req.onblocked = () => reject(new Error('Monster cache is blocked by another tab')); req.onsuccess = () => { req.result.onversionchange = () => { req.result.close(); opening = null; }; resolve(req.result); }; }).catch(error => { opening = null; throw error; }); return opening; } const value = req => new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); const done = tx => new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onerror = tx.onabort = () => reject(tx.error || new Error('Monster cache write aborted')); }); async function metadata(world) { const db = await open(); return await value(db.transaction('meta').objectStore('meta').get(world)) || {}; } async function claimRefresh(world) { const db = await open(), tx = db.transaction('meta', 'readwrite'), complete = done(tx); const store = tx.objectStore('meta'), req = store.get(world); let claimed = false; req.onsuccess = () => { const meta = req.result || {}; if (meta.day === day() || meta.retryAfter > now()) return; claimed = true; // This read and write share one transaction, so different tabs do // not both start the large daily download. Failure expires the lease. store.put({ ...meta, retryAfter: now() + 5 * 60 * 1000 }, world); }; await complete; return claimed; } async function refresh(world) { if (pending.has(world)) return pending.get(world); const job = (async () => { if (!await claimRefresh(world)) return false; const rows = await request(world); if (!Array.isArray(rows) || !rows.length || rows.length > 200000) throw new Error('Invalid monster database response'); const records = [], ids = new Set(); for (let offset = 0; offset < rows.length; offset += 500) { for (const input of rows.slice(offset, offset + 500)) { const row = normalize(input); if (!row) continue; if (ids.has(row.monsterId)) throw new Error('Monster database contains duplicate IDs'); ids.add(row.monsterId); records.push(row); } if (offset + 500 < rows.length) await new Promise(resolve => setTimeout(resolve, 0)); } if (records.length < rows.length * 0.95) throw new Error('Monster database contains invalid records'); const db = await open(), tx = db.transaction(['monsters', 'meta'], 'readwrite'), complete = done(tx); const store = tx.objectStore('monsters'); // Replace just this world's snapshot, atomically. Readers see the old // snapshot until commit; failed downloads/writes never erase it. store.delete(IDBKeyRange.bound([world, 0], [world, Number.MAX_SAFE_INTEGER])); let offset = 0; const batch = () => { try { const end = Math.min(offset + 250, records.length); let last; for (; offset < end; offset++) last = store.put({ ...records[offset], world }); // Continue inside IDB success events: the transaction remains // atomic while each small batch yields to rendering/input. if (offset < records.length) last.onsuccess = batch; else tx.objectStore('meta').put({ day: day(), count: records.length }, world); } catch { tx.abort(); } }; batch(); await complete; return true; })().finally(() => pending.delete(world)); pending.set(world, job); return job; } async function read(world, targets) { const result = {}, db = await open(); const tx = db.transaction(['monsters', 'scans']); const store = tx.objectStore('monsters'), scans = tx.objectStore('scans'); await Promise.all(targets.map(async target => { const base = target.id > 0 ? store.get([world, target.id]) : store.index('name').get([world, target.name]); // An authoritative spawned ID must never fall back to a different // monster with the same name. Name lookup is only for mid-round reloads. const scan = target.id > 0 ? scans.get([world, target.id]) : scans.index('name').get([world, target.name]); const [cached, local] = await Promise.all([value(base), value(scan)]); let row = local && (!cached || Date.parse(local.lastUpdate) >= Date.parse(cached.lastUpdate)) ? local : cached; row = row ? normalize(row) : null; if (row) result[target.key] = { ...row }; })); return result; } async function lookup(world, targets, download = true) { const cached = await read(world, targets); if (!download) return cached; if (Object.keys(cached).length) { refresh(world).then(updated => { if (updated) changed(); }).catch(error => console.warn('JPX monster database refresh failed; using cached data.', error)); return cached; } try { if (await refresh(world)) return await read(world, targets); } catch (error) { console.warn('JPX monster database unavailable.', error); } return cached; } async function scan(world, record) { const row = normalize(record); if (!row) return false; const db = await open(), tx = db.transaction('scans', 'readwrite'), complete = done(tx); tx.objectStore('scans').put({ ...row, world }); await complete; return true; } return { lookup, refresh, scan, normalize, metadata }; } // Parse only the fields displayed/used by JPX. Both old and new Scan layouts // use labelled table cells; parsing detached DOM also handles translation wrappers. function parseJpxMonsterScan(html, targets, document, timestamp = Date.now()) { if (!html?.includes('Scanning')) return null; const template = document.createElement('template'); template.innerHTML = html; const root = template.content; const name = root.textContent.match(/Scanning\s+(.+?)\.\.\./)?.[1]?.trim(); const target = targets.find(item => item.name === name); if (!target?.id) return null; const fields = {}; for (const cell of root.querySelectorAll('td')) { const label = cell.textContent.trim().replace(/:$/, ''); if (['Monster Class', 'Melee Attack', 'Attack Type', 'Attack'].includes(label)) fields[label] = cell.nextElementSibling?.textContent.trim(); } const type = fields['Monster Class']?.match(/^([A-Za-z]+)(?:,\s*Power Level (\d+))?$/); const attack = (fields['Melee Attack'] || fields['Attack Type'] || fields.Attack)?.match(/^([A-Za-z]+)(?:[;\s]|$)/)?.[1]; if (!type || !attack) return null; return { monsterId: target.id, monsterName: name, monsterClass: type[1], plvl: Number(type[2] || 0), attack, lastUpdate: new Date(timestamp).toISOString() }; } // END JPX MONSTER DATABASE function getMonsterInfoSignature(info) { // The fields consumed by display and battle conditions can change after Scan // even when the database mutates the same object and keeps the monster IDs. return JSON.stringify(Object.entries(info).map(([key, monster]) => [key, monster?.monsterId, monster?.monsterClass, monster?.attack, monster?.plvl, monster?.lastUpdate])); } function monsterDBReady(previousIds, previousSignature, generation, battleLog, refresh) { const request = { refresh, cancel: null, promise: null }; request.promise = new Promise(resolve => { const start = Date.now(); let timer = null; const finish = result => { clearTimeout(timer); timer = null; resolve(result); }; request.cancel = () => finish(); (function loop() { if (!isCurrentBattleUpdate(generation, battleLog)) { finish(); return; } const database = window.HVMonsterDB; const available = typeof database?.getCurrentMonstersInformation === 'function'; let info; try { if (available) info = database.getCurrentMonstersInformation(); } catch { /* An optional plugin may not have completed initialization. */ } const valid = info && typeof info === 'object' && !jpxUtils.isEmpty(info); const monsterIds = valid ? Object.values(info).map(monster => monster?.monsterId ?? '').join('|') : ''; const signature = valid && (monsterIds !== previousIds || request.refresh) ? getMonsterInfoSignature(info) : ''; const result = valid ? { info, monsterIds, signature } : undefined; if (valid && (monsterIds !== previousIds || (request.refresh && signature !== previousSignature))) { finish(result); return; } const remaining = 250 - (Date.now() - start); if (remaining <= 0) { finish(request.refresh ? result : undefined); return; } // Keep the existing ready-plugin cadence, but discover an absent API // at most five more times within the same bounded compatibility window. timer = setTimeout(loop, available ? Math.min(10, remaining) : 50); })(); }); return request; } function updateMonsterInfo(refresh = false) { const generation = battleUpdateGeneration, battleLog = log; if (!isCurrentBattleUpdate(generation, battleLog)) return Promise.resolve(); // Same IDs are safe for Scan refresh only after accepting this round's data. refresh = refresh && !jpxUtils.isEmpty(allMonsterInfo); if (monsterInfoRequest) { monsterInfoRequest.refresh ||= refresh; return monsterInfoRequest.promise; } const request = monsterDBReady(prevMonsterIds, prevMonsterInfoSignature, generation, battleLog, refresh); monsterInfoRequest = request; const builtin = updateJpxBuiltinMonsterInfo(); const companion = request.promise.then(result => { if (!result || !isCurrentBattleUpdate(generation, battleLog)) return; // Retain a newer local Scan if the companion has not processed it yet. const merged = { ...result.info }; for (const [key, current] of Object.entries(allMonsterInfo)) { const row = merged[key]; if (getJpxMonsterDatabase().normalize(current) && (!row || (current.monsterId === row.monsterId && Date.parse(current.lastUpdate) > Date.parse(row.lastUpdate)))) merged[key] = current; } allMonsterInfo = merged; prevMonsterIds = result.monsterIds; prevMonsterInfoSignature = result.signature; renderJpxMonsterInfo(); }); request.promise = Promise.all([companion, builtin]).finally(() => { if (monsterInfoRequest === request) monsterInfoRequest = null; }); return request.promise; } function checkEffectTurns(arr, effects, ignored = false) { const range = arr.slice(0, 2); const matches = name => { let turns = effects[name]?.turns ?? -1; if (turns === 'permanent') turns = 9999; return isNaN(+turns) || jpxUtils.inRange(+turns, range); }; return ignored ? !arr.slice(2).some(matches) : arr.slice(2).every(matches); } function checkEffectStacks(arr, effects) { const range = arr.slice(0, 2); return arr.slice(2).every(name => { const stack = effects[name]?.stack ?? -1; return isNaN(+stack) || jpxUtils.inRange(+stack, range); }); } function initConditions() { let { monsters, activeMonsters, bosses, activeBosses } = monstersObj; const checkActions = (arr, matches) => { const range = arr.slice(0, 2); return arr.slice(2).every(action => { const tier = action.match(/^T(\d)$/)?.[1]; const name = tier ? spellsDamageObj[getManagedSpellType()]?.[tier - 1] : action; return !!name && matches(name, range); }); }; const generalHandlers = { world: arr => arr.includes(!isekaiSuffix ? 'Persistent' : 'Isekai'), pLevel: range => jpxUtils.inRange(parseInt(localStorage.getItem(prefix + 'playerLevel' + isekaiSuffix) || 1), range), pMaxSpellType: arr => arr.includes(getManagedSpellType()), battleTypes: arr => arr.includes(battleType), difficulty: arr => arr.includes(localStorage.getItem(prefix + 'difficulty' + isekaiSuffix) || 'PFUDOR'), roundCurrent: range => jpxUtils.inRange(roundInfo.current, range), roundLeft: range => jpxUtils.inRange(roundInfo.total - roundInfo.current, range), roundTotal: range => jpxUtils.inRange(roundInfo.total, range), floor: range => (battleType !== 'Tower' || jpxUtils.inRange(towerFloor, range)), pActionCooldown: arr => checkActions(arr, (name, range) => { const cooldown = spellCooldowns[name] ?? itemCooldowns[name]; return jpxUtils.inRange(cooldown === '-' ? 9999 : cooldown, range); }), pActionHistory: arr => checkActions(arr, (name, range) => { const history = actionCounts.history; const end = Math.min(history.length - 1, Math.floor(range[1] - 1)); for (let index = Math.max(0, Math.ceil(range[0] - 1)); index <= end; index++) { if (history[index] === name) return true; } return false; }), pActionCounts: arr => checkActions(arr, (name, range) => jpxUtils.inRange(actionCounts[name] ?? 0, range)), pTotalActionCounts: arr => checkActions(arr, (name, range) => jpxUtils.inRange(combatRecords.use[name] || revenueRecords.consumable[name]?.use || 0, range)), pHP: range => jpxUtils.inRange(vitals.hpPercentage, range), pMP: range => jpxUtils.inRange(vitals.mpPercentage, range), pSP: range => jpxUtils.inRange(vitals.spPercentage, range), pOC: range => jpxUtils.inRange(vitals.oc, range), pSpiritStatus: flag => flag === spiritStatus, pEffects: arr => checkEffectTurns(arr, playerEffectsObj), pIgnoredEffects: arr => checkEffectTurns(arr, playerEffectsObj, true), pEffectStacks: arr => checkEffectStacks(arr, playerEffectsObj), monsters: range => jpxUtils.inRange(monsters.length, range), activeMonsters: range => jpxUtils.inRange(activeMonsters.length, range), defeatedMonsters: range => jpxUtils.inRange(monsters.length - activeMonsters.length, range), bosses: range => jpxUtils.inRange(bosses.length, range), activeBosses: range => jpxUtils.inRange(activeBosses.length, range), defeatedBosses: range => jpxUtils.inRange(bosses.length - activeBosses.length, range), mLevel: range => jpxUtils.inRange(monsters[0].level, range), mWithoutEffects: arr => { let range = arr.slice(0, 2); let effects = arr.slice(2); return jpxUtils.inRange(activeMonsters.filter(activeMonster => effects.some(effect => activeMonster.effectObj[effect]?.turns == null)).length, range); }, }; const targetHandlers = { tName: (str, t) => { let regex = jpxUtils.toRegExp(str); return !regex || regex.test(t.name); }, tTypes: (arr, t) => arr.includes(t.type), tClasses: (arr, t) => arr.includes(allMonsterInfo?.[`mkey_${(t.index + 1) % 10}`]?.monsterClass), tPowerLevel: (range, t) => jpxUtils.inRange(allMonsterInfo?.[`mkey_${(t.index + 1) % 10}`]?.plvl, range), tIndex: (range, t) => jpxUtils.inRange(t.index, range.map(n => n = n > 0 ? n - 1 : n === 0 ? 0 : monsters.length + n)), tHP: (range, t) => jpxUtils.inRange(t.hpPercentage, range), tMP: (range, t) => jpxUtils.inRange(t.mpPercentage, range), tSP: (range, t) => jpxUtils.inRange(t.spPercentage, range), tEffects: (arr, target) => checkEffectTurns(arr, target.effectObj), tIgnoredEffects: (arr, target) => checkEffectTurns(arr, target.effectObj, true), tEffectStacks: (arr, target) => checkEffectStacks(arr, target.effectObj), tDaysSinceUpdate: (range, t) => { let lastUpdate = allMonsterInfo?.[`mkey_${(t.index + 1) % 10}`]?.lastUpdate; let deltaDays = lastUpdate ? jpxUtils.daysSince(lastUpdate) : 9999; return !jpxUtils.isEmpty(allMonsterInfo) && jpxUtils.inRange(deltaDays, range); }, }; return { generalHandlers, targetHandlers }; } function checkConditions(conditions = [], target, checkGlobal = true, checkTarget = true) { let { monsters, activeMonsters } = monstersObj; conditionsObj ||= initConditions(); let { generalHandlers, targetHandlers } = conditionsObj; return conditions.every(condition => { let { key, value, offset = [0, 0], matched = [1, 1] } = condition; if (key in generalHandlers && checkGlobal) { return generalHandlers[key](value) === true; } if (key in targetHandlers && checkTarget) { if (!target) return false; let successCount = 0; for (let i = target.index + offset[0]; i <= target.index + offset[1]; i++) { if (i < 0 || i > monsters.length - 1) continue; let m = activeMonsters.find(activeMonster => activeMonster.index === i); if (m && targetHandlers[key](value, m) === true) successCount++; } return jpxUtils.inRange(successCount, matched); } return true; }); } const kamisamaCache = new WeakMap(); function getKamisama(action) { let cached = kamisamaCache.get(action); if (!cached || cached.code !== action.code) { cached = { code: action.code, fn: new Function('jpx', `'use strict';\n${action.code}`) }; kamisamaCache.set(action, cached); } return cached.fn; } function doTargetedSpell({ name, conditions }, monster) { return monster && checkConditions(conditions, monster) && doSpellGoNext(name, monster); } const actionHandlers = { stop(action, monster) { const { customMessage, conditions } = action; if (checkConditions(conditions, monster)) { // A rule stop waits for a fresh battle update; keep auto armed so // manual healing can clear the condition, as in upstream JPX. readyNext = t('cW.ruleStopped', { message: customMessage }); jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground('#ff5'); jpxPanelManager.dispatchState(); return true; } return false; }, spellSupport(action, monster) { const { name, conditions } = action; if ( spellCooldowns[name] === 0 && checkConditions(conditions, monster) ) { readyNext = 0; cast(name); return true; } return false; }, item(action, monster) { const { name, conditions } = action; if ( itemCooldowns[name] === 0 && checkConditions(conditions, monster) ) { readyNext = 0; use(name); return true; } return false; }, toggle(action, monster) { const { name, toggled, conditions } = action; return ( (name !== 'Spirit' || toggled !== spiritStatus) && checkConditions(conditions, monster) && doToggleGoNext(name) ); }, target(action, monster) { const { priorityRule, conditions } = action; if (!checkConditions(conditions, monster, true, false)) return null; let { activeMonsters } = monstersObj; monstersObj.sorted ??= {}; const getSorted = fn => monstersObj.sorted[priorityRule] ??= [...activeMonsters].sort( priorityRule.includes('Low to High') ? (a, b) => fn(a) - fn(b) : (a, b) => fn(b) - fn(a)); let list = activeMonsters; switch (priorityRule) { case 'Bottom Up': list = monstersObj.sorted[priorityRule] ??= [...activeMonsters].reverse(); break; case 'Current HP Low to High': case 'Current HP High to Low': list = getSorted(m => monsterData[m.index].maxHP * m.hpPercentage); break; case 'Current HP Percent Low to High': case 'Current HP Percent High to Low': list = getSorted(m => m.hpPercentage); break; } return list.find(activeMonster => checkConditions(conditions, activeMonster, false)) ?? null; }, smartDebuff(action, monster) { const { conditions } = action; return ( checkConditions(conditions, monster, true, false) && doSpellsDebuffGoNext(action) ); }, spellDebuff: doTargetedSpell, spellDamage(action, monster) { const { name, conditions } = action; let tier = name.match(/^T(\d)$/)?.[1]; const element = tier ? getManagedSpellType() : ''; let spell = tier ? spellsDamageObj[element]?.[tier - 1] : name; if (tier && !element && monster) { isActiveBattle = false; readyNext = t('cW.elementUnknown'); jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground('#ff5'); jpxPanelManager.dispatchState(); return true; } return ( monster && checkConditions(conditions, monster) && doSpellGoNext(spell, monster) ); }, skill: doTargetedSpell, normalAttack(action, monster) { const { conditions } = action; return ( monster && checkConditions(conditions, monster) && doAttackGoNext(monster) ) }, kamisamaniNattaHi(action) { try { const fn = getKamisama(action); return fn({ prefix, isekaiSuffix, battleStyle, battleType, worldLevel, towerFloor, roundInfo, monsterData, allMonsterInfo, monstersEffects, monstersObj, actionCounts, spellDamageBonus, spellCooldowns, itemCooldowns, vitals, spiritStatus, playerEffectsObj, actionHandlers, doSpellsDebuffGoNext, doSpellGoNext, doAttackGoNext, doToggleGoNext, }) === true; } catch (e) { console.error('kamisama action error:', e); jpxUtils.createToast(t('cB.customCodeFailed', { reason: String(e) }), 5000); isActiveBattle = false; if (cfgBattle.ctrlWidgetMouseEnter) jpxPanelManager.ready = false; readyNext = 0; jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground('#fef'); jpxPanelManager.dispatchState(); return true; } }, }; function actionManager(actions) { let targetPhase = false; let targetMonster = null; let targetLocked = false; for (const action of actions) { const handler = actionHandlers[action.type]; if (!handler) continue; if (action.disabled === true) continue; if (action.type === 'target') { targetPhase = true; if (!targetLocked) { targetMonster = null; let result = handler(action, targetMonster); if (result) { targetMonster = result; targetLocked = true; } } continue; } if (targetPhase && !targetMonster && ['spellDebuff', 'spellDamage', 'skill', 'normalAttack'].includes(action.type)) continue; if (handler(action, targetMonster)) return true; targetLocked = false; } return false; } //Battle Record function battleRecorder(turnLog) { if (!arguments.length) turnLog = getBattleLogHTML(log, true).match(regExp.turnLog)?.[0]; if (!turnLog) return; let action = turnLog.match(regExp.action)?.[1]; if (!action) { if (!turnLog.includes('Scanning')) return; turnLog = turnLog.replace(/[\t\r\n]+/g, '').replace(/>\s+<'); action = 'You use Scan'; } if (action.includes('gains the effect')) { let action2 = turnLog.match(regExp.action2)?.[1]; action2 && (action = action2); } let use = action.match(regExp.use)?.[2]; if (cfgBattle.recordBattleLog) battleLogRecorder(); timeRecorder(turnLog, action, use); combatRecorder(turnLog, action, use); revenueRecorder(turnLog, action, use); } function battleLogRecorder() { const cells = () => document.createTreeWalker(log, NodeFilter.SHOW_ELEMENT, { acceptNode: node => node.tagName === 'TD' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP }); const lastRow = (log.tBodies?.[0] || log).lastElementChild; const tail = lastRow?.getElementsByTagName('td'); const lastCell = tail?.[tail.length - 1]; if (lastCell && regExp.battleTypeLog.test(getBattleLogHTML(lastCell))) { // Only the first action includes initialization rows. Stop looking for // separators after the second one, independent of round history size. const separators = document.createTreeWalker(log, NodeFilter.SHOW_ELEMENT, { acceptNode: node => node.classList.contains('tls') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP }); if (separators.nextNode() && !separators.nextNode()) { const backwards = cells(); backwards.currentNode = lastCell; for (let td = lastCell; td; td = backwards.previousNode()) { if (!td.textContent.trim() || td.innerHTML.includes('
')) break; battleLogRecordCurrent.unshift(td.textContent); } } } battleLogRecordCurrent.push('--------------------------------------------------'); const current = cells(); for (let td = current.nextNode(); td; td = current.nextNode()) { if (!td.textContent.trim() || td.innerHTML.includes('
')) { break; } if (td.querySelector('table')) { let clone = td.cloneNode(true); clone.querySelector('table')?.remove(); clone = clone.textContent.replace(/\s+/g, ' ').trim(); battleLogRecordCurrent.push(clone); } else { battleLogRecordCurrent.push(td.textContent.replace(/\s+/g, ' ').trim()); } } let btcp = document.querySelector('#btcp'); if (btcp) { battleLogRecordCurrent.push('++++++++++++++++++++++++++++++++++++++++++++++++++'); } // A loop avoids both copying all prior rounds and argument-count limits on // unusually large batches. The history is private and otherwise append-only. for (const line of battleLogRecordCurrent) battleLogRecord.push(line); battleLogRecordCurrent = []; } function storeBattleLogRecord() { const key = prefix + 'battleLogRecord' + isekaiSuffix; if (!Array.isArray(battleLogRecord)) { localStorage.removeItem(key); battleLogCheckpoint = null; return; } const previous = battleLogCheckpoint; let json; if (previous?.record === battleLogRecord && previous.length <= battleLogRecord.length) { json = previous.json; if (previous.length < battleLogRecord.length) { const added = JSON.stringify(battleLogRecord.slice(previous.length)); json = json.slice(0, -1) + (previous.length ? ',' : '') + added.slice(1); } } else { json = JSON.stringify(battleLogRecord); } // Read the actual key so an external clear/replacement never causes a false // clean skip. Only acknowledge a checkpoint after a successful storage write. if (localStorage.getItem(key) !== json) localStorage.setItem(key, json); battleLogCheckpoint = { record: battleLogRecord, length: battleLogRecord.length, json }; } function timeRecorder(turnLog, action, use) { timeRecords['startTime'] ??= Date.now(); timeRecords['action'] += 1; if (!regExp.zeroturn.test(action)) timeRecords['turn'] += 1; if (use) timeRecords['lastUse'][use] = timeRecords['turn']; } function riddleRecorder() { if (jpxUtils.isEmpty(timeRecords)) timeRecords = JSON.parse(localStorage.getItem(prefix + 'timeRecords' + isekaiSuffix) || JSON.stringify(jpxUtils.createTimeRecords())); let riddlesubmit = document.querySelector('#riddlesubmit') riddlesubmit && riddlesubmit.addEventListener('click', () => { timeRecords.riddle.solved += 1; localStorage.setItem(prefix + 'timeRecords' + isekaiSuffix, JSON.stringify(timeRecords)); }, { once: true }); } function combatRecorder(turnLog, action, use) { let recordedUse = use; if (!recordedUse) { if (action.includes('Spirit Stance Engaged')) recordedUse = 'Spirit'; else if (action.includes('Defending.')) recordedUse = 'Defend'; else if (action.includes('Focusing.')) recordedUse = 'Focus'; else recordedUse = 'Attack'; } if (!use || !regExp.zeroturn.test(action) || use.includes('Gem') || use.includes('Caffeinated Candy') || use.includes('Energy Drink')) { jpxUtils.inc(combatRecords.use, recordedUse); jpxUtils.inc(actionCounts, recordedUse); actionCounts.history.unshift(recordedUse); if (use === 'Scan') { recordJpxMonsterScan(turnLog); updateMonsterInfo(true); } } if (turnLog.includes('You gain the effect Cloak of the Fallen.')) { jpxUtils.inc(combatRecords.use, 'Cloak of the Fallen'); jpxUtils.inc(actionCounts, 'Cloak of the Fallen'); } let damage = turnLog.match(regExp.damage); if (damage) { for (let i = 0; i < damage.length; i++) { let damageTaken = jpxUtils.matchAny(damage[i], regExp.damageTaken1, regExp.damageTaken2); let spiritShield = damage[i].match(regExp.spiritShield); let damageDealt = jpxUtils.matchAny(damage[i], regExp.damageDealt1, regExp.damageDealt2); let strike = damage[i].match(regExp.strike); let explode = damage[i].match(regExp.explode); let damagePlus = damage[i].match(regExp.damagePlus); let damagePoints = damage[i].match(regExp.damagePoints); //Taken if (damageTaken?.groups) { let glance = damageTaken.groups.v.includes('glance'); let crit = damageTaken.groups.v.includes('crit'); let hit = !glance && !crit; let damageType = jpxUtils.lowerFirst(damageTaken.groups.t); const records = damage[i].includes(' casts ') ? combatRecords.magicalTaken : combatRecords.physicalTaken; glance && (records.glance += 1); hit && (records.hit += 1); crit && (records.crit += 1); jpxUtils.inc(records, damageType, +damageTaken.groups.n); } else if (spiritShield) { jpxUtils.inc(combatRecords.physicalTaken, 'spiritShield' + 'hit'); jpxUtils.inc(combatRecords.physicalTaken, 'spiritShield' + 'damagePlus', +spiritShield[1]); //Dealt } else if (damageDealt?.groups) { let glance = damageDealt.groups.v.includes('glance'); let crit = damageDealt.groups.v.includes('crit'); let critStack = parseInt(damageDealt.groups.s) || 1; let hit = !glance && !crit; let damageType = jpxUtils.lowerFirst(damageDealt.groups.t); const magical = action.includes('You cast'); const records = magical ? combatRecords.magicalDealt : combatRecords.physicalDealt; glance && (records.glance += 1); hit && (records.hit += 1); crit && (records.crit += 1); if (crit && !magical) jpxUtils.inc(records, `crit${critStack}`); jpxUtils.inc(records, damageType, +damageDealt.groups.n); } else if (strike) { let damageType = jpxUtils.lowerFirst(strike[3]); jpxUtils.inc(combatRecords.physicalDealt, damageType, +strike[2]); } else if (explode) { let damageType = jpxUtils.lowerFirst(explode[2]); jpxUtils.inc(combatRecords.magicalDealt, damageType, +explode[1]); } else if (damagePlus) { //Physical Dealt // Bleeding Wound hits Monster for 1000 damage. // Spreading Poison hits Monster for 1000 damage. if (regExp.damagePhysicalPlus.test(damage[i])) { jpxUtils.inc(combatRecords.physicalDealt, 'damagePlus', +damagePlus[1]); //Magical Dealt // Burning Soul hits Monster for 1000 damage. // Ripened Soul hits Monster for 1000 damage. } else { jpxUtils.inc(combatRecords.magicalDealt, 'damagePlus', +damagePlus[1]); } } else if (damagePoints) { let damageType = jpxUtils.lowerFirst(damagePoints[2]); //counter // You counter Monster for 1000 points of void damage. if (damage[i].includes('You counter')) { jpxUtils.inc(combatRecords.physicalDealt, damageType, +damagePoints[1]); //spike shield // Your spike shield hits Monster for 1000 points of elec damage. } else { jpxUtils.inc(combatRecords.magicalDealt, damageType, +damagePoints[1]); } } } } //debuff let debuffLog = turnLog.match(regExp.debuffLog)?.[0]; if (debuffLog) { let debuffResist0 = debuffLog.match(regExp.debuffResist0)?.length || 0; let debuffResist1 = debuffLog.match(regExp.debuffResist1)?.length || 0; let debuffResist3 = debuffLog.match(regExp.debuffResist3)?.length || 0; jpxUtils.inc(combatRecords.magicalDealt, 'debuffResist0', debuffResist0 - debuffResist1); jpxUtils.inc(combatRecords.magicalDealt, 'debuffResist1', debuffResist1); jpxUtils.inc(combatRecords.magicalDealt, 'debuffResist3', debuffResist3); } /*patch*/ let patchBlock = turnLog.match(/You block the attack\./g); if (patchBlock) jpxUtils.inc(combatRecords.magicalTaken, 'block', -patchBlock.length); let patchBlockAndParry = turnLog.match(/You block and parry the attack/g); if (patchBlockAndParry) jpxUtils.inc(combatRecords.physicalTaken, 'blockAndParry', patchBlockAndParry.length); for (const [regexp, category, key] of COMBAT_LOG_COUNTERS) { let match = turnLog.match(regexp); if (match) jpxUtils.inc(combatRecords[category], key, match.length); } } function revenueRecorder(turnLog, action, use) { if ( use && regExp.zeroturn.test(action) && !use.includes('Gem') && !use.includes('Caffeinated Candy') && !use.includes('Energy Drink') ) { revenueRecords['consumable'][use] ??= { use: 0, drop: 0 }; revenueRecords['consumable'][use]['use'] += 1; jpxUtils.inc(actionCounts, use); actionCounts.history.unshift(use); } let gainExp = turnLog.match(regExp.gainExp); if (gainExp) revenueRecords['exp'] += +gainExp[1]; let gainCredit = turnLog.match(regExp.gainCredit); if (gainCredit) revenueRecords['credit'] += +gainCredit[1]; let proficiencies = turnLog.match(regExp.proficiencies); if (proficiencies) { for (let i = 0; i < proficiencies.length; i++) { let proficiency = proficiencies[i].match(regExp.proficiency); if (proficiency) { let prof = parseFloat(proficiency[1]); if (prof > 0) { jpxUtils.inc(revenueRecords.proficiency, proficiency[2], prof); } } } } let dropLogs = turnLog.match(regExp.dropsLogs) || []; for (let dropLog of dropLogs) { let drop = dropLog.match(regExp.drop) || []; //drop[4]: sold, salvaged switch (drop[2]) { //Equipment, Material case 'FF0000': { if (!drop[4]){ let quality = drop[3].match(regExp.quality)?.[1]; if (quality) { revenueRecords['equipment'][quality] ??= []; revenueRecords['equipment'][quality].push(drop[3]); } else { jpxUtils.inc(revenueRecords.material, drop[3], +drop[1].match(/\d+/)?.[0] || 1); } } break; } //Credit case 'A89000': { let credit = drop[3].match(regExp.credit); if (credit) { revenueRecords['credit'] += (+credit[1] || 1); } break; } //Consumable // Restorative: Draught, Potion, Elixir // Infusion: Flames, Frost, Storms, Lighting, Divinity, Darkness // Scroll: Swiftness, Protection, the Avatar, Absorption, Shadows, Life, the Gods // Shard: Voidseeker Shard, Aether Shard, Featherweight Shard, Amnesia Shard, World Seed // Special Item: Flower Vase, Bubble Gum case '00B000': { if (!drop[3].includes('Gem')) { revenueRecords['consumable'][drop[3]] ??= { use: 0, drop: 0 }; revenueRecords['consumable'][drop[3]]['drop'] += 1; } break; } //Token // Token of Blood, Chaos Token, Soul Fragment case '254117': { if (drop[3].includes('Blood')) { jpxUtils.inc(revenueRecords.token, 'Token of Blood'); } else if (drop[3].includes('Chaos')) { jpxUtils.inc(revenueRecords.token, 'Chaos Token'); } else if (drop[3].includes('Soul')) { jpxUtils.inc(revenueRecords.token, 'Soul Fragment', drop[1] === 'five' ? 5 : (+drop[1].match(/\d+/)?.[0] || 1)); } break; } //Food case '489EFF': { jpxUtils.inc(revenueRecords.food, drop[3]); break; } //Artifact, Collectable case '0000FF': { if (drop[3].includes('Figurine')) { jpxUtils.inc(revenueRecords.figurine, drop[3]); } else { jpxUtils.inc(revenueRecords.artifact, drop[3]); } break; } //Trophy, World Seed, Charm case '461B7E': { if (drop[3].includes('World Seed')) { revenueRecords['consumable'][drop[3]] ??= { use: 0, drop: 0 }; revenueRecords['consumable'][drop[3]]['drop'] += +drop[1].match(/\d+/)?.[0] || 1; } else { jpxUtils.inc(revenueRecords.trophy, drop[3]); } break; } //Crystal case 'BA05B4': { let crystal = drop[3].match(regExp.crystal); if (crystal) jpxUtils.inc(revenueRecords.crystal, crystal[2], +crystal[1] || 1); break; } } } } async function battleRecordPlayer(doFinal = true) { function revenueCalc(revenueRecords, priceData) { let revenueSnapshot = JSON.parse(JSON.stringify(revenueRecords)); for (const [categoryKey, categoryValue] of Object.entries(revenueSnapshot)) { switch (categoryKey) { case ('proficiency'): for (const [key, value] of Object.entries(categoryValue)) { categoryValue[key] = Math.round(value * 1000) / 1000; } break; case ('consumable'): for (const [key, value] of Object.entries(categoryValue)) { value['balance'] = value['drop'] - value['use']; jpxUtils.inc(categoryValue, 'profit', (priceData[key] || 0) * value['balance']); } break; case ('material'): case ('token'): case ('food'): case ('figurine'): case ('artifact'): case ('trophy'): for (const [key, value] of Object.entries(categoryValue)) { jpxUtils.inc(categoryValue, 'profit', (priceData[key] || 0) * value); } break; case ('crystal'): for (const [key, value] of Object.entries(categoryValue)) { jpxUtils.inc(categoryValue, 'total', value); jpxUtils.inc(categoryValue, 'profit', (priceData[key] || 0) * value); } break; } if (categoryValue?.['profit']) { categoryValue['profit'] = Math.round(categoryValue['profit'] * 10) / 10; revenueSnapshot['totalProfit'] += categoryValue['profit']; } } revenueSnapshot['totalProfit'] = Math.round(revenueSnapshot['totalProfit'] + (revenueSnapshot['credit'] || 0)); return revenueSnapshot; } function getStaminaCost() { if (battleType === 'Encounter' || battleType === 'Colosseum') return 0; let stamina = parseFloat(localStorage.getItem(prefix + 'stamina' + isekaiSuffix)) || 80; let greatCost = !isekaiSuffix ? 0.03 : 0.06; let normalCost = !isekaiSuffix ? 0.02 : 0.04; let greatRoundQuota = Math.floor(Math.max(0, stamina - (battleType === 'Battle1000' ? 1 : 0) - 60) / greatCost); let greatRound = Math.min(greatRoundQuota, roundInfo.current); let normalRound = roundInfo.current - greatRound; let staminaCost = greatRound * greatCost + normalRound * normalCost; if (battleType === 'Battle1000') staminaCost += 1; return staminaCost; } if (Object.keys(cfgStats).length < 1) loadStatsSettingsConfig(); let startTime = timeRecords['startTime'] || 0; let timestamp = new Date(timeRecords['startTime']).toISOString().slice(0, 19).replace('T', ' '); let date = timestamp.slice(0, 10); let result = 'inProgress'; const battleLogHTML = getBattleLogHTML(); if (battleLogHTML.includes('You are Victorious!') && roundInfo.current === roundInfo.total) { result = 'Victory'; } else if (battleLogHTML.includes('You have been defeated.')) { result = 'Defeat'; } else if (battleLogHTML.includes('You have escaped from the battle.')) { result = 'Flee'; } let deltaSeconds = (Date.now() - startTime) / 1000; let deltaTime = jpxUtils.secondsToTime(deltaSeconds, true); let action = timeRecords['action']; let tps = Math.round(action / deltaSeconds * 100) / 100; let priceData = await jpxMarket.getMarketPrice(doFinal); let revenueSnapshot = revenueCalc(revenueRecords, priceData); let staminaCost = getStaminaCost(); // Daily 24 and LongGoneBeforeDaylight 20 const staminaWorld = isekaiSuffix ? 'Isekai' : 'Persistent'; const staminaId = jpxShared.idOf({ world: staminaWorld, timestamp }); let staminaRecords = jpxShared.enabled ? { lastUpdate: Date.now(), staminaCost: jpxShared.stamina(staminaWorld, new Date().toISOString().slice(0, 10), staminaId) } : JSON.parse(localStorage.getItem(prefix + 'staminaRecords' + isekaiSuffix) || '{}'); let currentDate = new Date().toISOString().slice(0, 10); if ( !staminaRecords?.lastUpdate || new Date(staminaRecords.lastUpdate).toISOString().slice(0, 10) != currentDate ) { staminaRecords = { lastUpdate: Date.now(), staminaCost: 0 }; } let staminaQuota = 24 + (!isekaiSuffix ? cfgBattle.dailyStaminaQuotaPlus : 0) - staminaRecords.staminaCost; if (staminaCost > staminaQuota) { revenueSnapshot['staminaCost'] = Math.round((staminaCost - Math.max(0, staminaQuota)) * 10) / 10; } else { revenueSnapshot['staminaCost'] = 0; } if (doFinal && !jpxShared.enabled) { staminaRecords.staminaCost = Math.round((staminaRecords.staminaCost + staminaCost) * 10) / 10; localStorage.setItem(prefix + 'staminaRecords' + isekaiSuffix, JSON.stringify(staminaRecords)); } //Final Profit let staminaUnitPrice = priceData['Energy Drink'] / 10; let staminaProfit = Math.round(-revenueSnapshot['staminaCost'] * staminaUnitPrice * 10) / 10; revenueSnapshot['finalProfit'] = Math.round((revenueSnapshot['totalProfit'] + staminaProfit) * 10) / 10; let battleRecords = { world: !isekaiSuffix ? 'Persistent' : 'Isekai', timestamp: timestamp, date: date, playerLevel: parseInt(localStorage.getItem(prefix + 'playerLevel' + isekaiSuffix)) || 0, difficulty: difficultyMap[localStorage.getItem(prefix + 'difficulty' + isekaiSuffix)] || 0, persona: localStorage.getItem(prefix + 'persona' + isekaiSuffix), battleType: battleType, worldLevel: worldLevel, towerFloor: towerFloor, roundInfo: roundInfo, result: result, deltaSeconds: deltaSeconds, deltaTime: deltaTime, turns: timeRecords.action, tps: tps, riddle: timeRecords.riddle.total, combatRecords: combatRecords, revenueRecords: revenueSnapshot, } if (jpxShared.enabled && doFinal) battleRecords.sharedStamina = { world: staminaWorld, date: currentDate, used: staminaCost, quota: 24 + (!isekaiSuffix ? cfgBattle.dailyStaminaQuotaPlus : 0), unitPrice: staminaUnitPrice }; const renderRecords = () => { let battleLogEl = doFinal && cfgBattle.recordBattleLog ? battleLogPlayer() : null; let timeRecordEl = document.querySelector('#time-records-div') || timeRecordPlayer(battleRecords); let combatRecordEl = document.querySelector('#combat-records-table') || combatRecordPlayer(combatRecords); let combatRecord_UseEl = document.querySelector('#combat-records-use-table') || combatRecordPlayer_Use(combatRecords); let revenueRecordEl = document.querySelector('#revenue-records-table') || revenueRecordPlayer(revenueSnapshot, priceData); if (doFinal) { const combatPanel = document.getElementById('jpx-final-combat') || document.createElement('div'); combatPanel.id = 'jpx-final-combat'; combatPanel.className = 'jpx-record-detail jpx-record-detail-column jpx-record-final'; combatPanel.replaceChildren(...[battleLogEl, createRecordTableScroll(combatRecordEl, document), createRecordTableScroll(combatRecord_UseEl, document)].filter(Boolean)); log.parentNode.prepend(combatPanel); const revenuePanel = document.getElementById('jpx-final-revenue') || document.createElement('div'); revenuePanel.id = 'jpx-final-revenue'; revenuePanel.className = 'jpx-record-detail jpx-record-final'; const summary = document.createElement('div'); summary.className = 'jpx-record-detail-summary'; summary.append(timeRecordEl); revenuePanel.replaceChildren(summary, createRecordTableScroll(revenueRecordEl, document)); const resultPanel = document.querySelector('#btcp'); if (resultPanel) { resultPanel.classList.add('jpx-final-result'); resultPanel.append(revenuePanel); } } else { newWindowRecordPlayer(document.querySelector('#time-records-div'), battleRecords, timeRecordEl, combatRecordEl, combatRecord_UseEl, revenueRecordEl); } }; const skipResult = doFinal && cfgBattle.autoFinishBattle === true; if (!skipResult && (!jpxShared.enabled || !doFinal)) renderRecords(); if (doFinal) { try { console.log(await storeBattleRecords(battleRecords)); } catch (error) { if (skipResult || jpxShared.enabled) renderRecords(); throw error; } if (jpxShared.enabled && !skipResult || skipResult && cfgBattle.autoFinishBattle !== true) renderRecords(); } } function battleLogPlayer() { const record = battleLogRecord; let a = document.createElement('a'); a.innerText = t('sGen.downloadBattleLog'); a.style.cssText = 'display: block; margin: 10px 0px; text-align: left; font-size: 200%;'; a.href = '#'; a.download = 'battleLog.txt'; a.addEventListener('click', () => { // Viewing statistics must not allocate another full log download. const url = URL.createObjectURL(new Blob([JSON.stringify(record, null, '\t')], { type: 'text/plain;charset=utf-8' })); a.href = url; setTimeout(() => { URL.revokeObjectURL(url); if (a.getAttribute('href') === url) a.href = '#'; }, 30000); }); return a; } function timeRecordPlayer(battleRecords) { let div = document.createElement('div'); div.id = 'time-records-div'; let riddleSolved = timeRecords?.startTime && battleRecords.timestamp === new Date(timeRecords.startTime).toISOString().slice(0, 19).replace('T', ' ') && timeRecords.riddle.solved < battleRecords.riddle ? `${timeRecords.riddle.solved} / ` : ''; [ [t('tP.turns'), battleRecords.turns.toLocaleString()], [t('sP.deltaTime'), battleRecords.deltaTime], [t('tP.t/s'), battleRecords.tps], [t('tP.riddle'), `${riddleSolved}${battleRecords.riddle}`], [t('tP.spark'), battleRecords.combatRecords.use['Cloak of the Fallen'] || 0], ].forEach(([label, value]) => { const metric = document.createElement('span'); metric.className = 'jpx-record-metric'; const number = document.createElement('strong'); number.textContent = value; metric.append(label + ' ', number); div.append(metric); }); return div; } function combatRecordPlayer(combatRecords) { let table = document.createElement('table'); table.id = 'combat-records-table'; table.className = 'records-table'; table.innerHTML = ''; let tbody = document.createElement('tbody'); let innerHTML = ` ${t('cP.damageDealt')} ${t('cP.damageTaken')} ${t('cP.physical')}${t('cP.magical')}${t('cP.total')} ${t('cP.physical')}${t('cP.magical')}${t('cP.spirit')}${t('cP.total')} `; const readRow = id => ({ pd: combatRecords.physicalDealt[id] ?? 0, md: combatRecords.magicalDealt[id] ?? 0, pt: combatRecords.physicalTaken[id] ?? 0, pts: combatRecords.physicalTaken['spiritShield' + id] ?? 0, mt: combatRecords.magicalTaken[id] ?? 0, mts: combatRecords.magicalTaken['spiritShield' + id] ?? 0, }); function renderCombatRow(label, style, values, rowConfig) { const { pd, md, pt, pts, mt, mts } = values; const dataObj = { label, ...values, td: pd + md, tt: pt + pts + mt + mts }; let order = ['label', 'pd', 'md', 'td', 'pt', 'mt', 'pts', 'tt']; let html = ``; order.forEach((k, index) => { let v = dataObj[k]; let styleStr = rowConfig[`s_${k}`] || ''; let styleText = styleStr ? ` style="${styleStr}"` : ''; html += `${(v === 0 && index !== 0) ? '' : v.toLocaleString()}`; }); html += ''; return html; }; let totals = {}; let totalsTypes = ['damage', 'result', 'resultPartially']; COMBAT_FIELDS.forEach(f => { if (!totalsTypes.includes(f.type) || f.isTotal) return; totals[f.type] ??= { pd: 0, md: 0, pt: 0, pts: 0, mt: 0, mts: 0 }; for (const [key, value] of Object.entries(readRow(f.id))) totals[f.type][key] += value; }); cfgStats.combatRows.forEach(row => { if (row.disabled === true) return; let excludeIds = ['resist50', 'resist75', 'resist90']; if (excludeIds.includes(row.id)) return; let field = COMBAT_FIELDS.find(f => f.id === row.id); let styleNormal = row.styleText ? `style="${row.styleText}"` : ''; let styleTotal = `style="border-top: 1px solid; border-bottom: 1px solid; ${row.styleText || ''}"`; if (!totalsTypes.includes(field.type)) return; if (field.isTotal) { const values = { ...totals[field.type] }; if (isekaiSuffix && field.type === 'result') values.pt -= combatRecords.physicalTaken.blockAndParry || 0; for (const key of Object.keys(values)) values[key] ||= 0; innerHTML += renderCombatRow(t(field.label), styleTotal, values, row); } else innerHTML += renderCombatRow(t(field.label), styleNormal, readRow(field.id), row); }); innerHTML += ` ${t('cP.critStack')} ${t('cP.debuffResist')} `; let debuffResistTotal = 0; let debuffMap = { 1: { key: 'debuffResist0', label: t('cP.debuffResist0') }, 2: { key: 'debuffResist1', label: t('cP.debuffResist1-2') }, 3: { key: 'debuffResist3', label: t('cP.debuffResist3') }, }; for (let i = 1; i < 10; i++) { let critStack = combatRecords.physicalDealt[`crit${i}`]; if (i <= 4) { innerHTML += `${i}x-${t('cP.crit')}${(critStack || '').toLocaleString()}`; if (i < 4) { let value = combatRecords.magicalDealt[debuffMap[i].key] || 0; debuffResistTotal += value; innerHTML += `${debuffMap[i].label}${(value || '').toLocaleString()}`; } else if (i === 4) { innerHTML += `${t('cP.total')}${(debuffResistTotal || '').toLocaleString()}`; } innerHTML += ''; } else if (critStack) { innerHTML += `${i}x-${t('cP.crit')}${(critStack || '').toLocaleString()}`; } } tbody.innerHTML = innerHTML; table.appendChild(tbody); return table; } function combatRecordPlayer_Use(combatRecords) { let table = document.createElement('table'); table.id = 'combat-records-use-table'; table.innerHTML = ''; let tbody = document.createElement('tbody'); let innerHTML = `${t('cP.used')}`; function renderCombatUseRow(label, entries) { if (!entries.length) return; innerHTML += `${t(label)}${entries.join(', ')}`; } let useKeys = new Set(); COMBAT_USE_FIELDS.forEach(field => { let entries = []; for (const { key, label } of field.keys) { let count = combatRecords.use[key]; if (count) { entries.push(`${t(label)}: ${count}`); useKeys.add(key); } } renderCombatUseRow(field.label, entries); }); let others = []; for (const [key, value] of Object.entries(combatRecords.use)) { if (useKeys.has(key)) continue; others.push(`${t(`cB.${key}`)}: ${value}`); } renderCombatUseRow(t('cP.misc'), others); tbody.innerHTML = innerHTML; table.appendChild(tbody); return table; } function revenueRecordPlayer(revenueRecords, priceData) { let table = document.createElement('table'); table.id = 'revenue-records-table'; table.className = 'records-table'; table.innerHTML = ''; let tbody = document.createElement('tbody'); let innerHTML = ` ${t('rP.revenue')} ${t('rP.name')} ${t('rP.drop')}${t('rP.use')}${t('rP.balance')}${t('rP.unitPrice')}${t('rP.profit')} `; cfgStats.revenueRows.forEach(row => { if (row.disabled === true) return; let field = REVENUE_FIELDS.find(f => f.id === row.id); let data = revenueRecords[field.source || field.id]; let styleNormal = row.styleText ? `style="${row.styleText}"` : ''; let styleFirst = `style="border-top: 1px solid; ${row.styleText || ''}"`; switch (field.type) { case 'simple': { let value = field.key ? data[field.key] : data; if (value) { innerHTML += ` ${t(field.label)} ${value.toLocaleString()} `; } break; } case 'list_flat': case 'list_paired': { let dataKeys = Object.keys(data); let sortedKeys = jpxUtils.getSortedKeys(field.order || [], dataKeys); let items = []; sortedKeys.forEach(sortedKey => { if (field.type === 'list_flat' && Array.isArray(data[sortedKey])) items.push(...data[sortedKey]); else if (field.type === 'list_paired') items.push(`${t(`rP.${sortedKey}`)}: ${data[sortedKey]}`); }); if (!items.length) break; let firstItem = items.shift(); innerHTML += ` ${t(field.label)} ${firstItem} `; items.forEach(item => { innerHTML += `${item}`; }); break; } case 'grid': case 'grid_detailed': { let dataKeys = Object.keys(data).filter(key => { if (key === 'total' || key === 'profit') return false; let value = data[key]; if (value && typeof value === 'object') return !jpxUtils.isEmpty(value); return value; }); let sortedKeys = jpxUtils.getSortedKeys(field.order || [], dataKeys); if (!sortedKeys.length) break; const renderRow = (key, rowStyle) => { let value = data[key]; let balance = field.type === 'grid_detailed' ? Math.round((value.drop - value.use) * 10) / 10 : value; let unitPrice = priceData[key]; let tdClass = !isNaN(unitPrice) ? '' : ' class="noData"'; let tdUnitPrice = !isNaN(unitPrice) ? unitPrice.toLocaleString() : t('rP.noData'); let tdProfit = !isNaN(unitPrice) ? (Math.round(unitPrice * balance * 10) / 10).toLocaleString() : t('rP.noData') ; let profitTds = `${tdUnitPrice}${tdProfit}`; if (field.type === 'grid_detailed') { return ` ${t(`rP.${key}`)}${value.drop}${value.use}${balance}${profitTds} `; } else { return ` ${t(`rP.${key}`)}${value}${profitTds} `; } }; let firstKey = sortedKeys.shift(); innerHTML += renderRow(firstKey, styleFirst); sortedKeys.forEach(sortedKey => innerHTML += renderRow(sortedKey, styleNormal)); break; } case 'total': { if (data && data.total) { innerHTML += ` ${t(field.label)} ${data.total}${data.profit} `; } break; } case 'stamina': { let staminaRecords = jpxShared.enabled ? jpxShared.usage(isekaiSuffix ? 'Isekai' : 'Persistent') : JSON.parse(localStorage.getItem(prefix + 'staminaRecords' + isekaiSuffix) || '{}'); let staminaCost = staminaRecords?.staminaCost ?? 0; let staminaQuotaTotal = 24 + (cfgBattle.dailyStaminaQuotaPlus && !isekaiSuffix ? cfgBattle.dailyStaminaQuotaPlus : 0); let unitPrice = priceData['Energy Drink'] / 10; let balance = -revenueRecords.staminaCost || 0; let profit = Math.round(balance * unitPrice * 10) / 10; innerHTML += ` ${t(field.label)}${staminaQuotaTotal}${staminaCost}${balance} ${unitPrice.toLocaleString()}${profit.toLocaleString()} `; break; } case 'summary': { let trClass = data < 0 ? 'deficit' : (data > 0 ? 'surplus' : ''); innerHTML += ` ${t(field.label)} ${data.toLocaleString()} `; break; } } }); tbody.innerHTML = innerHTML; table.appendChild(tbody); return table; } async function createRecordImageBlob(root) { if (!root?.isConnected || root.closest('[aria-busy=true]')) throw new Error(t('sP.imageUnavailable')); const doc = root.ownerDocument, win = doc.defaultView; const detail = root.classList.contains('jpx-record-detail-page'), clone = root.cloneNode(true); const properties = ['display', 'box-sizing', 'color', 'background-color', 'font-family', 'font-size', 'font-weight', 'font-style', 'line-height', 'letter-spacing', 'text-align', 'text-decoration', 'vertical-align', 'white-space', 'overflow-wrap', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'border-top', 'border-right', 'border-bottom', 'border-left', 'border-radius', 'border-collapse', 'border-spacing', 'table-layout', 'flex-direction', 'flex-wrap', 'align-items', 'align-content', 'justify-content', 'gap', 'grid-template-columns']; const originals = [root, ...root.querySelectorAll('*')], copies = [clone, ...clone.querySelectorAll('*')]; originals.forEach((node, index) => { const copy = copies[index], style = win.getComputedStyle(node); copy.removeAttribute('style'); for (const property of properties) copy.style.setProperty(property, style.getPropertyValue(property)); copy.style.position = 'static'; copy.style.overflow = 'visible'; copy.style.maxHeight = 'none'; copy.style.outline = 'none'; copy.style.boxShadow = 'none'; // Export only local text and styling, without loading linked assets. for (const attribute of [...copy.attributes]) if (/^on/i.test(attribute.name)) copy.removeAttribute(attribute.name); }); clone.querySelectorAll('.jpx-record-image-actions, script, style, img, iframe, object, embed, link').forEach(node => node.remove()); clone.style.margin = '0'; if (detail) { const combatWidth = Math.ceil(root.querySelector('#combat-records-table').getBoundingClientRect().width), revenueWidth = Math.ceil(root.querySelector('#revenue-records-table').getBoundingClientRect().width); clone.style.width = (combatWidth + revenueWidth + 40) + 'px'; clone.style.maxWidth = 'none'; clone.style.padding = '12px'; const grid = clone.querySelector('.jpx-record-detail-grid'); if (grid) grid.style.gridTemplateColumns = (combatWidth + 2) + 'px ' + (revenueWidth + 2) + 'px'; clone.querySelectorAll('.jpx-record-detail-column, .jpx-record-detail-summary').forEach(node => { node.style.gridTemplateColumns = 'minmax(0, 1fr)'; node.style.minWidth = '0'; node.style.width = '100%'; }); clone.querySelectorAll('table').forEach(table => { table.style.width = table.id === 'combat-records-use-table' ? '100%' : (table.id === 'combat-records-table' ? combatWidth : revenueWidth) + 'px'; }); clone.querySelectorAll('#combat-records-use-table td:first-child').forEach(cell => cell.style.width = '96px'); } else { clone.style.width = Math.ceil(root.getBoundingClientRect().width) + 'px'; clone.style.minWidth = '0'; } // Inline styles keep the image independent of media queries and duplicate IDs. [clone, ...clone.querySelectorAll('*')].forEach(node => { node.removeAttribute('id'); node.removeAttribute('class'); }); const stage = doc.createElement('div'); stage.style.cssText = 'position:fixed;left:-100000px;top:0;width:max-content;pointer-events:none;'; stage.setAttribute('aria-hidden', 'true'); stage.append(clone); doc.body.append(stage); let width, height, markup; try { width = Math.ceil(Math.max(clone.scrollWidth, clone.getBoundingClientRect().width)) + 16; height = Math.ceil(Math.max(clone.scrollHeight, clone.getBoundingClientRect().height)) + 16; const content = doc.createElement('div'); content.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); content.style.cssText = 'box-sizing:border-box;width:' + width + 'px;padding:8px;'; content.style.backgroundColor = win.getComputedStyle(doc.body).backgroundColor; content.style.color = win.getComputedStyle(doc.body).color; content.append(clone); markup = new win.XMLSerializer().serializeToString(content); } finally { stage.remove(); } const scale = Math.min(2, 4096 / width, 4096 / height, Math.sqrt(12000000 / (width * height))); if (!Number.isFinite(scale) || scale < .5) throw new Error(t('sP.imageTooLarge')); const svg = '' + markup + ''; const image = new win.Image(); await new Promise((resolve, reject) => { image.onload = resolve; image.onerror = () => reject(new Error(t('sP.imageFailed'))); image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg); }); const canvas = doc.createElement('canvas'); canvas.width = Math.ceil(width * scale); canvas.height = Math.ceil(height * scale); const context = canvas.getContext('2d'); if (!context) throw new Error(t('sP.imageFailed')); context.fillStyle = win.getComputedStyle(doc.body).backgroundColor; context.fillRect(0, 0, canvas.width, canvas.height); context.drawImage(image, 0, 0, canvas.width, canvas.height); return new Promise((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error(t('sP.imageFailed'))), 'image/png')); } function createRecordImageActions(doc, getContent, inline = false) { const win = doc.defaultView, menu = doc.createElement('details'); const compact = win.matchMedia('(max-width: 650px), (pointer: coarse) and (orientation: landscape) and (max-height: 600px)'); menu.className = 'jpx-record-image-actions' + (inline ? ' jpx-record-image-inline' : ''); const summary = doc.createElement('summary'); summary.textContent = t('sP.image'); const actions = doc.createElement('div'); actions.setAttribute('role', 'group'); actions.setAttribute('aria-label', t('sP.image')); const notify = (message, success = false) => { if (success && !inline && compact.matches) menu.open = false; doc.querySelectorAll('.jpx-record-image-toast').forEach(toast => toast.remove()); const toast = jpxUtils.createToast(message, success ? 2400 : 5000, 'jpx-record-image-toast', doc); ['padding', 'background', 'color', 'font-size'].forEach(property => toast.style.removeProperty(property)); toast.setAttribute('role', 'status'); toast.setAttribute('aria-live', 'polite'); if (inline && menu.closest('dialog[open]')) menu.closest('dialog').append(toast); }; const buttons = []; for (const action of ['download', 'copy']) { const button = doc.createElement('button'); button.type = 'button'; button.dataset.imageAction = action; button.textContent = t(action === 'copy' ? 'sP.copyImage' : 'sP.downloadImage'); button.onclick = async () => { if (action === 'copy' && (!win.isSecureContext || !win.ClipboardItem || !win.navigator.clipboard?.write)) { notify(t('sP.imageCopyUnavailable')); return; } const restoreFocus = menu.contains(doc.activeElement); buttons.forEach(item => item.disabled = true); menu.setAttribute('aria-busy', 'true'); let imageError; const image = Promise.resolve().then(() => createRecordImageBlob(getContent())).catch(error => { imageError = error; throw error; }); image.catch(() => {}); try { if (action === 'copy') { // Pass a Blob promise during the gesture, using the clicked window's clipboard. await win.navigator.clipboard.write([new win.ClipboardItem({ 'image/png': image })]); notify(t('sP.imageCopied'), true); } else { const url = win.URL.createObjectURL(await image), link = doc.createElement('a'); link.href = url; link.download = ((doc.title || 'battle-statistics') + '_' + new Date().toISOString().slice(0, 10) + '.png').replace(/[<>:"/\|?*]/g, '-'); doc.body.append(link); link.click(); link.remove(); win.setTimeout(() => win.URL.revokeObjectURL(url), 30000); notify(t('sP.imageDownloaded'), true); } } catch (error) { notify(imageError?.message || t(action === 'copy' ? 'sP.imageCopyFailed' : 'sP.imageFailed')); } finally { menu.removeAttribute('aria-busy'); buttons.forEach(item => item.disabled = false); if (restoreFocus && menu.isConnected && (doc.activeElement === doc.body || menu.contains(doc.activeElement))) { (!inline && compact.matches && !menu.open ? summary : button).focus({ preventScroll: true }); } } }; if (inline) button.prepend(createSettingsIcon(action)); buttons.push(button); actions.append(button); } menu.append(summary, actions); const closeOutside = event => { if (!inline && compact.matches && !menu.contains(event.target)) menu.open = false; }; const cleanup = () => doc.removeEventListener('pointerdown', closeOutside, true); const updateLayout = () => { cleanup(); menu.open = inline || !compact.matches; }; compact.addEventListener('change', updateLayout); updateLayout(); menu.addEventListener('toggle', () => { cleanup(); if (menu.isConnected && !inline && compact.matches && menu.open) doc.addEventListener('pointerdown', closeOutside, true); }); menu.dispose = () => { cleanup(); compact.removeEventListener('change', updateLayout); }; menu.addEventListener('keydown', event => { if (!inline && compact.matches && event.key === 'Escape') { menu.open = false; summary.focus(); event.stopPropagation(); } }); return menu; } function createRecordTableScroll(table, doc, doClone = false) { const scroll = doc.createElement('div'); scroll.className = 'jpx-record-detail-scroll'; scroll.tabIndex = 0; scroll.setAttribute('role', 'region'); scroll.setAttribute('aria-label', table.id === 'revenue-records-table' ? t('rP.revenue') : table.id === 'combat-records-use-table' ? t('cP.used') : t('cP.damageDealt') + ' / ' + t('cP.damageTaken')); scroll.appendChild(doClone ? table.cloneNode(true) : table); return scroll; } // An explicit empty className still writes class="", as the original editors did. function createJpxElement(tag, className, text, doc = document) { const node = doc.createElement(tag); if (className !== undefined) node.className = className; if (text) node.textContent = text; return node; } // Icon-only controls carry the same visible tooltip and accessible name. function setJpxLabel(node, label) { node.title = label; node.setAttribute('aria-label', label); } // Shared head of the statistics page and its detail windows. function initJpxRecordDocument(doc, title) { doc.title = title; doc.documentElement.lang = document.documentElement.lang || 'en'; const viewport = doc.createElement('meta'); viewport.name = 'viewport'; viewport.content = 'width=device-width, initial-scale=1'; doc.head.append(viewport); } function newWindowRecordPlayer(doClone, battleRecords, timeRecordEl, combatRecordEl, combatRecord_UseEl, revenueRecordEl) { const newWin = window.open(); if (!newWin) return; const doc = newWin.document; initJpxRecordDocument(doc, t('sP.battleDetails') + ' · ' + (battleRecords.timestamp || battleRecords.date || '')); ensureJpxStyle(doc); doc.body.className = 'jpx-record-detail'; doc.documentElement.style.scrollbarColor = 'var(--jpx-theme-accent, #5c0d11) var(--jpx-theme-background, #e3e0d1)'; applyJpxTheme(doc); const [container, summary, grid, left, right] = [['main', 'page'], ['header', 'summary'], ['div', 'grid'], ['div', 'column'], ['div', 'column']] .map(([tag, name]) => createJpxElement(tag, 'jpx-record-detail-' + name, '', doc)); const info = doc.createElement('div'); info.id = 'info-records-div'; [ battleRecords.timestamp, t(`sP.${battleRecords.world}`), t(`sP.${battleRecords.battleType || ''}`) + (battleRecords.worldLevel ? ` (WL${battleRecords.worldLevel})` : '') + (battleRecords.towerFloor ? ` (${battleRecords.towerFloor}F)` : ''), `${battleRecords.roundInfo.current}/${battleRecords.roundInfo.total}` + (battleRecords.result !== 'Victory' ? ` (${t(`sP.${battleRecords.result}`)})` : ''), t(`sP.${Object.keys(difficultyMap).find(key => difficultyMap[key] === battleRecords.difficulty)}`), `LV: ${battleRecords.playerLevel}`, ].forEach(text => { info.appendChild(doc.createElement('span')).textContent = text; }); summary.appendChild(info); if (timeRecordEl) summary.appendChild(doClone ? timeRecordEl.cloneNode(true) : timeRecordEl); grid.append(left, right); container.append(summary, grid); doc.body.appendChild(container); for (const [el, column] of [[combatRecordEl, left], [combatRecord_UseEl, left], [revenueRecordEl, right]]) { if (el) column.appendChild(createRecordTableScroll(el, doc, doClone)); } summary.append(createRecordImageActions(doc, () => container)); } //Indexed DB function openDB() { return new Promise((resolve, reject) => { let request = window.indexedDB.open('jpx', 1); request.onupgradeneeded = (event) => { let db = event.target.result; if (!db.objectStoreNames.contains('battleRecords')) { let objectStore = db.createObjectStore('battleRecords', { keyPath: 'timestamp' }); objectStore.createIndex('date', 'date'); } }; request.onsuccess = (event) => { const db = event.target.result; db.onversionchange = () => db.close(); resolve(db); }; request.onerror = (event) => { reject(request.error); };; }); } async function storeBattleRecords(battleRecords) { if (jpxShared.enabled) { await ensureJpxSharedRecords(); await jpxShared.saveResult(battleRecords, battleRecords.sharedStamina); window.dispatchEvent(new Event('jpx:records-changed')); return 'Saved successfully'; } const db = await openDB(); try { return await new Promise((resolve, reject) => { const transaction = db.transaction('battleRecords', 'readwrite'); transaction.objectStore('battleRecords').put(battleRecords); transaction.oncomplete = () => resolve('Saved successfully'); transaction.onabort = () => reject(transaction.error || new Error('Record write aborted')); }); } finally { db.close(); } } function openBattleRecords() { newWindow = window.open(new URL((isekaiSuffix ? '/isekai/' : '/') + '#jpx-records', location.origin).href); } function normalizeJpxRecordsScope(value) { const scope = {}; for (const key of ['world', 'battleType', 'from', 'to']) { if (typeof value?.[key] !== 'string') throw new Error(t('cS.recordsRangeInvalid')); scope[key] = value[key]; } const validDate = date => !date || /^\d{4}-\d{2}-\d{2}$/.test(date) && Number.isFinite(Date.parse(date + 'T00:00:00Z')) && new Date(date + 'T00:00:00Z').toISOString().slice(0, 10) === date; if (!['', 'Persistent', 'Isekai'].includes(scope.world) || !['', ...STATS_FILTERS.find(field => field.key === 'battleType').options].includes(scope.battleType) || !validDate(scope.from) || !validDate(scope.to) || scope.from && scope.to && scope.from > scope.to) { throw new Error(t('cS.recordsRangeInvalid')); } return Object.freeze(scope); } function matchesJpxRecordsScope(record, scope) { if (!record || scope.world && record.world !== scope.world || scope.battleType && record.battleType !== scope.battleType) return false; if (!scope.from && !scope.to) return true; // Match the stored/displayed date, without converting it to the browser's timezone. const date = record.date; return typeof date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(date) && (!scope.from || date >= scope.from) && (!scope.to || date <= scope.to); } async function previewJpxRecordsCleanup(value, signal) { const scope = normalizeJpxRecordsScope(value), keys = []; if (jpxShared.enabled) { await ensureJpxSharedRecords(); const records = await jpxShared.allRecords(); if (signal?.aborted) throw new DOMException('Aborted', 'AbortError'); return Object.freeze({ scope, keys: Object.freeze(records.filter(record => matchesJpxRecordsScope(record, scope)).map(jpxShared.idOf)) }); } const db = await openDB(); try { if (signal?.aborted) throw new DOMException('Aborted', 'AbortError'); return await new Promise((resolve, reject) => { const tx = db.transaction('battleRecords', 'readonly'); const abort = () => { try { tx.abort(); } catch { /* Completion can precede its queued event. */ } }; signal?.addEventListener('abort', abort, { once: true }); const cursor = tx.objectStore('battleRecords').openCursor(); cursor.onsuccess = () => { if (!cursor.result) return; if (matchesJpxRecordsScope(cursor.result.value, scope)) keys.push(cursor.result.primaryKey); cursor.result.continue(); }; tx.oncomplete = () => { signal?.removeEventListener('abort', abort); if (signal?.aborted) reject(new DOMException('Aborted', 'AbortError')); else resolve(Object.freeze({ scope, keys: Object.freeze(keys) })); }; tx.onabort = () => { signal?.removeEventListener('abort', abort); reject(signal?.aborted ? new DOMException('Aborted', 'AbortError') : tx.error || new Error('Record preview aborted')); }; }); } finally { db.close(); } } async function deleteJpxRecordsCleanup(plan) { const scope = normalizeJpxRecordsScope(plan?.scope); if (!Array.isArray(plan?.keys)) throw new Error(t('cS.recordsRangeInvalid')); if (!plan.keys.length) return 0; if (jpxShared.enabled) { await ensureJpxSharedRecords(); const confirmed = new Set(plan.keys); const ids = (await jpxShared.allRecords()).filter(record => confirmed.has(jpxShared.idOf(record)) && matchesJpxRecordsScope(record, scope)).map(jpxShared.idOf); if (ids.length) jpxShared.deleteRecords(ids); window.dispatchEvent(new Event('jpx:records-changed')); return ids.length; } const db = await openDB(); try { return await new Promise((resolve, reject) => { const tx = db.transaction('battleRecords', 'readwrite'), store = tx.objectStore('battleRecords'); let index = 0, deleted = 0, failure = null; const abort = error => { failure = error; tx.abort(); }; // Only confirmed keys are eligible. New records from another battle tab survive. const next = () => { try { if (index >= plan.keys.length) return; const key = plan.keys[index++], request = store.get(key); request.onsuccess = () => { try { if (!matchesJpxRecordsScope(request.result, scope)) { next(); return; } const removal = store.delete(key); removal.onsuccess = () => { deleted++; next(); }; } catch (error) { abort(error); } }; } catch (error) { abort(error); } }; tx.oncomplete = () => resolve(deleted); tx.onabort = () => reject(failure || tx.error || new Error('Record cleanup aborted')); next(); }); } finally { db.close(); } } function openJpxRecordsCleanup(targetWindow = window, initial = {}) { const doc = targetWindow.document; if (doc.getElementById('jpx-records-cleanup-dialog')) return; if (!doc.getElementById('jpx-records-cleanup-style')) { const style = doc.createElement('style'); style.id = 'jpx-records-cleanup-style'; style.textContent = jpxThemeCSS(` #jpx-records-cleanup-dialog { box-sizing:border-box; width:min(460px,calc(100vw - 24px)); max-height:calc(100dvh - 24px); margin:auto; padding:20px; overflow:auto; border:1px solid #c8b49b; border-radius:4px; background:#f9f6ec; color:#392d25; font:13px/1.45 Arial,Helvetica,sans-serif; text-align:left; } #jpx-records-cleanup-dialog::backdrop { background:#0008; } html[data-jpx-theme=dark] #jpx-records-cleanup-dialog { color-scheme:dark; background:var(--jpx-theme-surface,#292c31); color:var(--jpx-theme-text,#e5e0d8); } #jpx-records-cleanup-dialog * { box-sizing:border-box; } #jpx-records-cleanup-dialog [hidden] { display:none!important; } #jpx-records-cleanup-dialog h2 { margin:0 0 8px; color:inherit; font-size:16px; } #jpx-records-cleanup-dialog p { margin:8px 0 12px; } #jpx-records-cleanup-dialog .jpx-records-cleanup-fields { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; } #jpx-records-cleanup-dialog label { display:flex; flex-direction:column; gap:4px; min-width:0; } #jpx-records-cleanup-dialog .jpx-records-cleanup-wide { grid-column:1/-1; } #jpx-records-cleanup-dialog :is(select,input,button) { margin:0; min-width:0; max-width:100%; min-height:34px; padding:5px 8px; border:1px solid #c8b49b; border-radius:2px; color:inherit; background:#fffdf7; font:inherit; } #jpx-records-cleanup-dialog select { width:100%; align-items:center; } #jpx-records-cleanup-dialog select option { color:var(--jpx-theme-text,#392d25); background:var(--jpx-theme-field,#fffdf7); } #jpx-records-cleanup-dialog select option:checked { background:var(--jpx-theme-selected,#ead8b4); } @supports (appearance:base-select) { #jpx-records-cleanup-dialog select, #jpx-records-cleanup-dialog select::picker(select) { appearance:base-select; } #jpx-records-cleanup-dialog select { gap:8px; cursor:pointer; } #jpx-records-cleanup-dialog select::picker(select) { box-sizing:border-box; min-width:anchor-size(width); max-width:min(560px,calc(100vw - 32px)); max-height:min(280px,50dvh); padding:3px; overflow:auto; border:1px solid var(--jpx-theme-border,#c8b49b); border-radius:2px; background:var(--jpx-theme-surface,#f9f6ec); color:var(--jpx-theme-text,#392d25); box-shadow:0 4px 12px #0003; } #jpx-records-cleanup-dialog select option { min-height:34px; padding:5px 8px; border:0; border-bottom:1px solid color-mix(in srgb,var(--jpx-theme-border,#c8b49b) 40%,transparent); background:transparent; } #jpx-records-cleanup-dialog select option:checked { background:var(--jpx-theme-selected,#ead9b8); } #jpx-records-cleanup-dialog select option:hover, #jpx-records-cleanup-dialog select option:focus { background:var(--jpx-theme-hover,#f1e2c5); outline:1px solid var(--jpx-theme-accent,#9b4e03); outline-offset:-1px; } } html[data-jpx-theme=dark] #jpx-records-cleanup-dialog :is(select,input) { border-color:var(--jpx-theme-border,#5a534c); color:var(--jpx-theme-text,#e5e0d8); background:var(--jpx-theme-field,#24272b); } #jpx-records-cleanup-dialog button { cursor:pointer; } #jpx-records-cleanup-dialog button:hover { background:#f1e2c5; } #jpx-records-cleanup-dialog button:disabled { opacity:.5; cursor:default; } #jpx-records-cleanup-dialog :focus-visible { outline:1px solid #5c0d11; outline-offset:-1px; } #jpx-records-cleanup-dialog .jpx-records-cleanup-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:12px; } #jpx-records-cleanup-dialog [data-action=clear] { border-color:#5c0d11; color:#5c0d11; } #jpx-records-cleanup-dialog .jpx-records-cleanup-hint { color:#71634f; font-size:12px; } @media(max-width:650px),(pointer:coarse) { #jpx-records-cleanup-dialog { padding:16px; } #jpx-records-cleanup-dialog :is(select,input,button) { min-height:44px; } } `); doc.head.append(style); } const el = (tag, text, className) => { const node = doc.createElement(tag); if (text) node.textContent = text; if (className) node.className = className; return node; }; const tr = key => t('cS.' + key), focused = doc.activeElement; const dialog = el('dialog'); dialog.id = 'jpx-records-cleanup-dialog'; const title = el('h2', tr('clearRecords')); title.id = 'jpx-records-cleanup-title'; dialog.setAttribute('aria-labelledby', title.id); const fields = el('div', '', 'jpx-records-cleanup-fields'); const select = (name, label, choices, value) => { const field = el('label', label), input = el('select'); input.name = name; for (const [key, text] of choices) { const option = el('option', text); option.value = key; input.append(option); } input.value = value; field.append(input); fields.append(field); return input; }; const world = select('world', t('sP.world'), [['', tr('recordsAllWorlds')], ...['Persistent','Isekai'].map(key => [key,t('sP.'+key)])], ['','Persistent','Isekai'].includes(initial.world) ? initial.world : isekaiSuffix ? 'Isekai' : 'Persistent'); const battleType = select('battleType', t('sP.battleType'), [['',tr('recordsAllBattles')], ...STATS_FILTERS.find(field => field.key === 'battleType').options.map(key => [key,t('sP.'+key)])], initial.battleType || ''); const period = select('period', tr('recordsPeriod'), [['all',tr('recordsAllDates')],['range',tr('recordsDateRange')]], 'all'); period.parentElement.classList.add('jpx-records-cleanup-wide'); const dates = ['from','to'].map(key => { const field = el('label',tr(key === 'from' ? 'recordsFrom' : 'recordsTo')), input = el('input'); input.type = 'date'; input.name = key; field.append(input); fields.append(field); field.hidden = true; return input; }); const dateHint = el('p',tr('recordsDateHint'),'jpx-records-cleanup-hint'); dateHint.hidden = true; const status = el('p'); status.setAttribute('role','status'); status.setAttribute('aria-live','polite'); const actions = el('div','','jpx-records-cleanup-actions'); const cancel = el('button',t('cM.close')), clear = el('button',tr('clearRecords')); cancel.type = clear.type = 'button'; clear.dataset.action = 'clear'; clear.disabled = true; actions.append(cancel,clear); dialog.append(title,el('p',tr('recordsScopeHint'),'jpx-records-cleanup-hint'),fields,dateHint,status,actions); let plan = null, revision = 0, preview = null, busy = false; const update = async () => { const current = ++revision; preview?.abort(); preview = new AbortController(); plan = null; clear.disabled = true; const range = period.value === 'range'; dates.forEach(input => input.parentElement.hidden = !range); dateHint.hidden = !range; dates[0].max = dates[1].value; dates[1].min = dates[0].value; if (range && ((!dates[0].value && !dates[1].value) || dates.some(input => !input.validity.valid))) { status.textContent = tr('recordsRangeInvalid'); return; } status.textContent = t('sP.loadingRecords'); try { const value = await previewJpxRecordsCleanup({ world:world.value, battleType:battleType.value, from:range?dates[0].value:'', to:range?dates[1].value:'' },preview.signal); if (!dialog.isConnected || current !== revision) return; plan = value; status.textContent = t('cS.recordsPreview',{count:plan.keys.length}); clear.disabled = !plan.keys.length; } catch (error) { if (dialog.isConnected && current === revision && error.name !== 'AbortError') status.textContent = t('sP.recordsError'); } }; fields.addEventListener('change',update); // Invalidate immediately while a date is being typed, before its change event. fields.addEventListener('input',() => { revision++; preview?.abort(); plan = null; clear.disabled = true; status.textContent = ''; }); cancel.addEventListener('click',() => dialog.close()); dialog.addEventListener('cancel',event => { if (busy) event.preventDefault(); }); dialog.addEventListener('close',() => { revision++; preview?.abort(); dialog.remove(); if (focused?.isConnected) focused.focus({preventScroll:true}); },{once:true}); clear.addEventListener('click',async () => { if (busy || !plan?.keys.length) return; const approved = plan; const summary = [world.selectedOptions[0].textContent,battleType.selectedOptions[0].textContent, period.value === 'all' ? tr('recordsAllDates') : `${approved.scope.from || '…'} → ${approved.scope.to || '…'}`].join(' · '); if (!targetWindow.confirm(summary + '\n\n' + t('cS.recordsClearConfirm',{count:approved.keys.length}))) return; busy = true; clear.disabled = cancel.disabled = true; fields.querySelectorAll('input,select').forEach(input => input.disabled = true); status.textContent = tr('cleanupRunning'); try { const count = await deleteJpxRecordsCleanup(approved); plan = null; status.textContent = t('cS.recordsCleared',{count}); try { targetWindow.localStorage.setItem(prefix+'recordsChanged',Date.now()+':'+Math.random()); } catch { /* Local refresh still works if browser storage is unavailable. */ } targetWindow.dispatchEvent(new targetWindow.Event('jpx:records-changed')); } catch (error) { status.textContent = tr('recordsClearFailed'); clear.disabled = false; console.error('Record cleanup failed:',error); } finally { busy = false; cancel.disabled = false; fields.querySelectorAll('input,select').forEach(input => input.disabled = false); } }); doc.body.append(dialog); dialog.showModal(); update(); } // Shared with the settings rule editor: native disclosure supports reversal // without measuring heights or scheduling per-frame JavaScript work. function jpxDisclosureCSS(selector) { return ` @supports (interpolate-size: allow-keywords) and selector(details::details-content) { ${selector}::details-content { interpolate-size: allow-keywords; block-size: 0; overflow: clip; transition: block-size var(--jpx-motion) ease-out, content-visibility var(--jpx-motion) allow-discrete; } ${selector}[open]::details-content { block-size: auto; } } `; } function createStatsColumnControls(doc, onChange) { const el = (tag, className) => createJpxElement(tag, className, '', doc); const root = el('section', 'jpx-records-columns'); root.setAttribute('aria-label', t('sP.displayColumns')); const editor = el('div', 'jpx-records-column-groups'); const status = el('p', 'jpx-records-column-status'); status.setAttribute('role', 'status'); status.setAttribute('aria-atomic','true'); let saveToast, toastTimer; const dismissToast = () => { doc.defaultView.clearTimeout(toastTimer); saveToast?.remove(); saveToast = null; }; const notifySaved = () => { dismissToast(); saveToast = el('div', 'jpx-records-save-toast'); saveToast.setAttribute('role','status'); saveToast.setAttribute('aria-live','polite'); saveToast.setAttribute('aria-atomic','true'); (root.closest('dialog') || doc.body).append(saveToast); saveToast.textContent = t('sP.displaySaved'); toastTimer = doc.defaultView.setTimeout(dismissToast,2000); }; const groupInputs = new Map(), fieldInputs = new Map(), counts = new Map(); const getColumns = () => { const copy = { statsColumns: jpxConfigClone(cfgStats.statsColumns || []) }; normalizeStatsConfig(copy); return copy.statsColumns; }; function update() { const columns = new Map(getColumns().map(column => [column.id, column])); for (const group of STATS_COLUMN_GROUPS) { const visible = statsColumnGroupVisible(cfgStats.columnGroups, group.id); groupInputs.get(group.id).checked = visible; let count = 0; for (const id of group.fields) { const column = columns.get(id), input = fieldInputs.get(id); input.checked = column?.disabled !== true; if (input.checked) count++; input.parentElement.lastChild.textContent = column?.customName || t(STATS_FIELDS.find(field => field.id === id).label); } counts.get(group.id).textContent = t(visible ? 'sP.columnsSelected' : 'sP.groupHidden', { count, total: group.fields.length }); } } function change(group, id, checked) { try { // Merge this display edit into the latest saved settings; never save // unrelated unsaved edits or overwrite another tab's colors/order. const raw = localStorage.getItem(prefix + 'cfgStats'); const saved = raw ? JSON.parse(raw) : jpxConfigClone(defaultCfgStats); validateStatsConfig(saved); normalizeStatsConfig(saved); if (id) saved.statsColumns.find(column => column.id === id).disabled = !checked; else saved.columnGroups = { ...saved.columnGroups, [group]: checked }; localStorage.setItem(prefix + 'cfgStats', JSON.stringify(saved)); normalizeStatsConfig(cfgStats); if (id) cfgStats.statsColumns.find(column => column.id === id).disabled = !checked; else cfgStats.columnGroups = { ...cfgStats.columnGroups, [group]: checked }; status.setAttribute('role','status'); status.textContent = ''; notifySaved(); update(); onChange(); } catch (error) { dismissToast(); update(); status.setAttribute('role','alert'); status.textContent = t('cM.storageError'); console.error('Could not save column preferences:', error); } } for (const group of STATS_COLUMN_GROUPS) { const section = el('section', 'jpx-records-column-group'); const header = el('div', 'jpx-records-column-heading'); const label = doc.createElement('label'), toggle = doc.createElement('input'); toggle.type = 'checkbox'; toggle.dataset.columnGroup = group.id; groupInputs.set(group.id, toggle); const caption = doc.createElement('span'), name = doc.createElement('strong'), count = doc.createElement('small'); name.textContent = t('sP.group_' + group.id); count.className = 'jpx-records-column-count'; counts.set(group.id,count); caption.append(name,count); label.append(toggle,caption); header.append(label); toggle.addEventListener('change', () => change(group.id, null, toggle.checked)); const fields = el('div', 'jpx-records-column-fields'); fields.id = 'jpx-records-fields-' + group.id; fields.inert = true; fields.setAttribute('role','group'); fields.setAttribute('aria-label',name.textContent); const expand = doc.createElement('button'); expand.type = 'button'; expand.className = 'jpx-records-icon jpx-records-column-expand'; expand.dataset.expandGroup = group.id; expand.append(createSettingsIcon('chevronDown')); setJpxLabel(expand, t('sP.displayColumns') + ' · ' + name.textContent); expand.setAttribute('aria-controls',fields.id); expand.setAttribute('aria-expanded','false'); const disclosure = el('details', 'jpx-records-column-disclosure'); const summary = doc.createElement('summary'); summary.hidden = true; disclosure.append(summary,fields); expand.onclick = () => { disclosure.open = !disclosure.open; fields.inert = !disclosure.open; expand.setAttribute('aria-expanded',String(disclosure.open)); }; header.append(expand); for (const id of group.fields) { const label = doc.createElement('label'), input = doc.createElement('input'); input.type = 'checkbox'; input.dataset.columnField = id; fieldInputs.set(id,input); label.append(input, doc.createTextNode('')); fields.append(label); input.addEventListener('change', () => change(group.id,id,input.checked)); } section.append(header,disclosure); editor.append(section); } root.append(editor,status); update(); return { node:root, update, dismissToast }; } function renderBattleRecordsPage(targetWindow = window) { if (Object.keys(cfgStats).length < 1) loadStatsSettingsConfig(); newWindow = targetWindow; const doc = targetWindow.document; doc.getElementById('jpx-records-cleanup-dialog')?.close(); const previousImageActions = doc.querySelector('.jpx-record-image-actions'); previousImageActions?.dispose?.(); previousImageActions?.remove(); const filterState = targetWindow._jpxRecordsFilterState ||= { panel: null, inputs: null }; const previousFilters = doc.getElementById('filtersDiv'); if (previousFilters) { const aggregate = doc.getElementById('filter-aggregate'); if (aggregate) previousFilters.querySelector('.jpx-records-tools-row').append(aggregate); filterState.inputs = [...previousFilters.querySelectorAll('input')].map(input => ({ value: input.value, checked: input.checked })); } filterState.cleanup?.(); doc.head.replaceChildren(); doc.body.replaceChildren(); doc.body.removeAttribute('style'); initJpxRecordDocument(doc, t('sP.jpxStats')); doc.head.appendChild(doc.createElement('style')).textContent = jpxThemeCSS(` ${JPX_SCROLLBAR_CSS} * { box-sizing: border-box; } ${JPX_RECORD_IMAGE_CSS} body { margin: 0; overflow:hidden; background: #edebdf; color: #392d25; font: 13px/1.45 Arial, Helvetica, sans-serif; } html[data-jpx-theme=dark] body { color-scheme: dark; } button, input { font: inherit; color: inherit; } button, input[type=checkbox] { cursor: pointer; } input { accent-color: #5c0d11; } :focus-visible { outline: 1px solid #9b4e03; outline-offset: -1px; box-shadow: 0 0 0 2px rgb(155 78 3 / 12%); } .jpx-records-page { display:flex; flex-direction:column; gap:10px; height:100vh; height:100dvh; padding:12px; } .jpx-records-toolbar { flex:none; display:flex; align-items:center; justify-content:space-between; gap:12px; min-width:0; } .jpx-records-heading { min-width:0; } .jpx-records-heading h1 { margin:0; font-size:17px; line-height:1.3; color:#5c0d11; } .jpx-records-count { margin:3px 0 0; color:#71634f; font-size:12px; } .jpx-records-actions { display:flex; flex:none; gap:8px; } .jpx-records-icon { display:inline-flex; flex:none; align-items:center; justify-content:center; width:44px; height:44px; padding:10px; border:1px solid #c8b49b; border-radius:2px; background:#f9f6ec; color:#5c0d11; touch-action:manipulation; transition:background-color 140ms; } .jpx-records-icon svg { width:22px; height:22px; pointer-events:none; } .jpx-records-icon:active { background:#ead9b8; } .jpx-records-icon[aria-expanded=true] { background:#ead9b8; border-color:#b49369; } @media(hover:hover) { .jpx-records-icon:hover { background:#eee2c9; } } .jpx-records-sheet { inset:0; width:min(600px,calc(100% - 32px)); max-width:none; max-height:calc(100dvh - 48px); margin:auto; padding:0; border:1px solid #c8b49b; border-radius:2px; background:#f9f6ec; color:#392d25; box-shadow:0 3px 10px #0002; overflow:hidden; --jpx-motion:160ms; --jpx-motion-fast:120ms; } .jpx-records-sheet[data-panel=columns] { height:min(620px,calc(100dvh - 48px)); } .jpx-records-sheet[open] { display:flex; flex-direction:column; } .jpx-records-sheet[data-panel=columns] .jpx-records-sheet-body { flex:1; } .jpx-records-sheet::backdrop { background:rgb(16 13 10 / 42%); } .jpx-records-sheet-header { flex:none; display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 16px; border-bottom:1px solid #ddd0bd; } .jpx-records-sheet-header h2 { margin:0; font-size:18px; color:#5c0d11; } .jpx-records-sheet-close { border-color:transparent; background:transparent; } .jpx-records-sheet-body { min-height:0; overflow:auto; overflow-y:scroll; scrollbar-gutter:stable; overscroll-behavior:contain; padding:16px; scroll-padding:12px; } @supports(scrollbar-gutter:stable) { .jpx-records-sheet-body { overflow-y:auto; } } .jpx-records-sheet [hidden] { display:none!important; } .jpx-records-sheet :focus-visible { outline:2px solid #9b4e03; outline-offset:2px; } #filtersDiv { display:grid; gap:16px; min-width:0; } .jpx-records-filter-scope, .jpx-records-filter-match, .jpx-records-filter-tools { display: grid; gap: 4px; min-width: 0; } .jpx-records-filter-match, .jpx-records-filter-tools { padding:16px 0 0; border-top:1px solid #ddd0bd; } .jpx-records-filter { display:flex; flex-direction:column; align-items:flex-start; gap:6px; min-width:0; max-width:100%; } .jpx-records-filter-label { color:#5c0d11; font-weight:700; line-height:1.5; } .jpx-records-filter-options { display:flex; flex-wrap:wrap; align-items:center; gap:8px; min-width:0; } #filtersDiv .jpx-records-filter-options label { display:inline-flex; align-items:center; gap:8px; min-height:44px; min-width:44px; padding:4px 2px; cursor:pointer; user-select:none; touch-action:manipulation; } #filtersDiv input[type=checkbox] { position:static; width:16px; height:16px; flex:none; margin:0; opacity:1; } #filter-aggregate { flex:none; margin-right:8px; } #filter-aggregate label { position:relative; display:inline-flex; align-items:center; justify-content:center; gap:6px; min-height:44px; padding:8px 10px; border:1px solid #c8b49b; border-radius:2px; background:#f9f6ec; color:#5c0d11; cursor:pointer; white-space:nowrap; user-select:none; touch-action:manipulation; } #filter-aggregate label:has(input:checked) { background:#ead9b8; border-color:#b49369; box-shadow:inset 0 -2px currentColor; } #filter-aggregate label:has(input:focus-visible) { outline:2px solid #9b4e03; outline-offset:2px; } #filter-aggregate input { position:absolute; inset:0; width:100%; height:100%; margin:0; opacity:0; cursor:pointer; } .jpx-records-filter-tools .jpx-records-filter-label { flex: none; font-weight: normal; } .jpx-records-tools-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 16px; min-width: 0; } .jpx-records-filter-tools .jpx-records-filter { flex-wrap: wrap; gap: 0 8px; } .jpx-records-range { display: inline-flex; align-items: center; gap: 6px; } #filtersDiv input[type=number] { width: 80px; min-width: 0; height: 44px; padding: 2px 5px; border: 1px solid #bda68e; border-radius: 2px; background: #fffdf7; } .jpx-records-table-scroll { --jpx-scrollbar-width: auto; flex: 1; min-height: 140px; min-width: 0; overflow: auto; border: 1px solid #bda68e; background: #fffdf7; overscroll-behavior: contain; } #battleStatsTable { border-collapse: separate; border-spacing: 0; width: max-content; min-width: 100%; font-size: 12px; font-variant-numeric: tabular-nums; } #battleStatsTable th, #battleStatsTable td { padding: 5px 10px; height: 30px; border-right: 1px solid #e1d7c7; border-bottom: 1px solid #e1d7c7; white-space: nowrap; text-align: left; } #battleStatsTable thead { position: sticky; top: 0; z-index: 2; } #battleStatsTable th { background: #e9d5ae; color: #5c0d11; font-weight: 700; } #battleStatsTable .jpx-records-group-header th { background: color-mix(in srgb, var(--jpx-theme-header,#e9d5ae) 78%, var(--jpx-theme-border,#bda68e)); border-bottom-color:var(--jpx-theme-border,#bda68e); } #battleStatsTable .jpx-records-group-header span { position:sticky; left:10px; display:inline-block; } .jpx-records-column-groups { display:grid; border-top:1px solid #c8b49b; } .jpx-records-column-group { border-bottom:1px solid #c8b49b; overflow:hidden; } .jpx-records-column-heading { display:flex; align-items:center; gap:8px; padding:8px 0; } .jpx-records-column-heading label { flex:1; } .jpx-records-columns label { display:flex; gap:12px; align-items:center; min-height:44px; cursor:pointer; min-width:0; overflow-wrap:anywhere; } .jpx-records-columns input { width:18px; height:18px; flex:none; margin:0; accent-color:var(--jpx-theme-accent,#5c0d11); } .jpx-records-column-heading strong { display:block; font-size:14px; } .jpx-records-column-count { display:block; color:#71634f; font-size:12px; margin-top:2px; } .jpx-records-column-expand { border:0; background:transparent; } .jpx-records-column-expand svg { transition:transform var(--jpx-motion) ease-out; } ${jpxDisclosureCSS('.jpx-records-column-disclosure')} .jpx-records-column-expand[aria-expanded=true] svg { transform:rotate(180deg); } .jpx-records-column-fields { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; border-top:1px solid #ddd0bd; padding:12px; } .jpx-records-column-fields label { padding:0 4px; font-size:13px; } .jpx-records-column-status { position:sticky; bottom:0; margin:12px 0 0; padding:10px 12px; border:1px solid #c8b49b; border-radius:2px; background:#f9f6ec; color:#5c0d11; } .jpx-records-column-status:empty { display:none; } .jpx-records-save-toast, .jpx-records-sheet > .jpx-record-image-toast { position:absolute; top:auto; left:50%; bottom:max(16px,env(safe-area-inset-bottom,0px)); transform:translateX(-50%); width:max-content; max-width:calc(100% - 32px); padding:10px 14px; border:1px solid #c8b49b; border-radius:2px; background:#f9f6ec; color:#5c0d11; box-shadow:0 2px 6px #0002; font-size:13px; text-align:center; pointer-events:none; } .jpx-records-sheet .jpx-record-image-inline { position:static; } .jpx-records-sheet .jpx-record-image-inline > summary { display:none; } .jpx-records-sheet .jpx-record-image-inline > div { position:static; display:grid; width:auto; max-width:none; padding:0; gap:12px; border:0; background:none; box-shadow:none; } .jpx-records-sheet .jpx-record-image-inline button { display:flex; align-items:center; gap:14px; min-height:56px; padding:12px 16px; border:1px solid #c8b49b; border-radius:2px; text-align:left; white-space:normal; } .jpx-records-sheet .jpx-record-image-inline button svg { width:24px; height:24px; flex:none; } #battleStatsTable tr { --record-row-bg: #fffdf7; background: var(--record-row-bg); } #battleStatsTable tbody tr:nth-child(even) { --record-row-bg: #f5f1e7; } #battleStatsTable tbody tr[data-summary] { --record-row-bg: #ece6d8; font-weight: 700; } #battleStatsTable tbody tr:hover, #battleStatsTable tbody tr:focus-within { --record-row-bg: #f1e2c5; } #battleStatsTable tbody td:hover, #battleStatsTable tbody td:focus-visible { outline: 1px solid #baa080; outline-offset: -1px; } #battleStatsTable td.tooltip { position: relative; cursor: help; } #battleStatsTable .jpx-records-number { text-align: right; } #battleStatsTable [data-column=date] { position: sticky; left: 0; z-index: 1; background: var(--record-row-bg, #fffdf7); box-shadow: 1px 0 #c8b49b; } #battleStatsTable th[data-column=date] { top: 0; z-index: 3; background: #e9d5ae; } .jpx-records-detail { display: block; border: 0; padding: 0; background: none; color: inherit; font: inherit; text-align: left; text-decoration: underline; text-decoration-color: #bda68e; text-underline-offset: 3px; } .jpx-records-detail:hover { color: #5c0d11; text-decoration-color: currentColor; } #battleStatsTable td.tooltip:is(:hover, :focus-visible)::after { content: attr(content); position: absolute; z-index: 4; right: 0; bottom: calc(100% + 4px); width: max-content; max-width: min(420px, calc(100vw - 32px)); padding: 6px 8px; border: 1px solid #bda68e; border-radius: 2px; background: #f9f6ec; color: #5c0d11; box-shadow: 0 2px 4px #0002; font: 12px/1.5 Arial, Helvetica, sans-serif; white-space: pre-wrap; overflow-wrap: anywhere; text-align: left; pointer-events: none; } #battleStatsTable tr:nth-child(-n+2) td.tooltip::after { bottom: auto; top: calc(100% + 4px); } .jpx-records-message { margin: 0; padding: 28px 16px; text-align: center; color: #71634f; } @media(max-width:650px),(pointer:coarse) and (orientation:landscape) and (max-height:600px) { .jpx-records-page { gap:10px; padding:max(8px,env(safe-area-inset-top,0px)) max(8px,env(safe-area-inset-right,0px)) max(8px,env(safe-area-inset-bottom,0px)) max(8px,env(safe-area-inset-left,0px)); } .jpx-records-toolbar { display:grid; grid-template-columns:minmax(0,1fr); gap:8px; } .jpx-records-heading { display:flex; align-items:baseline; justify-content:space-between; gap:12px; } .jpx-records-heading h1 { font-size:15px; } .jpx-records-count { margin:0; } .jpx-records-actions { min-width:0; } #filter-aggregate { flex:1; min-width:0; margin-right:0; } #filter-aggregate .jpx-records-filter-options { width:100%; } #filter-aggregate label { width:100%; max-width:100%; min-width:0; padding:6px 8px; white-space:normal; text-align:center; } .jpx-records-sheet[data-panel=columns] { height:min(620px,88dvh); } .jpx-records-sheet { inset:auto 0 0; width:100%; max-height:88dvh; margin:0; border-radius:0; border-bottom:0; } .jpx-records-sheet-header { padding:12px max(16px,env(safe-area-inset-right,0px)) 10px max(16px,env(safe-area-inset-left,0px)); } .jpx-records-sheet-body { padding:16px max(16px,env(safe-area-inset-right,0px)) max(20px,env(safe-area-inset-bottom,0px)) max(16px,env(safe-area-inset-left,0px)); } #filtersDiv { font-size:14px; } #filtersDiv input[type=number] { font-size:16px; } #battleStatsTable th,#battleStatsTable td { padding:6px 8px; } .jpx-records-table-scroll { min-height:0; border-radius:2px; } } @media(max-height:500px) { .jpx-records-sheet { max-height:calc(100dvh - 12px); } } @media(prefers-reduced-motion:reduce) { .jpx-records-icon { transition:none; } .jpx-records-sheet { --jpx-motion:0ms; --jpx-motion-fast:0ms; } } `); applyJpxTheme(doc); const el = (tag, className, text) => createJpxElement(tag, className, text, doc); const page = el('main', 'jpx-records-page'), tableRegion = el('div', 'jpx-records-table-scroll'); tableRegion.tabIndex = 0; tableRegion.setAttribute('role', 'region'); tableRegion.setAttribute('aria-label', t('sP.jpxStats')); tableRegion.append(el('p', 'jpx-records-message', t('sP.loadingRecords'))); let revision = 0, pendingRead, cachedRecords = null; const columnControls = createStatsColumnControls(doc, () => { if (cachedRecords) renderDynamicTable(cachedRecords, cfgStats.statsColumns, tableRegion); }); const refresh = async () => { pendingRead?.abort(); pendingRead = new AbortController(); const request = ++revision, filters = getFilters(targetWindow); tableRegion.setAttribute('aria-busy', 'true'); try { const records = await getBattleRecordsRender(filters, pendingRead.signal); if (targetWindow.closed || request !== revision) return; cachedRecords = records; count.textContent = t(filters.aggregate ? 'sP.dayCount' : 'sP.recordCount', {count:Math.max(0,records.length - 2)}); columnControls.update(); renderDynamicTable(records, cfgStats.statsColumns, tableRegion); } catch (error) { if (targetWindow.closed || request !== revision || error.name === 'AbortError') return; cachedRecords = null; count.textContent = t('sP.recordsError'); tableRegion.replaceChildren(el('p', 'jpx-records-message', t('sP.recordsError'))); console.error('Could not load battle records:', error); } finally { if (!targetWindow.closed && request === revision) tableRegion.setAttribute('aria-busy', 'false'); } }; filterState.refresh = refresh; const recordsChanged = event => { if (event.type === 'storage' && event.key === prefix + 'cfgStats') { loadStatsSettingsConfig(); columnControls.update(); if (cachedRecords) renderDynamicTable(cachedRecords, cfgStats.statsColumns, tableRegion); } else if (event.type !== 'storage' || event.key === prefix+'recordsChanged') refresh(); }; targetWindow.addEventListener('storage',recordsChanged); targetWindow.addEventListener('jpx:records-changed',recordsChanged); const filters = filterState.filters || createFilter(targetWindow, () => filterState.refresh?.()); filterState.filters = filters; if (filterState.inputs) [...filters.querySelectorAll('input')].forEach((input, index) => { const saved = filterState.inputs[index]; if (saved) { input.value = saved.value; input.checked = saved.checked; } }); // Reuse live input nodes during redraws, including a language-pack refresh. filters.setAttribute('aria-label', t('sP.filters')); for (const field of STATS_FILTERS) { const group = filters.querySelector('#' + field.id); const label = group.querySelector('.jpx-records-filter-label'); if (label) label.textContent = t(field.label); if (field.type === 'checkbox') group.querySelectorAll('label').forEach(label => { const input = label.querySelector('input'); for (const node of [...label.childNodes]) if (node !== input) node.remove(); label.append(doc.createTextNode(t('sP.' + input.value))); }); if (field.type === 'rangeNumber') ['min', 'max'].forEach((part, index) => group.querySelector('.range-' + part).setAttribute('aria-label', t(index ? 'sP.rangeMax' : 'sP.rangeMin'))); } const clearRecords = el('button', 'jpx-records-icon jpx-records-clear'); clearRecords.type = 'button'; clearRecords.append(createSettingsIcon('delete')); setJpxLabel(clearRecords, t('cS.clearRecords')); clearRecords.setAttribute('aria-haspopup','dialog'); clearRecords.onclick = () => { const current = getFilters(targetWindow); openJpxRecordsCleanup(targetWindow,{world:current.world?.length === 1 ? current.world[0] : '',battleType:current.battleType?.length === 1 ? current.battleType[0] : ''}); }; const toolbar = el('header', 'jpx-records-toolbar'), heading = el('div', 'jpx-records-heading'); const count = el('p', 'jpx-records-count', t('sP.loadingRecords')); count.setAttribute('role','status'); heading.append(el('h1', undefined, t('sP.jpxStats')), count); const actions = el('nav', 'jpx-records-actions'); actions.setAttribute('aria-label',t('sP.jpxStats')); const aggregate = filters.querySelector('#filter-aggregate'); aggregate.onchange = () => filterState.refresh?.(); actions.append(aggregate); toolbar.append(heading,actions); const sheet = doc.createElement('dialog'); sheet.id = 'jpx-records-sheet'; sheet.className = 'jpx-records-sheet'; sheet.setAttribute('aria-labelledby','jpx-records-sheet-title'); const sheetHeader = el('header', 'jpx-records-sheet-header'), sheetTitle = el('h2'); sheetTitle.id = 'jpx-records-sheet-title'; const close = doc.createElement('button'); close.type = 'button'; close.className = 'jpx-records-icon jpx-records-sheet-close'; setJpxLabel(close, t('cM.close')); close.append(createSettingsIcon('close')); close.autofocus = true; sheetHeader.append(sheetTitle,close); const sheetBody = el('div', 'jpx-records-sheet-body'); const imageActions = createRecordImageActions(doc, () => tableRegion.querySelector('#battleStatsTable'), true); const panels = { filters, columns:columnControls.node, image:imageActions }; const triggers = new Map(); let disposed = false, opener; const setExpanded = name => triggers.forEach((button,key) => button.setAttribute('aria-expanded',String(name === key))); const openPanel = name => { if (disposed) return; filterState.panel = name; for (const [key,node] of Object.entries(panels)) node.hidden = key !== name; opener = triggers.get(name); sheetTitle.textContent = opener.title; sheet.dataset.panel = name; setExpanded(name); sheetBody.scrollTop = 0; if (!sheet.open) sheet.showModal(); close.focus({preventScroll:true}); }; for (const [name,icon,key] of [['filters','filter','sP.filters'],['columns','columns','sP.displayColumns'],['image','image','sP.image']]) { const button = doc.createElement('button'); button.type = 'button'; button.className = 'jpx-records-icon'; button.dataset.recordsPanel = name; setJpxLabel(button, t(key)); button.setAttribute('aria-controls',sheet.id); button.setAttribute('aria-haspopup','dialog'); button.setAttribute('aria-expanded','false'); button.append(createSettingsIcon(icon)); button.onclick = () => openPanel(name); triggers.set(name,button); actions.append(button); panels[name].hidden = true; sheetBody.append(panels[name]); } actions.append(clearRecords); close.onclick = () => sheet.close(); sheet.addEventListener('keydown',event => { if (event.key !== 'Tab') return; const controls = [...sheet.querySelectorAll('button:not(:disabled),input:not(:disabled),[tabindex="0"]')].filter(node => node.getClientRects().length && !node.closest('[inert]')); const first = controls[0], last = controls[controls.length - 1]; if (event.shiftKey && doc.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && doc.activeElement === last) { event.preventDefault(); first.focus(); } }); sheet.addEventListener('close',() => { if (disposed) return; columnControls.dismissToast(); sheet.querySelectorAll('.jpx-record-image-toast').forEach(toast => toast.remove()); filterState.panel = null; setExpanded(null); opener?.focus({preventScroll:true}); }); // Require both press and release outside: dragging from inside the sheet // must not dismiss it when the pointer finishes on the backdrop. const outside = event => { const r = sheet.getBoundingClientRect(); return event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom; }; let pressedOutside = false; sheet.addEventListener('pointerdown',event => { pressedOutside = event.target === sheet && outside(event); }); sheet.addEventListener('click',event => { if (pressedOutside && event.target === sheet && outside(event)) sheet.close(); pressedOutside = false; }); sheet.append(sheetHeader,sheetBody); filterState.cleanup = () => { disposed = true; revision++; pendingRead?.abort(); targetWindow.removeEventListener('storage',recordsChanged); targetWindow.removeEventListener('jpx:records-changed',recordsChanged); columnControls.dismissToast(); imageActions.dispose(); if (sheet.open) sheet.close(); }; page.append(toolbar,tableRegion); doc.body.append(page,sheet); if (panels[filterState.panel]) openPanel(filterState.panel); refresh(); } async function getBattleRecordsRender(filters = getFilters(), signal) { if (signal?.aborted) throw new DOMException('Aborted', 'AbortError'); if (jpxShared.enabled) { await ensureJpxSharedRecords(); const archive = await jpxShared.allRecords(); if (signal?.aborted) throw new DOMException('Aborted', 'AbortError'); let records = archive.filter(record => filterData(record, filters)); records.sort((a, b) => String(b.timestamp).localeCompare(String(a.timestamp))); if (filters.aggregate) { const days = new Map(); for (const record of records) { if (!days.has(record.date)) days.set(record.date, []); days.get(record.date).push(record); } records = [...days].sort(([a], [b]) => b.localeCompare(a)).map(([date, rows]) => generateAggregate(rows, 'Total', date)); } records = records.slice(0, filters.rows); records.unshift(generateAggregate(records, 'Total'), generateAggregate(records, 'Average')); return records; } const db = await openDB(); try { if (signal?.aborted) throw new DOMException('Aborted', 'AbortError'); return await new Promise((resolve, reject) => { const transaction = db.transaction('battleRecords', 'readonly'); const objectStore = transaction.objectStore('battleRecords'); const source = filters.aggregate ? objectStore.index('date') : objectStore; const request = source.openCursor(IDBKeyRange.bound(0, 'z'), 'prevunique'); const records = []; let failure; const abort = () => { try { transaction.abort(); } catch { /* The completion event may already be queued. */ } }; const fail = error => { failure = error; abort(); }; const release = () => signal?.removeEventListener('abort', abort); signal?.addEventListener('abort', abort, { once: true }); transaction.oncomplete = () => { release(); if (signal?.aborted) { reject(new DOMException('Aborted', 'AbortError')); return; } try { records.unshift(generateAggregate(records, 'Total'), generateAggregate(records, 'Average')); resolve(records); } catch (error) { reject(error); } }; transaction.onabort = () => { release(); reject(signal?.aborted ? new DOMException('Aborted', 'AbortError') : failure || transaction.error || new Error('Record query aborted')); }; request.onsuccess = () => { if (signal?.aborted) return; const cursor = request.result; if (!cursor || records.length >= filters.rows) return; try { if (filters.aggregate) { const daily = source.getAll(cursor.key); daily.onsuccess = () => { if (signal?.aborted) return; try { const matches = daily.result.filter(record => filterData(record, filters)); if (matches.length) records.push(generateAggregate(matches, 'Total', matches[0].date)); cursor.continue(); } catch (error) { fail(error); } }; } else { if (filterData(cursor.value, filters)) records.push(cursor.value); cursor.continue(); } } catch (error) { fail(error); } }; }); } finally { db.close(); } } async function exportIndexedDB() { if (jpxShared.enabled) { await ensureJpxSharedRecords(); return { dbName: 'jpx', version: 1, stores: { battleRecords: await jpxShared.allRecords() } }; } const db = await openDB(); const exportData = { dbName: db.name, version: db.version, stores: {}, }; for (const storeName of db.objectStoreNames) { exportData.stores[storeName] = await new Promise((resolve, reject) => { const transaction = db.transaction(storeName, 'readonly'); const objectStore = transaction.objectStore(storeName); const req = objectStore.getAll(); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } db.close(); return exportData; } async function importIndexedDB(jsonData, merge = true) { if (jpxShared.enabled) { validateStatsBackup(jsonData); await ensureJpxSharedRecords(); await jpxShared.importRecords(jsonData.stores.battleRecords, merge); window.dispatchEvent(new Event('jpx:records-changed')); return; } const db = await openDB(); for (const storeName in jsonData.stores) { const transaction = db.transaction(storeName, 'readwrite'); const objectStore = transaction.objectStore(storeName); if (!merge) objectStore.clear(); let existingKeys = null; if (merge) { existingKeys = await new Promise((resolve, reject) => { const req = objectStore.getAllKeys(); req.onsuccess = () => resolve(new Set(req.result)); req.onerror = () => reject(req.error); }); } for (const record of jsonData.stores[storeName]) { const key = record[objectStore.keyPath]; if (!merge || !existingKeys.has(key)) objectStore.put(record); } await new Promise((resolve, reject) => { transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(transaction.error); }); } db.close(); } function filterData(data, filters) { if (filters.world && !filters.world.includes(data.world)) return false; if (filters.battleType && !filters.battleType.includes(data.battleType)) return false; if (filters.difficulties && !filters.difficulties.includes(data.difficulty.toString())) return false; if (filters.result && !filters.result.includes(data.result)) return false; if (filters.roundTotal && !jpxUtils.inRange(data.roundInfo.total, filters.roundTotal)) return false; return data; } function generateAggregate(data_array, type, timestamp_name = null) { //type: Average, Total if (data_array.length === 0) return false; const length = type === 'Average' ? data_array.length : 1; const aggregate = (get, scale = 100) => Math.round(data_array.reduce((sum, row) => sum + get(row), 0) / length * scale) / scale; const scalarCategories = ['exp', 'credit', 'staminaCost', 'totalProfit', 'finalProfit']; const countCategories = ['proficiency', 'material', 'token', 'food', 'figurine', 'artifact', 'trophy', 'crystal']; // The stored total/profit entries of item categories are derived, never summed. const items = fields => Object.entries(fields).filter(([key]) => key !== 'total' && key !== 'profit'); const new_data = { date: timestamp_name || t(`sP.${type}`), roundInfo: { current: aggregate(row => row.roundInfo.current), total: aggregate(row => row.roundInfo.total) }, deltaSeconds: aggregate(row => row.deltaSeconds, 1000), deltaTime: '', turns: aggregate(row => row.turns), tps: 0, riddle: aggregate(row => row.riddle), combatRecords: jpxUtils.createCombatRecords(), revenueRecords: jpxUtils.createRevenueRecords(), }; new_data.deltaTime = jpxUtils.secondsToTime(new_data.deltaSeconds, true); new_data.tps = Math.round(new_data.turns / new_data.deltaSeconds * 100) / 100; for (const row of data_array) { for (const [category, fields] of Object.entries(row.combatRecords)) { for (const [key, value] of Object.entries(fields)) jpxUtils.inc(new_data.combatRecords[category], key, value); } for (const [category, fields] of Object.entries(row.revenueRecords)) { const target = new_data.revenueRecords[category]; if (scalarCategories.includes(category)) new_data.revenueRecords[category] += fields; else if (category === 'equipment') { for (const [key, value] of Object.entries(fields)) target[key] = (target[key] ?? []).concat(value); } else if (category === 'consumable') { for (const [key, value] of items(fields)) { target[key] ??= {}; for (const prop of ['drop', 'use', 'balance']) jpxUtils.inc(target[key], prop, value[prop]); } } else if (countCategories.includes(category)) { for (const [key, value] of items(fields)) jpxUtils.inc(target, key, value); } } } new_data.revenueRecords.staminaCost = Math.round(new_data.revenueRecords.staminaCost * 10) / 10; for (const [key, value] of Object.entries(new_data.revenueRecords.proficiency)) { new_data.revenueRecords.proficiency[key] = Math.round(value * 1000) / 1000; } if (type === 'Average') { const average = (value, scale = 10) => Math.round(value / length * scale) / scale; for (const fields of Object.values(new_data.combatRecords)) { for (const [key, value] of Object.entries(fields)) fields[key] = average(value); } for (const [category, fields] of Object.entries(new_data.revenueRecords)) { if (scalarCategories.includes(category)) new_data.revenueRecords[category] = average(fields); else if (category === 'equipment') { for (const [key, value] of Object.entries(fields)) fields[`${key}_Avg`] = average(value.length); } else if (category === 'consumable') { for (const [, value] of items(fields)) for (const prop of ['drop', 'use', 'balance']) value[prop] = average(value[prop]); } else if (countCategories.includes(category)) { const scale = category === 'proficiency' ? 1000 : 10; for (const [key, value] of items(fields)) fields[key] = average(value, scale); } } } return new_data; } function createFilter(targetWindow, onChange) { const doc = targetWindow.document; const el = (tag, className) => createJpxElement(tag, className, '', doc); const input = (type, value) => { const node = doc.createElement('input'); node.type = type; node.value = value; return node; }; const filtersDiv = doc.createElement('div'); filtersDiv.id = 'filtersDiv'; filtersDiv.setAttribute('role', 'group'); filtersDiv.setAttribute('aria-label', t('sP.filters')); const groups = new Map(); for (const filter of STATS_FILTERS) { const group = doc.createElement('div'); group.id = filter.id; group.className = 'jpx-records-filter'; group.setAttribute('role', 'group'); const label = doc.createElement('span'); label.id = filter.id + '-label'; label.className = 'jpx-records-filter-label'; label.textContent = t(filter.label); if (filter.id !== 'filter-aggregate') { group.append(label); group.setAttribute('aria-labelledby', label.id); } const options = el('div', filter.type === 'rangeNumber' ? 'jpx-records-range' : 'jpx-records-filter-options'); if (filter.type === 'checkbox') for (const opt of filter.options) { const box = input('checkbox', opt); box.checked = filter.id === 'filter-world' ? opt === (isekaiSuffix ? 'Isekai' : 'Persistent') : filter.id !== 'filter-aggregate'; options.appendChild(el('label')).append(box, doc.createTextNode(t(`sP.${opt}`))); } else if (filter.type === 'rangeNumber') for (const [index, part] of ['min', 'max'].entries()) { if (index) options.append(doc.createTextNode('–')); const range = input('number', filter.value[index]); range.className = 'range-' + part; range.setAttribute('aria-label', t(index ? 'sP.rangeMax' : 'sP.rangeMin')); options.append(range); } else if (filter.type === 'number') options.appendChild(input('number', filter.value)).setAttribute('aria-labelledby', label.id); group.append(options); groups.set(filter.id, group); } const section = (className, ...ids) => { const node = el('div', className); node.append(...ids.map(id => groups.get(id))); return node; }; const tools = section('jpx-records-filter-tools', 'filter-roundTotal'); tools.append(section('jpx-records-tools-row', 'filter-rows', 'filter-aggregate')); filtersDiv.append(section('jpx-records-filter-scope', 'filter-world', 'filter-result'), section('jpx-records-filter-match', 'filter-battleType', 'filter-difficulties'), tools); filtersDiv.addEventListener('change', e => { if (e.target.tagName === 'INPUT') onChange(); }); return filtersDiv; } function getFilters(targetWindow = newWindow) { const filters = {}; for (const filter of STATS_FILTERS) { const filterEl = targetWindow.document.getElementById(filter.id); if (!filterEl) continue; if (filter.type === 'checkbox') { const checked = Array.from(filterEl.querySelectorAll('input:checked')).map(x => x.value); filters[filter.key] = filter.options.length === 1 ? !!checked.length : checked; } else if (filter.type === 'rangeNumber') { filters[filter.key] = [parseInt(filterEl.querySelector('.range-min').value), parseInt(filterEl.querySelector('.range-max').value)]; } else if (filter.type === 'number') filters[filter.key] = parseInt(filterEl.querySelector('input').value); } return filters; } // Shared by the table and the threshold preview, including invalid colors and duplicate minima. function parseStatsColorThresholds(tokens) { return tokens.map(token => { const [value, color] = token.split(':'); return { min: parseFloat(value.trim()), color: color?.trim() }; }).filter(threshold => !isNaN(threshold.min)).sort((a, b) => b.min - a.min); } function renderDynamicTable(battleRecords, displayedColumns, parent) { const doc = parent.ownerDocument; const scrollLeft = parent.scrollLeft, scrollTop = parent.scrollTop; parent.querySelector('#battleStatsTable')?.remove(); parent.querySelectorAll(':scope > .jpx-records-message').forEach(node => node.remove()); const notice = key => { const message = createJpxElement('p', 'jpx-records-message', '', doc); message.setAttribute('role', 'status'); message.textContent = t(key); parent.append(message); }; let activeFields = displayedColumns.filter(column => column.disabled !== true && statsColumnGroupVisible(cfgStats.columnGroups, STATS_COLUMN_GROUP_BY_ID.get(column.id))).map(column => { const baseField = STATS_FIELDS.find(f => f.id === column.id); return baseField ? { ...baseField, ...column } : null; }).filter(f => f); // Group only the rendered view. Preserve saved metadata and ordering inside // each category, without rewriting the user's column configuration. activeFields = STATS_COLUMN_GROUPS.flatMap(group => activeFields.filter(field => STATS_COLUMN_GROUP_BY_ID.get(field.id) === group.id)); const records = battleRecords.filter(record => record && typeof record === 'object'); if (!activeFields.length) return notice('sP.noColumns'); const table = doc.createElement('table'); table.id = 'battleStatsTable'; table.setAttribute('aria-label', t('sP.jpxStats')); const thead = doc.createElement('thead'); const groupRow = createJpxElement('tr', 'jpx-records-group-header', '', doc); let lastGroup, groupHeader, groupColumns, groupCount = 0; for (const field of activeFields) { const group = STATS_COLUMN_GROUP_BY_ID.get(field.id); if (group !== lastGroup || !groupHeader) { groupColumns = doc.createElement('colgroup'); table.append(groupColumns); groupCount = 0; groupHeader = doc.createElement('th'); groupHeader.scope = 'colgroup'; groupHeader.dataset.columnGroup = group; groupHeader.appendChild(doc.createElement('span')).textContent = t('sP.group_' + group); groupRow.append(groupHeader); lastGroup = group; } groupHeader.colSpan = ++groupCount; groupColumns.span = groupCount; } const headerRow = doc.createElement('tr'); for (const field of activeFields) { const th = doc.createElement('th'); th.scope = 'col'; th.dataset.column = field.id; if (field.style) th.style.cssText = field.style; th.textContent = field.customName || t(field.label); if (STATS_THRESHOLD_FIELDS.has(field.id)) th.classList.add('jpx-records-number'); headerRow.append(th); } thead.append(groupRow, headerRow); table.appendChild(thead); const tbody = doc.createElement('tbody'); const columnThresholds = new Map(); const tooltip = (td, content, label) => { td.classList.add('tooltip'); td.setAttribute('content', content); td.tabIndex = 0; td.setAttribute('aria-label', label); }; for (const [index, record] of records.entries()) { const tr = doc.createElement('tr'); if (index < 2 && [t('sP.Total'), t('sP.Average')].includes(record.date)) tr.dataset.summary = ''; for (const field of activeFields) { const td = doc.createElement('td'); td.dataset.column = field.id; let value = field.get(record); if (field.styleText) td.style.cssText = field.styleText; if (field.doI18n) value = t(`sP.${value}`); if (field.id === 'date') { const detail = doc.createElement('button'); detail.type = 'button'; detail.className = 'jpx-records-detail'; detail.textContent = value || ''; detail.title = t('sP.openRecord'); detail.setAttribute('aria-label', t('sP.openRecord') + ': ' + (value || '')); detail.addEventListener('click', () => jpxMarket.getMarketPrice(false).then(priceData => newWindowRecordPlayer(false, record, timeRecordPlayer(record), combatRecordPlayer(record.combatRecords), combatRecordPlayer_Use(record.combatRecords), revenueRecordPlayer(record.revenueRecords, priceData)))); td.append(detail); } else if (value && typeof value === 'object' && 'drop' in value) { const details = `${t('sP.drop')}: ${value.drop.toLocaleString()}\n${t('sP.use')}: ${value.use.toLocaleString()}`; tooltip(td, details, value.balance.toLocaleString() + '; ' + details); td.classList.add('jpx-records-number'); td.textContent = value.balance.toLocaleString(); } else if (typeof value === 'number') { td.classList.add('jpx-records-number'); td.textContent = value.toLocaleString(); if (field.colorThresholds) { if (!columnThresholds.has(field)) columnThresholds.set(field, parseStatsColorThresholds(field.colorThresholds.split(','))); const match = columnThresholds.get(field).find(thr => value >= thr.min); if (match) td.style.color = match.color; } } else { td.textContent = value || ''; } const equipment = record.revenueRecords?.equipment?.[field.equipmentQuality]; if (field.equipmentQuality && Array.isArray(equipment) && equipment.length) { const names = equipment.filter(name => typeof name === 'string' && name.trim()).join('\n'); if (names) tooltip(td, names, td.textContent + '; ' + names); } tr.appendChild(td); } tbody.appendChild(tr); } table.appendChild(tbody); parent.appendChild(table); if (!records.length) notice('sP.noRecords'); parent.scrollLeft = scrollLeft; parent.scrollTop = scrollTop; } //Settings let settingsEditHistory = null; let statsSettingsView = { section: 'combatRows', fields: {} }; let battleRulesView = { section: 'rules', scroll: {} }; const settingsChangeBindings = new WeakMap(); // List scroll belongs to the dialog view, never to saved/exported statistics configuration. function captureStatsListScroll(container) { container?.querySelectorAll('.jpx-stats-list[data-stats-field]').forEach(list => { const view = statsSettingsView.fields[list.dataset.statsField]; if (view && list.isConnected && list.getClientRects().length) view.scrollTop = list.scrollTop; }); } function restoreStatsListScroll(container) { container?.querySelectorAll('.jpx-stats-list[data-stats-field]').forEach(list => { const view = statsSettingsView.fields[list.dataset.statsField]; if (view && list.isConnected && list.getClientRects().length) list.scrollTop = view.scrollTop || 0; }); } // Bind actual configuration values, not input text or transient editor state. function bindSettingsChange(element, data, key, badgeTarget = element, item = false) { element.dataset.jpxChangeBound = ''; settingsChangeBindings.set(element, { data, key, badgeTarget, item }); } function createSettingsChangeTracker(container, readData) { const identities = new WeakMap(); let nextIdentity = 0; const roots = () => ({ battle: cfgBattle, shortcuts: userKeybinds, stats: cfgStats }); const identity = item => { if (item.id !== undefined) return `field:${item.id}`; if (!identities.has(item)) identities.set(item, ++nextIdentity); return identities.get(item); }; // Sidecar identities survive undo/redo without adding metadata to saved/exported configuration. function captureIdentities() { const result = {}; function visit(value, path, entries) { if (!value || typeof value !== 'object') return; Object.entries(value).forEach(([key, child]) => { const childPath = [...path, key]; if (Array.isArray(value) && child && typeof child === 'object') entries.push([childPath, identity(child)]); visit(child, childPath, entries); }); } Object.entries(roots()).forEach(([scope, value]) => { result[scope] = []; visit(value, [], result[scope]); }); return result; } function restoreIdentities(data, snapshot, scopes = Object.keys(data)) { scopes.forEach(scope => (snapshot[scope] || []).forEach(([path, id]) => { const item = path.reduce((value, key) => value?.[key], data[scope]); if (item && typeof item === 'object') identities.set(item, id); })); } const saved = {}; function save(scopes, initial = false) { const data = readData(), ids = captureIdentities(); scopes.forEach(scope => { saved[scope] = JSON.parse(data[scope]); }); restoreIdentities(saved, ids, scopes); if (!initial) refresh(); } // Empty containers materialized by the legacy renderer are equivalent to missing containers. function equal(a, b) { if (a === b) return true; if (a === undefined) return b && typeof b === 'object' && Object.entries(b).every(([key, value]) => !key.startsWith('kb_') && equal(undefined, value)); if (b === undefined) return equal(b, a); if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) !== Array.isArray(b)) return false; if (Array.isArray(a) && a.length !== b.length) return false; return [...new Set([...Object.keys(a), ...Object.keys(b)])].every(key => (!key.startsWith('kb_') || (key in a) === (key in b)) && equal(a[key], b[key])); } function refresh() { const matches = new WeakMap(); // Canonical content narrows recreated rules to a small candidate bucket. // Empty containers stay equivalent to missing fields; equal() remains // authoritative when those deliberately broad keys share a bucket. function matchKey(value) { if (value === undefined) return ''; if (!value || typeof value !== 'object') return JSON.stringify(value); const entries = Object.entries(value).map(([key, child]) => [key, matchKey(child)]); if (entries.every(([key, content]) => !key.startsWith('kb_') && content === '')) return ''; if (Array.isArray(value)) return 'a' + value.length + '[' + entries.map(([key, content]) => key + ':' + content).join(',') + ']'; return 'o{' + entries.filter(([key, content]) => key.startsWith('kb_') || content !== '') .sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, content]) => JSON.stringify(key) + ':' + content).join(',') + '}'; } function match(current, baseline, moved = false) { if (!current || typeof current !== 'object') return; matches.set(current, { baseline, moved }); if (Array.isArray(current)) { const old = Array.isArray(baseline) ? baseline : []; const oldById = new Map(old.filter(v => v && typeof v === 'object').map(v => [identity(v), v])); // Imports/reset recreate objects. Reuse unchanged entries first, then same-kind // replacements at the same position; copies cannot claim an identity still in use. const objects = current.filter(v => v && typeof v === 'object'); const claimed = new Set(objects.map(identity).filter(id => oldById.has(id))); const adopt = (value, previous) => { const id = identity(previous); identities.set(value, id); claimed.add(id); }; const recreated = objects.filter(value => value.id === undefined && !oldById.has(identity(value))); if (recreated.length) { const byContent = new Map(); for (const entry of old) { if (!entry || typeof entry !== 'object' || claimed.has(identity(entry))) continue; const key = matchKey(entry); if (!byContent.has(key)) byContent.set(key, { items: [], head: 0 }); byContent.get(key).items.push(entry); } for (const value of recreated) { const bucket = byContent.get(matchKey(value)); if (!bucket) continue; for (let i = bucket.head; i < bucket.items.length; i++) { const previous = bucket.items[i]; if (!previous || claimed.has(identity(previous))) continue; if (equal(value, previous)) { adopt(value, previous); bucket.items[i] = null; break; } } while (bucket.head < bucket.items.length && (!bucket.items[bucket.head] || claimed.has(identity(bucket.items[bucket.head])))) bucket.head++; } } current.forEach((value, index) => { if (!value || typeof value !== 'object' || value.id !== undefined || oldById.has(identity(value))) return; const previous = old[index]; const kind = value.type ? 'type' : value.key ? 'key' : null; if (kind && previous && !claimed.has(identity(previous)) && value[kind] === previous[kind] && value.name === previous.name) adopt(value, previous); }); const currentIds = current.filter(v => v && typeof v === 'object').map(identity); const currentIdSet = new Set(currentIds); const oldCommon = old.filter(v => v && typeof v === 'object' && currentIdSet.has(identity(v))).map(identity); const currentCommon = currentIds.filter(id => oldById.has(id)); const oldPositions = new Map(), currentPositions = new Map(); oldCommon.forEach((id, index) => { if (!oldPositions.has(id)) oldPositions.set(id, index); }); currentCommon.forEach((id, index) => { if (!currentPositions.has(id)) currentPositions.set(id, index); }); const unchanged = equal(current, old); current.forEach((value, index) => { if (!value || typeof value !== 'object') return; const id = identity(value); match(value, unchanged ? old[index] : oldById.get(id), !unchanged && oldById.has(id) && oldPositions.get(id) !== currentPositions.get(id)); }); } else Object.entries(current).forEach(([key, value]) => match(value, baseline?.[key])); } Object.entries(roots()).forEach(([scope, value]) => match(value, saved[scope])); container.querySelectorAll('[data-jpx-change-bound]:not(.jpx-config-manager *)').forEach(element => { const binding = settingsChangeBindings.get(element); if (!binding) return; const { data, key, item, badgeTarget } = binding; const info = matches.get(data); let state = ''; if (info) { if (item) state = info.baseline === undefined ? 'added' : !equal(data, info.baseline) || info.moved ? 'modified' : ''; else { const read = typeof key === 'function' ? key : value => value?.[key]; if (typeof key === 'string' && key.startsWith('kb_') && !(key in (info.baseline || {}))) state = 'added'; else if (!equal(read(data), read(info.baseline))) state = 'modified'; } } // A new row carries one color marker; its default fields need no repeated highlighting. if (element.parentElement?.closest('[data-change-state=added], .dynamic-array-row')) state = ''; let badge = [...badgeTarget.children].find(child => child.classList.contains('jpx-change-badge')); if (state) { element.dataset.changeState = state; if (!badge) { badge = document.createElement('span'); badge.className = 'jpx-change-badge jpx-sr-only'; badgeTarget.append(badge); } const label = t(state === 'added' ? 'cGen.unsavedAdded' : 'cGen.unsavedModified'); if (badge.textContent !== label) badge.textContent = label; badge.title = t('cGen.unsavedChange'); badge.dataset.state = state; } else { delete element.dataset.changeState; badge?.remove(); } }); } save(['battle', 'shortcuts', 'stats'], true); // Shortcut edits take effect immediately and survive closing the dialog in the legacy UI. // Compare those to persistence so reopening cannot silently label an unsaved binding clean. try { saved.shortcuts = JSON.parse(localStorage.getItem(prefix + 'userKeybinds' + isekaiSuffix)) || { ...KEYBINDS }; } catch { saved.shortcuts = { ...KEYBINDS }; } // Navigation can rebuild an editor without changing data (for example selecting a stats row). const observer = new MutationObserver(records => { // Text captions, previews and disclosure icons are view updates. Only // rebuilding bound fields requires scanning configuration badges again. if (records.some(record => !record.target.closest?.('.jpx-config-manager') && [...record.addedNodes, ...record.removedNodes].some(node => node.nodeType === 1 && !node.matches('.jpx-config-manager') && (node.matches('[data-jpx-change-bound]') || node.querySelector('[data-jpx-change-bound]:not(.jpx-config-manager *)'))))) refresh(); }); observer.observe(container, { childList: true, subtree: true }); return { refresh, save, captureIdentities, commit(scope, patch) { const committed = JSON.parse(JSON.stringify(patch)), current = roots()[scope]; // A committed snapshot already matches the live values. Carry its // array identities directly instead of rediscovering each rule by // scanning all earlier entries (quadratic on large imports). function shareIdentities(value, snapshot) { if (!value || typeof value !== 'object' || !snapshot || typeof snapshot !== 'object') return; for (const [key, child] of Object.entries(value)) { if (!child || typeof child !== 'object' || !snapshot[key] || typeof snapshot[key] !== 'object') continue; if (Array.isArray(value)) identities.set(snapshot[key], identity(child)); shareIdentities(child, snapshot[key]); } } for (const [key, value] of Object.entries(committed)) { if (equal(current?.[key], value)) shareIdentities(current[key], value); } // Only applied keys become clean; unrelated drafts keep their baseline. Object.assign(saved[scope], committed); refresh(); }, restore: (snapshot, scopes) => restoreIdentities(roots(), snapshot, scopes), dispose: () => observer.disconnect() }; } // Editing history is scoped to one open dialog. Persistence remains an explicit save action. function createSettingsEditHistory(container, toolbar, restoreView) { const entries = []; let position = 0, disposed = false, restoring = false, mergeKey = null, lastEditTime = 0, colorEdit = null; const pendingInputs = new WeakMap(); const scopes = ['battle', 'shortcuts', 'stats']; function readData() { // Merely visiting an empty mode materializes empty arrays in the legacy renderer. // Treat absent and empty modes alike, so navigation never marks the configuration dirty. const battle = { ...cfgBattle }; BATTLE_MODES.forEach(key => { const mode = battle[key]; if (mode && Object.entries(mode).every(([name, value]) => (name === 'rules' || name === 'supports' || name === 'attacks') && Array.isArray(value) && !value.length)) delete battle[key]; }); return { battle: JSON.stringify(battle), shortcuts: JSON.stringify(userKeybinds), stats: JSON.stringify(cfgStats) }; } function capture() { captureStatsListScroll(container); const activeRules = container.querySelector('.jpx-rule-section:not([hidden])'); const mode = container.querySelector('[data-role=battleMode]')?.dataset.currentValue; if (activeRules?.getClientRects().length) battleRulesView.scroll[`${mode}:${activeRules.dataset.fieldKey}`] = activeRules.querySelector('.jpx-rule-scroll').scrollTop; const expanded = []; const visit = (value, path) => { if (!value || typeof value !== 'object') return; if (fieldRenderers.expandedRuleItems.has(value)) expanded.push(path); Object.entries(value).forEach(([key, child]) => visit(child, [...path, key])); }; visit(cfgBattle, []); return { data: readData(), identities: changes.captureIdentities(), view: { tab: container.querySelector('[role=tab][aria-selected=true]')?.id.slice(4) || 'battle', mode, scroll: [...container.querySelectorAll('[role=tabpanel]')].map(panel => [panel.id, panel.scrollTop]), expanded, stats: JSON.parse(JSON.stringify(statsSettingsView)), rules: JSON.parse(JSON.stringify(battleRulesView)), } }; } const buttons = createJpxElement('div', 'jpx-history-buttons'); toolbar.prepend(buttons); const [undoButton, redoButton] = ['undo', 'redo'].map(name => { const button = jpxUtils.createButton(buttons, { id: `${name}-settings-button`, history: false, onClick: () => name === 'undo' ? undo() : redo() }); button.append(createSettingsIcon(name), createJpxElement('span', 'jpx-history-label', t(`cGen.${name}`))); button.setAttribute('aria-label', t(`cGen.${name}`)); return button; }); const changes = createSettingsChangeTracker(container, readData); const syncButtons = () => { undoButton.disabled = position === 0; redoButton.disabled = position === entries.length; }; function update() { if (disposed) return; changes.refresh(); syncButtons(); undoButton.title = position ? t('cGen.undoAction', { label: entries[position - 1].label }) + ' (Ctrl+Z)' : t('cGen.undoEmpty'); redoButton.title = position < entries.length ? t('cGen.redoAction', { label: entries[position].label }) + ' (Ctrl+Y / Ctrl+Shift+Z)' : t('cGen.redoEmpty'); } function finish(before, label, typingKey = null) { if (disposed || restoring || !before) return; const after = capture(); const changed = scopes.filter(key => before.data[key] !== after.data[key]); if (!changed.length) return; const previous = entries[position - 1]; if (typingKey && typingKey === mergeKey && position === entries.length && previous && Date.now() - lastEditTime < 900) { previous.after = after; previous.changed = scopes.filter(key => previous.before.data[key] !== after.data[key]); if (!previous.changed.length) { entries.pop(); position--; } } else { entries.splice(position); entries.push({ before, after, changed, label }); if (entries.length > 60) entries.shift(); position = entries.length; } mergeKey = typingKey; lastEditTime = Date.now(); update(); } // Native color pickers and range sliders stream input events while dragging. Snapshot once per gesture, // keeping live model/preview updates separate from the expensive full-dialog history scan. function flushColorEdit() { if (!colorEdit) return; const pending = colorEdit; colorEdit = null; finish(pending.before, pending.label); // A picker may return to its starting color, leaving no history entry to update buttons. syncButtons(); } function run(label, action) { if (disposed || restoring) return action(); flushColorEdit(); mergeKey = null; const before = capture(); try { return action(); } finally { finish(before, label); } } function apply(entry, snapshot) { restoring = true; mergeKey = null; fieldRenderers.dragState.cancel?.(); jpxUtils.keyCaptureController?.abort(); try { if (entry.changed.includes('battle')) cfgBattle = JSON.parse(snapshot.data.battle); if (entry.changed.includes('shortcuts')) userKeybinds = JSON.parse(snapshot.data.shortcuts); if (entry.changed.includes('stats')) cfgStats = JSON.parse(snapshot.data.stats); changes.restore(snapshot.identities, entry.changed); statsSettingsView = JSON.parse(JSON.stringify(snapshot.view.stats || { section: 'combatRows', fields: {} })); battleRulesView = snapshot.view.rules || { section: 'rules', scroll: {} }; fieldRenderers.expandedRuleItems = new WeakSet(); snapshot.view.expanded.forEach(path => { const item = path.reduce((value, key) => value?.[key], cfgBattle); if (item && typeof item === 'object') fieldRenderers.expandedRuleItems.add(item); }); restoreView(snapshot.view); } finally { restoring = false; update(); } } function undo() { flushColorEdit(); if (position > 0) { const entry = entries[--position]; apply(entry, entry.before); } } function redo() { flushColorEdit(); if (position < entries.length) { const entry = entries[position++]; apply(entry, entry.after); } } const inputLabel = target => target.getAttribute('aria-label') || target.labels?.[0]?.textContent.trim(); function beforeInput(event) { if (restoring || event.target.closest('.jpx-battle-mode-selects, .jpx-config-manager, #jpx-battle-export')) return; if (event.target.matches?.('input[type=color], input[type=range]')) { if (colorEdit?.target !== event.target) flushColorEdit(); colorEdit ||= { target: event.target, before: capture(), label: inputLabel(event.target) || t('cGen.configEdit') }; return; } flushColorEdit(); pendingInputs.set(event, capture()); } function afterInput(event) { const target = event.target; if (target.closest('.jpx-config-manager, #jpx-battle-export')) return; if (!target.matches?.('input, textarea, select')) return; if (target.matches('input[type=color], input[type=range]')) { if (event.type === 'change') flushColorEdit(); else if (colorEdit) { undoButton.disabled = false; redoButton.disabled = true; } return; } const label = inputLabel(target) || target.closest('[data-edit-label]')?.dataset.editLabel || t('cGen.configEdit'); finish(pendingInputs.get(event), label, event.type === 'input' && target.matches('input:not([type=checkbox]), textarea') ? target.id : null); pendingInputs.delete(event); } const endTyping = () => { flushColorEdit(); mergeKey = null; }; const beforeAction = event => { if (colorEdit && event.target !== colorEdit.target) flushColorEdit(); }; function onKeyDown(event) { if (event.target.closest('.jpx-config-manager, #jpx-battle-export')) return; beforeAction(event); if (jpxUtils.keyCaptureController || event.isComposing || !(event.ctrlKey || event.metaKey) || event.altKey) return; if (event.target.closest('input, textarea, [contenteditable=true]')) return; const key = event.key.toLowerCase(); if (key !== 'z' && key !== 'y') return; event.preventDefault(); event.stopPropagation(); if (key === 'y' || event.shiftKey) redo(); else undo(); } const listeners = [['input', beforeInput, true], ['input', afterInput], ['change', beforeInput, true], ['change', afterInput], ['focusout', endTyping], ['pointerdown', beforeAction, true], ['click', beforeAction, true], ['keydown', onKeyDown, true]]; listeners.forEach(args => container.addEventListener(...args)); update(); return { run, flushColorEdit, markSaved: scopes => { flushColorEdit(); changes.save(scopes); }, commit(scope, patch) { entries.length = 0; position = 0; mergeKey = null; changes.commit(scope, patch); update(); }, breakTypingGroup: endTyping, dispose() { flushColorEdit(); disposed = true; changes.dispose(); entries.length = 0; listeners.forEach(args => container.removeEventListener(...args)); }, }; } function getBattleMode(defaultBattleStyle = '') { const selected = getJpxSelectedBattleMode(); if (selected) return selected; return resolveJpxScene(battleStyle || defaultBattleStyle, battleType).mode; } function renderSchema(container, schema, data) { container.innerHTML = ''; if (schema.type !== 'object') return; for (const field of schema.properties) { const fieldDiv = createJpxElement('div', 'field-block'); fieldDiv.dataset.fieldKey = field.key; fieldDiv.dataset.fieldType = field.type; renderField(fieldDiv, field, data); container.appendChild(fieldDiv); } } // Defer complete rule forms. Legacy records needing the renderer's default // normalization still take the original eager path, before the undo baseline. function canDeferRuleFields(schema, data) { return schema.properties.every(field => { const value = data[field.key]; if (field.type === 'dropdown') return Array.isArray(field.options) && field.options.some(option => String(option.value) === String(value)) && jpxUtils.parseValue(String(value)) === value; if (field.type === 'rangeNumber') return Array.isArray(value); if (field.type === 'array') return Array.isArray(value) && (!field.hasRange || value.length >= 2) && (field.multiSelectOptions || value.every(item => { const child = resolveSchema(field.itemSchema, item); return !child || child.type !== 'object' || canDeferRuleFields(child, item); })); if (field.type === 'conditionsArray') return Array.isArray(value) && value.every(item => { const option = field.options.find(option => option.key === item.key); if (!option) return item.key !== undefined; const extras = option.extraFields || []; return extras.every(extra => item[extra.key] !== undefined) && canDeferRuleFields({ properties: [{ ...option, key: 'value' }, ...extras] }, item); }); if (field.type === 'object') return !!value && canDeferRuleFields(field, value); return ['constant', 'heading', 'text', 'textarea', 'number', 'boolean'].includes(field.type); }); } // Shortcut rule groups are the kb_* entries of a battle mode. const readKeyBindingRules = value => Object.fromEntries(Object.entries(value || {}).filter(([name]) => name.startsWith('kb_'))); function closeSettingsMultiSelects(root) { root.querySelectorAll('.multiSelect-popup-panel').forEach(panel => panel.style.display = 'none'); root.querySelectorAll('.multiSelect-summary').forEach(summary => summary.setAttribute('aria-expanded', 'false')); } // Wrapping arrow-key navigation shared by the section switchers. function getSettingsSectionStep(key, index, count) { return { ArrowLeft: (index + count - 1) % count, ArrowRight: (index + 1) % count, Home: 0, End: count - 1 }[key]; } function renderBattleRuleSections(container, schema, data, mode) { container.className = 'jpx-rule-sections'; const navigation = createJpxElement('div', 'jpx-rule-navigation'), nav = createJpxElement('div', 'jpx-rule-section-tabs'); nav.setAttribute('role', 'group'); nav.setAttribute('aria-label', t('cB.battleRules')); const controls = createJpxElement('div', 'jpx-rule-section-controls'); navigation.append(nav, controls); const sections = new Map(); const select = key => { fieldRenderers.dragState.cancel?.(); jpxUtils.keyCaptureController?.abort(); container.querySelectorAll('.jpx-rule-sort-popover:popover-open').forEach(menu => menu.hidePopover()); closeSettingsMultiSelects(container); battleRulesView.section = key; sections.forEach(({ panel, button, scroll, toolbar }, id) => { const selected = id === key; if (!panel.hidden && panel.isConnected) battleRulesView.scroll[`${mode}:${id}`] = scroll.scrollTop; panel.hidden = !selected; button.setAttribute('aria-pressed', String(selected)); button.tabIndex = selected ? 0 : -1; if (selected) { controls.replaceChildren(...(toolbar ? [toolbar] : [])); const top = battleRulesView.scroll[`${mode}:${id}`] || 0; requestAnimationFrame(() => { if (panel.isConnected && !panel.hidden) scroll.scrollTop = top; }); } }); }; ['rules', 'keyBindings'].forEach(key => { const field = schema.properties.find(field => field.key === key); const label = key === 'keyBindings' ? 'cB.keyRules' : field.label; const button = jpxUtils.createButton(nav, { text: t(label), history: false, onClick: () => select(key) }); button.dataset.ruleSection = key; button.id = `jpx-rule-section-${key}`; bindSettingsChange(button, data, key === 'keyBindings' ? readKeyBindingRules : key); const panel = createJpxElement('section', 'field-block jpx-rule-section'); panel.dataset.fieldKey = key; panel.dataset.fieldType = field.type; panel.id = `jpx-rule-panel-${key}`; panel.hidden = true; panel.setAttribute('role', 'region'); panel.setAttribute('aria-labelledby', button.id); button.setAttribute('aria-controls', panel.id); renderField(panel, { ...field, fixedActions: true }, data); const heading = panel.querySelector(':scope > .heading'); const toolbar = heading?.querySelector('.jpx-rule-list-toolbar'); if (heading) heading.hidden = true; const scroll = panel.querySelector('.jpx-rule-scroll'); scroll.addEventListener('scroll', () => { if (!panel.hidden) battleRulesView.scroll[`${mode}:${key}`] = scroll.scrollTop; }); sections.set(key, { panel, button, scroll, toolbar }); }); nav.addEventListener('keydown', event => { const keys = [...sections.keys()]; const index = keys.indexOf(event.target.closest('[data-rule-section]')?.dataset.ruleSection); const next = index < 0 ? undefined : getSettingsSectionStep(event.key, index, keys.length); if (next === undefined) return; event.preventDefault(); select(keys[next]); sections.get(keys[next]).button.focus({ preventScroll: true }); }); container.replaceChildren(navigation, ...[...sections.values()].map(section => section.panel)); select(sections.has(battleRulesView.section) ? battleRulesView.section : 'rules'); } function createSettingsPopover(className, idPrefix, role, label) { const menu = createJpxElement('div', className); menu.id = getUniqueId(idPrefix); menu.popover = 'auto'; menu.setAttribute('role', role); menu.setAttribute('aria-label', label); return menu; } // Keep the trigger inside the popover's light-dismiss boundary. function showSettingsPopover(anchor, menu) { anchor.setAttribute('aria-controls', menu.id); anchor.setAttribute('aria-expanded', 'true'); anchor.popoverTargetElement = menu; menu.showPopover(); positionSettingsPopover(anchor, menu); } function releaseSettingsPopoverAnchor(anchor, menu) { if (anchor.getAttribute('aria-controls') !== menu.id) return; anchor.setAttribute('aria-expanded', 'false'); anchor.removeAttribute('aria-controls'); anchor.popoverTargetElement = null; } // Context-menu actions share the row controls and undo history. function openJpxRuleMenu(anchor, row, actions = row.jpxRuleActions, label = t('cB.ruleActions')) { const current = anchor.popoverTargetElement; if (current?.matches('.jpx-rule-context-menu:popover-open')) { current.hidePopover(); return; } document.querySelectorAll('.jpx-rule-context-menu').forEach(menu => { if (menu.matches(':popover-open')) menu.hidePopover(); menu.remove(); }); const menu = createSettingsPopover('jpx-rule-context-menu', 'ruleMenu', 'group', label); let activePage; const showPage = (page, focus) => { if (activePage) { activePage.element.inert = true; activePage.element.setAttribute('aria-hidden', 'true'); } activePage = page; page.element.inert = false; page.element.removeAttribute('aria-hidden'); menu.setAttribute('aria-label', page.label); (focus || page.items.querySelector('button:not(:disabled)'))?.focus({ preventScroll: true }); }; const createPage = (items, pageLabel, back) => { const element = createJpxElement('div', 'jpx-rule-menu-page'), list = createJpxElement('div', 'jpx-rule-menu-items'); element.id = getUniqueId('ruleMenuPage'); element.inert = true; element.setAttribute('aria-hidden', 'true'); const page = { element, items: list, label: pageLabel, back }; if (back) { const button = jpxUtils.createButton(element, { text: pageLabel, history: false, className: 'jpx-rule-menu-back', onClick: back }); button.prepend(createSettingsIcon('chevronLeft')); button.setAttribute('aria-label', `${t('cM.back')}: ${pageLabel}`); button.title = t('cM.back'); } element.append(list); menu.append(element); for (const action of items || []) { if (action.separator) list.appendChild(createJpxElement('div', 'jpx-rule-menu-separator')).setAttribute('role', 'separator'); else if (action.children) { const button = jpxUtils.createButton(list, { text: action.label, history: false, className: 'jpx-rule-menu-next', disabled: action.disabled, onClick: () => { child.items.scrollTop = 0; showPage(child); } }); const child = createPage(action.children, action.label, () => showPage(page, button)); button.append(createSettingsIcon('chevronRight')); button.setAttribute('aria-controls', child.element.id); } else jpxUtils.createButton(list, { text: action.label, history: false, className: action.destructive ? 'jpx-rule-menu-delete' : '', disabled: action.disabled, onClick: () => { menu.hidePopover(); if (anchor.isConnected) anchor.focus({ preventScroll: true }); action.run(anchor); } }); } return page; }; const root = createPage(actions, label); row.append(menu); menu.addEventListener('toggle', event => { if (event.target !== menu || event.newState !== 'closed') return; releaseSettingsPopoverAnchor(anchor, menu); if ((menu.contains(document.activeElement) || document.activeElement === document.body) && anchor.isConnected) anchor.focus({ preventScroll: true }); menu.remove(); }); menu.addEventListener('keydown', event => { if (event.key === 'ArrowLeft' && activePage.back) activePage.back(); else if (event.key === 'ArrowRight' && document.activeElement?.matches('.jpx-rule-menu-next')) document.activeElement.click(); else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { const controls = [...activePage.element.querySelectorAll('button:not(:disabled)')]; const index = controls.indexOf(document.activeElement); const next = event.key === 'Home' ? 0 : event.key === 'End' ? controls.length - 1 : (index + (event.key === 'ArrowDown' ? 1 : -1) + controls.length) % controls.length; controls[next]?.focus({ preventScroll: true }); controls[next]?.scrollIntoView({ block: 'nearest' }); } else return; event.preventDefault(); event.stopPropagation(); }); showSettingsPopover(anchor, menu); showPage(root); } // Chromium dismisses a native picker before delivering a second click to its input, // then the click's default action opens it again. Remember the observed :open state // only while the popup is actually present, and suppress that one reopening click. function bindSettingsNativePickers(container) { if (!CSS.supports('selector(input:open)')) return () => {}; let watched = null, opened = null, suppress = null, frame = 0, pendingFrames = 0; const pickerFor = target => { if (!(target instanceof Element)) return null; const input = target.closest('input') || target.closest('label')?.control; return input && container.contains(input) && input.matches('input[type=color], input[type=time]') ? input : null; }; const stop = () => { if (frame) cancelAnimationFrame(frame); frame = 0; watched = opened = null; }; const sample = () => { frame = 0; if (!watched?.isConnected || !container.open) { stop(); return; } if (watched.matches(':open')) { opened = watched; pendingFrames = 2; } else { opened = null; if (--pendingFrames <= 0) { stop(); return; } } frame = requestAnimationFrame(sample); }; const watch = input => { watched = input; pendingFrames = 2; if (!frame) frame = requestAnimationFrame(sample); }; const onPointerDown = event => { suppress = null; if (event.button !== 0) return; const input = pickerFor(event.target); if (!input) { stop(); return; } if (opened === input || input.matches(':open')) { suppress = input; event.preventDefault(); // Some engines deliver pointerdown before dismissing the native popup. if (input.matches(':open')) { const type = input.type, value = input.value; input.type = 'text'; input.type = type; input.value = value; } opened = null; } watch(input); }; const onClick = event => { const input = pickerFor(event.target); if (input && input === suppress) { event.preventDefault(); suppress = null; settingsEditHistory?.flushColorEdit(); } else if (input) watch(input); }; const onKeyDown = event => { const input = pickerFor(event.target); if (input) watch(input); }; const listeners = [['pointerdown', onPointerDown, true], ['click', onClick, true], ['keydown', onKeyDown, true]]; listeners.forEach(args => container.addEventListener(...args)); return () => { stop(); listeners.forEach(args => container.removeEventListener(...args)); }; } // Small static SVGs keep the userscript self-contained and inherit the HV palette. const settingsIconTemplates = new Map(); const SETTINGS_ICON_PATHS = { filter: 'M4 7h16M7 12h10M10 17h4', columns: 'M3 4h18v16H3V4M9 4v16M15 4v16', image: 'M3 3h18v18H3V3M3 16l6-6 5 5 3-3 4 4M16 7h.01', close: 'M6 6l12 12M6 18 18 6', chevronDown: 'm6 9 6 6 6-6', chevronLeft: 'm15 6-6 6 6 6', chevronRight: 'm9 6 6 6-6 6', download: 'M12 3v12m-5-5 5 5 5-5M4 16v5h16v-5', copy: 'M8 8h13v13H8V8M16 8V3H3v13h5', configManager: 'M3 5h7l2 3h9v12H3V5M7 12h10M7 16h7', more: 'M5 11v2M12 11v2M19 11v2', add: 'M12 5v14M5 12h14', battle: 'M4 21v-7m0-4V3m8 18v-4m0-4V3m8 18V10m0-4V3M1 14h6m2-1h6m2-3h6', battleRules: 'M9 5h12M9 12h12M9 19h12M3 4l1 1 2-2M3 11l1 1 2-2M3 18l1 1 2-2', keyBindings: 'M7 4v16M17 4v16M4 7h16M4 17h16M9 4v3m6-3v3M9 17v3m6-3v3', stats: 'M4 3v18h17M9 17v-6m5 6V7m5 10V4', plugin: 'M8 3v4m8-4v4M5 7h14v3a7 7 0 0 1-14 0V7m7 10v4', edit: 'M14 4l5 5M4 18l5-1L20 6a2.8 2.8 0 0 0-4-4L5 13l-1 5M3 22h18', confirm: 'M5 12l4 4L19 6', collapse: 'M9 3v18M15 9l-3 3 3 3', expand: 'M9 3v18m4-12 3 3-3 3', collapseRules: 'M7 16l5-5 5 5M7 8l5-5 5 5', expandRules: 'M7 8l5 5 5-5M7 16l5 5 5-5', up: 'M12 20V4m-6 6 6-6 6 6', down: 'M12 4v16m-6-6 6 6 6-6', sort: 'M7 3v18m-3-3 3 3 3-3M14 5h7M14 11h5M14 17h3', ruleEnabled: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0M8 12l3 3 5-6', ruleDisabled: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0M8 12h8', delete: 'M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7m4-7v7', undo: 'M3 4v6h6M3 10l5-5a8 8 0 1 1-1 12', redo: 'M21 4v6h-6m6 0-5-5a8 8 0 1 0 1 12', }; function createSettingsIcon(name) { if (!settingsIconTemplates.has(name)) { const svg = (tag, attributes) => { const node = document.createElementNS('http://www.w3.org/2000/svg', tag); for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value); return node; }; const icon = svg('svg', { viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.8', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true', focusable: 'false' }); if (name === 'grip') { icon.setAttribute('fill', 'currentColor'); icon.setAttribute('stroke', 'none'); for (const cx of [8, 16]) for (const cy of [5, 12, 19]) icon.appendChild(svg('circle', { cx, cy, r: '1.7' })); } else icon.appendChild(svg('path', { d: SETTINGS_ICON_PATHS[name] })); settingsIconTemplates.set(name, icon); } return settingsIconTemplates.get(name).cloneNode(true); } function createSettingsMoveButtons(parent, index, count, move) { const actions = createJpxElement('div', 'jpx-rule-sort-actions'); parent.append(actions); for (const [step, icon, key] of [[-1, 'up', 'moveUp'], [1, 'down', 'moveDown']]) { jpxUtils.createButton(actions, { icon, text: t(`cGen.${key}`), className: `jpx-rule-${icon}`, disabled: index + step < 0 || index + step >= count, history: false, onClick: () => move(index + step, `.jpx-rule-${icon}:not(:disabled)`) }); } return actions; } // Fixed descendants of the scaled mobile dialog use its local CSS coordinates. function getSettingsCoordinateSpace(element) { const dialog = element.closest('#settings-container.jpx-settings-mobile'); if (!dialog) return { left: 0, top: 0, scale: 1 }; const rect = dialog.getBoundingClientRect(); return { left: rect.left, top: rect.top, scale: parseFloat(dialog.style.getPropertyValue('--settings-scale')) || 1 }; } function positionSettingsMultiSelect(summary) { const wrap = summary.parentElement, panel = wrap.querySelector('.multiSelect-popup-panel'); if (!panel || panel.style.display === 'none') return; // Local offsets also follow the mobile dialog's scale and wrapped rows. panel.style.left = `${Math.max(0, Math.min(summary.offsetLeft, wrap.clientWidth - panel.offsetWidth))}px`; panel.style.top = `${summary.offsetTop + summary.offsetHeight}px`; } function positionSettingsPopover(anchor, menu) { const rect = anchor.getBoundingClientRect(); const { scale } = getSettingsCoordinateSpace(anchor); const view = window.visualViewport; const left = view?.offsetLeft || 0, top = view?.offsetTop || 0; const right = left + (view?.width || innerWidth), bottom = top + (view?.height || innerHeight); const margin = 8 * scale, gap = 4 * scale; // Top-layer popovers do not inherit their parent's transform. menu.style.transformOrigin = 'top left'; menu.style.transform = `scale(${scale})`; menu.style.maxWidth = `${Math.max(0, (right - left - margin * 2) / scale)}px`; const below = bottom - rect.bottom - margin - gap, above = rect.top - top - margin - gap; menu.style.maxHeight = `${Math.max(0, Math.max(below, above)) / scale}px`; const size = menu.getBoundingClientRect(); menu.style.left = `${Math.max(left + margin, Math.min(rect.right - size.width, right - size.width - margin))}px`; menu.style.top = `${Math.max(top + margin, size.height <= below ? rect.bottom + gap : rect.top - size.height - gap)}px`; } function openRuleSortMenu(anchor, index, count, move) { const row = anchor.closest('.array-row'); const current = row.querySelector('.jpx-rule-sort-popover'); if (current?.matches(':popover-open')) { current.hidePopover(); return; } document.querySelectorAll('.jpx-rule-sort-popover:popover-open').forEach(menu => menu.hidePopover()); const menu = createSettingsPopover('jpx-rule-sort-popover', 'ruleSort', 'dialog', t('cGen.reorderRules')); const label = createJpxElement('label', undefined, t('cGen.moveToPosition')); const input = Object.assign(document.createElement('input'), { type: 'number', min: '1', max: String(count), step: '1', required: true, value: String(index + 1) }); input.setAttribute('aria-label', t('cGen.rulePosition')); label.append(input, createJpxElement('span', undefined, `/ ${count}`)); const apply = () => { if (!input.reportValidity()) return; menu.hidePopover(); move(input.valueAsNumber - 1); }; jpxUtils.createButton(label, { text: t('cGen.moveApply'), history: false, onClick: apply }); const presets = createJpxElement('div', 'jpx-rule-sort-presets'); for (const [key, destination] of [['moveTop', 0], ['moveBottom', count - 1]]) { jpxUtils.createButton(presets, { text: t(`cGen.${key}`), disabled: index === destination, history: false, onClick: () => { menu.hidePopover(); move(destination); } }); } input.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault(); apply(); } }); menu.addEventListener('toggle', event => { if (event.newState !== 'closed') return; releaseSettingsPopoverAnchor(anchor, menu); menu.remove(); }); menu.append(label, presets); row.append(menu); showSettingsPopover(anchor, menu); input.focus({ preventScroll: true }); input.select(); } // Record an editor action in the open dialog's undo history, when there is one. function runSettingsEdit(label, action) { if (settingsEditHistory) settingsEditHistory.run(label, action); else action(); } // Transient row metadata belongs to this dialog, not to the runtime's selected-row array. let controlPanelEditorState = null; // Preserve unrelated legacy declarations, including values this browser does not recognize. function setControlPanelStyleProperty(css, property, value, priority) { const chunks = []; let start = 0, depth = 0, quote = '', comment = false; for (let index = 0; index < css.length; index++) { const char = css[index], next = css[index + 1]; if (comment) { if (char === '*' && next === '/') { comment = false; index++; } continue; } if (quote) { if (char === '\\') index++; else if (char === quote) quote = ''; continue; } if (char === '/' && next === '*') { comment = true; index++; continue; } if (char === '"' || char === "'") { quote = char; continue; } if ('([{'.includes(char)) depth++; else if (')]}'.includes(char)) depth = Math.max(0, depth - 1); else if (char === ';' && depth === 0) { chunks.push(css.slice(start, index + 1)); start = index + 1; } } chunks.push(css.slice(start)); let found = false; const replacement = value + (priority ? ' !important' : ''); const result = chunks.map(chunk => { const match = chunk.match(/^(\s*(?:\/\*[\s\S]*?\*\/\s*)*)([\w-]+)(\s*:)/); if (!match || match[2].toLowerCase() !== property) return chunk; found = true; if (value === null) return match[1]; return match[0] + ' ' + replacement + (chunk.endsWith(';') ? ';' : ''); }).join(''); if (value === null) return result.trim(); return found ? result : result + (result.trim() && !result.trimEnd().endsWith(';') ? ';' : '') + (result ? ' ' : '') + property + ': ' + replacement + ';'; } function renderControlPanelSettings(container, field, data) { if (!settingsEditHistory || !controlPanelEditorState || (controlPanelEditorState.history && controlPanelEditorState.history !== settingsEditHistory)) { controlPanelEditorState = { history: settingsEditHistory, retained: new Map(), selected: null, previewState: 'manual' }; } const state = controlPanelEditorState; state.history = settingsEditHistory; const element = createJpxElement; const title = startSettingsGroup(container, 'controlPanel', field.label); const layout = element('div', 'jpx-control-panel-editor'); const rowsPane = element('div', ''); const appearance = element('div', 'jpx-control-appearance'); layout.append(rowsPane, appearance); container.append(title, layout); const updatePreview = renderControlPanelAppearance(appearance, data, state, element); renderControlPanelRows(rowsPane, data, state, element, updatePreview); } // A labelled settings group; the caller places the returned heading. function startSettingsGroup(container, idPrefix, label) { container.classList.add('jpx-settings-group'); const heading = createJpxElement('h3', 'heading', t(label)); heading.id = getUniqueId(idPrefix); container.setAttribute('role', 'group'); container.setAttribute('aria-labelledby', heading.id); return heading; } // One-pixel canvas used to resolve CSS colors into native picker values. function createSettingsColorContext() { const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; return canvas.getContext('2d', { willReadFrequently: true }); } const readSettingsPixel = context => [...context.getImageData(0, 0, 1, 1).data]; const toSettingsHex = rgb => '#' + rgb.slice(0, 3).map(value => value.toString(16).padStart(2, '0')).join(''); function renderControlPanelAppearance(container, data, state, element) { const heading = element('div', 'jpx-control-heading'); heading.append(element('strong', '', t('cB.panelAppearance'))); const resets = []; const addReset = (parent, key, label, properties, all = false) => { const button = jpxUtils.createButton(parent, { className: 'jpx-appearance-reset' + (all ? ' jpx-appearance-reset-all' : ''), text: all ? t('cGen.restoreDefaults') : t('cGen.restoreDefault') + ': ' + label, icon: all ? undefined : 'undo', onClick: () => { readStyle(); let css = typeof data.ctrlWidgetStyleText === 'string' ? data.ctrlWidgetStyleText : ''; const keys = properties(); // Old custom borders override every state. Bridge them before resetting just one. if (keys.includes(`--jpx-${state.previewState}-border`) && hasLegacyBorder()) { if (!all) for (const other of stateKeys.filter(value => value !== state.previewState)) { const property = `--jpx-${other}-border`; if (!parsed.getPropertyValue(property)) css = setControlPanelStyleProperty(css, property, getComputedStyle(sample).borderTopColor); } for (const side of ['top', 'right', 'bottom', 'left']) { css = setControlPanelStyleProperty(css, `border-${side}-color`, 'var(--jpx-state-border)', 'important'); } } for (const property of keys) css = setControlPanelStyleProperty(css, property, null); data.ctrlWidgetStyleText = css; update(); }, }); button.type = 'button'; button.dataset.controlReset = key; resets.push({ button, key, label, properties, all }); return button; }; addReset(heading, 'all', '', () => ['color', 'opacity', ...paletteProperties], true); const states = element('div', 'jpx-control-preview-states'); states.setAttribute('role', 'group'); states.setAttribute('aria-label', t('cB.panelPreview')); const stateKeys = ['auto', 'manual', 'waiting']; const stateButtons = stateKeys.map(key => { const button = jpxUtils.createButton(states, { text: t('cW.' + key), history: false, onClick: () => { settingsEditHistory?.flushColorEdit(); state.previewState = key; update(); }, }); button.dataset.controlPreviewState = key; return button; }); const body = element('div', 'jpx-control-appearance-body'); const controls = element('div', 'jpx-control-style'); const styleRow = (className, label, type, idPrefix) => { const row = element('div', className), caption = element('label', '', label), input = element('input', ''); input.type = type; input.id = getUniqueId(idPrefix); caption.htmlFor = input.id; row.append(caption, input); return [row, input]; }; const [colorRow, color] = styleRow('jpx-control-style-row', t('cB.panelTextColor'), 'color', 'controlColor'); color.dataset.controlColor = ''; addReset(colorRow, 'color', t('cB.panelTextColor'), () => ['color']); const [opacityRow, opacity] = styleRow('jpx-control-style-row jpx-control-opacity-row', t('cB.panelOpacity'), 'range', 'controlOpacity'); opacity.min = '0'; opacity.max = '100'; opacity.step = '1'; opacity.dataset.controlOpacity = ''; const amount = element('output', ''); amount.dataset.controlOpacityValue = ''; amount.htmlFor = opacity.id; opacityRow.append(amount); addReset(opacityRow, 'opacity', t('cB.panelOpacity'), () => ['opacity']); controls.append(colorRow); const paletteInputs = new Map(); for (const [key, labelKey] of [['header', 'panelHeaderColor'], ['surface', 'panelSurfaceColor'], ['border', 'panelBorderColor']]) { const [row, input] = styleRow('jpx-control-style-row', t('cB.' + labelKey), 'color', 'controlPalette'); input.dataset.controlPalette = key; input.addEventListener('input', () => { const property = `--jpx-${state.previewState}-${key}`; const changes = { [property]: input.value }; let bridgeBorder = false; if (key === 'border') { readStyle(); const oldColor = parsed.getPropertyValue('border-top-color'); bridgeBorder = !!oldColor && oldColor !== 'var(--jpx-state-border)'; if (bridgeBorder) { // Keep unedited states unchanged when adapting an older explicit border. const previousColor = getComputedStyle(sample).borderTopColor; for (const otherState of stateKeys.filter(value => value !== state.previewState)) { const otherProperty = `--jpx-${otherState}-border`; if (!parsed.getPropertyValue(otherProperty)) changes[otherProperty] = previousColor; } } } if (key === 'header') { const rgb = input.value.match(/\w{2}/g).map(value => { const channel = parseInt(value, 16) / 255; return channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4; }); const luminance = rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722; changes[`--jpx-${state.previewState}-ink`] = luminance > .179 ? '#000000' : '#ffffff'; } write(changes, input, bridgeBorder); }); addReset(row, key, t('cB.' + labelKey), () => [`--jpx-${state.previewState}-${key}`, ...(key === 'header' ? [`--jpx-${state.previewState}-ink`] : [])]); controls.append(row); paletteInputs.set(key, { input, labelKey }); } controls.append(opacityRow); const stage = element('div', 'jpx-control-preview-stage'); const sample = element('div', 'jpx-control-preview-sample'); sample.setAttribute('aria-label', t('cB.panelPreview')); const previewParts = createControlWidgetContents(sample, true); const content = previewParts.info; content.classList.add('jpx-control-preview-content'); stage.append(sample); const preview = element('div', 'jpx-control-preview'); preview.append(states, stage); body.append(controls, preview); container.append(heading, body); bindSettingsChange(controls, data, 'ctrlWidgetStyleText'); const parsed = document.createElement('span').style; const context = createSettingsColorContext(); const readStyle = () => { parsed.cssText = typeof data.ctrlWidgetStyleText === 'string' ? data.ctrlWidgetStyleText : ''; }; const paletteProperties = stateKeys.flatMap(key => ['header', 'surface', 'border', 'ink'].map(part => `--jpx-${key}-${part}`)); const borderProperties = ['top', 'right', 'bottom', 'left'].flatMap(side => ['width', 'style', 'color'].map(part => `border-${side}-${part}`)); const hasLegacyBorder = () => ['top', 'right', 'bottom', 'left'].some(side => { const value = parsed.getPropertyValue(`border-${side}-color`); return value && value !== 'var(--jpx-state-border)'; }); const syncColor = (input, rawColor, source) => { if (input._jpxRawColor === rawColor) return; input._jpxRawColor = rawColor; if (source !== input) { context.fillStyle = '#000000'; context.fillRect(0, 0, 1, 1); context.fillStyle = rawColor; context.fillRect(0, 0, 1, 1); input.value = toSettingsHex(readSettingsPixel(context)); } }; function update(source) { readStyle(); for (const property of ['color', 'opacity', 'font-weight', 'font-style', 'text-decoration-line', ...paletteProperties, ...borderProperties]) { const value = parsed.getPropertyValue(property), priority = parsed.getPropertyPriority(property); if (sample.style.getPropertyValue(property) !== value || sample.style.getPropertyPriority(property) !== priority) { if (value) sample.style.setProperty(property, value, priority); else sample.style.removeProperty(property); } } setControlWidgetState(sample, state.previewState); const surfaceStyle = getComputedStyle(sample); syncColor(color, surfaceStyle.color, source); color.title = t('cB.panelTextColor'); const palette = { header: getComputedStyle(previewParts.header).backgroundColor, surface: surfaceStyle.backgroundColor, border: surfaceStyle.borderTopColor }; const stateLabel = t('cW.' + state.previewState); for (const [key, { input, labelKey }] of paletteInputs) { syncColor(input, palette[key], source); setJpxLabel(input, stateLabel + ' · ' + t('cB.' + labelKey)); } const rawOpacity = parsed.opacity; const numericOpacity = rawOpacity ? Number(rawOpacity.replace(/%$/, '')) / (rawOpacity.endsWith('%') ? 100 : 1) : 1; const percent = Math.round(Math.max(0, Math.min(1, Number.isFinite(numericOpacity) ? numericOpacity : 1)) * 100); if (source !== opacity) opacity.value = String(percent); const valueText = percent + '%'; if (amount.textContent !== valueText) amount.textContent = valueText; const examples = { isActiveBattle: stateLabel, readyNext: '0', networkDelay: '120 ms', battleStyle: t('cW.OneHanded'), battleType: t('cW.Arena'), battleMode: 'OneHanded_General', round: '12 / 100' }; const rows = (Array.isArray(data.ctrlWidgetRows) ? data.ctrlWidgetRows : []).map(row => { const base = CTRLWIDGET_FIELDS.find(field => field.id === row?.id); return base ? { id: row.id, label: t(base.label), value: examples[base.id] } : null; }).filter(row => row !== null); updateControlWidgetRows(content, rows); stateButtons.forEach(button => button.setAttribute('aria-pressed', String(button.dataset.controlPreviewState === state.previewState))); for (const { button, key, label, properties, all } of resets) { button.disabled = !properties().some(property => parsed.getPropertyValue(property)) && !((all || key === 'border') && hasLegacyBorder()); if (!all) { setJpxLabel(button, t('cGen.restoreDefault') + ': ' + (['header', 'surface', 'border'].includes(key) ? stateLabel + ' · ' : '') + label); } } } function write(changes, source, bridgeBorder = false) { readStyle(); let css = typeof data.ctrlWidgetStyleText === 'string' ? data.ctrlWidgetStyleText : ''; for (const [property, value] of Object.entries(changes)) { css = setControlPanelStyleProperty(css, property, value, parsed.getPropertyPriority(property)); } if (bridgeBorder) css += (css.trimEnd().endsWith(';') ? '' : ';') + ' border-color: var(--jpx-state-border) !important;'; data.ctrlWidgetStyleText = css; update(source); } color.addEventListener('input', () => write({ color: color.value }, color)); opacity.addEventListener('input', () => write({ opacity: String(Number(opacity.value) / 100) }, opacity)); container._jpxRefreshTheme = update; update(); // Schema fields are built off-DOM; resolve theme colors once their styles can apply. if (!sample.isConnected) queueMicrotask(() => { if (sample.isConnected) update(); }); return update; } function renderControlPanelRows(container, data, state, element, updatePreview) { const heading = element('div', 'jpx-control-heading'); const count = element('span', 'jpx-control-count'); heading.append(element('strong', '', t('cB.panelFields')), count); const list = element('div', 'jpx-stats-list jpx-control-list'); list.setAttribute('role', 'list'); list.setAttribute('aria-label', t('cB.panelFields')); container.append(heading, list); bindSettingsChange(container, data, 'ctrlWidgetRows'); const known = new Set(CTRLWIDGET_FIELDS.map(field => field.id)); const selected = () => Array.isArray(data.ctrlWidgetRows) ? data.ctrlWidgetRows : []; const activeIds = () => [...new Set(selected().filter(row => known.has(row?.id)).map(row => row.id))]; const copy = value => JSON.parse(JSON.stringify(value)); const focusRow = (id, selector = '.jpx-stats-select') => list.querySelector(`[data-field-id="${id}"] ${selector}`)?.focus({ preventScroll: true }); function move(id, destination) { const ids = activeIds(), from = ids.indexOf(id); if (from < 0) return; destination = Math.max(0, Math.min(ids.length - 1, destination)); if (from === destination) return; const action = () => { ids.splice(destination, 0, ids.splice(from, 1)[0]); const rows = selected(); const reordered = ids.flatMap(id => rows.filter(row => row?.id === id)); data.ctrlWidgetRows = rows.map(row => known.has(row?.id) ? reordered.shift() : row); state.selected = id; refresh(); focusRow(id); }; runSettingsEdit(t('cB.panelReorder'), action); } const cancelDrag = bindStatsListDrag(list, move); function refresh() { cancelDrag(); const rows = selected(), ids = activeIds(); // Active configuration always wins over an older retained copy, including after undo/import. ids.forEach(id => state.retained.set(id, rows.flatMap((row, index) => row?.id === id ? [{ row: copy(row), index }] : []))); if (!state.selected || !known.has(state.selected)) state.selected = ids[0] || CTRLWIDGET_FIELDS[0].id; const ordered = [...ids, ...CTRLWIDGET_FIELDS.map(field => field.id).filter(id => !ids.includes(id))]; count.textContent = `${ids.length} / ${CTRLWIDGET_FIELDS.length}`; list.replaceChildren(); ordered.forEach(id => { const base = CTRLWIDGET_FIELDS.find(field => field.id === id), index = ids.indexOf(id), enabled = index >= 0; const row = element('div', 'jpx-stats-row'); row.dataset.fieldId = id; row.dataset.enabled = String(enabled); row.setAttribute('role', 'listitem'); const select = jpxUtils.createButton(row, { className: 'jpx-stats-select', history: false, onClick: () => { state.selected = id; list.querySelectorAll('.jpx-stats-select').forEach(button => button.setAttribute('aria-pressed', String(button === select))); }, }); select.setAttribute('aria-pressed', String(state.selected === id)); const grip = createStatsGrip(enabled ? 'jpx-stats-grip jpx-drag-grip' : 'jpx-drag-grip'); if (enabled) grip.title = t('cS.reorderHint'); select.append(grip, element('span', 'jpx-stats-row-label', t(base.label))); select.addEventListener('keydown', event => { if (enabled && event.altKey && ['ArrowUp', 'ArrowDown'].includes(event.key)) { event.preventDefault(); move(id, index + (event.key === 'ArrowUp' ? -1 : 1)); } }); const actions = element('div', 'jpx-array-item-actions'); row.append(actions); createSettingsMoveButtons(actions, enabled ? index : 0, enabled ? ids.length : 0, destination => move(id, destination)); createSettingsFieldToggle(actions, enabled, t(base.label), () => { if (enabled) data.ctrlWidgetRows = selected().filter(row => row?.id !== id); else { const restored = state.retained.get(id) || [{ row: { id }, index: selected().length }]; const next = [...selected()]; restored.forEach(({ row, index }) => next.splice(Math.min(index, next.length), 0, copy(row))); data.ctrlWidgetRows = next; } state.selected = id; refresh(); focusRow(id, '.jpx-rule-state-toggle'); }); list.append(row); }); updatePreview(); } refresh(); } function createSettingsFieldToggle(parent, enabled, name, onClick) { const toggle = jpxUtils.createButton(parent, { text: `${t(enabled ? 'cS.disableField' : 'cS.enableField')}: ${name}`, icon: enabled ? 'ruleEnabled' : 'ruleDisabled', className: 'jpx-rule-state-toggle', onClick }); toggle.dataset.enabled = String(enabled); toggle.setAttribute('aria-pressed', String(enabled)); return toggle; } const settingsLabelHTML = (field, id) => field.skipLabel ? '' : ``; function bindSettingsTextInput(input, field, dataObj) { if (field.placeholder) input.placeholder = field.placeholder; input.value = dataObj[field.key] ?? ''; input.oninput = event => dataObj[field.key] = event.target.value; } const fieldRenderers = { expandedRuleItems: new WeakSet(), group(container, field, dataObj) { if (field.controlPanelEditor) return renderControlPanelSettings(container, field, dataObj); const heading = startSettingsGroup(container, field.key, field.label); const fields = createJpxElement('div', 'jpx-settings-group-fields'); renderSchema(fields, { type: 'object', properties: field.properties }, dataObj); container.append(heading, fields); }, constant(container, field) { const div = createJpxElement('div', undefined, t(field.label)); if (field.class) div.classList.add(field.class); container.appendChild(div); }, boolean(container, field, dataObj) { const key = field.key, checkboxId = getUniqueId(key); container.innerHTML = ` `; container.querySelector('input').onchange = event => dataObj[key] = event.target.checked; }, text(container, field, dataObj) { const inputId = getUniqueId(field.key); container.innerHTML = ` ${settingsLabelHTML(field, inputId)} `; bindSettingsTextInput(container.querySelector('input'), field, dataObj); }, textarea(container, field, dataObj) { const inputId = getUniqueId(field.key); container.innerHTML = ` ${settingsLabelHTML(field, inputId)} `; bindSettingsTextInput(container.querySelector('textarea'), field, dataObj); }, number(container, field, dataObj) { const key = field.key, inputId = getUniqueId(key); container.innerHTML = ` ${settingsLabelHTML(field, inputId)} `; container.querySelector('input').oninput = event => dataObj[key] = +event.target.value; }, rangeNumber(container, field, dataObj) { const key = field.key; if (!Array.isArray(dataObj[key])) dataObj[key] = [0, 0]; const idMin = getUniqueId(`${key}_min`), idMax = getUniqueId(`${key}_max`); container.classList.add('jpx-range'); container.innerHTML = ` ${settingsLabelHTML(field, idMin)} ${t('cGen.rangeTo')} `; [idMin, idMax].forEach((id, index) => { const input = container.querySelector(`#${id}`); input.setAttribute('aria-label', `${t(field.label)}: ${t(index ? 'cGen.rangeMax' : 'cGen.rangeMin')}`); input.oninput = event => dataObj[key][index] = +event.target.value; }); }, dropdown(container, field, dataObj) { const createSelect = options => { const select = document.createElement('select'); select.id = getUniqueId(field.key); for (const opt of options) { const option = select.appendChild(document.createElement('option')); option.value = opt.value; option.textContent = t(opt.label); } return select; }; // Grouped options render one select per part; their values form one (optionally joined) value. const component = { onchange: () => {} }; if (!Array.isArray(field.options) && typeof field.options === 'object') { const selects = {}; component.element = createJpxElement('div', 'jpx-battle-mode-selects'); component.getValue = () => { const values = Object.keys(field.options).map(key => jpxUtils.parseValue(selects[key].value)); return field.flatten ? values.join(field.flatten) : values; }; component.setValue = value => { const values = field.flatten && typeof value === 'string' ? value.split(field.flatten === '_' ? /_(?!Mage(?:_|$))/ : field.flatten) : value; Object.keys(field.options).forEach((key, i) => { if (values?.[i] !== undefined) selects[key].value = values[i]; }); }; for (const [subLabel, subOptions] of Object.entries(field.options)) { const subWrap = document.createElement('div'); subWrap.style.display = 'inline-block'; subWrap.style.marginRight = '8px'; const select = createSelect(subOptions); const label = subWrap.appendChild(document.createElement('label')); label.textContent = t(`cB.${subLabel}`); label.htmlFor = select.id; select.onchange = () => component.onchange(); subWrap.appendChild(select); selects[subLabel] = select; component.element.appendChild(subWrap); } } else { const select = component.element = createSelect(field.options); component.getValue = () => jpxUtils.parseValue(select.value); component.setValue = value => { select.value = value; }; select.onchange = () => component.onchange(); } if (field.hasModeDropdown) { container.dataset.role = field.hasModeDropdown; const selectContent = document.createElement('div'); component.onchange = () => { fieldRenderers.dragState.cancel?.(); selectContent.innerHTML = ''; const currentValue = component.getValue(); container.dataset.currentValue = currentValue; if (jpxUtils.isEmpty(dataObj[currentValue])) dataObj[currentValue] = {}; renderBattleRuleSections(selectContent, field.itemSchema, dataObj[currentValue], currentValue); }; container.append(component.element, selectContent); // Import and reset hand the rebuilt editor the mode it should keep showing. const modeKey = getBattleMode('OneHanded'); const importBtn = document.getElementById('import-button'), resetBtn = document.getElementById('reset-current-button'); const finalKey = importBtn?.dataset.battleMode || resetBtn?.dataset.battleMode || modeKey; if (importBtn) delete importBtn.dataset.battleMode; if (resetBtn) delete resetBtn.dataset.battleMode; if (finalKey) component.setValue(finalKey); component.onchange(); } else { let initValue = dataObj[field.key]; if (initValue === undefined) { const defaults = Array.isArray(field.options) ? null : Object.values(field.options).map(opts => opts[0]?.value); initValue = !defaults ? field.options[0]?.value : field.flatten ? defaults.join(field.flatten) : defaults; } const wrap = document.createElement('div'); const label = wrap.appendChild(document.createElement('label')); label.htmlFor = component.element.id; label.textContent = t(field.label); component.setValue(initValue); dataObj[field.key] = component.getValue(); component.onchange = () => dataObj[field.key] = component.getValue(); wrap.appendChild(component.element); container.appendChild(wrap); } }, dragState: { pointerId: null, fromIndex: null, groupId: null, sourceRow: null, sourceHandle: null, dragImage: null, dragLayer: null, dropMarker: null, dropRow: null, dropPosition: null, startX: 0, startY: 0, pointerX: 0, pointerY: 0, handleOffsetX: 0, handleOffsetY: 0, grabOffsetY: 0, frameId: null, cancel: null, dragging: false }, array(container, field, dataObj) { if (!Array.isArray(dataObj[field.key])) dataObj[field.key] = []; const arrayGroupId = Symbol('array-group'); const renderedRuleItems = new Map(); let bulkFrame = 0, bulkTarget = null, bulkQueue = [], bulkIndex = 0; const cancelBulkToggle = () => { cancelAnimationFrame(bulkFrame); bulkFrame = 0; bulkTarget = null; bulkQueue = []; bulkIndex = 0; }; const setRuleExpanded = (item, open) => open ? fieldRenderers.expandedRuleItems.add(item) : fieldRenderers.expandedRuleItems.delete(item); const liveRegion = createJpxElement('span', 'jpx-sr-only'); liveRegion.setAttribute('aria-live', 'polite'); let updateAllRulesToggle = () => {}; let toolbar = null; if (!field.skipLabel) container.innerHTML = `${t(field.label)}`; if (field.collapsibleItems) { toolbar = createJpxElement('div', 'jpx-rule-list-toolbar'); let allRulesToggle; updateAllRulesToggle = () => { const allExpanded = bulkTarget ?? (renderedRuleItems.size > 0 && [...renderedRuleItems.values()].every(details => details.open)); if (allRulesToggle.getAttribute('aria-expanded') === String(allExpanded)) return; const label = t(allExpanded ? 'cGen.collapseAllRules' : 'cGen.expandAllRules'); allRulesToggle.replaceChildren(createSettingsIcon(allExpanded ? 'collapseRules' : 'expandRules'), createJpxElement('span', undefined, label)); setJpxLabel(allRulesToggle, label); allRulesToggle.setAttribute('aria-expanded', String(allExpanded)); }; allRulesToggle = jpxUtils.createButton(toolbar, { className: 'jpx-rule-list-toggle', history: false, onClick: () => { const shouldExpand = bulkTarget === null ? [...renderedRuleItems.values()].some(details => !details.open) : !bulkTarget; cancelBulkToggle(); bulkTarget = shouldExpand; bulkQueue = [...renderedRuleItems].filter(([, details]) => details.open !== shouldExpand); updateAllRulesToggle(); const batch = () => { bulkFrame = 0; if (!listDiv.isConnected) { cancelBulkToggle(); return; } const deadline = performance.now() + 5; let processed = 0; while (bulkIndex < bulkQueue.length && processed++ < 12 && performance.now() < deadline) { const [item, details] = bulkQueue[bulkIndex++]; if (shouldExpand) details.jpxBuildBody(); details.open = shouldExpand; setRuleExpanded(item, shouldExpand); } if (bulkIndex < bulkQueue.length) bulkFrame = requestAnimationFrame(batch); else { cancelBulkToggle(); updateAllRulesToggle(); } }; batch(); } }); toolbar.append(allRulesToggle, liveRegion); updateAllRulesToggle(); } const listDiv = document.createElement('div'); if (field.fixedActions) listDiv.className = 'jpx-rule-scroll'; container.appendChild(listDiv); if (!field.collapsibleItems) container.appendChild(liveRegion); else if (!field.skipLabel) { const heading = container.firstElementChild; heading.classList.add('jpx-rule-list-heading'); heading.appendChild(toolbar); } else container.insertBefore(toolbar, listDiv); const addBar = field.collapsibleItems ? container.appendChild(createJpxElement('div', 'jpx-rule-add-actions')) : null; const scrollContainer = () => field.fixedActions ? listDiv : container.closest('.jpx-rule-scroll, [role=tabpanel]'); const ruleRows = () => [...listDiv.children].filter(row => row.classList.contains('jpx-rule-array-item')); const clearDropTargets = () => container.querySelectorAll('.is-drop-before, .is-drop-after').forEach(target => { target.classList.remove('is-drop-before', 'is-drop-after'); }); const getRuleLabel = item => { if (item?.name) return t('cB.' + item.name); const type = t('cB.' + (item?.type || field.key)); const detail = item?.customMessage || (item?.priorityRule ? t('cB.' + item.priorityRule) : ''); return detail ? type + ' · ' + detail : type; }; const clearDragState = (announcement = '') => { const drag = fieldRenderers.dragState; const handle = drag.sourceHandle; const pointerId = drag.pointerId; cancelAnimationFrame(drag.frameId); drag.sourceRow?.classList.remove('is-dragging'); drag.sourceHandle?.setAttribute('aria-grabbed', 'false'); drag.dragLayer?.remove(); clearDropTargets(); Object.assign(drag, { pointerId: null, fromIndex: null, groupId: null, sourceRow: null, sourceHandle: null, dragImage: null, dragLayer: null, dropMarker: null, dropRow: null, dropPosition: null, handleOffsetX: 0, handleOffsetY: 0, grabOffsetY: 0, frameId: null, cancel: null, dragging: false }); window.removeEventListener('blur', cancelRuleDrag); window.removeEventListener('resize', cancelRuleDrag); if (handle?.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId); if (announcement) liveRegion.textContent = announcement; }; const cancelRuleDrag = () => { if (fieldRenderers.dragState.groupId === arrayGroupId) clearDragState(t('cGen.dragCancelled')); }; const updateDropTarget = (x, y) => { const drag = fieldRenderers.dragState; const area = getDragBounds(); const { scale } = getSettingsCoordinateSpace(listDiv); const inside = x >= area.left && x < area.right && y >= area.top && y < area.bottom; const hovered = inside ? document.elementFromPoint(x, y)?.closest('.jpx-rule-array-item') : null; if (!hovered || hovered.parentElement !== listDiv || hovered === drag.sourceRow) { clearDropTargets(); if (drag.dropMarker) drag.dropMarker.style.display = 'none'; Object.assign(drag, { dropRow: null, dropPosition: null }); return; } const bounds = hovered.getBoundingClientRect(); const position = y < bounds.top + bounds.height / 2 ? 'before' : 'after'; if (drag.dropMarker) { const markerTop = position === 'before' ? bounds.top : bounds.bottom - 3 * scale; const preview = drag.dragImage.getBoundingClientRect(); // Keep the landing cue at both edges without drawing a line through the lifted text. drag.dropMarker.classList.toggle('over-preview', markerTop < preview.bottom && markerTop + 3 * scale > preview.top); Object.assign(drag.dropMarker.style, { display: 'block', left: ((bounds.left - area.left) / scale) + 'px', width: (bounds.width / scale) + 'px', top: `${(markerTop - area.top) / scale}px` }); } if (drag.dropRow === hovered && drag.dropPosition === position) return; clearDropTargets(); hovered.classList.add(`is-drop-${position}`); Object.assign(drag, { dropRow: hovered, dropPosition: position }); liveRegion.textContent = t(position === 'before' ? 'cGen.dropBefore' : 'cGen.dropAfter', { label: getRuleLabel(dataObj[field.key][ruleRows().indexOf(hovered)]) }); }; const getDragBounds = () => { const listBounds = listDiv.getBoundingClientRect(); const panelBounds = scrollContainer()?.getBoundingClientRect(); const view = window.visualViewport; const viewLeft = view?.offsetLeft || 0, viewTop = view?.offsetTop || 0; const viewRight = viewLeft + (view?.width || innerWidth), viewBottom = viewTop + (view?.height || innerHeight); const left = Math.max(viewLeft, listBounds.left, panelBounds?.left ?? viewLeft); const top = Math.max(viewTop, listBounds.top, panelBounds?.top ?? viewTop); const right = Math.min(viewRight, listBounds.right, panelBounds?.right ?? viewRight); const bottom = Math.min(viewBottom, listBounds.bottom, panelBounds?.bottom ?? viewBottom, addBar?.getClientRects().length ? addBar.getBoundingClientRect().top : viewBottom); return { left, top, right: Math.max(left, right), bottom: Math.max(top, bottom) }; }; const startRuleDrag = (row, handle, event) => { const drag = fieldRenderers.dragState; const sourceIndex = ruleRows().indexOf(row); if (sourceIndex < 0) return; Object.assign(drag, { fromIndex: sourceIndex, groupId: arrayGroupId, pointerId: event.pointerId, sourceRow: row, sourceHandle: handle, dragging: true }); const rowBounds = row.getBoundingClientRect(); const handleBounds = handle.getBoundingClientRect(); const summary = row.querySelector('.jpx-rule-summary-text'); const summaryBounds = summary?.getBoundingClientRect(); const { scale } = getSettingsCoordinateSpace(row); drag.handleOffsetX = handleBounds.left + handleBounds.width / 2 - rowBounds.left; drag.handleOffsetY = summaryBounds && handleBounds.top >= summaryBounds.bottom ? 10 * scale + summaryBounds.height + handleBounds.height / 2 : handleBounds.top + handleBounds.height / 2 - rowBounds.top; drag.grabOffsetY = drag.handleOffsetY + drag.startY - handleBounds.top - handleBounds.height / 2; row.classList.add('is-dragging'); handle.setAttribute('aria-grabbed', 'true'); liveRegion.textContent = t('cGen.draggingRule', { label: getRuleLabel(dataObj[field.key][sourceIndex]) }); const hiddenPart = className => { const node = createJpxElement('div', className); node.setAttribute('aria-hidden', 'true'); return node; }; const dragLayer = container.appendChild(hiddenPart('jpx-rule-drag-layer')); drag.dragLayer = dragLayer; const dragImage = hiddenPart('jpx-rule-drag-image'); dragImage.style.width = `${rowBounds.width / scale}px`; dragImage.style.minHeight = `${(drag.handleOffsetY + handleBounds.height / 2) / scale + 6}px`; dragImage.style.setProperty('--jpx-drag-handle-x', `${drag.handleOffsetX / scale}px`); dragImage.style.setProperty('--jpx-drag-handle-y', `${drag.handleOffsetY / scale}px`); const labelPreview = summary?.cloneNode(true); if (labelPreview) { labelPreview.classList.add('jpx-rule-drag-label'); dragImage.style.setProperty('--jpx-drag-label-width', `${summaryBounds.width / scale}px`); dragImage.style.setProperty('--jpx-drag-label-x', `${(summaryBounds.left - rowBounds.left) / scale}px`); dragImage.appendChild(labelPreview); } dragImage.appendChild(createJpxElement('span', 'jpx-rule-drag-grip jpx-drag-grip')).appendChild(createSettingsIcon('grip')); drag.dragImage = dragLayer.appendChild(dragImage); const dropMarker = hiddenPart('jpx-rule-drop-marker'); dropMarker.style.display = 'none'; drag.dropMarker = dragLayer.appendChild(dropMarker); drag.frameId = requestAnimationFrame(trackRuleDrag); }; function updateDragImage(x, y) { const drag = fieldRenderers.dragState; if (!drag.dragImage) return; const bounds = getDragBounds(); const space = getSettingsCoordinateSpace(listDiv); Object.assign(drag.dragLayer.style, { left: `${(bounds.left - space.left) / space.scale}px`, top: `${(bounds.top - space.top) / space.scale}px`, width: `${(bounds.right - bounds.left) / space.scale}px`, height: `${(bounds.bottom - bounds.top) / space.scale}px` }); const image = drag.dragImage.getBoundingClientRect(); // Rule sorting has one axis: retain the row's horizontal position and the original grab point. const top = Math.max(0, Math.min(bounds.bottom - bounds.top - image.height, y - drag.grabOffsetY - bounds.top)); drag.dragImage.style.left = `${(drag.sourceRow.getBoundingClientRect().left - bounds.left) / space.scale}px`; drag.dragImage.style.top = `${top / space.scale}px`; } function trackRuleDrag() { const drag = fieldRenderers.dragState; if (drag.groupId !== arrayGroupId || !drag.dragging) return; if (!drag.sourceRow.isConnected || !listDiv.getClientRects().length) { cancelRuleDrag(); return; } const bounds = getDragBounds(); const { pointerX: x, pointerY: y } = drag; const panel = scrollContainer(); const panelBounds = panel?.getBoundingClientRect() || bounds; const edge = 28 * getSettingsCoordinateSpace(listDiv).scale; if (panel && x >= bounds.left && x < bounds.right && y >= bounds.top && y < bounds.bottom) { if (y < panelBounds.top + edge && panel.scrollTop > 0) { panel.scrollTop -= 8; } else if (y > panelBounds.bottom - edge && panel.scrollTop + panel.clientHeight < panel.scrollHeight) { panel.scrollTop += 8; } } updateDragImage(x, y); updateDropTarget(x, y); drag.frameId = requestAnimationFrame(trackRuleDrag); } container.addEventListener('pointerdown', event => { const handle = event.target.closest('.drag-handle'); const row = handle?.closest('.jpx-rule-array-item'); if (!row || row.parentElement !== listDiv || !event.isPrimary || event.button !== 0) return; const drag = fieldRenderers.dragState; if (drag.pointerId !== null) return; Object.assign(drag, { pointerId: event.pointerId, groupId: arrayGroupId, fromIndex: ruleRows().indexOf(row), sourceRow: row, sourceHandle: handle, startX: event.clientX, startY: event.clientY, pointerX: event.clientX, pointerY: event.clientY, cancel: cancelRuleDrag }); window.addEventListener('blur', cancelRuleDrag); window.addEventListener('resize', cancelRuleDrag); try { handle.setPointerCapture(event.pointerId); } catch {} event.preventDefault(); }); const ownsPointer = event => fieldRenderers.dragState.groupId === arrayGroupId && fieldRenderers.dragState.pointerId === event.pointerId; container.addEventListener('pointermove', event => { const drag = fieldRenderers.dragState; if (!ownsPointer(event)) return; drag.pointerX = event.clientX; drag.pointerY = event.clientY; if (!drag.dragging && Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) >= 6 * getSettingsCoordinateSpace(listDiv).scale) { startRuleDrag(drag.sourceRow, drag.sourceHandle, event); } if (!drag.dragging) return; updateDragImage(event.clientX, event.clientY); updateDropTarget(event.clientX, event.clientY); }); container.addEventListener('pointerup', event => { const drag = fieldRenderers.dragState; if (!ownsPointer(event)) return; if (!drag.dragging) return clearDragState(); updateDropTarget(event.clientX, event.clientY); const from = drag.fromIndex; const targetIndex = ruleRows().indexOf(drag.dropRow); const target = targetIndex + (drag.dropPosition === 'after' ? 1 : 0); if (targetIndex < 0 || target === from || target === from + 1) { clearDragState(t('cGen.dragCancelled')); return; } const moved = dataObj[field.key][from]; const label = getRuleLabel(moved); const move = () => { dataObj[field.key].splice(from, 1); const destination = target > from ? target - 1 : target; dataObj[field.key].splice(destination, 0, moved); clearDragState(t('cGen.ruleMoved', { label, index: destination + 1 })); renderArray(); }; runSettingsEdit(t('cGen.reorderRules'), move); }); container.addEventListener('lostpointercapture', event => { if (ownsPointer(event)) cancelRuleDrag(); }); container.addEventListener('pointercancel', event => { if (ownsPointer(event)) clearDragState(t('cGen.dragCancelled')); }); function renderRowButtons(row, index) { row.jpxRuleActions = []; const disabled = dataObj[field.key][index].disabled === true; if (field.collapsibleItems) row.classList.toggle('is-disabled', disabled); else row.style.opacity = disabled ? '0.5' : '1'; const actions = createJpxElement('div', 'jpx-array-item-actions'); const summary = row.querySelector(':scope > .jpx-rule-item > summary'); (summary || row).appendChild(actions); const actionButton = (label, options, parent = actions) => { const change = options.onClick; const run = change && options.history !== false ? () => runSettingsEdit(t(label), change) : change; if (change && options.history !== false) row.jpxRuleActions.push({ label: t(label), run, destructive: label === 'delete' }); if (options.menuOnly && field.collapsibleItems) return null; const button = jpxUtils.createButton(parent, { ...options, history: false, onClick: run }); setJpxLabel(button, t(label)); return button; }; const moveTo = (destination, focus = '.drag-handle') => { const items = dataObj[field.key]; if (!Number.isInteger(destination) || destination < 0 || destination >= items.length || destination === index) return; const move = () => { const moved = items.splice(index, 1)[0]; items.splice(destination, 0, moved); renderArray(); const movedRow = ruleRows()[destination]; (movedRow?.querySelector(focus) || movedRow?.querySelector('.drag-handle'))?.focus({ preventScroll: true }); movedRow?.scrollIntoView({ block: 'nearest' }); liveRegion.textContent = t('cGen.ruleMoved', { label: getRuleLabel(moved), index: destination + 1 }); }; runSettingsEdit(t('cGen.reorderRules'), move); }; if (field.collapsibleItems) { const insert = (offset, schema) => { const item = createEmptyObject(schema); const change = () => { dataObj[field.key].splice(index + offset, 0, item); fieldRenderers.expandedRuleItems.add(item); renderArray(); const inserted = ruleRows()[index + offset]; inserted?.scrollIntoView({ block: 'nearest' }); inserted?.querySelector('summary')?.focus({ preventScroll: true }); }; runSettingsEdit(t('add'), change); }; for (const [label, offset] of [['insertBefore', 0], ['insertAfter', 1]]) row.jpxRuleActions.push({ label: t('cB.' + label), children: Object.entries(field.itemSchema.oneOf).map(([type, schema]) => ({ label: t('cB.' + type), run: () => insert(offset, schema) })) }); row.jpxRuleActions.push({ separator: true }); for (const [label, destination] of [['moveTop', 0], ['moveUp', index - 1], ['moveDown', index + 1], ['moveBottom', dataObj[field.key].length - 1]]) row.jpxRuleActions.push({ label: t('cGen.' + label), disabled: destination === index || destination < 0 || destination >= dataObj[field.key].length, run: () => moveTo(destination) }); row.jpxRuleActions.push({ label: t('cGen.moveToPosition'), run: anchor => openRuleSortMenu(anchor, index, dataObj[field.key].length, moveTo) }, { separator: true }); const more = actionButton('cB.ruleActions', { history: false, className: 'jpx-rule-more', onClick: (button, event) => { event.preventDefault(); openJpxRuleMenu(button, row); } }); more.append(createSettingsIcon('more')); more.setAttribute('aria-haspopup', 'true'); more.setAttribute('aria-expanded', 'false'); row.addEventListener('contextmenu', event => { if (event.target.closest('input, textarea, select, .jpx-rule-context-menu')) return; event.preventDefault(); event.stopPropagation(); openJpxRuleMenu(more, row); }); } let handle = actionButton('cGen.dragRule', { className: 'drag-handle jpx-drag-grip', history: false }, summary || actions); if (summary) summary.prepend(handle); handle.replaceChildren(createSettingsIcon('grip')); handle.setAttribute('aria-grabbed', 'false'); handle.setAttribute('aria-keyshortcuts', 'Alt+ArrowUp Alt+ArrowDown Alt+Home Alt+End'); handle.title = `${t('cGen.dragRule')} · Alt+↑/↓ · Alt+Home/End`; handle.draggable = false; handle.addEventListener('keydown', event => { if (!event.altKey) return; const target = { ArrowUp: index - 1, ArrowDown: index + 1, Home: 0, End: dataObj[field.key].length - 1 }[event.key]; if (target === undefined) return; event.preventDefault(); event.stopPropagation(); moveTo(target); }); if (!field.collapsibleItems) { const sortActions = createSettingsMoveButtons(actions, index, dataObj[field.key].length, moveTo); const sortMenu = actionButton('cGen.reorderRules', { history: false, onClick: (button, event) => { event.preventDefault(); openRuleSortMenu(button, index, dataObj[field.key].length, moveTo); } }, sortActions); sortMenu.append(createSettingsIcon('sort')); sortMenu.setAttribute('aria-haspopup', 'dialog'); sortMenu.setAttribute('aria-expanded', 'false'); } actionButton('cGen.duplicateRule', { menuOnly: true, text: decodeURIComponent('%E2%A7%89'), onClick: () => { const copy = JSON.parse(JSON.stringify(dataObj[field.key][index])); dataObj[field.key].splice(index + 1, 0, copy); if (field.collapsibleItems) fieldRenderers.expandedRuleItems.add(copy); renderArray(); ruleRows()[index + 1]?.querySelector('summary')?.focus({ preventScroll: true }); }}); if (field.canDisable) { const action = disabled ? 'cGen.enableRule' : 'cGen.disableRule', stateLabel = t(disabled ? 'cGen.ruleDisabled' : 'cGen.ruleEnabled'); const toggle = actionButton(action, { className: 'jpx-rule-state-toggle', onClick: () => { const rule = dataObj[field.key][index]; if (rule?.disabled === true) delete rule.disabled; else if (rule && typeof rule === 'object') rule.disabled = true; renderArray(); ruleRows()[index]?.querySelector('.jpx-rule-state-toggle')?.focus({ preventScroll: true }); } }); toggle.dataset.enabled = String(!disabled); toggle.setAttribute('aria-pressed', String(!disabled)); if (field.collapsibleItems) actions.prepend(toggle); const status = createJpxElement('span', 'jpx-sr-only', stateLabel); status.id = getUniqueId('rule-state'); toggle.append(status); toggle.setAttribute('aria-describedby', status.id); toggle.prepend(createSettingsIcon(disabled ? 'ruleDisabled' : 'ruleEnabled')); toggle.title = `${stateLabel} · ${t(action)}`; } if (field.collapsibleItems) row.jpxRuleActions.push({ separator: true }); actionButton('delete', { menuOnly: true, text: t('delete'), className: 'jpx-delete-button', onClick: () => { dataObj[field.key].splice(index, 1); renderArray(); (ruleRows()[Math.min(index, dataObj[field.key].length - 1)]?.querySelector('summary') || addBar?.querySelector('button'))?.focus({ preventScroll: true }); }}); }; function renderAddButtons(addContainer) { const addAction = (targetSchema) => { const item = targetSchema.type === 'text' ? '' : createEmptyObject(targetSchema); dataObj[field.key].push(item); if (field.collapsibleItems) fieldRenderers.expandedRuleItems.add(item); renderArray(); if (field.collapsibleItems) { const row = ruleRows().at(-1); if (row?.isConnected) { row.scrollIntoView({ block: 'start' }); (row.querySelector('.object-item input, .object-item select, .object-item textarea') || row.querySelector('summary'))?.focus({ preventScroll: true }); } } }; if (field.itemSchema.discriminator) { if (field.collapsibleItems) { const label = t('cB.addRule'); const button = jpxUtils.createButton(addContainer, { text: label, className: 'jpx-rule-add', history: false, onClick: (anchor, event) => { event.preventDefault(); openJpxRuleMenu(anchor, addContainer, Object.entries(field.itemSchema.oneOf).map(([type, schema]) => ({ label: t('cB.' + type), run: () => runSettingsEdit(label, () => addAction(schema)) })), label); } }); button.prepend(createSettingsIcon('add')); button.append(createSettingsIcon('chevronDown')); button.setAttribute('aria-haspopup', 'true'); button.setAttribute('aria-expanded', 'false'); return; } for (const subSchema of Object.values(field.itemSchema.oneOf)) jpxUtils.createButton(addContainer, { text: `${t('add')} ${t(subSchema.properties.find(item => item.type === 'constant')?.label)}`, onClick: () => addAction(subSchema) }); } else jpxUtils.createButton(addContainer, { text: t('add'), onClick: () => addAction(field.itemSchema) }); } function renderMultiSelectMode() { if (field.hasRange) { if (dataObj[field.key].length < 2) dataObj[field.key].unshift(0, 0); const rangeBox = document.createElement('div'); rangeBox.style.cssText = 'display: inline-flex; align-items: baseline; margin-right: 8px;'; fieldRenderers.rangeNumber(rangeBox, { ...field, label: field.hasRange, skipLabel: false }, dataObj); listDiv.appendChild(rangeBox); } if (field.popup) { listDiv.classList.add('multiSelect-popup'); const summary = document.createElement('button'); summary.type = 'button'; summary.className = 'multiSelect-summary'; summary.setAttribute('aria-haspopup', 'group'); summary.setAttribute('aria-expanded', 'false'); const selectedText = summary.appendChild(createJpxElement('span', 'multiSelect-value')); summary.onclick = e => { e.stopPropagation(); const show = panel.style.display === 'none'; document.querySelectorAll('.multiSelect-popup-panel').forEach(p => { p.style.display = p === panel && show ? 'block' : 'none'; }); document.querySelectorAll('.multiSelect-summary').forEach(item => { item.setAttribute('aria-expanded', String(item === summary && panel.style.display !== 'none')); }); positionSettingsMultiSelect(summary); }; const panel = createJpxElement('div', 'multiSelect-popup-panel'); panel.id = getUniqueId(`${field.key}_options`); panel.setAttribute('role', 'group'); summary.setAttribute('aria-controls', panel.id); panel.style.display = 'none'; panel.onclick = e => e.stopPropagation(); listDiv.style.position = 'relative'; listDiv.append(summary, panel); const updateSummary = () => { const values = field.hasRange ? dataObj[field.key].slice(2) : dataObj[field.key]; const labels = values.map(v => t(field.multiSelectOptions.find(opt => opt.value === v)?.label || v)); selectedText.textContent = labels.join(', ') || t('cB.clickToSelect'); summary.title = labels.join(', '); positionSettingsMultiSelect(summary); }; renderCheckboxes(panel, updateSummary); updateSummary(); } else { listDiv.classList.add('jpx-checkbox-options'); renderCheckboxes(listDiv); } function renderCheckboxes(targetContainer, onUpdate) { for (const opt of field.multiSelectOptions) { const span = document.createElement('span'); span.style.cssText = 'display: inline-flex; align-items: center; margin-right: 8px;'; const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = getUniqueId(`${field.key}_${opt.value}`); checkbox.checked = dataObj[field.key].includes(opt.value); checkbox.onchange = e => { const values = dataObj[field.key]; if (e.target.checked) { if (!values.includes(opt.value)) values.push(opt.value); } else if (field.hasRange) dataObj[field.key] = [...values.slice(0, 2), ...values.slice(2).filter(v => v !== opt.value)]; else dataObj[field.key] = values.filter(v => v !== opt.value); onUpdate?.(); }; const label = createJpxElement('label', undefined, t(opt.label)); label.htmlFor = checkbox.id; span.append(checkbox, label); targetContainer.appendChild(span); } } } function renderDynamicListMode() { dataObj[field.key].forEach((value, index) => { const row = createJpxElement('div', 'array-row'); if (field.collapsibleItems) row.classList.add('jpx-rule-array-item'); let itemSchema = field.itemSchema; if (itemSchema.discriminator) itemSchema = resolveSchema(itemSchema, value); // Preserve extension rules without guessing their type or discarding data. if (!itemSchema) { const unknown = createJpxElement('details', 'jpx-rule-unknown'); const summary = createJpxElement('summary', undefined, `${index + 1}. ${t('cM.unsupportedRule')} · ${value.type || value.key || ''}`); const raw = document.createElement('pre'); raw.style.cssText = 'white-space:pre-wrap;overflow-wrap:anywhere;max-width:100%'; raw.textContent = JSON.stringify(value, null, 2); unknown.append(summary, raw); row.append(unknown); itemSchema = { type: 'readonly' }; } if (itemSchema.type === 'text') { renderField(row, { ...itemSchema, key: index, label: index + 1 }, dataObj[field.key]); } else if (itemSchema.type === 'object') { const objDiv = createJpxElement('div', 'object-item'); let bodyReady = false; const buildBody = () => { if (bodyReady) return; bodyReady = true; renderSchema(objDiv, itemSchema, value); }; if (field.collapsibleItems) { row.classList.add('jpx-rule-array-item'); const details = createJpxElement('details', 'jpx-rule-item'); details.open = fieldRenderers.expandedRuleItems.has(value); details.jpxBuildBody = buildBody; if (details.open || !canDeferRuleFields(itemSchema, value)) buildBody(); const summary = document.createElement('summary'); const [summaryText, heading, name, preview] = ['summary-text', 'summary-heading', 'item-name', 'item-preview'] .map(part => createJpxElement('span', 'jpx-rule-' + part)); heading.append(name); summaryText.append(heading, preview); summary.appendChild(summaryText); // Build before the native open action, so its first paint // already has the final content size for the transition. summary.addEventListener('click', event => { if (event.target.closest('button,input,select,textarea,a')) return; cancelBulkToggle(); if (!details.open) buildBody(); }); const updateSummary = () => { const nameText = (index + 1) + '. ' + getRuleLabel(value); if (name.textContent !== nameText) { name.textContent = nameText; name.title = nameText; } const conditions = value.conditions || []; const previewText = conditions.length ? conditions.map(condition => { const raw = condition.value; const formatted = Array.isArray(raw) ? raw.map(v => typeof v === 'string' ? t(`cB.${v}`) : String(v)).join(' / ') : typeof raw === 'boolean' ? t(raw ? 'cGen.on' : 'cGen.off') : typeof raw === 'string' ? raw : String(raw); return `${t(`cB.${condition.key}`)}: ${formatted}`; }).join(';') : ''; if (preview.textContent !== previewText) { preview.textContent = previewText; preview.title = previewText; } }; objDiv.classList.add('jpx-rule-item-body'); for (const type of ['input', 'change', 'click']) objDiv.addEventListener(type, updateSummary); details.addEventListener('toggle', () => { if (!details.isConnected) return; if (details.open) buildBody(); // Bulk disclosure already updates the view state once. if (fieldRenderers.expandedRuleItems.has(value) !== details.open) { setRuleExpanded(value, details.open); updateAllRulesToggle(); } if (!details.open) closeSettingsMultiSelects(objDiv); }); updateSummary(); details.append(summary, objDiv); renderedRuleItems.set(value, details); row.appendChild(details); } else { buildBody(); row.appendChild(objDiv); } } if (itemSchema.type === 'object') bindSettingsChange(row, value, null, row.querySelector('.jpx-rule-summary-heading') || row, true); renderRowButtons(row, index); listDiv.appendChild(row); }); renderAddButtons(addBar || listDiv); }; function renderArray() { cancelBulkToggle(); for (const [item, details] of renderedRuleItems) setRuleExpanded(item, details.open); renderedRuleItems.clear(); const scrollTop = listDiv.scrollTop; listDiv.innerHTML = ''; addBar?.replaceChildren(); if (field.multiSelectOptions) renderMultiSelectMode(); else renderDynamicListMode(); if (field.collapsibleItems) updateAllRulesToggle(); listDiv.scrollTop = scrollTop; } renderArray(); }, fieldPicker: renderStatsFieldPicker, object(container, field, dataObj) { renderSchema(container, field, dataObj[field.key]); }, keyBasedObjectArray(container, field, dataObj) { const targetData = field.flatten ? dataObj : dataObj[field.key]; container.innerHTML = `${t(field.label)}`; const listDiv = document.createElement('div'); if (field.fixedActions) listDiv.className = 'jpx-rule-scroll'; container.appendChild(listDiv); const addBindingBar = container.appendChild(createJpxElement('div', 'jpx-rule-add-actions')); function renderKeyBinding(key) { const row = createJpxElement('div', 'jpx-keybinding-rule-group'); row.style.cssText = 'border: 1px solid #444; padding: 10px; margin-bottom: 15px;'; const header = createJpxElement('div', 'jpx-keybinding-header'); header.style.cssText = 'display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #444; padding-bottom: 5px;'; const span = document.createElement('span'); span.append(`${t('cB.binding')}: `); jpxUtils.createButton(span, { text: jpxUtils.formatKeyCombo(key, ' + '), onClick: btn => { const originalText = btn.textContent; btn.textContent = '...'; jpxUtils.captureKeyCombo(result => { const newKey = 'kb_' + result.comboString; if (newKey === key) return renderAll(); if (targetData[newKey]) { jpxUtils.createToast(t('cB.duplicateKeys')); return renderAll(); } // Rename in place, keeping the binding's position among the mode's keys. const newEntries = Object.entries(targetData).map(([k, v]) => (k === key ? [newKey, v] : [k, v])); for (const k in targetData) delete targetData[k]; Object.assign(targetData, Object.fromEntries(newEntries)); renderAll(); }, () => { btn.textContent = originalText; }); } }); header.appendChild(span); const deleteBindingButton = jpxUtils.createButton(header, { text: t('delete'), className: 'jpx-delete-button', onClick: () => { if (confirm(`${t('delete')} ${jpxUtils.formatKeyCombo(key, ' + ')}?`)) { delete targetData[key]; renderAll(); } } }); row.appendChild(header); bindSettingsChange(row, targetData, key, span); const arrayContainer = document.createElement('div'); renderField(arrayContainer, { key, skipLabel: true, type: 'array', canDisable: field.canDisable, collapsibleItems: field.collapsibleItems, itemSchema: field.itemSchema }, targetData); const toolbar = arrayContainer.querySelector(':scope > .jpx-rule-list-toolbar'); if (toolbar) header.insertBefore(toolbar, deleteBindingButton); row.appendChild(arrayContainer); listDiv.appendChild(row); } function renderAll() { listDiv.innerHTML = ''; for (const k of Object.keys(targetData)) if (!field.flatten || k.startsWith('kb_')) renderKeyBinding(k); } jpxUtils.createButton(addBindingBar, { text: t('cB.addNewKeyBinding'), onClick: btn => { const originalText = btn.textContent; btn.textContent = `... ${t('cB.recording')} ...`; jpxUtils.captureKeyCombo(result => { const newKey = 'kb_' + result.comboString; if (targetData[newKey]) jpxUtils.createToast(t('cB.duplicateKeys')); else targetData[newKey] = []; renderAll(); requestAnimationFrame(() => listDiv.lastElementChild?.scrollIntoView({ block: 'start' })); btn.textContent = originalText; }, () => { btn.textContent = originalText; }); } }); renderAll(); }, conditionsArray(container, field, dataObj) { if (!Array.isArray(dataObj[field.key])) dataObj[field.key] = []; const listDiv = container.appendChild(document.createElement('div')); const getDefaultValue = (type, defaultValue) => { if (defaultValue !== undefined) return JSON.parse(JSON.stringify(defaultValue)); switch (type) { case 'boolean': return false; case 'text': return ''; case 'number': return 0; case 'rangeNumber': return [0, 0]; case 'array': return []; case 'dropdown': return ''; default: return null; } }; function createRow(item, index) { const selectId = getUniqueId('condition'); const row = createJpxElement('div', 'dynamic-array-row'); const select = document.createElement('select'); select.id = selectId; select.setAttribute('aria-label', `${t('conditions')} ${index + 1}`); for (const opt of field.options) { const option = select.appendChild(document.createElement('option')); option.value = opt.key; option.textContent = t(opt.label); } select.value = item.key ?? field.options[0]?.key; const inputDiv = createJpxElement('div', 'jpx-condition-value'), extraDiv = createJpxElement('div', 'jpx-condition-extra'); row.append(select, inputDiv, extraDiv); function renderInput() { inputDiv.innerHTML = ''; inputDiv.classList.remove('jpx-range'); extraDiv.innerHTML = ''; const selectedOption = field.options.find(option => option.key === select.value); if (!selectedOption) return; // Switching the condition type starts that condition from its defaults. if (item.key === undefined || item.key !== select.value) { Object.keys(item).forEach(k => delete item[k]); item.key = selectedOption.key; item.value = getDefaultValue(selectedOption.type, selectedOption.defaultValue); } selectedOption.extraFields?.forEach(f => { if (item[f.key] === undefined) item[f.key] = getDefaultValue(f.type, f.defaultValue); }); renderField(inputDiv, { ...selectedOption, key: 'value', skipLabel: true }, item); selectedOption.extraFields?.forEach(f => { const wrap = document.createElement('div'); renderField(wrap, f, item); extraDiv.appendChild(wrap); }); } select.onchange = () => { renderInput(); }; const deleteButton = jpxUtils.createButton(row, { className: 'jpx-delete-button', onClick: () => { dataObj[field.key].splice(index, 1); renderList(); } }); setJpxLabel(deleteButton, t('cGen.deleteCondition')); deleteButton.replaceChildren(createSettingsIcon('delete')); renderInput(); bindSettingsChange(row, item, null, row, true); return row; } function renderList() { listDiv.innerHTML = ''; dataObj[field.key].forEach((item, index) => listDiv.appendChild(createRow(item, index))); } jpxUtils.createButton(container, { text: `${t('add')} ${t(field.key)}`, onClick: () => { const newItem = {}; dataObj[field.key].push(newItem); listDiv.appendChild(createRow(newItem, dataObj[field.key].length - 1)); } }); renderList(); } }; function renderField(container, field, dataObj) { if (field.label) container.dataset.editLabel = t(field.label); const renderer = fieldRenderers[field.type === 'heading' ? 'constant' : field.type]; if (renderer) renderer(container, field, dataObj); if (field.help) { const help = createJpxElement('p', 'jpx-field-help'); help.id = getUniqueId('help'); help.textContent = t(field.help); container.querySelector('input, select, textarea')?.setAttribute('aria-describedby', help.id); container.appendChild(help); } if (!['group', 'heading', 'constant'].includes(field.type) && !field.hasModeDropdown) { const key = field.type === 'keyBasedObjectArray' && field.flatten ? readKeyBindingRules : field.key; const badgeTarget = container.querySelector(':scope > label, :scope > .jpx-rule-list-heading') || container; bindSettingsChange(container, dataObj, key, badgeTarget); } } function resolveSchema(schema, dataObj) { return schema.discriminator ? schema.oneOf[dataObj[schema.discriminator]] : schema; } function createEmptyObject(schema) { const obj = {}; for (const property of schema.properties) { if (property.type === 'constant') obj[property.key] = property.value; else if (property.default !== undefined) obj[property.key] = property.default; else { // Built per property, so new rules never share container values. const defaults = { text: '', number: 0, rangeNumber: [0, 0], boolean: false, array: [], fieldPicker: [], object: () => createEmptyObject(property), keyBasedObjectArray: {} }; const value = defaults[property.type]; obj[property.key] = typeof value === 'function' ? value() : value; } } return obj; } function getUniqueId(prefix = 'input') { return `${prefix}_${idCounter++}`; } function mergeCfg(storedCfg, defaultCfg, mergedCfg, mergedType) { let vKey = mergedType === 'battle' ? 'battleVersion' : 'statsVersion'; //patch 20260109 if (mergedType === 'battle' && storedCfg) { if (storedCfg.version && !storedCfg.battleVersion) { storedCfg.battleVersion = storedCfg.version; delete storedCfg.version; } } //- if (!storedCfg?.[vKey] || storedCfg[vKey] < defaultCfg[vKey]) storedCfg = {}; if (mergedType === 'battle') { for (const key of BATTLE_MODES) { let localObj = storedCfg[key]; //patch 20260208 key === '1H_Mage_General' && (localObj ??= storedCfg.Battlecaster_General); //- if (normalizeJpxBattleMode(localObj)) { mergedCfg[key] = localObj; } else { if (jpxUtils.isEmpty(defaultCfg[key])) continue; mergedCfg[key] = JSON.parse(JSON.stringify(defaultCfg[key])); normalizeJpxBattleMode(mergedCfg[key]); } } for (const key in defaultCfg) { if (BATTLE_MODES.includes(key)) continue; mergedCfg[key] = (key in storedCfg) ? storedCfg[key] : defaultCfg[key]; } } else if (mergedType === 'stats') { for (const key in defaultCfg) { mergedCfg[key] = JSON.parse(JSON.stringify((key in storedCfg) ? storedCfg[key] : defaultCfg[key])); } normalizeStatsConfig(mergedCfg); } } function parseJpxSettingsImport(content) { const data = JSON.parse(content, (key, value) => { if (['__proto__', 'prototype', 'constructor'].includes(key)) throw new Error('Invalid configuration key'); return value; }); if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid configuration'); return data; } function renderSettings() { let container = document.getElementById('settings-container'); if (container) { if (container.open) container.jpxRequestClose ? container.jpxRequestClose() : container.close(); else container.remove(); return; } ensureJpxStyle(); const previouslyFocused = document.activeElement; container = document.createElement('dialog'); container.id = 'settings-container'; container.className = 'jpx-settings-dialog'; container.tabIndex = -1; container.setAttribute('aria-label', 'JPX-PLUS'); let editHistory = null; const requestClose = () => { if (container.classList.contains('jpx-settings-mobile') && document.getElementById('tab_configManager')?.getAttribute('aria-selected') === 'true' && jpxConfigManagerView?.back()) return; return jpxConfigManagerView?.isEditing() ? jpxConfigManagerView.leave(() => container.close()) : container.close(); }; container.jpxRequestClose = requestClose; container.addEventListener('cancel', event => { if (jpxConfigManagerView?.isEditing()) { event.preventDefault(); requestClose(); } }); const disposeNativePickers = bindSettingsNativePickers(container); const windowPanel = createJpxElement('div', 'jpx-settings-window'), titleBar = createJpxElement('div', 'jpx-settings-titlebar'); const title = titleBar.appendChild(createJpxElement('strong', 'jpx-settings-title', 'JPX-PLUS')); const themeToggle = jpxUtils.createButton(titleBar, { id: 'jpx-theme-toggle', history: false, onClick: toggleJpxTheme }); themeToggle.setAttribute('role', 'switch'); const closeButton = jpxUtils.createButton(titleBar, { id: 'close-button', text: '×', history: false, onClick: requestClose }); closeButton.setAttribute('aria-label', t('cGen.closeSettings')); const navigationButton = jpxUtils.createButton(titleBar, { id: 'jpx-settings-menu-button', history: false, onClick: () => setMobileNavigation(!container.classList.contains('jpx-settings-navigation-open'), true), }); navigationButton.innerHTML = ''; navigationButton.setAttribute('aria-controls', 'jpx-settings-navigation'); navigationButton.setAttribute('aria-expanded', 'false'); navigationButton.setAttribute('aria-label', t('cGen.settingsSections')); windowPanel.appendChild(titleBar); const tabHeader = createJpxElement('nav', 'settings-tab-header'); tabHeader.id = 'jpx-settings-navigation'; tabHeader.setAttribute('role', 'tablist'); tabHeader.setAttribute('aria-label', t('cGen.settingsSections')); const settingsWorkspace = createJpxElement('div', 'jpx-settings-workspace'), settingsPanels = createJpxElement('div', 'jpx-settings-panels'); const sidebar = createJpxElement('div', 'jpx-settings-sidebar'); let sidebarCollapsed = localStorage.getItem(prefix + 'settingsSidebarCollapsed') === 'true'; const sidebarToggle = jpxUtils.createButton(sidebar, { className: 'jpx-settings-sidebar-toggle', history: false, onClick: () => { sidebarCollapsed = !sidebarCollapsed; localStorage.setItem(prefix + 'settingsSidebarCollapsed', String(sidebarCollapsed)); updateSidebar(); } }); sidebarToggle.setAttribute('aria-controls', tabHeader.id); function updateSidebar() { settingsWorkspace.classList.toggle('sidebar-collapsed', sidebarCollapsed); const label = t(sidebarCollapsed ? 'cGen.expandSidebar' : 'cGen.collapseSidebar'); sidebarToggle.setAttribute('aria-expanded', String(!sidebarCollapsed)); sidebarToggle.setAttribute('aria-label', label); sidebarToggle.title = label; sidebarToggle.replaceChildren(createSettingsIcon(sidebarCollapsed ? 'expand' : 'collapse')); } updateSidebar(); sidebar.appendChild(tabHeader); settingsWorkspace.append(sidebar, settingsPanels); function setMobileNavigation(open, focus = false) { const mobile = container.classList.contains('jpx-settings-mobile'); open = mobile && open; container.classList.toggle('jpx-settings-navigation-open', open); sidebar.inert = mobile && !open; navigationButton.setAttribute('aria-expanded', String(open)); if (open) { fieldRenderers.dragState.cancel?.(); closeMultiSelectPopups(); container.querySelectorAll('[popover]:popover-open').forEach(popup => popup.hidePopover()); } if (focus) (open ? tabHeader.querySelector('[aria-selected=true]') : navigationButton)?.focus({ preventScroll: true }); } windowPanel.appendChild(settingsWorkspace); const viewport = window.visualViewport; const touchMedia = window.matchMedia('(pointer: coarse)'); // Compensate the game's initial shrink-to-fit only. Subsequent pinch zoom // keeps its normal magnification; the game viewport itself is untouched. let pageScale = 1 / Math.min(1, viewport?.scale || 1); let screenWidth = Math.round((viewport?.width || window.innerWidth) * (viewport?.scale || 1)); const updateSettingsViewport = () => { const width = viewport?.width || window.innerWidth; const height = viewport?.height || window.innerHeight; const physicalWidth = width * (viewport?.scale || 1); const physicalHeight = height * (viewport?.scale || 1); // Rotation can also magnify the fixed-width game. A pinch leaves the // physical viewport width unchanged, so its magnification is retained. if (Math.abs(Math.round(physicalWidth) - screenWidth) > 1) { pageScale = 1 / (viewport?.scale || 1); screenWidth = Math.round(physicalWidth); } const mobile = physicalWidth <= 650 || (touchMedia.matches && physicalWidth <= 1024 && physicalHeight <= 600); const changed = mobile !== container.classList.contains('jpx-settings-mobile'); container.classList.toggle('jpx-settings-mobile', mobile); if (mobile) for (const [name, value] of [['left', `${viewport?.offsetLeft || 0}px`], ['top', `${viewport?.offsetTop || 0}px`], ['width', `${width / pageScale}px`], ['height', `${height / pageScale}px`], ['scale', pageScale]]) container.style.setProperty('--settings-' + name, value); if (changed || !tabHeader.hasAttribute('aria-orientation')) { tabHeader.setAttribute('aria-orientation', 'vertical'); closeButton.textContent = mobile ? `‹ ${t('cGen.back')}` : '×'; closeButton.setAttribute('aria-label', t(mobile ? 'cGen.back' : 'cGen.closeSettings')); title.textContent = mobile ? t('cGen.settings') : 'JPX-PLUS'; } if (changed) { setMobileNavigation(false); switchTab(tabs.find(tab => tab.btn.getAttribute('aria-selected') === 'true')?.id || 'battle', tabs); } container.querySelectorAll('.multiSelect-summary[aria-expanded=true]').forEach(positionSettingsMultiSelect); }; tabHeader.addEventListener('keydown', event => { const currentIndex = tabs.findIndex(tab => tab.btn === event.target.closest('[role=tab]')); if (currentIndex < 0) return; const vertical = tabHeader.getAttribute('aria-orientation') === 'vertical'; const step = { [vertical ? 'ArrowDown' : 'ArrowRight']: 1, [vertical ? 'ArrowUp' : 'ArrowLeft']: -1 }[event.key]; const nextIndex = step ? (currentIndex + step + tabs.length) % tabs.length : { Home: 0, End: tabs.length - 1 }[event.key]; if (nextIndex === undefined) return; event.preventDefault(); tabs[nextIndex].btn.focus(); switchTab(tabs[nextIndex].id, tabs); }); function closeMultiSelectPopups() { closeSettingsMultiSelects(container); } const onPointerDown = event => { if (container.classList.contains('jpx-settings-navigation-open') && !sidebar.contains(event.target) && !navigationButton.contains(event.target)) { setMobileNavigation(false, sidebar.contains(document.activeElement)); } if (!event.target.closest?.('.multiSelect-popup-panel, .multiSelect-summary')) closeMultiSelectPopups(); }; const onNavigationFocus = event => { // Safari can focus the dialog instead of a tapped button. That is not // navigation outside the menu; hiding it here would swallow the click. if (container.classList.contains('jpx-settings-navigation-open') && event.target !== container && !sidebar.contains(event.target) && !navigationButton.contains(event.target)) setMobileNavigation(false); }; const onKeyDown = event => { if (event.key !== 'Escape') return; const consume = () => { event.preventDefault(); event.stopPropagation(); }; if (container.classList.contains('jpx-settings-navigation-open')) { consume(); setMobileNavigation(false, true); return; } if (fieldRenderers.dragState.cancel) { consume(); fieldRenderers.dragState.cancel(); return; } const sortMenu = container.querySelector('.jpx-rule-sort-popover:popover-open'); if (sortMenu) { consume(); const anchor = container.querySelector(`[aria-controls="${sortMenu.id}"]`); sortMenu.hidePopover(); anchor?.focus({ preventScroll: true }); } else if ([...container.querySelectorAll('.multiSelect-popup-panel')].some(panel => panel.style.display !== 'none')) { consume(); closeMultiSelectPopups(); } }; const viewportListeners = [[window, 'resize'], [viewport, 'resize'], [viewport, 'scroll'], [touchMedia, 'change']]; const cleanup = () => { jpxConfigManagerView?.dispose(); disposeNativePickers(); editHistory?.dispose(); if (settingsEditHistory === editHistory) settingsEditHistory = null; controlPanelEditorState = null; jpxUtils.keyCaptureController?.abort(); fieldRenderers.dragState.cancel?.(); document.removeEventListener('pointerdown', onPointerDown, true); document.removeEventListener('keydown', onKeyDown, true); container.removeEventListener('focusin', onNavigationFocus); viewportListeners.forEach(([target, type]) => target?.removeEventListener(type, updateSettingsViewport)); }; document.addEventListener('pointerdown', onPointerDown, true); document.addEventListener('keydown', onKeyDown, true); container.addEventListener('focusin', onNavigationFocus); container.addEventListener('close', () => { cleanup(); container.remove(); if (previouslyFocused?.isConnected) previouslyFocused.focus({ preventScroll: true }); }, { once: true }); function saveBattleConfig() { let modeKey = document.querySelector('[data-role="battleMode"]')?.dataset.currentValue; for (const key of BATTLE_MODES) { if ( key !== modeKey && !key.includes('_General') && cfgBattle[key] && jpxUtils.isEmpty(defaultCfgBattle[key]) && Array.isArray(cfgBattle[key].rules) && cfgBattle[key].rules.length === 0 && !Object.keys(cfgBattle[key]).some(key => key.startsWith('kb_')) ) { delete cfgBattle[key]; jpxUtils.createToast(t('cB.emptyRulesRemoved', { name: jpxConfigModeLabel(key) }), 5000); } } console.log(cfgBattle); localStorage.setItem(prefix + 'cfgBattle' + isekaiSuffix, JSON.stringify(cfgBattle)); localStorage.setItem(prefix + 'userKeybinds' + isekaiSuffix, JSON.stringify(userKeybinds)); refreshJpxSelectedConfig(); jpxPanelManager.refreshAppearance?.(); if (log?.isConnected) { monstersObj = getMonsters(true); updateMonsterInfo(); } else if (!document.querySelector('#riddlemaster') && needsJpxMonsterDatabase()) getJpxMonsterDatabase().refresh(jpxMonsterWorld()).catch(error => console.warn('JPX monster database update failed.', error)); } function saveKeyBindings() { localStorage.setItem(prefix + 'userKeybinds' + isekaiSuffix, JSON.stringify(userKeybinds)); } function refreshBattleViews() { const oldUI = document.getElementById('cfgBattle-ui'); if (!oldUI) return; const newUI = document.createElement('div'); newUI.id = 'cfgBattle-ui'; oldUI.replaceWith(newUI); renderSchema(newUI, getSettingsSchemas().cfgBattleSettingsSchema, cfgBattle); } function exportBattleConfig() { return chooseJpxBattleExport(container, cfgBattle); } container.jpxConfigApplied = (patch, scope) => { if (scope === 'battle') refreshBattleViews(); else if (document.getElementById('cfgStats-ui')) renderStatsSettingsUI(document.getElementById('cfgStats-ui')); editHistory?.commit(scope, patch); }; function importBattleConfig(content) { const temporary = new Map(); const validator = createJpxConfigLibrary({ storage: { getItem: key => temporary.get(key) || null, setItem: (key, value) => temporary.set(key, value) }, key: 'check', modes: BATTLE_MODES, battleVersion: defaultCfgBattle.battleVersion, statsVersion: defaultCfgStats.statsVersion }); const data = validator.save({ schemaVersion: 1, kind: 'battle', title: 'Settings import', description: '', world: jpxConfigWorld(), config: parseJpxSettingsImport(content) }).envelope.config; if ([...BATTLE_MODES, 'Battlecaster_General'].some(key => Object.entries(data[key] || {}).some(([group, rules]) => (group === 'rules' || group.startsWith('kb_')) && Array.isArray(rules) && rules.some(rule => rule?.type === 'kamisamaniNattaHi'))) && !confirm(t('cB.importCustomCodeWarning'))) { throw Object.assign(new Error('Custom code import rejected'), { code: 'importCancelled' }); } // Prepare all modes before touching live rules: invalid later modes must // not leave a half-imported strategy running in the current battle. const next = {}; mergeCfg(data, cfgBattle, next, 'battle'); pauseForJpxConfigApplication(); Object.assign(cfgBattle, next); refreshJpxSelectedConfig(); return { refreshBattleViews: true, transModeKey: true }; } // Load every configuration before taking the history baseline, but build each // tab only when visited. Battle rules can contain thousands of hidden controls. loadStatsSettingsConfig(); statsSettingsView = { section: 'combatRows', fields: {} }; battleRulesView = { section: 'rules', scroll: {} }; const tabs = [ { id: 'battle', text: t('cB.basicSettings'), saveBtnText: t('cB.saveBattleConfig'), exportBtnText: t('cB.exportBattleConfig'), importBtnText: t('cB.importBattleConfig'), render: renderBattleTab, onSave: saveBattleConfig, onExport: exportBattleConfig, onImport: importBattleConfig }, { id: 'keyBindings', text: t('cB.keyBindings'), saveBtnText: t('cB.saveKeyBindings'), render: renderKeybindingsTab, onSave: saveKeyBindings, showTransfer: false }, { id: 'configManager', text: t('cM.name'), ownActions: true, render: parent => renderJpxConfigManager(parent, { onApplied: container.jpxConfigApplied }) }, { id: 'stats', text: t('cS.statsSettings'), saveBtnText: t('cS.saveStatsConfig'), exportBtnText: t('cS.exportStatsConfig'), importBtnText: t('cS.importStatsConfig'), render: renderStatsTab, onSave() { console.log(cfgStats); localStorage.setItem(prefix + 'cfgStats', JSON.stringify(cfgStats)); }, onExport() { return { data: cfgStats, fileName: 'cfgStats.txt', depth: 2 }; }, onImport(content) { let data = parseJpxSettingsImport(content); const version = data.statsVersion; if (!['number', 'string'].includes(typeof version) || String(version).trim() === '' || !Number.isFinite(Number(version)) || Number(version) < defaultCfgStats.statsVersion) throw new Error('Unsupported configuration version'); validateStatsConfig(data); const next = {}; mergeCfg(data, cfgStats, next, 'stats'); Object.assign(cfgStats, next); delete cfgStats.darkMode; return { refreshStats: true }; }, }, ]; function mountTab(tab) { tab.btn = jpxUtils.createButton(tabHeader, { className: 'settings-tab-btn', text: tab.text, history: false, onClick: () => { editHistory?.breakTypingGroup(); switchTab(tab.id, tabs); if (container.classList.contains('jpx-settings-mobile')) setMobileNavigation(false, true); }, }); tab.btn.id = `tab_${tab.id}`; tab.btn.replaceChildren(createSettingsIcon(tab.plugin ? 'plugin' : tab.id), createJpxElement('span', 'jpx-tab-label', tab.text)); tab.btn.title = tab.text; for (const [name, value] of [['aria-label', tab.text], ['role', 'tab'], ['aria-controls', `panel_${tab.id}`], ['aria-selected', 'false']]) tab.btn.setAttribute(name, value); tab.panel = document.createElement('div'); tab.panel.id = `panel_${tab.id}`; tab.panel.setAttribute('role', 'tabpanel'); tab.panel.setAttribute('aria-labelledby', tab.btn.id); tab.panel.style.display = 'none'; tab.rendered = false; settingsPanels.appendChild(tab.panel); } tabs.forEach(mountTab); const draftWorld = isekaiSuffix ? 'Isekai' : 'Persistent'; const selectedDraftMode = () => document.querySelector('[data-role="battleMode"]')?.dataset.currentValue || getBattleMode('OneHanded'); const hasDraftRules = jpxConfigHasContent; const readDraftBattle = world => { if (world === draftWorld) return cfgBattle; if (!['Persistent', 'Isekai'].includes(world)) return null; try { const saved = JSON.parse(localStorage.getItem(prefix + 'cfgBattle' + (world === 'Isekai' ? '_isekai' : '')) || 'null'); if (!saved || Array.isArray(saved) || typeof saved !== 'object' || (saved.battleVersion || saved.version || 0) < defaultCfgBattle.battleVersion) return null; // Apply existing migrations on this detached copy, without filling an unvisited world with defaults. mergeCfg(saved, { battleVersion: defaultCfgBattle.battleVersion }, saved, 'battle'); return saved; } catch { return null; } }; const mountPlugins = () => { for (const plugin of settingsPlugins.values()) { if (tabs.some(tab => tab.id === plugin.id)) continue; const tab = { id: plugin.id, text: String(plugin.title()), plugin: true, showTransfer: false, render: parent => plugin.render(parent, { version: window.JPXPlus.version, translate: t, notify: message => jpxUtils.createToast(String(message)), listDrafts() { const drafts = [], selected = selectedDraftMode(); for (const world of [draftWorld, draftWorld === 'Persistent' ? 'Isekai' : 'Persistent']) { const data = readDraftBattle(world); if (!data) continue; const modes = BATTLE_MODES.filter(mode => hasDraftRules(data[mode])); const source = world === draftWorld ? 'draft' : 'saved'; for (const mode of modes) drafts.push({ kind: 'battle-mode', world, mode, source, rules: data[mode].rules.length, current: world === draftWorld && mode === selected }); if (modes.length) drafts.push({ kind: 'battle', world, source, modes: modes.length, current: world === draftWorld }); } drafts.push({ kind: 'stats', world: 'Any', source: 'draft', current: true }); return drafts; }, getDraft(kind, selection = {}) { if (!['battle-mode', 'battle', 'stats'].includes(kind)) throw new Error('Invalid configuration type'); const world = selection.world || (kind === 'stats' ? 'Any' : draftWorld); if (kind === 'stats' ? world !== 'Any' : !['Persistent', 'Isekai'].includes(world)) throw new Error('Invalid configuration world'); const battle = kind === 'stats' ? null : readDraftBattle(world); if (kind !== 'stats' && !battle) throw new Error('Configuration unavailable'); const mode = selection.mode || selectedDraftMode(); if (kind === 'battle-mode' && (!BATTLE_MODES.includes(mode) || !hasDraftRules(battle[mode]))) throw new Error('Configuration unavailable'); const data = kind === 'stats' ? cfgStats : kind === 'battle' ? battle : { battleVersion: battle.battleVersion, [mode]: battle[mode] }; return JSON.parse(JSON.stringify({ schemaVersion: 1, kind, title: '', description: '', world, ...(kind === 'battle-mode' ? { mode } : {}), scriptVersion: window.JPXPlus.version, config: data })); }, importConfig(envelope) { if (!container.isConnected || !container.open) throw new Error('Settings closed'); const copy = JSON.parse(JSON.stringify(envelope), (key, value) => { if (['__proto__', 'prototype', 'constructor'].includes(key)) throw new Error('Invalid configuration key'); return value; }); if (!copy || !['battle-mode', 'battle', 'stats'].includes(copy.kind) || !copy.config || Array.isArray(copy.config) || typeof copy.config !== 'object') throw new Error('Invalid configuration'); const target = copy.kind === 'stats' ? 'stats' : 'battle'; const targetTab = tabs.find(item => item.id === target); let config = copy.config; if (copy.kind === 'battle-mode') { if (!BATTLE_MODES.includes(copy.mode) || !config[copy.mode]) throw new Error('Invalid battle mode'); config = { battleVersion: config.battleVersion, [copy.mode]: config[copy.mode] }; } const versionKey = copy.kind === 'stats' ? 'statsVersion' : 'battleVersion'; const requiredVersion = copy.kind === 'stats' ? defaultCfgStats.statsVersion : defaultCfgBattle.battleVersion; if ((config[versionKey] || config.version || 0) < requiredVersion) throw new Error('Unsupported configuration version'); if (copy.kind !== 'stats') { // Use the editor's schema so a plugin cannot import rules it cannot render. const { cfgBattleSchema, conditionsGeneral, conditionsTarget } = getSettingsSchemas(); const groups = cfgBattleSchema.properties.find(field => field.key === 'modes').itemSchema.properties; const conditions = new Map([...conditionsGeneral, ...conditionsTarget].map(field => [field.key, field])); const object = value => value && typeof value === 'object' && !Array.isArray(value); for (const mode of [...BATTLE_MODES, 'Battlecaster_General']) { if (!(mode in config)) continue; const data = config[mode]; if (copy.kind === 'battle' && object(data) && !Object.keys(data).length) continue; if (!object(data) || !normalizeJpxBattleMode(data)) throw new Error('Invalid battle rules'); for (const [key, rules] of Object.entries(data)) { const group = groups.find(field => field.key === (key.startsWith('kb_') ? 'keyBindings' : key)); if (!group) continue; if (!Array.isArray(rules)) throw new Error('Invalid battle rules'); for (const rule of rules) { if (!object(rule) || !Object.hasOwn(group.itemSchema.oneOf, rule.type) || ('conditions' in rule && !Array.isArray(rule.conditions))) throw new Error('Unsupported battle rule'); for (const condition of rule.conditions || []) { const field = object(condition) && conditions.get(condition.key); if (!field || (field.type === 'boolean' ? typeof condition.value !== 'boolean' : field.type === 'text' ? typeof condition.value !== 'string' : !Array.isArray(condition.value))) throw new Error('Invalid battle condition'); } } } } } // Build the target before applying the import; lazy renderers load saved settings. switchTab(target, tabs); editHistory.run(t('cGen.importConfig'), () => { const info = targetTab.onImport(JSON.stringify(config)); if (copy.mode) document.getElementById('import-button').dataset.battleMode = copy.mode; if (info.refreshStats) renderStatsSettingsUI(document.getElementById('cfgStats-ui')); else refreshBattleViews(); }); return true; } }) }; tabs.push(tab); mountTab(tab); } }; mountPlugins(); window.addEventListener('jpx:settings-plugin', mountPlugins); container.addEventListener('close', () => window.removeEventListener('jpx:settings-plugin', mountPlugins), { once: true }); const buttonsUI = createJpxElement('div', 'jpx-settings-footer'); const importFeedback = createJpxImportFeedback(); container.jpxClearImportFeedback = importFeedback.clear; // A later edit must not leave a stale Saved confirmation on screen. for (const eventName of ['input', 'change', 'click']) container.addEventListener(eventName, event => { if (importFeedback.node.dataset.stage === 'saved' && event.target.id !== 'save-button' && !importFeedback.node.contains(event.target)) importFeedback.clear(); }, true); const shownTab = () => tabs.find(tab => tab.panel.style.display === 'flex'); jpxUtils.createButton(buttonsUI, { id: 'export-button', history: false, onClick: async () => { const activeTab = shownTab(); if (!activeTab || !activeTab.onExport) return t('cGen.exportFailed!'); const info = await activeTab.onExport(); if (!info) return; downloadSettingsFile(jpxUtils.stringifyLimited(info.data, info.depth), 'text/plain;charset=utf-8', info.fileName); return t('cGen.exported!'); } }); jpxUtils.createButton(buttonsUI, { id: 'import-button', history: false, onClick: btn => { const activeTab = shownTab(); if (!activeTab || !activeTab.onImport) return t('cGen.importFailed!'); const generation = container.jpxImportGeneration = (container.jpxImportGeneration || 0) + 1; if (importFeedback.node.dataset.stage === 'reading') importFeedback.clear(); const current = () => container.isConnected && container.open && container.jpxImportGeneration === generation && activeTab.btn.getAttribute('aria-selected') === 'true'; const input = document.createElement('input'); input.type = 'file'; input.accept = '.txt,.json'; return new Promise((resolve, reject) => { input.addEventListener('change', async e => { const file = e.target.files[0]; if (!file || !current()) return resolve(); importFeedback.show(t('cM.importReading', { name: jpxImportDisplayName(file.name) }), 'reading', file.name); let reading = false; try { if (file.size > 2 * 1024 * 1024) throw Object.assign(new Error('Configuration file too large'), { code: 'tooLarge' }); reading = true; const content = await file.text(); reading = false; if (!current()) return resolve(); editHistory.run(t('cGen.importConfig'), () => { const info = activeTab.onImport(content); if (info.transModeKey) { const modeKey = document.querySelector('[data-role="battleMode"]')?.dataset.currentValue; if (modeKey) btn.dataset.battleMode = modeKey; } // Both importing tabs report which view they changed. if (info.refreshBattleViews) refreshBattleViews(); else if (info.refreshStats) renderStatsSettingsUI(document.getElementById('cfgStats-ui')); }); importFeedback.show(t('cM.importDraft', { name: jpxImportDisplayName(file.name) }) + (activeTab.id === 'battle' && log ? ' ' + t('cM.importPaused') : ''), 'draft', file.name); resolve(t('cGen.imported!')); } catch (err) { if (!current()) return resolve(); console.error(err); importFeedback.show(t('cM.importFailed', { name: jpxImportDisplayName(file.name), reason: t('cM.' + (reading ? 'importReadError' : err?.code && Object.hasOwn(I18N.cM, err.code) ? err.code : 'invalidConfig')) }), 'error', file.name); reject(t('cGen.importFailed!')); } }); input.addEventListener('cancel', () => resolve(), { once: true }); input.click(); }); } }); jpxUtils.createButton(buttonsUI, { id: 'save-button', history: false, onClick: () => { const activeTab = shownTab(); if (!activeTab || !activeTab.onSave) return t('cGen.error!'); try { if (activeTab.onSave() === false) throw new Error('Save failed'); } catch (cause) { importFeedback.show(t('cM.storageError'), 'error'); console.error(cause); return t('cGen.error!'); } editHistory.markSaved(activeTab.id === 'stats' ? ['stats'] : activeTab.id === 'keyBindings' ? ['shortcuts'] : ['battle', 'shortcuts']); editHistory.breakTypingGroup(); if (!importFeedback.node.hidden) importFeedback.show(t('cM.saved'), 'saved'); return t('cGen.saved!'); } }); const fileActions = createJpxElement('div', 'jpx-settings-file-actions'); fileActions.append(...buttonsUI.children); buttonsUI.appendChild(fileActions); windowPanel.append(importFeedback.node, buttonsUI); container.appendChild(windowPanel); document.body.appendChild(container); applyJpxTheme(); switchTab('battle', tabs); editHistory = createSettingsEditHistory(container, buttonsUI, view => { importFeedback.clear(); closeMultiSelectPopups(); if (view.mode) document.getElementById('import-button').dataset.battleMode = view.mode; refreshBattleViews(); const shortcuts = tabs.find(tab => tab.id === 'keyBindings'); if (shortcuts.rendered) { shortcuts.panel.replaceChildren(); renderKeybindingsTab(shortcuts.panel); } const stats = document.getElementById('cfgStats-ui'); if (stats) renderStatsSettingsUI(stats, true); switchTab(view.tab, tabs); view.scroll.forEach(([id, top]) => { document.getElementById(id).scrollTop = top; }); }); settingsEditHistory = editHistory; updateSettingsViewport(); viewportListeners.forEach(([target, type]) => target?.addEventListener(type, updateSettingsViewport)); container.showModal(); container.focus({ preventScroll: true }); } function switchTab(targetId, tabs) { if (targetId !== 'configManager' && jpxConfigManagerView?.isEditing()) { jpxConfigManagerView.leave(() => switchTab(targetId, tabs)); return; } const container = document.getElementById('settings-container'); const previousId = tabs.find(tab => tab.btn.getAttribute('aria-selected') === 'true')?.id; if (previousId !== targetId && container) { container.jpxImportGeneration = (container.jpxImportGeneration || 0) + 1; container.jpxClearImportFeedback?.(); } if (previousId === 'configManager' && targetId !== previousId) jpxConfigManagerView?.onHidden(); if (targetId === 'configManager' && previousId !== targetId) jpxConfigManagerView?.onShown(); if (targetId !== 'stats') captureStatsListScroll(document.getElementById('cfgStats-ui')); tabs.forEach(tab => { const isActive = tab.id === targetId; if (isActive && !tab.rendered) { tab.render(tab.panel); tab.rendered = true; } if (!isActive) tab.panel.querySelectorAll('[popover]:popover-open').forEach(popup => popup.hidePopover()); tab.btn.setAttribute('aria-selected', String(isActive)); tab.panel.style.display = isActive ? 'flex' : 'none'; if (!isActive) return; const footer = container?.querySelector('.jpx-settings-footer'); if (footer) footer.style.display = tab.plugin || tab.ownActions ? 'none' : ''; const mobile = container?.classList.contains('jpx-settings-mobile'); if (mobile) container.querySelector('.jpx-settings-title').textContent = tab.text; // Compact layouts show short captions; the full action stays in the title. for (const [name, fallback] of [['save', 'Save Settings'], ['export', 'Export Settings'], ['import', 'Import Settings']]) { const button = document.getElementById(`${name}-button`); if (!button) continue; const text = tab[`${name}BtnText`] || fallback; button.textContent = mobile ? t(`cGen.${name}`) : text; button.title = text; if (name !== 'save') button.style.display = tab.showTransfer === false ? 'none' : ''; } }); if (targetId === 'stats') restoreStatsListScroll(document.getElementById('cfgStats-ui')); } function renderBattleTab(parent) { loadBattleConfig(); const cfgBattleUI = parent.appendChild(document.createElement('div')); cfgBattleUI.id = 'cfgBattle-ui'; renderSchema(cfgBattleUI, getSettingsSchemas().cfgBattleSettingsSchema, cfgBattle); } function renderKeybindingsTab(parent) { parent.appendChild(createJpxElement('div', 'heading', t('cB.keyBindings'))); const keybindsUI = createJpxElement('div', 'jpx-keybindings-settings'); for (const action of Object.keys(KEYBINDS)) { const row = document.createElement('div'); bindSettingsChange(row, userKeybinds, action); row.appendChild(document.createElement('span')).textContent = t(`cB.${action}`) + ': '; jpxUtils.createButton(row, { id: `btn_${action}`, text: jpxUtils.formatKeyCombo(userKeybinds[action], ' + '), onClick: (btn, e) => { e.stopPropagation(); const originalText = btn.textContent; btn.textContent = '...'; jpxUtils.captureKeyCombo(result => { userKeybinds[action] = { key: result.key, ctrl: result.ctrl, alt: result.alt, shift: result.shift }; btn.textContent = jpxUtils.formatKeyCombo(userKeybinds[action], ' + '); }, () => { btn.textContent = originalText; }); } }); keybindsUI.appendChild(row); } parent.appendChild(keybindsUI); } function downloadSettingsFile(text, type, fileName) { const url = URL.createObjectURL(new Blob([text], { type })); const link = document.createElement('a'); link.href = url; link.download = fileName; link.click(); URL.revokeObjectURL(url); } // Legacy lists contain only displayed fields. Keep their order/styles and append missing fields disabled. function normalizeStatsConfig(data) { for (const field of getSettingsSchemas().cfgStatsSchema.properties.filter(field => field.statsEditor)) { const known = new Set(field.allFields.map(item => item.id)), seen = new Set(); const items = (Array.isArray(data[field.key]) ? data[field.key] : []).filter(item => { if (!item || !known.has(item.id) || seen.has(item.id)) return false; seen.add(item.id); return true; }); for (const base of field.allFields) { if (seen.has(base.id)) continue; // EXP is a new default stats column; enable it once for existing configs. if (field.key === 'statsColumns' && base.id === 'exp') { const item = { ...defaultCfgStats.statsColumns.find(entry => entry.id === 'exp'), id: 'exp', disabled: false }; const index = items.findIndex(entry => entry.id === 'tps'); items.splice(index >= 0 ? index + 1 : items.length, 0, item); } else { items.push({ ...defaultCfgStats[field.key].find(item => item.id === base.id), id: base.id, disabled: true }); } } data[field.key] = items; } } function validateStatsConfig(data) { const invalid = () => { throw new Error(t('cS.invalidConfig')); }; if (!data || Array.isArray(data) || typeof data !== 'object' || !['statsVersion', 'combatRows', 'revenueRows', 'statsColumns'].some(key => key in data)) invalid(); if ('columnGroups' in data && (!data.columnGroups || Array.isArray(data.columnGroups) || typeof data.columnGroups !== 'object' || Object.values(data.columnGroups).some(value => typeof value !== 'boolean'))) invalid(); for (const field of getSettingsSchemas().cfgStatsSchema.properties.filter(field => field.statsEditor)) { if (!(field.key in data)) continue; const seen = new Set(); if (!Array.isArray(data[field.key])) invalid(); for (const item of data[field.key]) { if (!item || typeof item.id !== 'string' || !item.id || seen.has(item.id)) invalid(); seen.add(item.id); if ('disabled' in item && typeof item.disabled !== 'boolean') invalid(); if (field.editFields.some(edit => edit.key in item && typeof item[edit.key] !== 'string')) invalid(); } } } function validateStatsBackup(data) { if (!data || typeof data !== 'object' || Array.isArray(data) || !data.stores || typeof data.stores !== 'object' || !Array.isArray(data.stores.battleRecords)) throw new Error(t('cS.invalidBackup')); for (const record of data.stores.battleRecords) { if (!record || typeof record !== 'object' || !(typeof record.timestamp === 'number' && Number.isFinite(record.timestamp) || typeof record.timestamp === 'string' && record.timestamp.trim() && (Number.isFinite(Number(record.timestamp)) || /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(record.timestamp) && Number.isFinite(Date.parse(record.timestamp.replace(' ', 'T') + 'Z'))))) throw new Error(t('cS.invalidBackup')); } } function renderStatsImportPreview(parent, data, fileName) { parent.querySelector('.jpx-stats-transfer')?.remove(); const panel = createJpxElement('div', 'jpx-stats-transfer'); const summary = createJpxElement('p', 'jpx-stats-help', `${fileName} · ${t('cS.importSummary', { count: data.stores.battleRecords.length })}`); const modeLabel = createJpxElement('label', undefined, t('cS.importMode')); const mode = modeLabel.appendChild(document.createElement('select')); mode.innerHTML = ``; const actions = createJpxElement('div', 'jpx-stats-toolbar'); jpxUtils.createButton(actions, { text: t('cS.importConfirmAction'), history: false, onClick: async button => { button.disabled = true; try { await importIndexedDB(data, mode.value === 'merge'); panel.remove(); jpxUtils.createToast(t('cGen.imported!')); } catch (error) { console.error(error); button.disabled = false; jpxUtils.createToast(t('cGen.importFailed!'), 5000); } } }); jpxUtils.createButton(actions, { text: t('cGen.cancel'), history: false, onClick: () => panel.remove() }); panel.append(createJpxElement('strong', undefined, t('cS.importPreview')), summary, modeLabel, actions); parent.appendChild(panel); } // Keep the preview clipped to this list and retain the original grab point. function bindStatsListDrag(list, moveField, options = {}) { const rowSelector = options.row || '.jpx-stats-row', handleSelector = options.handle || '.jpx-stats-grip'; const scroller = options.scroller || list; let drag = null; let suppressClick = false; const clearMarkers = () => list.querySelectorAll('.is-drop-before, .is-drop-after').forEach(row => row.classList.remove('is-drop-before', 'is-drop-after')); const bounds = () => { const rect = scroller.getBoundingClientRect(); const panel = list.closest('[role=tabpanel]').getBoundingClientRect(); const { scale } = getSettingsCoordinateSpace(list); return { left: Math.max(rect.left, panel.left), right: Math.min(rect.left + scroller.clientWidth * scale, panel.right), top: Math.max(rect.top, panel.top), bottom: Math.min(rect.top + scroller.clientHeight * scale, panel.bottom) }; }; const cancel = () => { if (!drag) return; const old = drag; drag = null; cancelAnimationFrame(old.frame); old.row.classList.remove('is-dragging'); old.layer?.remove(); clearMarkers(); if (fieldRenderers.dragState.cancel === cancel) fieldRenderers.dragState.cancel = null; window.removeEventListener('blur', cancel); window.removeEventListener('resize', cancel); if (old.handle.hasPointerCapture(old.pointerId)) old.handle.releasePointerCapture(old.pointerId); if (old.started) { suppressClick = true; setTimeout(() => { suppressClick = false; }, 0); } }; function update() { const area = bounds(), row = drag.row.getBoundingClientRect(); const space = getSettingsCoordinateSpace(list); Object.assign(drag.layer.style, { left: `${(area.left - space.left) / space.scale}px`, top: `${(area.top - space.top) / space.scale}px`, width: `${Math.max(0, area.right - area.left) / space.scale}px`, height: `${Math.max(0, area.bottom - area.top) / space.scale}px` }); const height = drag.preview.getBoundingClientRect().height; const offset = options.preview ? Math.min(drag.offsetY, height / 2) : drag.offsetY; const top = Math.max(0, Math.min(area.bottom - area.top - height, drag.y - offset - area.top)); Object.assign(drag.preview.style, { left: `${(row.left - area.left) / space.scale}px`, top: `${top / space.scale}px` }); clearMarkers(); drag.target = null; drag.marker.hidden = true; if (drag.x < area.left || drag.x >= area.right || drag.y < area.top || drag.y >= area.bottom) return; const target = document.elementFromPoint(drag.x, drag.y)?.closest(rowSelector); if (!target || target.parentElement !== list || target === drag.row) return; const rect = target.getBoundingClientRect(); drag.target = target; drag.after = drag.y >= rect.top + rect.height / 2; target.classList.add(drag.after ? 'is-drop-after' : 'is-drop-before'); const markerTop = (drag.after ? rect.bottom - 3 * space.scale : rect.top) - area.top; drag.marker.hidden = false; drag.marker.style.top = `${markerTop / space.scale}px`; drag.marker.classList.toggle('over-preview', markerTop < top + height && markerTop + 3 * space.scale > top); } function track() { if (!drag?.started) return; if (!list.isConnected || !list.getClientRects().length) { cancel(); return; } const area = bounds(); const edge = 24 * getSettingsCoordinateSpace(list).scale; if (drag.x >= area.left && drag.x < area.right && drag.y >= area.top && drag.y < area.bottom) { if (drag.y < area.top + edge) scroller.scrollTop -= 5; else if (drag.y > area.bottom - edge) scroller.scrollTop += 5; } update(); drag.frame = requestAnimationFrame(track); } list.addEventListener('pointerdown', event => { const handle = event.target.closest(handleSelector); if (!handle || !event.isPrimary || event.button !== 0) return; fieldRenderers.dragState.cancel?.(); const row = handle.closest(rowSelector); drag = { row, handle, pointerId: event.pointerId, x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY, offsetY: event.clientY - row.getBoundingClientRect().top }; fieldRenderers.dragState.cancel = cancel; window.addEventListener('blur', cancel); window.addEventListener('resize', cancel); handle.setPointerCapture(event.pointerId); event.preventDefault(); }); list.addEventListener('pointermove', event => { if (!drag || drag.pointerId !== event.pointerId) return; drag.x = event.clientX; drag.y = event.clientY; const { scale } = getSettingsCoordinateSpace(list); if (!drag.started && Math.hypot(drag.x - drag.startX, drag.y - drag.startY) >= 6 * scale) { drag.started = true; const rect = drag.row.getBoundingClientRect(); drag.layer = createJpxElement('div', 'jpx-stats-drag-layer'); drag.layer.setAttribute('aria-hidden', 'true'); drag.layer.inert = true; drag.preview = createJpxElement('div', 'jpx-stats-drag-preview' + (options.previewClass ? ' ' + options.previewClass : '')); Object.assign(drag.preview.style, { width: `${rect.width / scale}px`, height: options.preview ? 'auto' : `${rect.height / scale}px`, fontWeight: getComputedStyle(drag.row).fontWeight }); drag.preview.append(...(options.preview ? options.preview(drag.row) : [...drag.row.children].map(child => child.cloneNode(true)))); drag.marker = createJpxElement('div', 'jpx-stats-drop-marker'); drag.layer.append(drag.preview, drag.marker); list.append(drag.layer); drag.row.classList.add('is-dragging'); drag.frame = requestAnimationFrame(track); } if (drag.started) update(); }); list.addEventListener('pointerup', event => { if (!drag || drag.pointerId !== event.pointerId) return; if (drag.started) { drag.x = event.clientX; drag.y = event.clientY; update(); } const id = drag.row.dataset[options.idKey || 'fieldId']; const rows = [...list.querySelectorAll(':scope > ' + rowSelector)]; const from = rows.indexOf(drag.row), target = rows.indexOf(drag.target); let destination = target + (drag.after ? 1 : 0); if (from < destination) destination--; cancel(); if (target >= 0 && destination !== from) { moveField(id, destination); if (options.afterMove) options.afterMove(); else list.querySelector('.jpx-stats-select[aria-pressed=true]')?.focus({ preventScroll: true }); } }); for (const type of ['pointercancel', 'lostpointercapture']) list.addEventListener(type, event => { if (drag?.pointerId === event.pointerId) cancel(); }); list.addEventListener('click', event => { if (suppressClick) { event.preventDefault(); event.stopImmediatePropagation(); } }, true); return cancel; } // Native color inputs edit individual CSS properties; opening them never changes the stored style. function renderStatsColorControls(container, input, updateStyle, defaultStyle = '') { const parsed = document.createElement('span').style; const defaults = document.createElement('span').style; defaults.cssText = defaultStyle; const context = createSettingsColorContext(); const palette = container.appendChild(createJpxElement('div', 'jpx-stats-palette')); const colors = [['color', 'textColor', '#5c0d11'], ['background-color', 'backgroundColor', '#edebdf']]; const controls = colors.map(([property, titleKey, fallback]) => { const label = createJpxElement('div', 'jpx-stats-color'); const picker = document.createElement('input'); picker.type = 'color'; picker.id = getUniqueId('statsColor'); picker.dataset.colorProperty = property; picker.setAttribute('aria-label', input.getAttribute('aria-label') + ': ' + t('cS.' + titleKey)); label.append(picker); palette.append(label); const reset = jpxUtils.createButton(label, { className: 'jpx-appearance-reset', icon: 'undo', text: t('cGen.restoreDefault') + ': ' + picker.getAttribute('aria-label'), onClick: () => { parsed.cssText = input.value; const value = defaults.getPropertyValue(property); if (value) parsed.setProperty(property, value, defaults.getPropertyPriority(property)); else parsed.removeProperty(property); input.value = parsed.cssText; updateStyle(); }, }); reset.type = 'button'; reset.dataset.colorReset = property; picker.addEventListener('input', () => { parsed.cssText = input.value; parsed.setProperty(property, picker.value, parsed.getPropertyPriority(property)); input.value = parsed.cssText; updateStyle(picker); }); return { picker, reset, property, fallback }; }); const preview = createJpxElement('div', 'jpx-stats-preview'); const sample = createJpxElement('span', 'jpx-stats-preview-sample', '1,234'); sample.setAttribute('aria-label', input.getAttribute('aria-label') + ': ' + t('cS.livePreview')); preview.append(sample); palette.append(preview); const syncColors = sourcePicker => { parsed.cssText = input.value; // Copy only visual properties: arbitrary CSS must never move or cover the settings UI. for (const property of ['color', 'background-color', 'font-weight', 'font-style', 'text-decoration-line']) { const value = parsed.getPropertyValue(property); if (sample.style.getPropertyValue(property) !== value) sample.style.setProperty(property, value); } const computed = getComputedStyle(sample); for (const control of controls) { const { picker, reset, property, fallback } = control; const color = parsed.getPropertyValue(property); reset.disabled = color === defaults.getPropertyValue(property) && parsed.getPropertyPriority(property) === defaults.getPropertyPriority(property); picker.dataset.default = String(reset.disabled); picker.title = picker.getAttribute('aria-label') + ': ' + (color || t('cS.defaultColor')); const resolvedColor = computed.getPropertyValue(property) || color || fallback; if (control.lastColor === color && control.lastResolvedColor === resolvedColor) continue; control.lastColor = color; control.lastResolvedColor = resolvedColor; // Do not write back to the open native picker or read pixels on each drag event. if (picker !== sourcePicker) { context.clearRect(0, 0, 1, 1); context.fillStyle = fallback; context.fillRect(0, 0, 1, 1); context.fillStyle = resolvedColor; context.fillRect(0, 0, 1, 1); const hex = toSettingsHex(readSettingsPixel(context)); if (picker.value !== hex) picker.value = hex; } } }; palette._jpxRefreshTheme = syncColors; if (!sample.isConnected) queueMicrotask(() => { if (sample.isConnected) syncColors(); }); return syncColors; } // Keep original comma-separated tokens verbatim until that particular rule is edited. // The runtime parser remains unchanged, including ordering and legacy parseFloat behavior. function renderStatsThresholdControls(container, item, view) { const element = createJpxElement; const labelled = (text, idPrefix, type) => { const label = element('label', '', text), input = element('input', ''); input.type = type; input.id = getUniqueId(idPrefix); label.htmlFor = input.id; return [label, input]; }; const section = element('div', 'jpx-stats-thresholds'); const heading = element('div', 'jpx-stats-threshold-heading'); const title = element('strong', '', t('cS.thresholdTitle')); title.id = getUniqueId('statsThresholdTitle'); section.setAttribute('role', 'group'); section.setAttribute('aria-labelledby', title.id); heading.append(title); const list = element('div', 'jpx-stats-threshold-list'); const note = element('p', 'jpx-stats-threshold-note'); const legacyNote = element('p', 'jpx-stats-threshold-note', t('cS.thresholdLegacyHelp')); const preview = element('details', 'jpx-stats-threshold-preview'); preview.append(element('summary', '', t('cS.thresholdTry'))); const previewControls = element('div', 'jpx-stats-threshold-preview-controls'); const [previewLabel, previewInput] = labelled(t('cS.previewValue'), 'statsThresholdPreview', 'number'); previewInput.step = 'any'; previewInput.dataset.thresholdPreview = ''; previewInput.value = view.previewValue ?? '1234'; const sample = element('span', 'jpx-stats-preview-sample'); sample.setAttribute('aria-label', t('cS.livePreview')); const matchText = element('output', 'jpx-stats-threshold-match'); matchText.setAttribute('for', previewInput.id); previewControls.append(previewLabel, previewInput, element('span', '', '→'), sample, matchText); preview.append(previewControls); const readTokens = () => item.colorThresholds ? item.colorThresholds.split(',') : []; const writeTokens = tokens => { if (tokens.length) item.colorThresholds = tokens.join(','); else delete item.colorThresholds; syncPreview(); }; const context = createSettingsColorContext(); const pickerColor = color => { if (!color || /currentcolor|inherit|initial|unset|revert|var\(|env\(/i.test(color)) return null; // A native opaque picker cannot faithfully edit context-dependent or transparent legacy colors. context.fillStyle = '#000000'; context.fillStyle = color; const first = context.fillStyle; context.fillStyle = '#ffffff'; context.fillStyle = color; if (first !== context.fillStyle) return null; context.clearRect(0, 0, 1, 1); context.fillRect(0, 0, 1, 1); const rgba = readSettingsPixel(context); return rgba[3] === 255 ? toSettingsHex(rgba) : null; }; function syncPreview() { const style = document.createElement('span').style; style.cssText = item.styleText || ''; const number = previewInput.valueAsNumber; const match = parseStatsColorThresholds(readTokens()).find(threshold => number >= threshold.min); if (match) style.color = match.color; sample.removeAttribute('style'); for (const property of ['color', 'background-color', 'font-weight', 'font-style']) { sample.style.setProperty(property, style.getPropertyValue(property)); } const valueText = Number.isFinite(number) ? number.toLocaleString() : '—'; if (sample.textContent !== valueText) sample.textContent = valueText; const ruleText = !Number.isFinite(number) ? '' : match ? t('cS.thresholdMatched', { value: String(match.min) }) : t('cS.thresholdBase'); if (matchText.textContent !== ruleText) matchText.textContent = ruleText; } function renderRules() { list.replaceChildren(); const tokens = readTokens(); let hasLegacy = false; tokens.forEach((token, index) => { const row = element('div', 'jpx-stats-threshold-row'); row.dataset.thresholdIndex = index; const parts = token.split(':'); const minText = parts[0].trim(), colorText = parts[1]?.trim(); const hex = pickerColor(colorText); const editable = parts.length === 2 && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(minText) && Number.isFinite(Number(minText)) && hex; if (editable) { const [minLabel, min] = labelled(t('cS.thresholdAtLeast'), 'statsThresholdMin', 'number'); min.step = 'any'; min.value = String(Number(minText)); min.dataset.thresholdMin = ''; const [colorLabel, color] = labelled(t('cS.textColor'), 'statsThresholdColor', 'color'); color.value = hex; color.title = colorText; color.dataset.thresholdColor = ''; min.addEventListener('input', () => { const valid = min.validity.valid && Number.isFinite(min.valueAsNumber); min.setAttribute('aria-invalid', String(!valid)); if (!valid) return; const current = readTokens(); const colon = current[index].indexOf(':'); current[index] = min.value + current[index].slice(colon); writeTokens(current); }); min.addEventListener('blur', () => { if (min.getAttribute('aria-invalid') === 'true') { min.value = String(Number(readTokens()[index].split(':')[0])); min.removeAttribute('aria-invalid'); } }); color.addEventListener('input', () => { const current = readTokens(); current[index] = current[index].slice(0, current[index].indexOf(':') + 1) + color.value; color.title = color.value; writeTokens(current); }); row.append(minLabel, min, colorLabel, color); } else { hasLegacy = true; const legacy = element('span', 'jpx-stats-threshold-legacy', token || t('cS.thresholdLegacy')); legacy.title = t('cS.thresholdLegacy') + ': ' + token; row.append(legacy); } const remove = jpxUtils.createButton(row, { text: '×', className: 'jpx-stats-threshold-delete', historyLabel: t('cS.thresholdDelete'), onClick: () => { const current = readTokens(); current.splice(index, 1); writeTokens(current); renderRules(); (list.children[Math.min(index, list.children.length - 1)]?.querySelector('input, button') || add).focus(); }, }); setJpxLabel(remove, t('cS.thresholdDelete')); list.append(row); }); note.textContent = t(tokens.length ? 'cS.thresholdOrder' : 'cS.thresholdEmpty'); note.hidden = tokens.length === 1; legacyNote.hidden = !hasLegacy; preview.hidden = !tokens.length; syncPreview(); } const add = jpxUtils.createButton(heading, { text: t('cS.thresholdAdd'), className: 'jpx-stats-threshold-add', onClick: () => { const tokens = readTokens(); tokens.push('0:#5c0d11'); writeTokens(tokens); renderRules(); const min = list.lastElementChild.querySelector('[data-threshold-min]'); min.focus(); min.select(); }, }); previewInput.addEventListener('input', () => { view.previewValue = previewInput.value; syncPreview(); }); section.append(heading, list, note, legacyNote, preview); bindSettingsChange(section, item, 'colorThresholds'); container.append(section); renderRules(); return syncPreview; } function renderStatsFieldPicker(container, field, data) { const view = statsSettingsView.fields[field.key] ||= { selected: data[field.key][0]?.id }; const labelFor = item => t(field.allFields.find(base => base.id === item.id)?.label || item.id); const nameOf = item => item.customName || labelFor(item); const element = createJpxElement; const picker = element('div', 'jpx-stats-picker'); const selectedPane = element('div', 'jpx-stats-pane jpx-stats-selected-pane'); const selectedHeading = element('div', 'jpx-stats-pane-heading'); const count = element('span', 'jpx-stats-pane-count'); count.setAttribute('role', 'status'); count.setAttribute('aria-atomic', 'true'); const selectedList = element('div', 'jpx-stats-list'); selectedList.dataset.statsField = field.key; selectedList.addEventListener('scroll', () => { if (selectedList.isConnected && selectedList.getClientRects().length) view.scrollTop = selectedList.scrollTop; }); selectedList.setAttribute('role', 'list'); selectedList.setAttribute('aria-label', t('cS.allFields')); selectedHeading.append(element('strong', '', t('cS.allFields')), count); selectedPane.append(selectedHeading, selectedList); const editor = element('div', 'jpx-stats-edit'); editor.id = getUniqueId('statsEditor'); picker.append(selectedPane, editor); container.append(picker); const selectedButton = () => selectedList.querySelector('.jpx-stats-select[aria-pressed=true]'); const moveField = (id, destination) => { const items = data[field.key], index = items.findIndex(item => item.id === id); if (index < 0 || destination < 0 || destination >= items.length || destination === index) return; const move = () => { items.splice(destination, 0, items.splice(index, 1)[0]); view.selected = id; refresh(); selectedButton()?.scrollIntoView({ block: 'nearest' }); }; runSettingsEdit(t('cS.reorderFields'), move); }; const cancelDrag = bindStatsListDrag(selectedList, moveField); function renderEditor() { editor.replaceChildren(); const item = data[field.key].find(item => item.id === view.selected); editor.hidden = !item; if (!item) return; const defaults = defaultCfgStats[field.key]?.find(row => row.id === item.id) || {}; const styleFields = field.editFields.filter(edit => edit.key.startsWith('s_') || edit.key === 'styleText'); const title = element('div', 'jpx-stats-edit-title'); const titleText = element('strong', '', nameOf(item)); title.append(titleText); editor.append(title); if (field.key === 'statsColumns') { const nameInput = Object.assign(element('input', 'jpx-stats-name-input'), { type: 'text', id: getUniqueId('statsColumnName'), hidden: true, placeholder: labelFor(item), title: t('cS.renameHelp') }); nameInput.dataset.editKey = 'customName'; nameInput.setAttribute('aria-label', t('cS.renameColumn')); let editing = false, initialValue = ''; const showNameInput = open => { nameInput.hidden = !open; titleText.hidden = open; rename.replaceChildren(createSettingsIcon(open ? 'confirm' : 'edit')); setJpxLabel(rename, t(open ? 'cS.confirmName' : 'cS.renameColumn')); rename.setAttribute('aria-expanded', String(open)); }; const finishName = (commit, focus = false) => { if (!editing) return; editing = false; const changed = commit && nameInput.value !== initialValue; const apply = () => { if (changed) { if (nameInput.value.trim()) item.customName = nameInput.value; else delete item.customName; const row = selectedButton(); if (row) row.querySelector('.jpx-stats-row-label').textContent = `${data[field.key].indexOf(item) + 1}. ${nameOf(item)}`; titleText.textContent = nameOf(item); } showNameInput(false); }; if (changed) runSettingsEdit(t('cS.renameColumn'), apply); else apply(); if (focus) rename.focus({ preventScroll: true }); }; title.append(nameInput); const rename = jpxUtils.createButton(title, { className: 'jpx-stats-name-edit', text: t('cS.renameColumn'), icon: 'edit', history: false, onClick: () => { if (editing) { finishName(true, true); return; } initialValue = nameOf(item); nameInput.value = initialValue; editing = true; showNameInput(true); nameInput.focus(); nameInput.select(); }, }); rename.setAttribute('aria-controls', nameInput.id); rename.setAttribute('aria-expanded', 'false'); // Confirming with the mouse must not blur/commit and immediately reopen the editor. rename.addEventListener('pointerdown', event => { if (editing) event.preventDefault(); }); nameInput.addEventListener('blur', () => finishName(true)); nameInput.addEventListener('keydown', event => { if (event.isComposing) return; if (event.key !== 'Enter' && event.key !== 'Escape') return; event.preventDefault(); event.stopPropagation(); finishName(event.key === 'Enter', true); }); bindSettingsChange(title, item, 'customName'); } const resetStyles = jpxUtils.createButton(title, { text: t('cGen.restoreDefaults'), className: 'jpx-appearance-reset jpx-appearance-reset-all', onClick: () => { for (const { key } of styleFields) { if (defaults[key]) item[key] = defaults[key]; else delete item[key]; } renderEditor(); editor.querySelector('[data-stats-reset]')?.focus({ preventScroll: true }); }, }); resetStyles.type = 'button'; resetStyles.dataset.statsReset = ''; const currentStyle = document.createElement('span').style, defaultStyle = document.createElement('span').style; const syncResetStyles = () => { resetStyles.disabled = styleFields.every(({ key }) => { currentStyle.cssText = item[key] || ''; defaultStyle.cssText = defaults[key] || ''; return currentStyle.cssText === defaultStyle.cssText; }); }; syncResetStyles(); const colorHeading = element('div', 'jpx-stats-color-heading'); colorHeading.setAttribute('aria-hidden', 'true'); const colorLabels = element('div', ''); for (const key of ['textColor', 'backgroundColor', 'livePreview']) colorLabels.append(element('span', '', t('cS.' + key))); colorHeading.append(element('span', ''), colorLabels); editor.append(colorHeading); const styles = element('div', 'jpx-stats-style-fields'); const groups = new Map(); let syncThresholdPreview; for (const edit of field.editFields) { if (edit.key === 'colorThresholds' || edit.key === 'customName') continue; if (!groups.has(edit.group)) { const group = element(edit.group ? 'fieldset' : 'div', 'jpx-stats-edit-group'); if (edit.group) group.append(element('legend', '', t(`cS.${edit.group}`))); groups.set(edit.group, group); styles.append(group); } const row = element('div', 'jpx-stats-edit-field'); const caption = t(edit.key === 'styleText' ? 'cS.appearance' : edit.label); const label = element('label', '', caption); const control = element('div', 'jpx-stats-style-control'); const input = Object.assign(element('input', ''), { type: 'text', id: getUniqueId('statsField'), value: item[edit.key] || '', placeholder: edit.placeholder || '', spellcheck: false, title: t('cS.styleHelp') }); label.htmlFor = input.id; input.dataset.editKey = edit.key; input.dataset.styleField = ''; input.setAttribute('aria-label', edit.group ? `${t(`cS.${edit.group}`)}: ${t(edit.label)}` : caption); let syncColors; const updateStyle = sourcePicker => { if (input.value) item[edit.key] = input.value; else delete item[edit.key]; syncColors?.(sourcePicker); syncThresholdPreview?.(); syncResetStyles(); }; input.addEventListener('input', updateStyle); control.append(input); if (edit.key.startsWith('s_') || edit.key === 'styleText') { input.hidden = true; syncColors = renderStatsColorControls(control, input, updateStyle, defaults[edit.key] || ''); syncColors(); } row.append(label, control); bindSettingsChange(row, item, edit.key); groups.get(edit.group).append(row); } editor.append(styles); if (field.key === 'statsColumns' && STATS_THRESHOLD_FIELDS.has(item.id)) { syncThresholdPreview = renderStatsThresholdControls(editor, item, view); } } function selectField(id) { settingsEditHistory?.flushColorEdit(); if (view.selected === id) return; view.selected = id; refresh(); } function refresh() { settingsEditHistory?.flushColorEdit(); cancelDrag(); const items = data[field.key]; if (!items.some(item => item.id === view.selected)) view.selected = items[0]?.id; count.textContent = t('cS.enabledCount', { count: items.filter(item => item.disabled !== true).length, total: items.length }); // A newly constructed or hidden list has no meaningful DOM scroll position yet. const scrollTop = selectedList.childElementCount && selectedList.getClientRects().length ? selectedList.scrollTop : view.scrollTop || 0; view.scrollTop = scrollTop; selectedList.replaceChildren(); items.forEach((item, index) => { const row = element('div', 'jpx-stats-row'); row.setAttribute('role', 'listitem'); row.dataset.fieldId = item.id; row.dataset.selected = String(item.id === view.selected); row.dataset.enabled = String(item.disabled !== true); selectedList.append(row); const button = jpxUtils.createButton(row, { className: 'jpx-stats-select', history: false, onClick: () => { selectField(item.id); selectedButton()?.focus({ preventScroll: true }); } }); const grip = createStatsGrip('jpx-stats-grip jpx-drag-grip'); grip.title = t('cS.reorderHint'); button.append(grip, element('span', 'jpx-stats-row-label', `${index + 1}. ${nameOf(item)}`)); button.title = labelFor(item); bindSettingsChange(row, item, null, row, true); button.setAttribute('aria-pressed', String(item.id === view.selected)); button.setAttribute('aria-controls', editor.id); button.addEventListener('keydown', event => { if (event.altKey && ['ArrowUp', 'ArrowDown'].includes(event.key)) { event.preventDefault(); moveField(item.id, index + (event.key === 'ArrowUp' ? -1 : 1)); selectedButton()?.focus({ preventScroll: true }); return; } const next = { ArrowUp: index - 1, ArrowDown: index + 1, Home: 0, End: items.length - 1 }[event.key]; if (next === undefined) return; event.preventDefault(); selectField(items[Math.max(0, Math.min(next, items.length - 1))].id); selectedButton()?.focus(); }); const actions = element('div', 'jpx-array-item-actions'); row.append(actions); createSettingsMoveButtons(actions, index, items.length, destination => { moveField(item.id, destination); selectedButton()?.focus({ preventScroll: true }); }); const enabled = item.disabled !== true; createSettingsFieldToggle(actions, enabled, nameOf(item), () => { if (enabled) item.disabled = true; else delete item.disabled; view.selected = item.id; refresh(); selectedButton()?.closest('.jpx-stats-row').querySelector('.jpx-rule-state-toggle').focus({ preventScroll: true }); }); }); if (selectedList.getClientRects().length) selectedList.scrollTop = scrollTop; renderEditor(); } refresh(); } function createStatsGrip(className) { const grip = createJpxElement('span', className); grip.append(createSettingsIcon('grip')); grip.setAttribute('aria-hidden', 'true'); return grip; } function renderStatsSettingsUI(container, restoringView = false) { settingsEditHistory?.flushColorEdit(); if (!restoringView) captureStatsListScroll(container); normalizeStatsConfig(cfgStats); container.replaceChildren(); const nav = createJpxElement('div', 'jpx-stats-nav'); nav.setAttribute('role', 'group'); nav.setAttribute('aria-label', t('cS.statsSettings')); container.append(nav); const fields = getSettingsSchemas().cfgStatsSchema.properties.filter(field => field.statsEditor); const sections = [...fields.map(field => field.key), 'data']; const panels = new Map(), buttons = new Map(); const selectSection = (key, initial = false) => { if (!initial) captureStatsListScroll(container); statsSettingsView.section = key; const selected = panels.get(key); if (!selected.hasChildNodes()) { if (key === 'data') renderStatsDataActions(selected); else { const editor = selected.appendChild(document.createElement('div')); editor.dataset.fieldKey = key; renderStatsFieldPicker(editor, fields.find(field => field.key === key), cfgStats); } } panels.forEach((panel, id) => { panel.hidden = id !== key; }); buttons.forEach((button, id) => button.setAttribute('aria-pressed', String(id === key))); restoreStatsListScroll(container); }; sections.forEach(key => { const button = jpxUtils.createButton(nav, { text: t(`cS.section_${key}`), history: false, onClick: () => selectSection(key) }); button.dataset.statsSection = key; if (key !== 'data') bindSettingsChange(button, cfgStats, key); const panel = document.createElement('section'); panel.id = `jpx-stats-${key}`; panel.hidden = true; button.setAttribute('aria-controls', panel.id); button.id = `jpx-stats-nav-${key}`; panel.setAttribute('aria-labelledby', button.id); button.addEventListener('keydown', event => { const next = getSettingsSectionStep(event.key, sections.indexOf(key), sections.length); if (next === undefined) return; event.preventDefault(); selectSection(sections[next]); buttons.get(sections[next]).focus(); }); panels.set(key, panel); buttons.set(key, button); container.append(panel); button.title = t(`cS.help_${key}`); }); selectSection(sections.includes(statsSettingsView.section) ? statsSettingsView.section : sections[0], true); } function loadStatsSettingsConfig() { let storedCfgStats = {}; try { storedCfgStats = JSON.parse(localStorage.getItem(prefix + 'cfgStats') || '{}'); } catch (err) { console.warn('Failed to load cfgStats. Using default cfgStats.'); storedCfgStats = {}; } mergeCfg(storedCfgStats, defaultCfgStats, cfgStats, 'stats'); delete cfgStats.darkMode; } function renderStatsTab(parent) { const cfgStatsUI = parent.appendChild(document.createElement('div')); cfgStatsUI.id = 'cfgStats-ui'; renderStatsSettingsUI(cfgStatsUI); } function renderStatsDataActions(parent) { const root = parent.appendChild(createJpxElement('div', 'jpx-stats-data')); root.appendChild(document.createElement('style')).textContent = jpxThemeCSS(JPX_STATS_DATA_CSS + jpxDisclosureCSS('.jpx-stats-data .jpx-shared-data')); const records = root.appendChild(createJpxElement('section', 'jpx-stats-data-section')); records.append(createJpxElement('h3', undefined, t('cS.dataRecords'))); const maintenance = createJpxElement('section', 'jpx-stats-data-maintenance'), buttonsUI = createJpxElement('div', 'jpx-stats-toolbar'); jpxUtils.createButton(maintenance, { id: 'reset-cfgStats-button', text: t('cS.resetStatsSettings'), onClick: () => { cfgStats = JSON.parse(JSON.stringify(defaultCfgStats)); delete cfgStats.darkMode; renderStatsSettingsUI(document.getElementById('cfgStats-ui')); } }); jpxUtils.createButton(buttonsUI, { id: 'export-db-button', text: t('cS.exportDB'), history: false, onClick: async () => { downloadSettingsFile(jpxUtils.stringifyLimited(await exportIndexedDB(), 3), 'application/json', `battleStats_${Date.now()}.json`); return t('cGen.exported!'); } }); jpxUtils.createButton(buttonsUI, { id: 'import-db-button', text: t('cS.importDB'), history: false, onClick: () => { const input = document.createElement('input'); input.type = 'file'; input.accept = 'application/json'; return new Promise((resolve, reject) => { input.addEventListener('change', async e => { const file = e.target.files[0]; if (!file) return resolve(); try { const json = JSON.parse(await file.text()); validateStatsBackup(json); if (parent.isConnected) renderStatsImportPreview(records, json, file.name); resolve(); } catch (err) { console.error(err); reject(t('cGen.importFailed!')); } }); input.click(); }); } }); jpxUtils.createButton(buttonsUI, { id:'clear-records-button', text:t('cS.clearRecords'), history:false, onClick:() => openJpxRecordsCleanup() }); records.append(buttonsUI); renderJpxSharedDataActions(root); jpxUtils.createButton(maintenance, { id:'cleanup-data-button', text:t('cS.cleanup'), history:false, onClick:requestJpxCleanup }); root.append(maintenance); } //Misc function storeTmp() { if (cleanupInProgress) return; if (log) { let btcp = document.querySelector('#btcp'); let finishBattle = document.querySelector('img[src$="finishbattle.png"]'); if (!btcp) { localStorage.setItem(prefix + 'monsterData' + isekaiSuffix, JSON.stringify(monsterData)); } else { // Native navigation can precede the throttled final log callback. // Never carry this round's IDs/HP into a document for the next one. localStorage.removeItem(prefix + 'monsterData' + isekaiSuffix); } if (!finishBattle) { // Navigation can beat either the observer microtask or its trailing // throttle. Record the outstanding turn without rendering or acting. const unobserved = battleLogObserver?.takeRecords().length; if ((battleLogPending || unobserved) && log.isConnected && !document.querySelector('#riddlemaster')) { battleLogUpdate?.cancel(); battleLogPending = false; battleRecorder(); } localStorage.setItem(prefix + 'timeRecords' + isekaiSuffix, JSON.stringify(timeRecords)); localStorage.setItem(prefix + 'combatRecords' + isekaiSuffix, JSON.stringify(combatRecords)); localStorage.setItem(prefix + 'revenueRecords' + isekaiSuffix, JSON.stringify(revenueRecords)); // A full optional log can exceed storage quota. Save the compact // counters first so that failure does not also lose the battle stats. if (cfgBattle.recordBattleLog) { storeBattleLogRecord(); } } } } //I18n function initDoI18n(onChange) { const mergeI18N = () => {Object.assign(mergedI18N, jpxUtils.deepMerge(JSON.parse(JSON.stringify(I18N)), window.jpxI18N || {}));}; let externalI18n = window.jpxI18N; Object.defineProperty(window, 'jpxI18N', { get: () => externalI18n, set: (v) => { externalI18n = v; mergeI18N(); refreshJpxTheme(); if (onChange) { onChange(); return; } jpxPanelManager.updateContent(); initMobileEntry.refresh?.(); initHvutEntry.refresh?.(); }, configurable: true }); mergeI18N(); } function t(path, args = {}) { if (typeof path === 'number' || (!isNaN(path) && !isNaN(parseFloat(path)))) return String(path); if (typeof path !== 'string') return path; let keys = path.split('.'); let lastKey = keys.at(-1); if (!isNaN(lastKey) && !isNaN(parseFloat(lastKey))) return String(lastKey); let text = jpxUtils.getValueByPath(mergedI18N, keys); if (text === undefined) text = jpxUtils.sentenceCase(lastKey); if (args && typeof args === 'object') { for (const prop in args) { text = text.split('${' + prop + '}').join(String(args[prop])); } } return text; } // Shared by the live floating widget and the appearance preview. function createControlWidgetContents(root, preview = false) { root.classList.add('jpx-widget-card'); const header = document.createElement(preview ? 'div' : 'button'); header.className = 'jpx-widget-drag'; if (!preview) { header.type = 'button'; header.title = t('cW.movePanel'); header.setAttribute('aria-label', header.title); } const title = document.createElement('strong'); title.textContent = 'JPX-PLUS'; header.append(title, createSettingsIcon('grip')); const info = document.createElement('div'); info.className = 'jpx-widget-info'; if (!preview) { info.tabIndex = 0; info.setAttribute('role', 'button'); info.setAttribute('aria-label', t('cW.toggleBattle')); } const actions = document.createElement('div'); actions.className = 'jpx-widget-actions'; const buttons = {}; for (const [key, icon, label] of [['stats', 'stats', 'openStats'], ['settings', 'battle', 'openSettings']]) { const button = document.createElement(preview ? 'span' : 'button'); button.className = 'jpx-widget-action'; if (!preview) button.type = 'button'; button.dataset.widgetAction = key; const text = document.createElement('span'); text.textContent = t('cW.' + label); button.append(createSettingsIcon(icon), text); actions.append(button); buttons[key] = button; } root.append(header, info, actions); return { header, info, ...buttons }; } function updateControlWidgetRows(container, rows) { let nodes = container._jpxRows; if (!nodes || nodes.length !== rows.length || rows.some((row, index) => nodes[index].id !== row.id)) { nodes = rows.map(row => { const element = document.createElement('div'); element.className = 'jpx-widget-info-row'; element.dataset.rowId = row.id; const label = document.createElement('span'); label.className = 'jpx-widget-info-label'; const value = document.createElement('span'); value.className = 'jpx-widget-info-value'; element.append(label, value); return { id: row.id, element, label, value }; }); container.replaceChildren(...nodes.map(row => row.element)); container._jpxRows = nodes; } rows.forEach((row, index) => { const label = row.label + ':'; const value = row.id === 'isActiveBattle' && container._jpxBattleState ? t('cW.' + container._jpxBattleState) : String(row.value ?? ''); if (nodes[index].label.textContent !== label) nodes[index].label.textContent = label; if (nodes[index].value.textContent !== value) nodes[index].value.textContent = value; }); } function setControlWidgetState(root, state) { if (root.dataset.battleState !== state) root.dataset.battleState = state; const info = root.querySelector('.jpx-widget-info'), label = t('cW.' + state); if (info) { info._jpxBattleState = state; const status = info._jpxRows?.find(row => row.id === 'isActiveBattle')?.value; if (status && status.textContent !== label) status.textContent = label; if (info.getAttribute('role') === 'button') { const name = t('cW.toggleBattle') + ': ' + label, pressed = String(state === 'auto'); if (info.getAttribute('aria-label') !== name) info.setAttribute('aria-label', name); if (info.getAttribute('aria-pressed') !== pressed) info.setAttribute('aria-pressed', pressed); } } const color = `var(--jpx-${state}-surface, ${{ auto: '#edf1e4', manual: '#edebdf', waiting: '#f6edcf' }[state]})`; if (root._jpxSurface !== color) { root.style.backgroundColor = color; root._jpxSurface = color; } } function bindControlWidgetPosition(widget, handle, owner) { const key = prefix + 'ctrlWidgetPosition' + isekaiSuffix; let preferred = null, drag = null, frame = 0; try { const saved = JSON.parse(localStorage.getItem(key) || 'null'); if (saved && Number.isFinite(saved.left) && Number.isFinite(saved.top)) preferred = { left: saved.left, top: saved.top }; } catch { /* Invalid or inaccessible position storage uses the viewport corner. */ } const viewport = () => { const view = window.visualViewport; return { left: view?.offsetLeft || 0, top: view?.offsetTop || 0, width: view?.width || innerWidth, height: view?.height || innerHeight }; }; function place(position) { const view = viewport(), margin = 8; const width = widget.offsetWidth, height = widget.offsetHeight; const maxLeft = view.left + Math.max(margin, view.width - width - margin); const maxTop = view.top + Math.max(margin, view.height - height - margin); const desired = position || { left: maxLeft - 4, top: maxTop - 4 }; const left = Math.max(view.left + margin, Math.min(maxLeft, desired.left)); const top = Math.max(view.top + margin, Math.min(maxTop, desired.top)); // Home stays anchored to the viewport edge as rows/fonts change height. // Numeric top/left would leave one stale frame until ResizeObserver runs. widget.style.setProperty('left', position ? left + 'px' : 'auto', 'important'); widget.style.setProperty('top', position ? top + 'px' : 'auto', 'important'); widget.style.setProperty('right', position ? 'auto' : (innerWidth - left - width) + 'px', 'important'); widget.style.setProperty('bottom', position ? 'auto' : (innerHeight - top - height) + 'px', 'important'); return { left, top }; } function constrain() { // Existing appearance declarations stay intact; viewport placement is owned by dragging. for (const [property, value] of [['position', 'fixed'], ['right', 'auto'], ['bottom', 'auto'], ['transform', 'none'], ['margin', '0'], ['min-width', '0'], ['min-height', '0']]) widget.style.setProperty(property, value, 'important'); const view = viewport(); widget.style.setProperty('max-width', Math.max(0, view.width - 16) + 'px', 'important'); widget.style.setProperty('max-height', Math.max(0, view.height - 16) + 'px', 'important'); widget.style.setProperty('overflow-y', 'auto', 'important'); return place(preferred); } const schedule = () => { if (frame || drag || !widget.isConnected) return; frame = requestAnimationFrame(() => { frame = 0; if (drag || !widget.isConnected) return; const before = widget.getBoundingClientRect(), after = constrain(); if (Math.abs(before.left - after.left) > 1 || Math.abs(before.top - after.top) > 1) owner.suppressHover = true; }); }; const save = position => { preferred = position; try { if (position) localStorage.setItem(key, JSON.stringify(position)); else localStorage.removeItem(key); } catch { /* Dragging still works when local storage is unavailable. */ } }; function finish(cancel = false) { if (!drag) return; const current = drag; drag = null; if (current.moved && !cancel) preferred = current.latest; // Resizing can occur while pointer capture is active; apply deferred size limits now. const finalPosition = constrain(); if (current.moved) { owner.suppressHover = true; if (cancel) place(current.start); else save(finalPosition); } owner.dragging = false; widget.classList.remove('is-dragging'); if (handle.hasPointerCapture(current.id)) handle.releasePointerCapture(current.id); } handle.addEventListener('pointerdown', event => { if (event.button !== 0 || event.isPrimary === false || drag) return; owner.roundHoverResume = null; event.preventDefault(); event.stopPropagation(); if (frame) { cancelAnimationFrame(frame); frame = 0; } const rect = widget.getBoundingClientRect(); drag = { id: event.pointerId, x: event.clientX, y: event.clientY, start: { left: rect.left, top: rect.top }, latest: null, moved: false }; handle.setPointerCapture(event.pointerId); handle.focus({ preventScroll: true }); }); handle.addEventListener('pointermove', event => { if (!drag || drag.id !== event.pointerId) return; const dx = event.clientX - drag.x, dy = event.clientY - drag.y; if (!drag.moved && Math.hypot(dx, dy) < 4) return; event.preventDefault(); drag.moved = true; owner.dragging = true; widget.classList.add('is-dragging'); drag.latest = place({ left: drag.start.left + dx, top: drag.start.top + dy }); }); handle.addEventListener('pointerup', event => { if (drag?.id === event.pointerId) finish(); }); for (const type of ['pointercancel', 'lostpointercapture']) handle.addEventListener(type, event => { if (drag?.id === event.pointerId) finish(true); }); handle.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); }); handle.addEventListener('keydown', event => { if (event.key === 'Escape' && drag) { event.preventDefault(); event.stopPropagation(); finish(true); return; } if (event.key === 'Home') { event.preventDefault(); owner.roundHoverResume = null; owner.suppressHover = true; save(null); constrain(); return; } const direction = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key]; if (!direction || event.ctrlKey || event.metaKey || event.altKey || drag) return; event.preventDefault(); owner.roundHoverResume = null; owner.suppressHover = true; const rect = widget.getBoundingClientRect(), step = event.shiftKey ? 10 : 1; save(place({ left: rect.left + direction[0] * step, top: rect.top + direction[1] * step })); }); window.addEventListener('blur', () => finish(true)); widget.addEventListener('mouseleave', event => { if (!drag && !event.buttons) owner.suppressHover = false; }); const rememberPointer = event => { owner.lastPointer = { x: event.clientX, y: event.clientY }; }; widget.addEventListener('pointermove', rememberPointer, true); widget.addEventListener('pointerdown', rememberPointer, true); window.addEventListener('resize', schedule); window.visualViewport?.addEventListener('resize', schedule); window.visualViewport?.addEventListener('scroll', schedule); new ResizeObserver(schedule).observe(widget); constrain(); return { refresh: constrain, cancel: () => finish(true) }; } //Panel function jpxPanelManager(panelType) { const ns = jpxPanelManager; if (ns._init) return ns; ns.ready = true; ns.currentType = panelType; ns.createCtrlWidget = function(type) { if (ns.ctrlWidget) { !document.querySelector('#ctrl-widget') && document.body.appendChild(ns.ctrlWidget); ns.refreshAppearance(); return; } ns.currentType = type || ns.currentType; ns.ctrlWidget = document.createElement('div'); ns.ctrlWidget.id = 'ctrl-widget'; ns.ctrlWidget.className = 'jpx-floating-widget'; if (cfgBattle.ctrlWidgetStyleText) ns.ctrlWidget.style.cssText = cfgBattle.ctrlWidgetStyleText; const parts = createControlWidgetContents(ns.ctrlWidget); ns.parts = parts; ns.infoDiv = parts.info; switch (ns.currentType) { case 'battle': { const throttledToggleBattle = jpxUtils.throttle(toggleActive, 200); ns.infoDiv.addEventListener('pointerdown', (e) => { if (e.pointerType === 'mouse' && e.button !== 0) return; if (ns.dragging) return; ns.roundHoverResume = null; e.stopPropagation(); throttledToggleBattle(); }); ns.infoDiv.addEventListener('keydown', event => { if (event.key !== 'Enter' && event.key !== ' ') return; event.preventDefault(); event.stopPropagation(); ns.roundHoverResume = null; if (!event.repeat && !ns.dragging) throttledToggleBattle(); }); ns.infoDiv.addEventListener('mouseenter', event => { if (!cfgBattle.ctrlWidgetMouseEnter || !ns.ready || ns.dragging || event.buttons) return; if (ns.suppressHover) { ns.suppressHover = false; const pointer = ns.lastPointer; if (pointer && Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) < 1) return; } // Hover starts by default; only explicit opt-in may stop an // already-running battle. Click/keyboard toggles stay intact. if (isActiveBattle && cfgBattle.ctrlWidgetMouseEnterPause !== true) return; throttledToggleBattle(); }); ns.infoDiv.addEventListener('pointermove', event => { const pending = ns.roundHoverResume; if (!pending || !cfgBattle.ctrlWidgetMouseEnter || isActiveBattle || !event.isTrusted || event.pointerType !== 'mouse' || event.buttons || ns.dragging || !log?.isConnected || document.querySelector('#riddlemaster, #btcp img[src$="finishbattle.png"]')) return; const pointer = pending.pointer; if (pointer && Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) < 1) return; ns.suppressHover = false; // The window mousemove listener runs after this panel handler. ns.ready = true; throttledToggleBattle(); }); parts.stats.addEventListener('click', event => { event.stopPropagation(); battleRecordPlayer(false); }); parts.settings.addEventListener('click', event => { event.stopPropagation(); if (!window.matchMedia('(hover: hover) and (pointer: fine)').matches) { let proficiencyRecord = document.querySelector('#proficiency-record'); if (proficiencyRecord) proficiencyRecord.style.left = '800px'; } renderSettings(); }); break; } } ns.setBackground(isActiveBattle ? '#4f4' : '#fef'); ns.updateContent(); document.body.appendChild(ns.ctrlWidget); ns.position = bindControlWidgetPosition(ns.ctrlWidget, parts.header, ns); ns.dispatchState(); }; ns.refreshAppearance = function() { if (!ns.ctrlWidget) return; ns.ctrlWidget.style.cssText = typeof cfgBattle.ctrlWidgetStyleText === 'string' ? cfgBattle.ctrlWidgetStyleText : ''; ns.ctrlWidget._jpxSurface = null; ns.setBackground(ns.background || (isActiveBattle ? '#4f4' : '#fef')); ns.updateContent(); ns.position?.refresh(); }; ns.updateContent = function(type) { if (!ns.infoDiv) return; ns.currentType = type || ns.currentType; switch (ns.currentType) { case 'battle': { const rows = cfgBattle.ctrlWidgetRows.map(row => { const field = CTRLWIDGET_FIELDS.find(field => field.id === row.id); return field ? { id: row.id, label: t(field.label), value: field.get() } : null; }).filter(row => row !== null); setControlWidgetState(ns.ctrlWidget, ns.warning ? 'waiting' : isActiveBattle ? 'auto' : 'manual'); updateControlWidgetRows(ns.infoDiv, rows); const moveLabel = t('cW.movePanel'); if (ns.parts.header.title !== moveLabel) ns.parts.header.title = moveLabel; if (ns.parts.header.getAttribute('aria-label') !== moveLabel) ns.parts.header.setAttribute('aria-label', moveLabel); for (const [key, label] of [['stats', 'openStats'], ['settings', 'openSettings']]) { const text = ns.parts[key].lastElementChild, value = t('cW.' + label); if (text.textContent !== value) text.textContent = value; } break; } } }; ns.setBackground = function(color) { document.documentElement.classList.toggle('jpx-hide-round-popup', !!(cfgBattle.hideRoundPopup && cfgBattle.advanceToNextRound && isActiveBattle)); // Preserve event colors while using quieter colors on the visible panel. const style = document.createElement('span').style; style.background = color; ns.background = style.background; ns.warning = ns.background === 'rgb(255, 255, 85)'; if (ns.ctrlWidget) setControlWidgetState(ns.ctrlWidget, ns.warning ? 'waiting' : isActiveBattle ? 'auto' : 'manual'); }; ns.dispatchState = function() { setTimeout(()=> { window.dispatchEvent(new CustomEvent('jpx_ctrlWidget_update', { detail: { active: isActiveBattle, background: ns.background, suffix: isekaiSuffix, timestamp: Date.now() } })); }, 0); }; ns._init = true; return ns; } //Market function jpxMarket() { const ns = jpxMarket; if (ns._init) return ns; ns.defaultPriceData = { //Stamina 'Energy Drink': 400, //Material 'Low-Grade Cloth': 2, 'Mid-Grade Cloth': 10, 'High-Grade Cloth': 50, 'Low-Grade Leather': 2, 'Mid-Grade Leather': 10, 'High-Grade Leather': 50, 'Low-Grade Metals': 2, 'Mid-Grade Metals': 10, 'High-Grade Metals': 50, 'Low-Grade Wood': 2, 'Mid-Grade Wood': 10, 'High-Grade Wood': 50, 'Scrap Cloth': 1, 'Scrap Leather': 1, 'Scrap Metal': 1, 'Scrap Wood': 1, 'Energy Cell': 2, //Consumable // Restorative 'Health Draught': 1, 'Health Potion': 2, 'Health Elixir': 20, 'Mana Draught': 2, 'Mana Potion': 4, 'Mana Elixir': 40, 'Spirit Draught': 2, 'Spirit Potion': 4, 'Spirit Elixir': 40, 'Last Elixir': 40, // Infusion 'Infusion of Flames': 8, 'Infusion of Frost': 8, 'Infusion of Storms': 8, 'Infusion of Lightning': 8, 'Infusion of Divinity': 8, 'Infusion of Darkness': 8, // Scroll 'Scroll of Swiftness': 8, 'Scroll of Protection': 8, 'Scroll of the Avatar': 20, 'Scroll of Absorption': 4, 'Scroll of Shadows': 8, 'Scroll of Life': 12, 'Scroll of the Gods': 32, // Shard 'Voidseeker Shard': 10, 'Aether Shard': 50, 'Featherweight Shard': 10, 'Amnesia Shard': 50, 'World Seed': 50, // Special Item 'Flower Vase': 200, 'Bubble-Gum': 200, //Token of Blood, Chaos Token, Soul Fragment 'Token of Blood': 0, 'Chaos Token': 0, 'Soul Fragment': 0, //Food 'Monster Chow': 1, 'Monster Edibles': 1, 'Monster Cuisine': 1, 'Happy Pills': 10, //Figurine 'Twilight Sparkle Figurine': 10000, 'Rainbow Dash Figurine': 10000, 'Applejack Figurine': 10000, 'Fluttershy Figurine': 10000, 'Pinkie Pie Figurine': 10000, 'Rarity Figurine': 10000, 'Trixie Figurine': 10000, 'Princess Celestia Figurine': 10000, 'Princess Luna Figurine': 10000, 'Apple Bloom Figurine': 10000, 'Scootaloo Figurine': 10000, 'Sweetie Belle Figurine': 10000, 'Big Macintosh Figurine': 10000, 'Spitfire Figurine': 10000, 'Derpy Hooves Figurine': 10000, 'Lyra Heartstrings Figurine': 10000, 'Octavia Figurine': 10000, 'Zecora Figurine': 10000, 'Cheerilee Figurine': 10000, 'Vinyl Scratch Figurine': 10000, 'Daring Do Figurine': 10000, 'Doctor Whooves Figurine': 10000, 'Berry Punch Figurine': 10000, 'Bon-Bon Figurine': 10000, 'Fluffle Puff Figurine': 10000, 'Angel Bunny Figurine': 10000, 'Gummy Figurine': 10000, //Artifacts 'Precursor Artifact': 2000, //Trophy 'ManBearPig Tail': 200, 'Holy Hand Grenade of Antioch': 200, "Mithra's Flower": 200, 'Dalek Voicebox': 200, 'Lock of Blue Hair': 200, 'Bunny-Girl Costume': 400, 'Hinamatsuri Doll': 400, 'Broken Glasses': 400, 'Black T-Shirt': 800, 'Sapling': 800, 'Unicorn Horn': 1000, 'Noodly Appendage': 1000, //Crystal 'Crystal of Vigor': 1, 'Crystal of Finesse': 1, 'Crystal of Swiftness': 1, 'Crystal of Fortitude': 1, 'Crystal of Cunning': 1, 'Crystal of Knowledge': 1, 'Crystal of Flames': 1, 'Crystal of Frost': 1, 'Crystal of Lightning': 1, 'Crystal of Tempest': 1, 'Crystal of Devotion': 1, 'Crystal of Corruption': 1, //Upgrade Material 'Wispy Catalyst': 1, 'Diluted Catalyst': 5, 'Regular Catalyst': 10, 'Robust Catalyst': 25, 'Vibrant Catalyst': 50, 'Coruscating Catalyst': 100, } ns.getMarketPrice = async function (update = true) { let priceData = JSON.parse(localStorage.getItem(prefix + 'priceData' + isekaiSuffix) || '{}'); if (!update) return priceData.lastUpdate ? priceData : ns.defaultPriceData; let currentDate = new Date().toISOString().slice(0, 10); if ( !priceData?.lastUpdate || new Date(priceData.lastUpdate).toISOString().slice(0, 10) != currentDate ) { priceData = await this.updatePrice(priceData); } return priceData; }; ns.updatePrice = async function (priceData) { let finishBattle = document.querySelector('img[src$="finishbattle.png"]'); let isekaiSuffixUrl = document.URL.includes('isekai') ? 'isekai/' : ''; let urlArray = ['co', 'ma', 'tr'].map(filter => `${location.origin}/${isekaiSuffixUrl}?s=Bazaar&ss=mk&screen=browseitems&filter=${filter}`); if (!isekaiSuffix) { urlArray.push(...['ar', 'fi', 'mo'].map(filter => `${location.origin}/?s=Bazaar&ss=mk&screen=browseitems&filter=${filter}`)); } let latestPriceData = {}; if (!log || finishBattle) { priceData['lastUpdate'] = Date.now(); await jpxUtils.xhrGet(urlArray).then((results) => { console.log('jpxUtils.xhrGet Results:'); console.log(results); for (let result of results){ if (result.status === 'rejected') { console.error(result.reason); break; } try { let parser = new DOMParser(); let doc = parser.parseFromString(result.value.responseText, 'text/html'); let itemListTrs = doc.querySelectorAll('#market_itemlist > table > tbody > tr'); itemListTrs.forEach((itemListTr, index) => { if (index === 0) return; let itemListTds = itemListTr.querySelectorAll('td'); if (itemListTds.length >= 4) { let name = itemListTds[0].textContent.trim(); let bid = parseFloat(itemListTds[2].textContent.trim().replace(' C', '').replace(',', '')); let defaultBid = ns.defaultPriceData[name]; if (!isNaN(defaultBid) && (isNaN(bid) || bid < defaultBid)) bid = defaultBid; if (!isNaN(bid)) latestPriceData[name] = bid; } }); } catch (e) { console.error('Parsing error for url: ' + result.value.url); } } }); } for (let latestPriceDataKey in latestPriceData) { priceData[latestPriceDataKey] = latestPriceData[latestPriceDataKey]; } for (let defaultPriceDataKey in ns.defaultPriceData) { if (!priceData[defaultPriceDataKey]) { priceData[defaultPriceDataKey] = ns.defaultPriceData[defaultPriceDataKey]; } } if (isekaiSuffix) { priceData['Energy Drink'] = 0; } localStorage.setItem(prefix + 'priceData' + isekaiSuffix, JSON.stringify(priceData)); return priceData; }; ns._init = true; return ns; } //Utils function jpxUtils() { const ns = jpxUtils; if (ns._init) return ns; ns.throttle = function (func, cooldownMillis, trailing = false) { let lastRan = 0; let timeoutId = null; let trailingThis = null; let trailingArgs = null; const throttled = (...args) => { if (Date.now() - lastRan > cooldownMillis) { // A background/split tab can delay the pending trailing timer // beyond the cooldown. This fresh call supersedes that timer. clearTimeout(timeoutId); timeoutId = trailingThis = trailingArgs = null; lastRan = Date.now(); func.call(this, ...args); } else if (trailing) { trailingThis = this; trailingArgs = args; if (timeoutId === null) { timeoutId = setTimeout(() => { lastRan = Date.now(); timeoutId = null; const context = trailingThis, args = trailingArgs; trailingThis = trailingArgs = null; func.call(context, ...args); }, cooldownMillis - (Date.now() - lastRan)); } } }; throttled.cancel = () => { clearTimeout(timeoutId); timeoutId = trailingThis = trailingArgs = null; lastRan = 0; }; return throttled; }; ns.secondsToTime = function (seconds, showMillisecond = false) { let tHours = Math.floor(seconds / 3600); let tMinutes = Math.floor(seconds / 60) % 60; let tSeconds = showMillisecond ? Math.floor(seconds % 60) : Math.round(seconds % 60); let time = tHours.toString().padStart(2, '0') + ':' + tMinutes.toString().padStart(2, '0') + ':' + tSeconds.toString().padStart(2, '0'); if (showMillisecond) { let tMilliseconds = seconds.toFixed(3).split('.')[1]; time += '.' + tMilliseconds; } return time; }; ns.daysSince = function(dateStr) { if (!dateStr) return null; let date = new Date(dateStr + 'T00:00:00Z'); if (isNaN(date)) return null; let now = new Date(); let today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())); return Math.floor((today - date) / (1000 * 60 * 60 * 24)); }; ns.lowerFirst = function (str) { if (!str) return str; return str.charAt(0).toLowerCase() + str.slice(1); }; ns.sentenceCase = function (str, multiWord = false) { if (!str) return str; if (!multiWord && /\s/.test(str)) return str; return str .replace(/([a-z])([A-Z])/g, '$1 $2') .replace(/_/g, ' ') .toLowerCase() .replace(/^./, c => c.toUpperCase()); }; ns.matchAny = function (str, ...regexps) { for (const regexp of regexps) { let matches = str.match(regexp); if (matches) { return matches; } } return null; }; ns.parseValue = (val) => { if (typeof val === 'string' && val.trim() !== '' && !isNaN(val)) return Number(val); return val; }; ns.isEmpty = function (obj) { if (!obj || typeof obj !== 'object') return true; for (const prop in obj) { if (Object.hasOwn(obj, prop)) return false; } return true; }; ns.inRange = function (value, range) { let [min, max] = range; return value >= min && value <= max; }; ns.getValueByPath = function(obj, keys) { let current = obj; for (const key of keys) { if (current[key] === undefined) return undefined; current = current[key]; } return current; }; ns.deepMerge = function (target, source) { if (!source) return target; for (const key in source) { if (source[key] instanceof Object && key in target) { Object.assign(source[key], ns.deepMerge(target[key], source[key])); } } Object.assign(target || {}, source); return target; }; ns.getSortedKeys = function(order, keys) { let sortedKeys = order.filter(key => keys.includes(key)); let extraKeys = keys.filter(key => !order.includes(key)); return [...sortedKeys, ...extraKeys]; }; ns.inc = function (obj, key, step = 1) { if (!obj || key == null) return; obj[key] = (obj[key] ?? 0) + (step || 0); }; ns.createButton = function (container, options) { let { id, className, cssText, text, icon, disabled, onClick, history = true, historyLabel } = options; let btn = document.createElement('button'); if (id) btn.id = id; if (className) btn.className = className; if (cssText) btn.style.cssText = cssText; if (text) btn.textContent = text; if (disabled) btn.disabled = true; if (icon || btn.classList.contains('jpx-delete-button')) { btn.setAttribute('aria-label', text || t('delete')); btn.title = text || t('delete'); btn.replaceChildren(createSettingsIcon(icon || 'delete')); } container.appendChild(btn); if (onClick) { btn.addEventListener('click', (e) => { let invoke = () => onClick(btn, e); let result = settingsEditHistory && history !== false && btn.closest('#settings-container') ? settingsEditHistory.run(historyLabel || btn.getAttribute('aria-label') || btn.textContent || 'Configuration', invoke) : invoke(); const handleTempText = (tempText) => { if (!tempText) return; let originalText = btn.textContent; btn.style.width = btn.offsetWidth + 'px'; btn.textContent = tempText; btn.disabled = true; setTimeout(() => { // Switching sections may already have replaced the button's caption. if (btn.textContent === tempText) btn.textContent = originalText; btn.style.width = ''; btn.disabled = false; }, 1500); }; if (result instanceof Promise) result.then(handleTempText).catch(handleTempText); else handleTempText(result); }); } return btn; }; ns.createToast = function(content, duration = 3000, styleName, targetDocument = document) { const targetWindow = targetDocument.defaultView; let container = targetDocument.getElementById('toast-container'); if (!container) { container = targetDocument.createElement('div'); container.id = 'toast-container'; container.style.cssText = 'position: fixed; right: 16px; bottom: 16px; display: flex; flex-direction: column-reverse; gap: 8px; z-index: 99999;'; targetDocument.body.appendChild(container); } let toast = targetDocument.createElement('div'); toast.textContent = content; toast.style.cssText = 'padding: 10px 14px; background: #333; color: #fff; font-size: 14px; cursor: pointer; opacity: 0; transition: opacity .2s;'; if (styleName) toast.className = styleName; container.appendChild(toast); targetWindow.requestAnimationFrame(() => toast.style.opacity = '1'); const close = () => { toast.style.opacity = '0'; targetWindow.setTimeout(() => toast.remove(), 200); }; toast.addEventListener('pointerdown', close); targetWindow.setTimeout(close, duration); return toast; }; ns.stringifyLimited = function(obj, maxPrettyLevel = 3) { function helper(value, level) { if (!value || typeof value !== 'object' || !(level < maxPrettyLevel)) return JSON.stringify(value); const isArray = Array.isArray(value), indent = '\t'.repeat(level + 1); const entries = isArray ? value.map(item => indent + helper(item, level + 1)) : Object.entries(value).map(([key, item]) => indent + JSON.stringify(key) + ': ' + helper(item, level + 1)); return (isArray ? '[' : '{') + '\n' + entries.join(',\n') + '\n' + '\t'.repeat(level) + (isArray ? ']' : '}'); } return helper(obj, 0); }; ns.toRegExp = function(input) { let match = input.match(/^\/(.*?)\/([dgimsuvy]*)$/); if (match) { let [, pattern, flags] = match; try { return new RegExp(pattern, flags); } catch (e) { console.error('Invalid regex syntax:', e.message); return null; } } return new RegExp(input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i'); }; ns.keyCaptureController = null; ns.captureKeyCombo = function(onComplete, onAbort) { if (ns.keyCaptureController) ns.keyCaptureController.abort(); let currentController = new AbortController(); ns.keyCaptureController = currentController; let signal = currentController.signal; const history = settingsEditHistory; window.addEventListener('keydown', (e) => { e.preventDefault(); if (e.key === 'Escape') { currentController.abort(); return; } if (['Control', 'Alt', 'Shift', 'Meta'].includes(e.key)) return; let result = { key: e.key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, comboString: '', }; result.comboString = ns.formatKeyCombo(result, '+'); currentController.abort(); if (onComplete) { if (history && history === settingsEditHistory) history.run(t('cGen.shortcutConfig'), () => onComplete(result)); else onComplete(result); } }, { signal }); window.addEventListener('pointerdown', () => { currentController.abort(); }, { signal, once: true }); signal.addEventListener('abort', () => { if (ns.keyCaptureController === currentController) ns.keyCaptureController = null; if (onAbort) onAbort(); }); }; ns.formatKeyCombo = function(input, separator = '+') { if (input == null) return 'Unassigned'; let key, ctrl, alt, shift; if (typeof input === 'string') { let pureKey = input.startsWith('kb_') ? input.slice(3) : input; let isPlusKey = pureKey === '+' || pureKey.endsWith('++'); let parts = pureKey.split('+'); key = isPlusKey ? '+' : parts.pop(); ctrl = parts.includes('Ctrl'); alt = parts.includes('Alt'); shift = parts.includes('Shift'); } else { ({ key, ctrl, alt, shift } = input); } let result = []; if (ctrl) result.push('Ctrl'); if (alt) result.push('Alt'); if (shift) result.push('Shift'); result.push(key === ' ' ? 'SPACE' : key.toUpperCase()); return result.join(separator); }; const HVClasses = { '2a': '.', '2b': ',', '2c': '!', '2d': '?', '2e': '%', '2f': '+', '2g': '-', '2h': '=', '2i': '/', '2j': '\\', '2k': "'", '2l': '"', '2m': ':', '2n': ';', '2o': '(', '2p': ')', '2q': '[', '2r': ']', '2s': '_', '39': ' ', }; ns.parseHVClasses = function (container, preserveSmallWords = false){ let content = Array.from(container?.children, div => HVClasses[div.className.slice(-2)] ?? div.className.slice(-1)) .join('') .toLowerCase() .split(' ') .map(word => word ? word.charAt(0).toUpperCase() + word.slice(1) : word) .join(' '); if (preserveSmallWords) { content = content.replace(/(? match.toLowerCase()); } return content; }; ns.createTimeRecords = function() { return { action: 0, turn: 0, riddle: { lastTurn: -1, solved: 0, total: 0 }, lastUse: {} }; }; ns.createCombatRecords = function() { return { use: {}, physicalDealt: { glance:0, hit:0, crit:0, miss:0, evade:0, parryPartially:0, parry:0 }, magicalDealt: { glance:0, hit:0, crit:0, miss:0, evade:0, resist50:0, resist75:0, resist90:0, resistPartially:0, resist:0 }, physicalTaken: { glance:0, hit:0, crit:0, miss:0, evade:0, parryPartially:0, parry:0, blockPartially:0, block:0 }, magicalTaken: { glance:0, hit:0, crit:0, miss:0, evade:0, resist50:0, resist75:0, resist90:0, resistPartially:0, resist:0, blockPartially:0, block:0 }, }; }; ns.createRevenueRecords = function() { return { exp: 0, credit: 0, proficiency: {}, equipment: {}, material: {}, consumable: {}, token: {}, food: {}, figurine: {}, artifact: {}, trophy: {}, crystal: {}, staminaCost: 0, totalProfit: 0, finalProfit: 0, }; }; ns.xhrGet = async function(urlArray, interval = 250) { const promises = urlArray.map((url, index) => new Promise((resolve, reject) => { setTimeout(() => { let xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onload = () => { if (xhr.status === 200) { resolve({ url: url, responseText: xhr.responseText, }); } else { reject('Failed to load: ' + url); } }; xhr.onerror = () => { reject('XHR error for URL: ' + url); }; xhr.send(); }, index * interval); })); return Promise.allSettled(promises); }; ns._init = true; return ns; } // BEGIN JPX CONFIG MANAGEMENT (tools/build-config-manager.cjs) I18N.cM = {"name":"Configs","mine":"My configs","store":"Store","new":"New","import":"Import","search":"Search configs","apply":"Apply","edit":"Edit","more":"More","inUse":"In use","updateApply":"Update & apply","settings":"Config settings","duplicate":"Duplicate","export":"Export","share":"Share","delete":"Delete","title":"Name","style":"Style","element":"Element","world":"World","scenario":"Battle","auto":"Auto","anyWorld":"Both worlds","create":"Create","cancel":"Cancel","back":"Back","save":"Save","undo":"Undo","redo":"Redo","saveChanges":"Save changes?","keepEditing":"Keep editing","discard":"Discard","deleteConfirm":"Delete this config?","empty":"No configs yet.","noMatches":"No matching configs.","copySuffix":"copy","chooseGroup":"Choose rules to edit","allBattle":"All battle settings","stats":"Stats","applyScope":"Apply this config?","applyAll":"Updates only the settings and rules included in this config.","applyWorld":"Apply in","applyPaused":"Applied. Auto-battle is paused.","applied":"Applied.","saved":"Saved.","reset":"Reset rules","resetConfirm":"Replace this group's rules with the defaults?","imported":"Added to My configs.","savedFromStore":"Saved to My configs.","sourceExists":"You already saved this config.","updateCopy":"Update saved copy","keepCopy":"Save another copy","invalidConfig":"This config cannot be read.","unsupportedVersion":"This config version is not supported.","storageCorrupt":"Could not read your saved configs. Your data is unchanged.","storageError":"Could not save. Check browser storage and try again.","tooLarge":"This config is too large.","notFound":"This config no longer exists.","appliedConfig":"Apply another config before deleting this one.","migrationConflict":"This config conflicts with saved data.","error":"Could not complete this action.","groupCount":"${count} rule groups","rename":"Rename","current":"Current settings","close":"Close","fire":"Fire","cold":"Cold","wind":"Wind","elec":"Lightning","holy":"Holy","dark":"Dark","restore":"Undo delete","deleted":"Config deleted.","refresh":"Refresh","worldMismatch":"This config is for another world.","description":"Description","editor":"Rule editor","customCode":"This config contains custom code. Apply it only if you trust its source.","recovery":"Import backup","importWorld":"Save config","statsEdit":"Edit stats","preserveModes":"Rules","applyCurrent":"Apply here","libraryChanged":"This config was changed in another tab. Reopen it before saving.","unsupportedRule":"Unsupported rule (kept unchanged)","currentStyle":"Current style","filters":"Filters","allWorlds":"All worlds","allStyles":"All styles","allBattles":"All battles","allTypes":"All types","type":"Type","singleMode":"Battle mode","clearFilters":"Clear filters","sort":"Sort","latest":"Updated","nameSort":"Name","typeSort":"By type","manualSort":"Manual","multiStyle":"Mixed styles","multiBattle":"Multiple battles","resultCount":"${count} found","exportCurrent":"In use","exportAll":"Full config","exportChoose":"Choose rules","exportUnknown":"No active rules detected yet.","bind":"Link loadout","unbind":"Unlink","persona":"Persona","equipSet":"Equipment set","personaNumber":"Persona ${id}","setNumber":"Set ${id}","replaceBinding":"Link this loadout here instead of “${name}”?","bound":"Loadout linked.","bindingUnknown":"Could not read your persona and equipment set. Reload outside battle and try again.","bindingUnavailable":"No saved persona or equipment set. Try again outside battle.","importReading":"Reading “${name}”…","importReady":"Ready to import. Check the name and world, then save to My configs. It will not apply automatically.","importDraft":"Loaded “${name}” for review. Save to keep these changes.","importPaused":"Auto-battle is paused.","importAdded":"“${name}” is in My configs. Choose Apply to use it.","importFailed":"Could not import “${name}”. ${reason}","importReadError":"Could not read the file. Select it again and retry.","importCancelled":"Import cancelled. Custom code was not approved.","fixedMode":"Fixed rules","automaticMode":"Auto by battle","restoreAutomatic":"Switch to auto","detach":"Remove links","detachDelete":"Unlink and delete","detached":"Links removed.","detachHint":"Removes this config from auto-selection, loadout links and past applications. Your current settings stay unchanged.","sceneAssignments":"Battle strategies","inheritGeneral":"Use General rules","unassigned":"None selected","noSceneRules":"Paused: no rules for this battle and no General rules.","assign":"Assign","assigned":"Assigned","executing":"Current strategy","assignmentOlder":"This strategy is still using the previous version.","grindfest":"Grindfest","fixedHint":"Uses these rules for every battle in this world, even after reloading."}; I18N.cShared = {"title":"Shared site data","backupSection":"Settings before sharing","historySection":"Previous shared settings","quotaShort":"Stamina used before sharing","restoreAction":"Restore","scope":"The main and alt sites share settings, records and daily stamina within this userscript. Persistent and Isekai stay separate. Sharing starts with the first site's settings. Both sites' old settings are backed up below.","backup":"Download original settings","restore":"Restore this site's old settings","confirm":"Use this backup on both sites? You can restore the current settings later. Auto-battle will pause.","history":"Download earlier settings","restoreRevision":"Choose an earlier backup","quota":"Stamina used today before sharing (UTC)","quotaHelp":"To avoid counting battles twice, we keep the larger of the two old totals. Open both sites once, then adjust today's earlier usage here if needed. New battles count separately.","save":"Save","saved":"Saved","resetScope":"Also deletes shared settings and records on the main and alt sites, for both worlds.","fail":"Could not save shared data. Your original data is kept."}; const JPX_CONFIG_MANAGER_CSS = "#settings-container #panel_configManager{overflow:hidden;padding:0;min-width:0;min-height:0}\n#settings-container .jpx-export-dialog{box-sizing:border-box;width:min(520px,calc(100vw - 24px));max-height:min(640px,calc(100dvh - 32px));padding:20px;border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:4px;background:var(--jpx-theme-surface,#f9f6ec);color:var(--jpx-theme-text,#392d25);font:13px/1.45 Arial,Helvetica,sans-serif;text-align:left;box-shadow:0 12px 40px #0004;overflow:hidden}\n#settings-container .jpx-export-dialog[open]{display:flex;flex-direction:column;gap:16px}\n#settings-container .jpx-export-dialog::backdrop{background:#0006}\n#settings-container .jpx-export-dialog h3{margin:0;font-size:16px}\n#settings-container .jpx-export-dialog .jpx-rule-section-tabs{flex:none;border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-export-summary{margin:0;padding:4px 0;overflow-wrap:anywhere}\n#settings-container .jpx-export-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}\n#settings-container .jpx-export-fields label{display:grid;min-width:0;gap:6px}\n#settings-container .jpx-export-fields select{width:100%;min-width:0;min-height:32px;margin:0;font:inherit}\n#settings-container .jpx-export-dialog .jpx-export-submit{background:var(--jpx-theme-selected,#ead8b4);border-color:var(--jpx-theme-accent,#5c0d11);color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-export-footer{display:flex;flex:none;align-items:center;justify-content:flex-end;gap:8px}\n#settings-container .jpx-export-dialog button{font:inherit;white-space:nowrap}\n#settings-container.jpx-settings-mobile .jpx-export-dialog{padding:12px;gap:12px;margin:0;inset:auto;left:calc(var(--settings-left) + var(--settings-width)*var(--settings-scale)/2);top:calc(var(--settings-top) + var(--settings-height)*var(--settings-scale)/2);width:min(520px,calc(var(--settings-width) - 24px));max-height:min(640px,calc(var(--settings-height) - 32px));transform:translate(-50%,-50%) scale(var(--settings-scale));transform-origin:center;overflow:auto}\n#settings-container.jpx-settings-mobile .jpx-export-dialog :is(button,select){min-height:56px}\n#settings-container .jpx-config-manager{display:flex;flex:1;flex-direction:column;min-width:0;min-height:0;gap:0;text-align:left;color:var(--jpx-theme-text,#392d25);font:13px/1.45 Arial,Helvetica,sans-serif;position:relative}\n#settings-container .jpx-config-manager *{box-sizing:border-box}\n#settings-container :is(.jpx-export-dialog,.jpx-config-manager) [hidden]{display:none!important}\n#settings-container :where(.jpx-config-manager) button{font:inherit;font-weight:400;line-height:1.35;min-height:32px;margin:0;padding:5px 12px;border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:2px;color:var(--jpx-theme-accent,#5c0d11);background:var(--jpx-theme-surface,#f9f6ec);cursor:pointer;white-space:nowrap}\n#settings-container :where(.jpx-config-manager) button:hover{background:var(--jpx-theme-hover,#f1e2c5)}\n#settings-container :where(.jpx-config-manager) button:disabled{cursor:default;opacity:.5}\n#settings-container :where(.jpx-config-manager) button[aria-pressed=true],#settings-container .jpx-config-manager .jpx-config-primary{background:var(--jpx-theme-selected,#ead8b4);border-color:var(--jpx-theme-accent,#5c0d11);color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container :where(.jpx-config-manager) :is(input,select,textarea){font:inherit;min-width:0;max-width:100%;color:var(--jpx-theme-text,#392d25);background:var(--jpx-theme-field,#fffdf7);border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:2px;padding:6px 8px}\n#settings-container .jpx-config-manager :is(button,input,select,textarea,a):focus-visible{outline:1px solid var(--jpx-theme-accent,#5c0d11);outline-offset:-1px}\n#settings-container .jpx-config-toolbar,#settings-container .jpx-config-editor-header{display:flex;align-items:center;gap:10px;flex:none;padding:12px 16px;border-bottom:1px solid var(--jpx-theme-border,#c8b49b);min-width:0}\n#settings-container .jpx-config-nav,#settings-container .jpx-config-actions{display:flex;align-items:center;gap:8px;flex:none}\n#settings-container .jpx-config-manager .jpx-config-toolbar input{margin:0;width:220px;flex:1;max-width:280px;min-height:32px}\n#settings-container .jpx-config-toolbar>.jpx-config-actions{margin-left:auto}\n#settings-container .jpx-config-manager :is(.jpx-config-nav,.jpx-rule-section-tabs,.jpx-store-navigation){gap:0}\n#settings-container .jpx-config-manager :is(.jpx-config-nav,.jpx-rule-section-tabs,.jpx-store-navigation)>button{padding:6px 12px 7px;border:0;border-bottom:2px solid transparent;border-radius:0;background:transparent;color:var(--jpx-theme-muted,#71634f)}\n#settings-container .jpx-config-manager :is(.jpx-config-nav,.jpx-rule-section-tabs,.jpx-store-navigation)>button:hover{background:transparent;color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-config-manager :is(.jpx-config-nav,.jpx-rule-section-tabs,.jpx-store-navigation)>button[aria-pressed=true]{border-color:transparent;border-bottom-color:var(--jpx-theme-accent,#5c0d11);background:transparent;color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-config-body{min-width:0;min-height:0;flex:1;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;padding:4px 16px 16px}\n#settings-container .jpx-config-row{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:8px 16px;padding:14px 0;border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-config-row[data-active=true]{border-left:3px solid var(--jpx-theme-accent,#5c0d11);padding-left:12px}\n#settings-container .jpx-config-info{min-width:0}\n#settings-container .jpx-config-title{display:flex;align-items:baseline;gap:10px;min-width:0}\n#settings-container .jpx-config-title strong{font-size:14px;font-weight:600;overflow-wrap:anywhere}\n#settings-container .jpx-config-status{font-size:12px;white-space:nowrap;color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-config-detected{font-size:12px;white-space:nowrap;color:var(--jpx-theme-muted,#71634f)}\n#settings-container .jpx-config-tags{display:flex;align-items:center;flex-wrap:wrap;gap:4px;margin-top:6px}\n#settings-container .jpx-config-manager .jpx-config-tags .jpx-config-tag{display:inline-flex;align-items:center;min-height:20px;margin:0;padding:1px 6px;border:0;border-radius:3px;font:500 11px/18px Arial,Helvetica,sans-serif;white-space:normal;text-align:left;color:var(--jpx-tag-fg,#584b3d);background:var(--jpx-tag-bg,#e3dbcb)}\n#settings-container .jpx-config-tag{--jpx-tag-hue:35;--jpx-tag-saturation:16%;--jpx-tag-bg:hsl(var(--jpx-tag-hue) var(--jpx-tag-saturation) 86%);--jpx-tag-fg:hsl(var(--jpx-tag-hue) var(--jpx-tag-saturation) 25%)}\n/* Stable rule identifiers keep colors identical across lists and languages. */\n#settings-container .jpx-config-tag[data-tag-kind=style]{--jpx-tag-saturation:48%}\n#settings-container .jpx-config-tag[data-tag-value=OneHanded]{--jpx-tag-hue:140}\n#settings-container .jpx-config-tag[data-tag-value=\"1H_Mage\"]{--jpx-tag-hue:175}\n#settings-container .jpx-config-tag[data-tag-value=TwoHanded]{--jpx-tag-hue:20}\n#settings-container .jpx-config-tag[data-tag-value=\"2H_Mage\"]{--jpx-tag-hue:350}\n#settings-container .jpx-config-tag[data-tag-value=DualWielding]{--jpx-tag-hue:210}\n#settings-container .jpx-config-tag[data-tag-value=DW_Mage]{--jpx-tag-hue:245}\n#settings-container .jpx-config-tag[data-tag-value=NitenIchiryu]{--jpx-tag-hue:45}\n#settings-container .jpx-config-tag[data-tag-value=NI_Mage]{--jpx-tag-hue:80}\n#settings-container .jpx-config-tag[data-tag-value=Staff]{--jpx-tag-hue:280}\n#settings-container .jpx-config-tag[data-tag-value=Unarmed]{--jpx-tag-hue:30;--jpx-tag-saturation:20%}\n#settings-container .jpx-config-tag[data-tag-value=mixed]{--jpx-tag-hue:215;--jpx-tag-saturation:16%}\n#settings-container .jpx-config-tag[data-tag-kind=world]{--jpx-tag-saturation:40%}\n#settings-container .jpx-config-tag[data-tag-value=Persistent]{--jpx-tag-hue:38}\n#settings-container .jpx-config-tag[data-tag-value=Isekai]{--jpx-tag-hue:265}\n#settings-container .jpx-config-tag[data-tag-value=Any]{--jpx-tag-hue:215;--jpx-tag-saturation:14%}\n#settings-container .jpx-config-tag[data-tag-kind=scenario]{--jpx-tag-saturation:32%}\n#settings-container .jpx-config-tag[data-tag-value=Arena]{--jpx-tag-hue:210}\n#settings-container .jpx-config-tag[data-tag-value=Encounter]{--jpx-tag-hue:145}\n#settings-container .jpx-config-tag[data-tag-value=Colosseum]{--jpx-tag-hue:355}\n#settings-container .jpx-config-tag[data-tag-value=Battle1000]{--jpx-tag-hue:28}\n#settings-container .jpx-config-tag[data-tag-value=Item]{--jpx-tag-hue:175}\n#settings-container .jpx-config-tag[data-tag-value=Tower]{--jpx-tag-hue:275}\n#settings-container .jpx-config-tag[data-tag-value=General]{--jpx-tag-hue:215;--jpx-tag-saturation:14%}\n#settings-container .jpx-config-tag[data-tag-kind=kind]{--jpx-tag-saturation:30%}\n#settings-container .jpx-config-tag[data-tag-value=stats]{--jpx-tag-hue:190}\n#settings-container .jpx-config-tag[data-tag-value=battle]{--jpx-tag-hue:30}\n#settings-container .jpx-config-tag[data-tag-kind=element]{--jpx-tag-saturation:55%}\n#settings-container .jpx-config-tag[data-tag-value=fire]{--jpx-tag-hue:8}\n#settings-container .jpx-config-tag[data-tag-value=cold]{--jpx-tag-hue:200}\n#settings-container .jpx-config-tag[data-tag-value=wind]{--jpx-tag-hue:150}\n#settings-container .jpx-config-tag[data-tag-value=elec]{--jpx-tag-hue:250}\n#settings-container .jpx-config-tag[data-tag-value=holy]{--jpx-tag-hue:45}\n#settings-container .jpx-config-tag[data-tag-value=dark]{--jpx-tag-hue:285}\n#settings-container .jpx-config-tags button.jpx-config-tag:hover{box-shadow:inset 0 0 0 1px currentColor;background:var(--jpx-tag-bg,#e3dbcb)}\nhtml[data-jpx-theme=dark] #settings-container .jpx-config-tag{--jpx-tag-bg:hsl(var(--jpx-tag-hue) var(--jpx-tag-saturation) 21%);--jpx-tag-fg:hsl(var(--jpx-tag-hue) var(--jpx-tag-saturation) 82%)}\n#settings-container .jpx-config-title .jpx-config-grip{display:inline-flex;flex:none;align-items:center;justify-content:center;width:24px;min-height:28px;padding:2px;border:0;background:transparent;color:var(--jpx-theme-muted,#756753);cursor:grab;touch-action:none}\n#settings-container .jpx-config-grip svg{width:16px;height:18px}\n#settings-container .jpx-config-row.is-dragging{opacity:.35}\n#settings-container .jpx-config-drag-preview{display:flex;align-items:center;gap:8px;min-height:40px;padding:8px 12px;background:var(--jpx-theme-surface,#f9f6ec);color:var(--jpx-theme-text,#392d25);box-shadow:inset 0 0 0 1px var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-config-drag-preview>svg{width:16px;height:18px;flex:none;color:var(--jpx-theme-muted,#756753)}\n#settings-container .jpx-config-drag-preview>strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600}\n#settings-container .jpx-config-manager .jpx-stats-drop-marker{background:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-config-manager .jpx-stats-drop-marker.over-preview{background:transparent;border-color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-config-actions .jpx-config-more{width:32px;padding:4px}\n#settings-container .jpx-config-more svg{display:block;width:18px;height:18px;margin:auto}\n#settings-container .jpx-config-notice{position:absolute;z-index:10;bottom:12px;left:50%;transform:translateX(-50%);max-width:calc(100% - 32px);width:max-content;margin:0;padding:8px 14px;border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:2px;box-shadow:0 3px 12px #0002;background:var(--jpx-theme-selected,#ead8b4);color:var(--jpx-theme-text,#392d25)}\n#settings-container .jpx-config-notice:empty{display:none}\n#settings-container .jpx-import-feedback{display:flex;flex:none;align-items:flex-start;gap:12px;margin:8px 16px;padding:10px 12px;max-height:30%;overflow:auto;border:1px solid var(--jpx-theme-border,#c8b49b);border-left:3px solid var(--jpx-theme-accent,#5c0d11);background:var(--jpx-theme-selected,#ead8b4);color:var(--jpx-theme-text,#392d25);font:13px/1.5 Arial,Helvetica,sans-serif;text-align:left;box-sizing:border-box}\n#settings-container .jpx-import-feedback[hidden]{display:none}\n#settings-container .jpx-import-feedback p{flex:1;min-width:0;margin:0;white-space:pre-line;overflow-wrap:anywhere}\n#settings-container .jpx-import-feedback button{flex:none;min-width:32px;min-height:32px;margin:0;padding:0 6px;border:1px solid var(--jpx-theme-border,#c8b49b);background:var(--jpx-theme-surface,#f9f6ec);color:inherit;font:20px/1 Arial,Helvetica,sans-serif;cursor:pointer}\n#settings-container .jpx-import-feedback button:focus-visible{outline:2px solid var(--jpx-theme-accent,#5c0d11);outline-offset:2px}\n#settings-container.jpx-settings-mobile .jpx-import-feedback{margin:8px 12px;padding:8px;gap:8px}\n#settings-container.jpx-settings-mobile .jpx-import-feedback button{min-width:44px;min-height:44px}\n#settings-container .jpx-config-editor-header strong{flex:1;font-size:15px;min-width:0;overflow-wrap:anywhere}\n#settings-container .jpx-config-editor{display:flex;flex:1;flex-direction:column;min-width:0;min-height:0;overflow:hidden}\n#settings-container .jpx-config-editor-content{display:flex;flex:1;flex-direction:column;min-width:0;min-height:0;padding:10px 16px 0}\n#settings-container .jpx-config-editor-content>.jpx-rule-sections{flex:1;min-height:0;overflow:hidden}\n#settings-container .jpx-config-editor-footer{display:flex;gap:8px;flex:none;padding:10px 16px;border-top:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-config-editor-footer>.jpx-config-primary{margin-left:auto}\n#settings-container .jpx-config-menu{position:fixed;inset:auto;margin:0;min-width:140px;max-width:calc(100vw - 24px);padding:5px;border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:2px;background:var(--jpx-theme-surface,#f9f6ec);color:var(--jpx-theme-text,#392d25);box-shadow:0 5px 20px #0002;overflow-y:auto;overscroll-behavior:contain}\n#settings-container .jpx-config-menu button{display:block;width:100%;border:0;text-align:left;background:transparent}\n#settings-container .jpx-config-form{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;gap:16px;max-width:600px;padding-top:16px}\n#settings-container .jpx-config-form label{display:flex;flex-direction:column;align-items:stretch;gap:5px;min-width:0}\n#settings-container .jpx-config-form .jpx-config-wide{grid-column:1/-1}\n#settings-container .jpx-config-form .jpx-config-actions{justify-content:flex-end}\n#settings-container .jpx-config-group{display:flex;width:100%;justify-content:space-between;margin-top:8px!important;padding:12px!important;text-align:left}\n#settings-container .jpx-config-manager .jpx-store{padding:12px 16px;min-height:0;overflow:hidden}\n#settings-container .jpx-config-manager .jpx-store .jpx-store-title{min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere}\n#settings-container .jpx-config-manager .jpx-store :is(button,input,select,textarea,.jpx-store-link){border-radius:2px}\n#settings-container .jpx-config-toolbar{min-height:49px;padding-block:8px}\n#settings-container .jpx-config-manager select:not([multiple]){align-items:center;white-space:nowrap}\n#settings-container .jpx-config-store-header{flex-wrap:wrap}\n#settings-container .jpx-config-manager .jpx-config-toolbar>.jpx-store-toolbar{flex:none;align-self:stretch;flex-wrap:nowrap;gap:8px;margin-left:auto;padding:0;border:0}\n#settings-container .jpx-config-manager .jpx-config-toolbar>.jpx-store-querybar{flex:1;min-width:140px;max-width:280px;margin:0;flex-wrap:nowrap}\n#settings-container .jpx-config-manager .jpx-config-toolbar>.jpx-store-querybar input{min-width:0;max-width:none;margin:0}\n#settings-container .jpx-config-manager .jpx-config-toolbar .jpx-store-account button{max-width:140px;overflow:hidden;text-overflow:ellipsis}\n#settings-container .jpx-config-manager .jpx-store-browse-header{display:flex;flex-wrap:wrap;align-items:center}\n#settings-container .jpx-config-manager .jpx-store-browse-header>.jpx-store-filter-grid{flex:1;min-width:min(400px,100%)}\n#settings-container .jpx-config-manager .jpx-store-browse-header>.jpx-store-results select{max-width:none}\n#settings-container .jpx-config-manager .jpx-store-refresh{display:inline-flex;align-items:center;justify-content:center;width:32px;padding:0}\n#settings-container .jpx-config-manager .jpx-store-refresh[aria-busy=true] svg{animation:jpx-config-refresh 900ms linear infinite}\n@keyframes jpx-config-refresh{to{transform:rotate(360deg)}}\n@media(prefers-reduced-motion:reduce){#settings-container .jpx-config-manager .jpx-store-refresh[aria-busy=true] svg{animation:none}}\n#settings-container .jpx-config-manager .jpx-store-view-header{gap:8px}\n#settings-container .jpx-config-manager .jpx-store.jpx-store-browsing{padding:0;gap:0}\n#settings-container .jpx-config-manager .jpx-store-browsing>.jpx-store-stage{padding:4px 16px 16px;scrollbar-gutter:stable}\n#settings-container .jpx-config-manager .jpx-store-browsing .jpx-store-list{border-top:0}\n#settings-container .jpx-config-list-header{flex:none;min-width:0;padding:8px 16px;border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-config-manager .jpx-config-list-header :is(select,button){height:32px;min-height:32px;font:inherit;margin:0}\n#settings-container:not(.jpx-settings-mobile) .jpx-config-manager>.jpx-config-list-header .jpx-store-results::after{content:\"\";flex:none;width:32px}\n#settings-container .jpx-config-manager .jpx-store-querybar{display:flex;flex-wrap:wrap;align-items:center;gap:8px;min-width:0}\n#settings-container .jpx-config-manager .jpx-store-querybar input{flex:1;width:0}\n#settings-container .jpx-config-manager .jpx-store-querybar button{flex:none;white-space:nowrap}\n#settings-container .jpx-config-manager .jpx-store-filter-toggle{display:none}\n#settings-container .jpx-config-manager .jpx-store-filter-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;min-width:0}\n#settings-container .jpx-config-manager .jpx-store-filter-grid select{width:100%;max-width:100%}\n#settings-container .jpx-config-manager .jpx-store-results{display:flex;align-items:center;gap:8px;min-width:0}\n#settings-container .jpx-config-manager .jpx-store-result-count{min-width:5em;color:var(--jpx-theme-muted,#71634f);font-size:12px;white-space:nowrap}\n#settings-container .jpx-config-manager .jpx-store-results select{margin-left:auto;width:7em;max-width:50%;field-sizing:fixed}\n#settings-container .jpx-config-manager .jpx-store-querybar>.jpx-store-results{flex:none}\n#settings-container .jpx-config-manager .jpx-store-querybar>.jpx-store-results select{margin:0;max-width:none}\n#settings-container:not(.jpx-settings-mobile) .jpx-config-manager .jpx-store-querybar input{min-width:140px}\n#settings-container .jpx-config-manager .jpx-store-clear{border-color:transparent;background:transparent;padding-inline:5px}\n#settings-container .jpx-config-manager .jpx-store-date{color:var(--jpx-theme-muted,#71634f);font-size:12px;white-space:nowrap;align-self:center}\n#settings-container .jpx-config-manager .jpx-store-row[data-store-id]>p{grid-column:1}\n#settings-container .jpx-store-row>.jpx-config-tags{grid-column:1/-1;margin-top:0}\n#settings-container .jpx-store-row[data-store-id]>.jpx-config-tags{grid-column:1}\n#settings-container .jpx-config-tag-author{color:var(--jpx-theme-muted,#71634f);font-size:12px;margin-right:4px;overflow-wrap:anywhere;min-width:0}\n#settings-container .jpx-config-manager .jpx-store-row-tools{display:flex;flex-direction:column;align-items:center;justify-content:space-between;gap:4px;grid-column:2;grid-row:1/span 4;align-self:stretch}\n#settings-container .jpx-config-manager .jpx-store-download{display:inline-flex;align-items:center;justify-content:center;flex:none;width:32px;padding:0}\n#settings-container .jpx-config-manager .jpx-store-show-more{justify-self:center;margin-top:12px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-filter-toggle{display:inline-flex;align-items:center}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-filter-grid{grid-template-columns:repeat(2,minmax(0,1fr))}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-filter-grid select{min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-filter-grid[data-open=false]{display:none}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-filter-grid[data-open=true]{animation:jpx-settings-reveal var(--jpx-motion-fast,120ms) ease-out}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-results{gap:6px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-results select{width:auto}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store .jpx-store-view-header :is(input,select){min-height:44px}\n#settings-container .jpx-config-empty{padding:24px 0;color:var(--jpx-theme-muted,#756753);text-align:center}\n#settings-container .jpx-config-overlay{position:absolute;inset:0;z-index:20;display:grid;place-items:center;background:#0006;padding:16px}\n#settings-container .jpx-config-confirm{width:min(440px,100%);border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:0;padding:20px;background:var(--jpx-theme-surface,#f9f6ec);color:var(--jpx-theme-text,#392d25);box-shadow:0 12px 40px #0004}\n#settings-container .jpx-config-confirm h3{margin:0 0 16px;font-size:16px}\n#settings-container .jpx-config-confirm p{margin:0 0 16px}\n#settings-container .jpx-config-confirm .jpx-config-actions{justify-content:flex-end;flex-wrap:wrap}\n#settings-container .jpx-config-confirm label{display:flex;gap:12px;align-items:center;margin-bottom:16px}\n#settings-container .jpx-config-confirm:has(.jpx-config-bindings){max-height:100%;overflow:auto}\n#settings-container .jpx-config-binding-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin-bottom:16px}\n#settings-container .jpx-config-binding-fields label{display:grid;gap:6px;margin:0;min-width:0}\n#settings-container .jpx-config-binding-fields label:first-child{grid-column:1/-1}\n#settings-container .jpx-config-binding-fields select{width:100%;margin:0}\n#settings-container .jpx-config-binding-item{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-config-binding-item span{min-width:0;overflow-wrap:anywhere}\n#settings-container .jpx-config-binding-list:not(:empty){margin-bottom:16px}\n#settings-container .jpx-config-info .jpx-config-binding{display:block;max-width:100%;min-height:28px;padding:3px 0;margin-top:4px;border:0;background:transparent;color:var(--jpx-theme-muted,#71634f);font-size:12px;text-align:left;white-space:normal;overflow-wrap:anywhere}\n#settings-container .jpx-config-info .jpx-config-binding:hover{color:var(--jpx-theme-accent,#5c0d11);text-decoration:underline}\n#settings-container .jpx-config-rename{margin-bottom:16px}\n#settings-container .jpx-config-rename input{width:100%}\n#settings-container.jpx-settings-mobile .jpx-config-toolbar{padding:10px 12px;gap:8px;flex-wrap:wrap}\n#settings-container.jpx-settings-mobile .jpx-config-toolbar :is(.jpx-config-nav,.jpx-store-navigation){border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container.jpx-settings-mobile .jpx-config-toolbar>.jpx-config-actions{margin-left:auto}\n#settings-container.jpx-settings-mobile .jpx-config-toolbar>input{order:3;max-width:none;width:100%;flex-basis:100%;margin:0}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-config-toolbar>.jpx-store-querybar{flex-basis:100%;max-width:none;margin:0}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-config-toolbar:not(.jpx-config-store-header)>.jpx-store-querybar{order:3}\n#settings-container.jpx-settings-mobile .jpx-config-list-header{padding:8px 12px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-config-list-header :is(select,button){min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-config-rename input{min-height:32px}\n#settings-container.jpx-settings-mobile .jpx-config-confirm{padding:12px}\n#settings-container.jpx-settings-mobile .jpx-config-confirm>:is(h3,p,label),#settings-container.jpx-settings-mobile .jpx-config-rename{margin-bottom:12px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-browsing>.jpx-store-stage{padding:0 12px 12px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-querybar input{min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-config-manager :is(.jpx-store-refresh,.jpx-store-download){width:44px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-config-toolbar>.jpx-store-toolbar{margin-left:auto;gap:6px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-config-toolbar .jpx-store-account button{max-width:100px}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-browse-header{display:grid}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store-browse-header>.jpx-store-filter-grid{min-width:0}\n#settings-container.jpx-settings-mobile .jpx-config-manager button:where(:not(.jpx-config-stats-editor *)){min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-config-manager :is(.jpx-config-nav,.jpx-rule-section-tabs,.jpx-store-navigation)>button{padding-inline:8px}\n#settings-container.jpx-settings-mobile .jpx-config-row{padding:12px 0;gap:8px}\n#settings-container.jpx-settings-mobile .jpx-config-row[data-active=true]{padding-left:8px}\n#settings-container.jpx-settings-mobile .jpx-config-row .jpx-config-actions{gap:4px}\n#settings-container.jpx-settings-mobile .jpx-config-actions button{padding:5px 8px}\n#settings-container.jpx-settings-mobile .jpx-config-actions .jpx-config-more{width:36px}\n#settings-container.jpx-settings-mobile .jpx-config-title .jpx-config-grip{width:32px;min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-config-tags .jpx-config-tag{min-height:26px;padding:3px 7px}\n#settings-container.jpx-settings-mobile .jpx-config-body{padding:0 12px 12px}\n#settings-container.jpx-settings-mobile .jpx-config-title{flex-wrap:wrap;gap:2px 8px}\n#settings-container.jpx-settings-mobile .jpx-config-editor-header,#settings-container.jpx-settings-mobile .jpx-config-editor-footer{padding:8px 12px}\n#settings-container.jpx-settings-mobile .jpx-config-editor-content{padding:8px 10px 0}\n#settings-container.jpx-settings-mobile .jpx-config-manager :is(.jpx-config-back,.jpx-store-back){display:none}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store:not(.jpx-store-browsing){padding:10px 12px}\n@media(max-width:380px){#settings-container .jpx-config-form{gap:12px}}\n#settings-container .jpx-config-selection{display:flex;align-items:center;justify-content:space-between;gap:8px 16px;flex:none;padding:8px 16px;flex-wrap:wrap;border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-selection-summary,#settings-container .jpx-selection-actions{display:flex;align-items:center;gap:8px;min-width:0;flex-wrap:wrap}\n#settings-container .jpx-selection-summary{flex:1}.jpx-selection-name{overflow-wrap:anywhere}\n#settings-container .jpx-selection-mode{font-weight:600;color:var(--jpx-theme-text,#392d25)}\n#settings-container .jpx-selection-world{color:var(--jpx-theme-muted,#71634f)}\n#settings-container .jpx-selection-mode[data-fixed=true]{border-inline-start:3px solid var(--jpx-theme-accent,#5c0d11);padding-inline-start:8px}\n#settings-container .jpx-scenes-body{padding:16px;scroll-padding-block:16px}\n#settings-container .jpx-scene-context{gap:12px;margin:0 0 20px;max-width:none}\n#settings-container .jpx-scene-context label{margin:0}\n#settings-container .jpx-scenes-table{border:1px solid var(--jpx-theme-border,#c8b49b);border-radius:0;overflow:hidden;background:var(--jpx-theme-surface,#f9f6ec)}\n#settings-container .jpx-scene-row{position:relative;display:grid;grid-template-columns:minmax(100px,.75fr) minmax(0,2fr);align-items:center;gap:16px;padding:16px;border-bottom:1px solid var(--jpx-theme-border,#c8b49b)}\n#settings-container .jpx-scene-row:last-child{border-bottom:0}\n#settings-container .jpx-scene-row[data-general=true]{background:var(--jpx-theme-hover,#f1e2c5)}\n#settings-container .jpx-scene-row[data-executing=true]{box-shadow:inset 3px 0 var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-scene-label{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;min-width:0;cursor:pointer;margin:0}\n#settings-container .jpx-scene-label strong{font-weight:600;overflow-wrap:anywhere}\n#settings-container .jpx-scene-badge{display:inline-flex;align-items:center;gap:5px;font-size:12px;line-height:1.5;color:var(--jpx-theme-accent,#5c0d11);white-space:nowrap}\n#settings-container .jpx-scene-badge:before{content:'';width:5px;height:5px;border-radius:50%;background:currentColor;flex:none}\n#settings-container .jpx-scene-controls{display:grid;gap:8px;min-width:0}\n#settings-container .jpx-scene-controls select{width:100%;max-width:100%;min-width:0;min-height:36px;margin:0;cursor:pointer;field-sizing:fixed;text-overflow:ellipsis}\n#settings-container .jpx-scene-controls select>button{display:contents}\n#settings-container .jpx-scene-controls selectedcontent{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n#settings-container .jpx-scene-controls select::picker-icon{flex:none}\n#settings-container .jpx-scene-pending{display:flex;justify-content:flex-end;gap:8px}\n#settings-container .jpx-scene-executing{display:flex;gap:6px 12px;flex-wrap:wrap;align-items:center;margin:0 0 16px;color:var(--jpx-theme-muted,#71634f);overflow-wrap:anywhere}\n#settings-container .jpx-scene-executing strong{color:var(--jpx-theme-text,#392d25);font-weight:500}\n#settings-container :is(.jpx-scene-update,.jpx-config-assigned){font-size:12px;color:var(--jpx-theme-muted,#71634f)}\n#settings-container .jpx-scene-row :is(button,select):focus-visible,#settings-container .jpx-selection-actions button:focus-visible{outline:2px solid var(--jpx-theme-accent,#5c0d11);outline-offset:2px}\n#settings-container .jpx-scene-row button:active,#settings-container .jpx-selection-actions button:active{background:var(--jpx-theme-selected,#ead8b4)}\n#settings-container.jpx-settings-mobile .jpx-config-selection{padding:8px 12px;gap:8px}\n#settings-container.jpx-settings-mobile .jpx-scenes-body{padding:12px;font-size:inherit}\n#settings-container.jpx-settings-mobile .jpx-scene-context{gap:8px;margin-bottom:12px}\n#settings-container.jpx-settings-mobile .jpx-scene-context select,#settings-container.jpx-settings-mobile .jpx-scene-controls select,#settings-container.jpx-settings-mobile .jpx-scenes-body button{font-size:inherit;min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-scene-row{grid-template-columns:minmax(0,1fr);gap:8px;padding:10px 12px}\n#settings-container.jpx-settings-mobile .jpx-scene-label{justify-content:space-between}\n#settings-container.jpx-settings-mobile .jpx-scene-pending button{min-height:44px;min-width:72px}\n#settings-container.jpx-settings-mobile .jpx-scene-executing{font-size:13px}\n#settings-container .jpx-store-comments{margin-top:16px;padding-top:12px;border-top:1px solid var(--jpx-theme-border,#c8b49b);min-width:0;text-align:left}\n#settings-container :is(.jpx-comment-heading,.jpx-rating-heading){display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}\n#settings-container .jpx-comment-heading h4{margin:0;font-size:14px}\n#settings-container .jpx-comment-header{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}\n#settings-container .jpx-comment-byline{display:flex;align-items:baseline;flex-wrap:wrap;gap:2px 12px;min-width:0}\n#settings-container .jpx-comment-header a{overflow-wrap:anywhere;color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-comment-header time{font-size:12px;color:var(--jpx-theme-muted,#71634f)}\n#settings-container .jpx-comment-row{padding:8px 0 12px;border-bottom:1px solid var(--jpx-theme-border,#c8b49b);min-width:0}\n#settings-container .jpx-comment-row:last-child{border-bottom:0}\n#settings-container .jpx-comment-body{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6;margin:4px 0 0}\n#settings-container .jpx-comment-actions{display:flex;flex:none;justify-content:flex-end;gap:8px}\n#settings-container .jpx-comment-row[data-editing=true]>.jpx-comment-actions{margin-top:8px}\n#settings-container .jpx-comment-composer{display:grid;gap:8px;margin:8px 0 12px}\n#settings-container .jpx-comment-compose-footer{display:flex;justify-content:flex-end}\n#settings-container .jpx-store-comments textarea{display:block;box-sizing:border-box;width:100%;min-width:0;max-width:100%;min-height:68px;padding:8px;resize:vertical;line-height:1.5}\n#settings-container .jpx-comment-row textarea{margin-top:8px;min-height:100px}\n#settings-container .jpx-comment-more{margin-top:12px}\n#settings-container :is(.jpx-comment-status,.jpx-rating-status){margin:0 0 8px;overflow-wrap:anywhere;font-size:12px;line-height:1.5}\n#settings-container :is(.jpx-comment-status,.jpx-rating-status)[role=alert]{color:var(--jpx-theme-danger,#a42b26)}\n#settings-container .jpx-store-rating-summary{font-size:12px;color:var(--jpx-theme-muted,#71634f);margin:4px 0 0;display:flex;align-items:center;flex-wrap:wrap;gap:4px 16px}\n#settings-container .jpx-download-count{display:inline-flex;align-items:center;gap:4px;white-space:nowrap;font-size:12px;color:var(--jpx-theme-muted,#71634f)}\n#settings-container .jpx-download-count svg{flex:none}\n#settings-container .jpx-rating-heading .jpx-download-count{margin-right:auto}\n#settings-container .jpx-store-rating{display:grid;gap:4px;margin-top:12px;padding-top:12px;border-top:1px solid var(--jpx-theme-border,#c8b49b);text-align:left}\n#settings-container .jpx-rating-heading strong{font-size:14px;font-weight:600}\n#settings-container .jpx-rating-actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px}\n#settings-container .jpx-rating-stars{display:flex;gap:8px}\n#settings-container .jpx-config-manager .jpx-store :is(.jpx-store-comments,.jpx-store-rating) :is(button,textarea){border-radius:0}\n#settings-container .jpx-config-manager .jpx-store :is(.jpx-community-icon,.jpx-rating-star){display:inline-flex;align-items:center;justify-content:center;flex:none;width:36px;min-height:36px;padding:0;border:1px solid transparent;background:transparent;box-shadow:none;color:var(--jpx-theme-accent,#5c0d11)}\n#settings-container .jpx-rating-star svg{width:24px;height:24px}\n#settings-container .jpx-rating-star[data-filled=true] svg{fill:currentColor}\n#settings-container .jpx-config-manager .jpx-store .jpx-rating-star[aria-pressed=true]{border-bottom-color:currentColor}\n#settings-container .jpx-config-manager .jpx-store .jpx-rating-remove{padding-inline:8px;border-color:transparent;background:transparent}\n#settings-container .jpx-config-manager .jpx-store :is(.jpx-community-icon,.jpx-rating-star,.jpx-rating-remove):hover:not(:disabled){background:var(--jpx-theme-hover,#f1e2c5)}\n#settings-container .jpx-config-manager .jpx-store :is(.jpx-community-icon,.jpx-rating-star,.jpx-rating-remove):active:not(:disabled){background:var(--jpx-theme-selected,#ead8b4)}\n#settings-container .jpx-community-icon[aria-busy=true] svg{animation:jpx-community-refresh 1s linear infinite}\n@keyframes jpx-community-refresh{to{transform:rotate(360deg)}}\n@media(prefers-reduced-motion:reduce){#settings-container .jpx-community-icon[aria-busy=true] svg{animation:none}}\n#settings-container.jpx-settings-mobile .jpx-config-manager .jpx-store :is(.jpx-community-icon,.jpx-rating-star){width:44px;min-height:44px}\n#settings-container.jpx-settings-mobile .jpx-store-comments textarea{font-size:16px}\n\n/* Keep every control in the store header on the same vertical center line. */\n#settings-container .jpx-config-toolbar :is(.jpx-config-nav,.jpx-store-navigation),#settings-container .jpx-config-manager .jpx-config-toolbar>.jpx-store-toolbar>.jpx-store-account,#settings-container .jpx-config-manager .jpx-config-toolbar>.jpx-store-querybar{align-self:center;align-items:center;margin-bottom:0}\n#settings-container.jpx-settings-mobile .jpx-config-toolbar :is(.jpx-config-nav,.jpx-store-navigation)>button{margin-bottom:0}\n"; // The local library is deliberately independent of the editor and battle runtime. // Keep PLUS metadata outside native JPX configuration objects. function normalizeJpxBattleMode(mode) { if (!mode || typeof mode !== 'object' || Array.isArray(mode)) return false; if (Object.hasOwn(mode, 'rules')) { if (!Array.isArray(mode.rules)) return false; } else { if (!Array.isArray(mode.supports) || !Array.isArray(mode.attacks)) return false; mode.rules = [...mode.supports, ...mode.attacks]; } delete mode.supports; delete mode.attacks; for (const [key, rules] of Object.entries(mode)) { if (key !== 'rules' && !key.startsWith('kb_') || !Array.isArray(rules)) continue; for (const rule of rules) { if (!rule || typeof rule !== 'object') continue; if (['spellInstant', 'spellDuration'].includes(rule.type)) rule.type = 'spellSupport'; else if (['itemInstant', 'itemDuration'].includes(rule.type)) rule.type = 'item'; if (rule.type === 'target' && 'bottomUp' in rule) { rule.priorityRule = rule.bottomUp ? 'Bottom Up' : 'Top Down'; delete rule.bottomUp; } if (rule.type === 'smartDebuff' && typeof rule.targetCount === 'string' && rule.targetCount.trim() && !isNaN(rule.targetCount)) rule.targetCount = Number(rule.targetCount); } } return true; } function createJpxConfigLibrary({ storage, key, modes, battleVersion, statsVersion }) { const MAX_JSON = 8 * 1024 * 1024; const MAX_ENVELOPE = 2 * 1024 * 1024; const MAX_ENTRIES = 500; const blockedKeys = new Set(['__proto__', 'prototype', 'constructor']); const modeSet = new Set(modes || []); const worlds = new Set(['Persistent', 'Isekai', 'Any']); const backupKey = `${key}:backup`; const object = value => value !== null && typeof value === 'object' && !Array.isArray(value); const fail = (code, message = code) => { const error = new Error(message); error.code = code; throw error; }; if (!storage || typeof storage.getItem !== 'function' || typeof storage.setItem !== 'function' || typeof key !== 'string' || !key || !modeSet.size) fail('invalidConfig'); function encode(value, limit = MAX_JSON) { let nodes = 0; const seen = new Set(); function visit(item, depth) { if (++nodes > 250000 || depth > 80) fail('tooLarge'); if (item === null || typeof item === 'string' || typeof item === 'boolean') return; if (typeof item === 'number') { if (!Number.isFinite(item)) fail('invalidConfig'); return; } if (typeof item !== 'object' || seen.has(item)) fail('invalidConfig'); const proto = Object.getPrototypeOf(item); if (!Array.isArray(item) && proto !== null && Object.getPrototypeOf(proto) !== null) fail('invalidConfig'); seen.add(item); if (Array.isArray(item)) { if (item.length > 100000) fail('tooLarge'); for (let i = 0; i < item.length; i++) if (!Object.hasOwn(item, i)) fail('invalidConfig'); } for (const name of Reflect.ownKeys(item)) { if (typeof name !== 'string' || blockedKeys.has(name)) fail('invalidConfig'); if (Array.isArray(item) && name === 'length') continue; const descriptor = Object.getOwnPropertyDescriptor(item, name); if (!descriptor.enumerable || descriptor.get || descriptor.set) fail('invalidConfig'); if (Array.isArray(item) && !/^(0|[1-9]\d*)$/.test(name)) fail('invalidConfig'); visit(descriptor.value, depth + 1); } seen.delete(item); } visit(value, 0); const result = JSON.stringify(value); if (result.length > limit) fail('tooLarge'); return result; } const clone = (value, limit) => JSON.parse(encode(value, limit)); function getRaw(name) { try { return storage.getItem(name); } catch { return fail('storageError'); } } function putRaw(name, raw) { try { storage.setItem(name, raw); } catch { fail('storageError'); } } function parse(raw) { if (typeof raw !== 'string' || raw.length > MAX_JSON) fail('storageCorrupt'); try { // JSON.parse already creates an owned tree with no accessors, cycles, // sparse arrays or custom prototypes. Keep the data limits and unsafe // key checks without the generic-object descriptor walk or a clone. const value = JSON.parse(raw); let nodes = 0; function visit(item, depth) { if (++nodes > 250000 || depth > 80) fail('tooLarge'); if (typeof item === 'number' && !Number.isFinite(item)) fail('invalidConfig'); if (item === null || typeof item !== 'object') return; if (Array.isArray(item)) { if (item.length > 100000) fail('tooLarge'); for (const child of item) visit(child, depth + 1); } else { for (const name of Object.keys(item)) { if (blockedKeys.has(name)) fail('invalidConfig'); visit(item[name], depth + 1); } } } visit(value, 0); // Numeric JSON spellings can expand when serialized (e.g. 1e10). if (JSON.stringify(value).length > MAX_JSON) fail('tooLarge'); return value; } catch { return fail('storageCorrupt'); } } function validId(id) { return typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/.test(id) && !blockedKeys.has(id); } function validateRules(mode) { if (!object(mode)) fail('invalidConfig'); // Native JPX permits an explicitly empty scene and falls back to General. if (!Object.keys(mode).length) return; if (!normalizeJpxBattleMode(mode)) fail('invalidConfig'); for (const [group, rules] of Object.entries(mode)) { if (group !== 'rules' && !group.startsWith('kb_')) continue; if (!Array.isArray(rules)) fail('invalidConfig'); for (const rule of rules) { if (!object(rule) || typeof rule.type !== 'string' || !rule.type) fail('invalidConfig'); if ('conditions' in rule && (!Array.isArray(rule.conditions) || rule.conditions.some(condition => !object(condition) || typeof condition.key !== 'string' || !condition.key))) fail('invalidConfig'); } } } function envelopeCopy(input) { return normalizeEnvelope(clone(input, MAX_ENVELOPE)); } // Only call with a detached, structurally validated JSON tree. The save and // migration boundaries still use envelopeCopy for arbitrary caller objects. function normalizeEnvelope(envelope) { if (!object(envelope) || envelope.schemaVersion !== 1 || !['battle', 'battle-mode', 'stats'].includes(envelope.kind) || !object(envelope.config) || typeof envelope.title !== 'string' || (envelope.description !== undefined && typeof envelope.description !== 'string') || !worlds.has(envelope.world)) fail('invalidConfig'); const config = envelope.config; const versionKey = envelope.kind === 'stats' ? 'statsVersion' : 'battleVersion'; const minimum = envelope.kind === 'stats' ? statsVersion : battleVersion; if (envelope.kind !== 'stats' && config.version && !config.battleVersion) { config.battleVersion = config.version; delete config.version; } if (!['number', 'string'].includes(typeof config[versionKey]) || String(config[versionKey]).trim() === '' || !Number.isFinite(Number(config[versionKey])) || config[versionKey] < minimum) fail('unsupportedVersion'); if (envelope.kind === 'stats') { if ('columnGroups' in config && (!object(config.columnGroups) || Object.values(config.columnGroups).some(value => typeof value !== 'boolean'))) fail('invalidConfig'); for (const field of ['combatRows', 'revenueRows', 'statsColumns']) { if (field in config && (!Array.isArray(config[field]) || config[field].some(row => !object(row) || typeof row.id !== 'string'))) fail('invalidConfig'); } return envelope; } if (config.Battlecaster_General && !config['1H_Mage_General']) { config['1H_Mage_General'] = config.Battlecaster_General; delete config.Battlecaster_General; } if (envelope.mode === 'Battlecaster_General') envelope.mode = '1H_Mage_General'; if (envelope.kind === 'battle-mode' && (!modeSet.has(envelope.mode) || !Object.hasOwn(config, envelope.mode))) fail('invalidConfig'); for (const mode of [...modeSet, 'Battlecaster_General']) { if (!Object.hasOwn(config, mode)) continue; const data = config[mode]; validateRules(data); } return envelope; } const emptyState = () => ({ schemaVersion: 1, entries: [], applied: {}, migrations: [] }); const validSlot = value => typeof value === 'string' && /^[1-9]\d{0,5}$/.test(value); const validBinding = value => object(value) && ['Persistent', 'Isekai'].includes(value.world) && validSlot(value.personaId) && validSlot(value.setId); const sameBinding = (a, b) => a.world === b.world && a.personaId === b.personaId && a.setId === b.setId; const validTime = value => typeof value === 'string' && Number.isFinite(Date.parse(value)); const validRecordMode = record => !Object.hasOwn(record, 'mode') || typeof record.mode === 'string' && modeSet.has(record.mode) && record.scopes.includes(record.mode) && Object.hasOwn(record.config, record.mode); let validatedRaw, validatedState, validatedJSON; function readValidatedState() { const raw = getRaw(key); if (raw === null || raw === undefined) return emptyState(); // This tree stays private. Public reads copy only the requested portion; // every changed raw value still receives complete validation. if (raw === validatedRaw) return validatedState; const state = parse(raw); try { if (!object(state) || state.schemaVersion !== 1 || !Array.isArray(state.entries) || state.entries.length > MAX_ENTRIES || !object(state.applied) || !Array.isArray(state.migrations) || state.migrations.some(marker => typeof marker !== 'string' || !marker)) fail('storageCorrupt'); const entries = new Map(); for (const entry of state.entries) { if (!object(entry) || !validId(entry.id) || entries.has(entry.id) || !Number.isSafeInteger(entry.revision) || entry.revision < 1 || !validTime(entry.createdAt) || !validTime(entry.updatedAt) || ('execution' in entry && !object(entry.execution))) fail('storageCorrupt'); entries.set(entry.id, entry); if (JSON.stringify(entry.envelope)?.length > MAX_ENVELOPE) fail('storageCorrupt'); entry.envelope = normalizeEnvelope(entry.envelope); } for (const [world, records] of Object.entries(state.applied)) { if (!worlds.has(world) || !object(records)) fail('storageCorrupt'); for (const [id, record] of Object.entries(records)) { const entry = entries.get(id); if (!entry || !object(record) || record.id !== id || !Number.isSafeInteger(record.revision) || record.revision < 1 || record.revision > entry.revision || !Array.isArray(record.scopes) || !record.scopes.length || record.scopes.some(scope => typeof scope !== 'string' || !scope) || !object(record.config) || ('execution' in record && !object(record.execution)) || !validRecordMode(record)) fail('storageCorrupt'); if (entry.envelope.kind !== 'stats') for (const mode of modeSet) if (Object.hasOwn(record.config, mode)) validateRules(record.config[mode]); } } if (Object.hasOwn(state, 'active')) { if (!object(state.active)) fail('storageCorrupt'); for (const [world, id] of Object.entries(state.active)) { if (!worlds.has(world) || !validId(id) || !Object.hasOwn(state.applied[world] || {}, id)) fail('storageCorrupt'); } } if (Object.hasOwn(state, 'bindings')) { if (!Array.isArray(state.bindings) || state.bindings.length > 2000) fail('storageCorrupt'); const slots = new Set(); for (const binding of state.bindings) { const entry = entries.get(binding?.id); const slot = JSON.stringify([binding?.world, binding?.personaId, binding?.setId]); if (!validBinding(binding) || !entry || entry.envelope.kind === 'stats' || slots.has(slot) || !Number.isSafeInteger(binding.trustedRevision) || binding.trustedRevision < 1 || binding.trustedRevision > entry.revision) fail('storageCorrupt'); slots.add(slot); } } if (state.scenes !== undefined) { if (!object(state.scenes)) fail('storageCorrupt'); for (const [world, routes] of Object.entries(state.scenes)) { if (!['Persistent', 'Isekai'].includes(world) || !object(routes)) fail('storageCorrupt'); for (const [target, route] of Object.entries(routes)) { if (!validScene(world, target)) fail('storageCorrupt'); if (route === null) continue; const entry = entries.get(route?.id); if (!object(route) || !entry || !modeSet.has(route.mode) || !Number.isSafeInteger(route.revision) || route.revision < 1 || route.revision > entry.revision) fail('storageCorrupt'); if (route.mode.slice(0, route.mode.lastIndexOf('_')) !== target.slice(0, target.lastIndexOf('_'))) fail('storageCorrupt'); validateRules(route.rules); } } } } catch { return fail('storageCorrupt'); } validatedRaw = raw; validatedState = state; validatedJSON = undefined; return state; } const copyValidated = value => JSON.parse(JSON.stringify(value)); function readState() { const state = readValidatedState(); if (state !== validatedState) return copyValidated(state); return JSON.parse(validatedJSON ??= JSON.stringify(state)); } function hasBinding(world, personaId, setId) { const raw = getRaw(key); if (raw === null || raw === undefined) return false; if (typeof raw !== 'string' || raw.length > MAX_JSON) fail('storageCorrupt'); // Existence only. Applying a match still requires readState's full validation. let state; try { state = raw === validatedRaw ? validatedState : JSON.parse(raw); } catch { return fail('storageCorrupt'); } if (!object(state) || state.schemaVersion !== 1 || Object.hasOwn(state, 'bindings') && (!Array.isArray(state.bindings) || state.bindings.length > 2000)) fail('storageCorrupt'); return !!state.bindings?.some(binding => binding?.world === world && (personaId === undefined || binding.personaId === personaId && binding.setId === setId)); } function readSelection(world) { if (!worlds.has(world)) fail('invalidConfig'); const state = readValidatedState(), id = state.active?.[world]; return id ? copyValidated(state.applied[world][id]) : null; } function readRuntime(world) { if (!['Persistent', 'Isekai'].includes(world)) fail('invalidConfig'); const state = readValidatedState(), id = state.active?.[world]; return copyValidated({ selection: id ? state.applied[world][id] : null, scenes: state.scenes?.[world] || {} }); } function validScene(world, mode) { const scene = mode.slice(mode.lastIndexOf('_') + 1); return ['Persistent', 'Isekai'].includes(world) && modeSet.has(mode) && ['General', 'Arena', 'Item', 'Battle1000', world === 'Isekai' ? 'Tower' : 'Encounter'].includes(scene); } function assignScene(world, target, id, mode, expectedRevision, previous = null) { if (typeof target !== 'string' || !validScene(world, target)) fail('invalidConfig'); const state = readState(), routes = (state.scenes ||= {})[world] ||= {}; if (JSON.stringify(routes[target] || null) !== JSON.stringify(previous)) fail('libraryChanged'); if (id === null) routes[target] = null; else { const entry = state.entries.find(item => item.id === id); if (!entry) fail('notFound'); if (entry.revision !== expectedRevision) fail('libraryChanged'); if (!['Any', world].includes(entry.envelope.world) || entry.envelope.kind === 'stats' || !modeSet.has(mode) || mode.slice(0, mode.lastIndexOf('_')) !== target.slice(0, target.lastIndexOf('_')) || !object(entry.envelope.config[mode])) fail('invalidConfig'); validateRules(entry.envelope.config[mode]); routes[target] = { id, revision: entry.revision, mode, rules: clone(entry.envelope.config[mode]) }; } write(state); return clone(routes[target]); } function write(state) { putRaw(key, encode(state)); } function newId(state) { let id; do { id = typeof globalThis.crypto?.randomUUID === 'function' ? globalThis.crypto.randomUUID() : `config-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`; } while (state.entries.some(entry => entry.id === id)); return id; } function save(input, options = {}) { const envelope = envelopeCopy(input); const state = readState(); const previous = options.id === undefined ? null : state.entries.find(entry => entry.id === options.id); if (options.id !== undefined && !previous) fail('notFound'); if (envelope.kind === 'stats' && state.bindings?.some(binding => binding.id === previous?.id)) fail('invalidConfig'); if (!previous && state.entries.length >= MAX_ENTRIES) fail('tooLarge'); const now = new Date().toISOString(); const entry = { ...(previous || {}), id: previous?.id || newId(state), envelope, revision: (previous?.revision || 0) + 1, createdAt: previous?.createdAt || now, updatedAt: now }; for (const name of ['source', 'execution']) if (Object.hasOwn(options, name)) { if (options[name] === null || options[name] === undefined) delete entry[name]; else entry[name] = clone(options[name]); } if ('execution' in entry && !object(entry.execution)) fail('invalidConfig'); if (previous) state.entries[state.entries.indexOf(previous)] = entry; else state.entries.push(entry); write(state); return clone(entry); } function rename(id, title, expectedRevision) { if (typeof title !== 'string' || !title.trim() || title.trim().length > 100 || /[\x00-\x1f\x7f]/.test(title)) fail('invalidConfig'); const state = readState(), entry = state.entries.find(item => item.id === id); if (!entry) fail('notFound'); if (entry.revision !== expectedRevision) fail('libraryChanged'); title = title.trim(); if (entry.envelope.title === title) return clone(entry); const previousRevision = entry.revision; entry.envelope.title = title; entry.revision++; entry.updatedAt = new Date().toISOString(); // A name change does not alter applied rules. Keep genuinely stale // snapshots stale, but do not ask users to reapply a metadata-only edit. for (const records of Object.values(state.applied)) { if (records[id]?.revision === previousRevision) records[id].revision = entry.revision; } for (const binding of state.bindings || []) { if (binding.id === id && binding.trustedRevision === previousRevision) binding.trustedRevision = entry.revision; } for (const routes of Object.values(state.scenes || {})) for (const route of Object.values(routes)) { if (route?.id === id && route.revision === previousRevision) route.revision = entry.revision; } write(state); return clone(entry); } function reorder(ids, expected) { const state = readState(); if (!Array.isArray(ids) || ids.length > MAX_ENTRIES || ids.some(id => !validId(id)) || new Set(ids).size !== ids.length) fail('invalidConfig'); const selected = new Set(ids), entries = new Map(state.entries.map(entry => [entry.id, entry])); if (ids.some(id => !entries.has(id))) fail('notFound'); const current = state.entries.filter(entry => selected.has(entry.id)).map(entry => entry.id); if (expected !== undefined && (!Array.isArray(expected) || JSON.stringify(current) !== JSON.stringify(expected))) fail('libraryChanged'); if (JSON.stringify(current) === JSON.stringify(ids)) return; let index = 0; // Reorder only the visible subset. Hidden entries and rule revisions stay intact. state.entries = state.entries.map(entry => selected.has(entry.id) ? entries.get(ids[index++]) : entry); write(state); } function remove(id) { const state = readState(); if (!state.entries.some(entry => entry.id === id)) fail('notFound'); if (Object.values(state.applied).some(records => Object.hasOwn(records, id))) fail('appliedConfig'); if (Object.values(state.scenes || {}).some(routes => Object.values(routes).some(route => route?.id === id))) fail('appliedConfig'); state.entries = state.entries.filter(entry => entry.id !== id); if (state.bindings) state.bindings = state.bindings.filter(binding => binding.id !== id); write(state); return true; } function setBinding(context, id, expectedRevision, previousId = null) { if (!validBinding(context)) fail('invalidConfig'); const state = readState(), entry = state.entries.find(item => item.id === id); if (!entry || entry.envelope.kind === 'stats') fail('invalidConfig'); if (entry.revision !== expectedRevision) fail('libraryChanged'); const bindings = state.bindings ||= [], index = bindings.findIndex(binding => sameBinding(binding, context)); if ((index < 0 ? null : bindings[index].id) !== previousId) fail('libraryChanged'); const binding = { world: context.world, personaId: context.personaId, setId: context.setId, id, trustedRevision: entry.revision }; if (index < 0) { if (bindings.length >= 2000) fail('tooLarge'); bindings.push(binding); } else bindings[index] = binding; write(state); return clone(binding); } function removeBinding(context, id) { if (!validBinding(context)) fail('invalidConfig'); const state = readState(), index = state.bindings?.findIndex(binding => sameBinding(binding, context)) ?? -1; if (index < 0) return false; if (state.bindings[index].id !== id) fail('libraryChanged'); state.bindings.splice(index, 1); write(state); return true; } function backup() { readValidatedState(); // Never replace or hide a corrupt source with an apparently valid backup. const raw = getRaw(key), previous = getRaw(backupKey); if (previous === null || previous === undefined) { putRaw(backupKey, JSON.stringify({ savedAt: new Date().toISOString(), raw: raw ?? null })); } return backupKey; } function migrate(entries, marker, options = {}) { if (!Array.isArray(entries) || typeof marker !== 'string' || !marker || marker.length > 200) fail('invalidConfig'); const state = readState(); if (state.migrations.includes(marker)) return clone(state); const migratedIds = new Map(); entries.forEach((input, index) => { if (!object(input) || !object(input.envelope)) fail('invalidConfig'); const envelope = envelopeCopy(input.envelope); let id = validId(input.id) ? input.id : `migrated-${marker.replace(/[^A-Za-z0-9_.:-]/g, '-').slice(0, 100)}-${index}`; const same = state.entries.find(entry => entry.id === id); if (same && encode(same.envelope) === encode(envelope)) { migratedIds.set(input.id, same.id); return; } const base = id.slice(0, 140); let suffix = 0; while (state.entries.some(entry => entry.id === id)) id = `${base}-migrated${suffix++ ? '-' + suffix : ''}`; const now = new Date().toISOString(); const entry = { id, envelope, revision: Number.isSafeInteger(input.revision) && input.revision > 0 ? input.revision : 1, createdAt: validTime(input.createdAt) ? input.createdAt : validTime(input.savedAt) ? input.savedAt : now, updatedAt: validTime(input.updatedAt) ? input.updatedAt : validTime(input.savedAt) ? input.savedAt : now }; for (const name of ['source', 'execution']) if (input[name] !== undefined) entry[name] = clone(input[name]); if ('execution' in entry && !object(entry.execution)) fail('invalidConfig'); state.entries.push(entry); migratedIds.set(input.id, entry.id); }); if (state.entries.length > MAX_ENTRIES) fail('tooLarge'); if (options.applied !== undefined) { if (!Array.isArray(options.applied)) fail('invalidConfig'); for (const request of clone(options.applied)) { const id = migratedIds.get(request.id); const entry = state.entries.find(item => item.id === id); if (!entry || !worlds.has(request.world) || !Array.isArray(request.scopes) || !request.scopes.length || request.scopes.some(scope => typeof scope !== 'string' || !scope)) fail('invalidConfig'); const records = state.applied[request.world] ||= {}; // Seeding must never replace a user's explicit application. if (Object.values(records).some(record => overlaps(record.scopes, request.scopes))) continue; records[id] = { id, revision: entry.revision, scopes: [...new Set(request.scopes)], config: clone(entry.envelope.config) }; } } state.migrations.push(marker); const serialized = encode(state); // Validate everything before writing either record. backup(); putRaw(key, serialized); return clone(state); } const overlaps = (a, b) => a.includes('*') || b.includes('*') || a.some(scope => b.includes(scope)); function pruneActive(state) { if (!state.active) return; for (const [world, id] of Object.entries(state.active)) { if (!Object.hasOwn(state.applied[world] || {}, id)) delete state.active[world]; } if (!Object.keys(state.active).length) delete state.active; } function setApplied(world, input, { activate = false } = {}) { if (!worlds.has(world)) fail('invalidConfig'); const record = clone(input); const state = readState(); const entry = state.entries.find(item => item.id === record?.id); if (!entry) fail('notFound'); if (!object(record) || !Number.isSafeInteger(record.revision) || record.revision < 1 || record.revision > entry.revision || !Array.isArray(record.scopes) || !record.scopes.length || record.scopes.some(scope => typeof scope !== 'string' || !scope) || !object(record.config) || ('execution' in record && !object(record.execution)) || !validRecordMode(record)) fail('invalidConfig'); if (entry.envelope.kind !== 'stats') for (const mode of modeSet) if (Object.hasOwn(record.config, mode)) validateRules(record.config[mode]); record.scopes = [...new Set(record.scopes)]; const records = state.applied[world] ||= {}; for (const [id, applied] of Object.entries(records)) { if (overlaps(applied.scopes, record.scopes)) delete records[id]; } records[record.id] = record; if (activate === true) (state.active ||= {})[world] = record.id; pruneActive(state); write(state); return clone(record); } function clearApplied(world, id) { if (!worlds.has(world) || !validId(id)) fail('invalidConfig'); const state = readState(); const records = state.applied[world]; if (!records || !Object.hasOwn(records, id)) return false; delete records[id]; if (!Object.keys(records).length) delete state.applied[world]; pruneActive(state); write(state); return true; } function clearSelection(world) { if (!worlds.has(world)) fail('invalidConfig'); const state = readState(); if (!state.active?.[world]) return false; delete state.active[world]; pruneActive(state); write(state); return true; } function references(id) { const state = readState(); return { applied: Object.entries(state.applied).flatMap(([world, records]) => records[id] ? [{ world, scopes: records[id].scopes, selected: state.active?.[world] === id }] : []), bindings: (state.bindings || []).filter(binding => binding.id === id), scenes: Object.entries(state.scenes || {}).flatMap(([world, routes]) => Object.entries(routes) .filter(([, route]) => route?.id === id).map(([mode]) => ({ world, mode }))) }; } function detach(id, expectedRevision, removeEntry = false, expectedReferences) { const state = readState(), entry = state.entries.find(item => item.id === id); if (!entry) fail('notFound'); if (entry.revision !== expectedRevision) fail('libraryChanged'); if (expectedReferences !== undefined && JSON.stringify(references(id)) !== JSON.stringify(expectedReferences)) fail('libraryChanged'); for (const [world, records] of Object.entries(state.applied)) { delete records[id]; if (!Object.keys(records).length) delete state.applied[world]; } if (state.bindings) state.bindings = state.bindings.filter(binding => binding.id !== id); for (const routes of Object.values(state.scenes || {})) for (const [mode, route] of Object.entries(routes)) { if (route?.id === id) routes[mode] = null; } pruneActive(state); if (removeEntry) state.entries = state.entries.filter(item => item.id !== id); write(state); return true; } return Object.freeze({ list: () => copyValidated(readValidatedState().entries), get: id => copyValidated(readValidatedState().entries.find(entry => entry.id === id) || null), save, rename, reorder, remove, migrate, backup, readState, hasBinding, readSelection, setApplied, clearApplied, setBinding, removeBinding, clearSelection, references, detach, readRuntime, assignScene }); } // Comments are plain text. GitHub handles storage and permissions; the UI never // renders remote HTML or writes config rules while discussing a shared config. function jpxStoreActionIcon(node, name, label) { const paths = { refresh: '', edit: '', delete: '', star: '' }; node.innerHTML = ''; node.setAttribute('aria-label', label); node.title = label; return node; } // Successes fade after a moment; errors and the loading notice stay until replaced. function jpxStoreStatusMessage(status, tr, current) { let timer; const say = (text, error = false) => { clearTimeout(timer); status.textContent = text; status.hidden = !text; status.setAttribute('role', error ? 'alert' : 'status'); if (text && !error && text !== tr('loading')) timer = setTimeout(() => { if (current()) status.hidden = true; }, 2500); }; say.cancel = () => clearTimeout(timer); return say; } function renderJpxStoreComments(parent, { service, entry, tr, el, confirm, signIn, user, isCurrent, draft }) { const root = el('section', undefined, 'jpx-store-comments'), heading = el('div', undefined, 'jpx-comment-heading'); const list = el('div', undefined, 'jpx-comment-list'), composer = el('div', undefined, 'jpx-comment-composer'); const status = el('p', '', 'jpx-comment-status'); status.setAttribute('role', 'status'); status.hidden = true; const current = () => !disposed && root.isConnected && isCurrent(); let disposed = false, loading = false, mutating = false, nextPage = null, request = 0, items = []; let editing = null, userId = user()?.id; const buttons = new Map(), busy = () => loading || mutating || !!editing; function button(text, action, className, disabled = () => false) { const node = el('button', text, className); node.type = 'button'; let pending = false; buttons.set(node, () => pending || disabled()); node.addEventListener('click', async () => { if (pending || disabled() || !current()) return; pending = true; controls(); try { await action(); } catch (error) { if (current()) failure(error); } finally { pending = false; if (current()) { syncAuth(); controls(); } } }); return node; } const say = jpxStoreStatusMessage(status, tr, current); const failure = (error, sending = false) => { const code = error?.code, key = code === 'loginRequired' ? 'commentSignIn' : code === 'rateLimited' ? 'rateLimit' : ['commentNotOwner', 'commentChanged', 'commentMissing', 'commentInvalid', 'commentDenied', 'commentsClosed'].includes(code) ? code : sending ? 'commentSendFailed' : 'requestFailed'; say(tr(key), true); }; const controls = () => { for (const [node, disabled] of buttons) { if (root.contains(node)) node.disabled = disabled(); else buttons.delete(node); } more.hidden = !nextPage; refresh.setAttribute('aria-busy', String(loading)); root.setAttribute('aria-busy', String(loading || mutating)); }; const valid = value => !!value.trim() && value.length <= 10000; function renderComposer() { if (mutating) return; composer.replaceChildren(); if (!user()) { composer.append(button(tr('commentSignIn'), () => signIn())); return; } const input = el('textarea'); input.rows = 2; input.maxLength = 10000; input.value = draft.body || ''; input.placeholder = tr('writeComment'); input.setAttribute('aria-label', tr('writeComment')); input.setAttribute('aria-description', tr('commentsPublic')); const publish = button(tr('postComment'), async () => { if (busy() || !valid(input.value) || !current()) return; const identity = user(), body = input.value; if (!identity) { failure({ code: 'loginRequired' }); return; } mutating = true; input.disabled = true; controls(); say(''); try { const saved = await service.addComment(entry.id, body, identity.id); if (draft.body === body) draft.body = ''; if (!current()) return; items = items.filter(item => item.id !== saved.id); items.push(saved); renderList(); input.value = ''; say(tr('commentPosted')); } catch (error) { if (current()) failure(error, true); } finally { mutating = false; if (current()) { input.disabled = false; controls(); input.focus({ preventScroll: true }); } } }, 'jpx-store-primary', () => busy() || !valid(input.value)); input.addEventListener('input', () => { draft.body = input.value; controls(); }); const footer = el('div', undefined, 'jpx-comment-compose-footer'); publish.title = tr('commentsPublic'); footer.append(publish); composer.append(input, footer); } const focusComment = id => list.querySelector('[data-comment-id="' + id + '"] button')?.focus({ preventScroll: true }); function renderList() { list.replaceChildren(); if (!items.length) { list.append(el('p', tr('noComments'), 'jpx-store-meta')); return; } for (const item of items) { const row = el('article', undefined, 'jpx-comment-row'); row.dataset.commentId = String(item.id); const header = el('div', undefined, 'jpx-comment-header'); const link = el('a', '@' + item.author.login); link.href = item.url; link.target = '_blank'; link.rel = 'noopener noreferrer'; const date = el('time', new Date(item.createdAt).toLocaleDateString(), 'jpx-store-meta'); date.dateTime = item.createdAt; date.title = new Date(item.createdAt).toLocaleString(); const byline = el('div', undefined, 'jpx-comment-byline'); byline.append(link, date); header.append(byline); row.append(header); const content = el('p', item.body, 'jpx-comment-body'); row.append(content); if (user()?.id === item.author.id) { const actions = el('div', undefined, 'jpx-comment-actions'); const edit = button(tr('editComment'), () => { if (busy() || !current()) return; editing = item.id; row.dataset.editing = 'true'; controls(); const input = el('textarea'); input.rows = 4; input.maxLength = 10000; const savedDraft = draft.edits[item.id] || { body: item.body, original: item }; draft.edits[item.id] = savedDraft; input.value = savedDraft.body; input.setAttribute('aria-label', tr('editComment')); const save = button(tr('save'), async () => { if (mutating || !valid(input.value) || !current()) return; const identity = user(); if (!identity) { failure({ code: 'loginRequired' }); return; } mutating = true; input.disabled = true; cancel.disabled = true; controls(); say(''); try { const updated = await service.updateComment(entry.id, savedDraft.original, input.value, identity.id); delete draft.edits[item.id]; if (!current()) return; items = items.map(value => value.id === item.id ? updated : value); editing = null; renderList(); say(tr('saved')); focusComment(item.id); } catch (error) { if (current()) failure(error); } finally { mutating = false; if (current()) { input.disabled = false; cancel.disabled = false; controls(); } } }, 'jpx-store-primary', () => mutating || !valid(input.value)); const cancel = button(tr('cancel'), () => { if (mutating) return; delete draft.edits[item.id]; editing = null; renderList(); controls(); focusComment(item.id); }, undefined, () => mutating); input.addEventListener('input', () => { savedDraft.body = input.value; controls(); }); content.replaceWith(input); actions.replaceChildren(cancel, save); row.append(actions); controls(); input.focus(); }, undefined, busy); const remove = button(tr('delete'), async () => { if (busy() || !current()) return; const identity = user(); if (!identity) return; if (!await confirm(tr('deleteCommentConfirm'), '', tr('delete'))) return; if (!current() || busy() || user()?.id !== identity.id) return; mutating = true; controls(); say(''); try { await service.deleteComment(entry.id, item, identity.id); delete draft.edits[item.id]; if (!current()) return; items = items.filter(value => value.id !== item.id); renderList(); say(tr('commentDeleted')); } catch (error) { if (current()) failure(error); } finally { mutating = false; if (current()) { controls(); refresh.focus({ preventScroll: true }); } } }, undefined, busy); jpxStoreActionIcon(edit, 'edit', tr('editComment')); jpxStoreActionIcon(remove, 'delete', tr('delete')); edit.classList.add('jpx-community-icon'); remove.classList.add('jpx-community-icon'); actions.append(edit, remove); header.append(actions); } list.append(row); } } async function load(page = 1) { if (busy() || !current()) return; const generation = ++request; loading = true; controls(); say(tr('loading')); try { const result = await service.comments(entry.id, page); if (!current() || generation !== request) return; const collected = new Map((page === 1 ? [] : items).map(item => [item.id, item])); for (const item of result.items) collected.set(item.id, item); items = [...collected.values()].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id - b.id); nextPage = result.nextPage; renderList(); say(''); } catch (error) { if (current() && generation === request) failure(error); } finally { loading = false; if (current()) controls(); } } function syncAuth() { if (!current() || mutating || userId === user()?.id) return; userId = user()?.id; editing = null; renderList(); renderComposer(); controls(); } const refresh = jpxStoreActionIcon(button('', () => load(), 'jpx-community-icon', busy), 'refresh', tr('refresh')); const more = button(tr('showMore'), () => load(nextPage), 'jpx-comment-more', busy); more.hidden = true; heading.append(el('h4', tr('comments')), refresh); root.append(heading, composer, status, list, more); parent.append(root); renderComposer(); load(); return { authChanged: syncAuth, dispose() { disposed = true; request++; say.cancel(); buttons.clear(); } }; } function jpxStoreRatingText(value, tr) { if (!value?.count) return tr('noRatings'); return '★ ' + (value.sum / value.count).toFixed(1) + ' · ' + tr(value.count === 1 ? 'ratingCountOne' : 'ratingCount').replace('${count}', String(value.count)); } function renderJpxStoreRating(parent, { service, entry, summary, tr, el, user, signIn, isCurrent, onChange }) { const root = el('section', undefined, 'jpx-store-rating'), total = el('strong', jpxStoreRatingText(summary, tr)); const actions = el('div', undefined, 'jpx-rating-actions'), status = el('p', '', 'jpx-rating-status'); status.hidden = true; status.setAttribute('role', 'status'); const heading = el('div', undefined, 'jpx-rating-heading'); heading.append(total); root.append(heading, actions, status); parent.append(root); let disposed = false, busy = false, ready = false, score = null, generation = 0, identity = user()?.id; const current = () => !disposed && root.isConnected && isCurrent(); const say = jpxStoreStatusMessage(status, tr, current); const failure = error => { const key = ({ loginRequired: 'ratingSignIn', rateLimited: 'rateLimit', ratingsTooMany: 'ratingsTooMany', ratingInvalid: 'ratingInvalid', commentsClosed: 'ratingsClosed', commentDenied: 'ratingDenied', commentChanged: 'ratingChanged', commentMissing: 'ratingChanged' })[error?.code] || 'ratingFailed'; say(tr(key), true); }; const controls = () => { root.setAttribute('aria-busy', String(busy)); for (const node of root.querySelectorAll('button')) node.disabled = busy || node.dataset.score !== undefined && !ready; root.querySelector('.jpx-rating-refresh')?.setAttribute('aria-busy', String(busy)); }; function render() { actions.replaceChildren(); heading.querySelector('button')?.remove(); const action = (text, handler, className) => { const node = el('button', text, className); node.type = 'button'; node.addEventListener('click', () => { if (!busy && current()) handler(); }); return node; }; if (!identity) { actions.append(action(tr('ratingSignIn'), signIn)); controls(); return; } const stars = el('div', undefined, 'jpx-rating-stars'); stars.setAttribute('role', 'group'); stars.setAttribute('aria-label', tr('yourRating')); const preview = value => { for (const node of stars.children) node.dataset.filled = String(Number(node.dataset.score) <= value); }; for (let value = 1; value <= 5; value++) { const node = jpxStoreActionIcon(action('', () => change(value), 'jpx-rating-star'), 'star', tr('ratingStars').replace('${score}', String(value))); node.dataset.score = String(value); node.setAttribute('aria-pressed', String(value === score)); node.addEventListener('pointerenter', event => { if (event.pointerType === 'mouse' && !busy && ready) preview(value); }); node.addEventListener('focus', () => { if (!busy && ready) preview(value); }); stars.append(node); } preview(score); stars.addEventListener('pointerleave', () => preview(score)); stars.addEventListener('focusout', event => { if (!stars.contains(event.relatedTarget)) preview(score); }); actions.append(stars); if (ready && score !== null) actions.append(action(tr('removeRating'), () => change(null), 'jpx-rating-remove')); heading.append(jpxStoreActionIcon(action('', () => load(), 'jpx-rating-refresh jpx-community-icon'), 'refresh', tr('refresh'))); controls(); } function accept(value) { score = value.score; ready = true; total.textContent = jpxStoreRatingText(value, tr); onChange({ count: value.count, sum: value.sum }); } async function load() { if (!identity || busy || !current()) return; const request = ++generation, expected = identity; busy = true; controls(); say(tr('loading')); try { const value = await service.rating(entry.id, expected); if (!current() || request !== generation || user()?.id !== expected) return; accept(value); say(''); } catch (error) { if (current() && request === generation) failure(error); } finally { if (current() && request === generation) { busy = false; render(); } } } async function change(value) { if (!ready || busy || value === score || !identity || !current()) return; const request = ++generation, expected = identity; busy = true; controls(); say(''); try { const saved = await service.setRating(entry.id, value, expected); if (!current() || request !== generation || user()?.id !== expected) return; accept(saved); say(tr(value === null ? 'ratingRemoved' : 'ratingSaved')); } catch (error) { if (current() && request === generation) failure(error); } finally { if (current() && request === generation) { busy = false; render(); (actions.querySelector('[aria-pressed=true]') || actions.querySelector('button'))?.focus({ preventScroll: true }); } } } render(); load(); return { authChanged() { if (!current() || identity === user()?.id) return; identity = user()?.id; generation++; busy = false; ready = false; score = null; say(''); render(); load(); }, dispose() { disposed = true; generation++; say.cancel(); } }; } const jpxStoreHex = bytes => [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join(''); function createJpxStoreDownloads() { const endpoint = 'https://jpx-plus-downloads.lernsc.workers.dev/v1/downloads'; const seedKey = 'jpx-config-download-seed-v1', receiptKey = 'jpx-config-download-day-v1:'; const totals = new Map(), reads = new Map(), writes = new Map(), attempts = new Map(); const validId = id => Number.isSafeInteger(id) && id > 0 && id <= 9999999999; const remember = (id, count) => { if (!Number.isSafeInteger(count) || count < 0) throw Error('Invalid download count'); const value = Math.max(totals.get(id)?.count || 0, count); totals.set(id, { count: value, at: Date.now() }); return value; }; function request(method, suffix = '', data) { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { reject(Error('Transport unavailable')); return; } const url = endpoint + suffix; GM_xmlhttpRequest({ method, url, timeout: 4000, anonymous: true, redirect: 'error', headers: { Accept: 'application/json', ...(data ? { 'Content-Type': 'application/json' } : {}) }, ...(data ? { data: JSON.stringify(data) } : {}), onload(response) { try { if (response.status !== 200 || response.finalUrl && response.finalUrl !== url || typeof response.responseText !== 'string' || response.responseText.length > 32000) throw Error('Counter unavailable'); resolve(JSON.parse(response.responseText)); } catch (error) { reject(error); } }, onerror: () => reject(Error('Counter unavailable')), ontimeout: () => reject(Error('Counter timeout')), onabort: () => reject(Error('Counter cancelled')) }); }); } async function counts(ids) { const wanted = [...new Set(ids.filter(validId))].slice(0, 100); const missing = wanted.filter(id => Date.now() - (totals.get(id)?.at ?? -Infinity) > 60000 && Date.now() - (attempts.get(id) ?? -Infinity) > 10000); if (missing.length) { const key = missing.sort((a, b) => a - b).join(','); if (!reads.has(key)) { missing.forEach(id => attempts.set(id, Date.now())); const pending = request('GET', '?ids=' + key).then(value => { if (!value?.counts || typeof value.counts !== 'object' || Array.isArray(value.counts)) return; for (const id of missing) if (Object.hasOwn(value.counts, id)) remember(id, value.counts[id]); }).catch(() => {}).finally(() => reads.delete(key)); reads.set(key, pending); } await reads.get(key); } await Promise.all([...reads.values()]); return Object.fromEntries(wanted.filter(id => totals.has(id)).map(id => [id, totals.get(id).count])); } async function record(id) { if (!validId(id)) return null; if (writes.has(id)) return writes.get(id); const pending = (async () => { try { if (typeof GM_getValue !== 'function' || typeof GM_setValue !== 'function') return null; const day = new Date().toISOString().slice(0, 10); if (GM_getValue(receiptKey + id) === day) return null; let seed = GM_getValue(seedKey); if (typeof seed !== 'string' || !/^[a-f0-9]{64}$/.test(seed)) { seed = jpxStoreHex(crypto.getRandomValues(new Uint8Array(32))); GM_setValue(seedKey, seed); if (GM_getValue(seedKey) !== seed) return null; } // Each config and UTC day gets an unrelated public token; the seed never leaves GM storage. const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed + ':' + id + ':' + day)); const visitor = jpxStoreHex(digest); const result = await request('POST', '', { configId: id, day, visitor }); if (result?.configId !== id || result.day !== day || typeof result.counted !== 'boolean') return null; const count = remember(id, result.count); GM_setValue(receiptKey + id, day); return count; } catch { return null; } })().finally(() => writes.delete(id)); writes.set(id, pending); return pending; } return Object.freeze({ counts, record, peek: id => totals.get(id)?.count ?? null }); } // Config Store stays inside the userscript sandbox. No credentials or transport are exposed to the page. // Construction is offline; network activity starts only after render() is explicitly called. function createJpxIntegratedStore(host, translate) { 'use strict'; const translations = {"en":{"name":"Config store","browse":"Browse","mine":"My configs","share":"Share config","signIn":"Sign in","signOut":"Sign out","signedOut":"Signed out.","currentMode":"Battle mode","allBattle":"All battle settings","stats":"Statistics","persistent":"Persistent","isekai":"Isekai","anyWorld":"Both worlds","back":"Back","retry":"Retry","refresh":"Refresh","search":"Search configs or authors","type":"Type","allTypes":"All types","loading":"Loading…","noMatches":"No matching configs.","noConfigs":"No configs shared yet.","cannotLoad":"Could not load this content.","columns":"Columns","combatRows":"Combat stats","revenueRows":"Earnings","supports":"Support rules","attacks":"Attack rules","customCode":"Custom code","viewConfig":"View config","scriptVersion":"Script version","import":"Import into settings","download":"Download config","imported":"Imported. Review your settings, then save.","connecting":"Connecting to GitHub…","authHint":"Enter this code on GitHub to authorize JPX-PLUS.","authorize":"Authorize on GitHub","waitingAuth":"Finish signing in on GitHub. This page will update automatically.","copyCode":"Copy code","copied":"Copied","copyFailed":"Copy failed","cancel":"Cancel","updateShare":"Update","configContents":"Included settings","keepSharedConfig":"Keep shared config","noMatchingLocal":"No saved configs match.","shareChanged":"This shared config changed. Reopen it before submitting.","localChanged":"This saved config changed. Select it again before submitting.","updateSubmitted":"Update submitted for review.","world":"World","title":"Title","description":"Description","submit":"Submit for review","submitUpdate":"Submit update","reviewHint":"Shared publicly on GitHub. Code and suspicious content require AI security review and maintainer approval.","submitting":"Submitting…","submitted":"Submitted for review.","pending":"In review","published":"Published","changes":"Changes needed","needsReview":"Maintainer review","unavailable":"Review unavailable","hidden":"Hidden","withdrawn":"Withdrawn","noShares":"No shared configs.","withdraw":"Withdraw","removeShare":"Remove from list","removeShareConfirm":"Remove this withdrawn config from the list? Its GitHub record and your saved copies stay.","withdrawFirst":"Withdraw this share before removing its record. Refresh the list and try again.","withdrawConfirm":"Remove this config from the store? Players keep copies they already imported.","review":"Review feedback","noReview":"This version has no review yet.","loginRequired":"Sign in to GitHub to manage your shared configs.","notConfigured":"GitHub sign-in is not configured yet.","rateLimit":"Too many GitHub requests. Try again later.","networkError":"Could not reach GitHub. Check your connection and try again.","invalidConfig":"This config has an invalid format.","tooLarge":"This config is too large.","integrityError":"The downloaded file does not match the published config.","requestFailed":"The request failed. Please try again.","OneHanded":"One-handed","1H_Mage":"1H Mage","TwoHanded":"Two-handed","2H_Mage":"2H Mage","DualWielding":"Dual wield","DW_Mage":"DW Mage","NitenIchiryu":"Niten Ichiryu","NI_Mage":"NI Mage","Staff":"Staff","Unarmed":"Unarmed","General":"General","Arena":"Arena","Encounter":"Encounter","Colosseum":"Colosseum","Battle1000":"Grindfest","Item":"Item World","Tower":"Tower","publishedVersion":"Published version","accessDenied":"GitHub authorization was cancelled.","loginExpired":"The authorization code expired. Please sign in again.","managerUnavailable":"Enable the plugin permissions in your userscript manager.","notOwner":"Only the author can edit this config.","submissionClosed":"This config was withdrawn. Create a new share to publish it again.","tooManySubmissions":"Too many shared configs to load here. Manage them on GitHub.","local":"Current","shared":"Shared","style":"Style","battleType":"Battle type","all":"All","appliesTo":"Applies to","save":"Save","apply":"Apply config","delete":"Delete","storageCorrupt":"Could not read saved configs. Your data is unchanged.","storageError":"Could not access saved configs. Check browser storage and try again.","localNotFound":"This saved config is no longer available.","savedConfig":"Saved to My configs.","saved":"Saved","filters":"Filters","allWorlds":"Any world","allStyles":"All styles","allBattles":"All battles","clearFilters":"Clear filters","sort":"Sort","latest":"Updated","nameSort":"Name","resultCount":"${count} found","showMore":"Show more","comments":"Comments","writeComment":"Write a comment…","postComment":"Post","commentSignIn":"Sign in to comment","noComments":"No comments yet.","commentsPublic":"Comments are public on GitHub","editComment":"Edit","deleteCommentConfirm":"Delete this comment?","commentPosted":"Comment posted.","commentDeleted":"Comment deleted.","commentNotOwner":"You can only change your own comments.","commentChanged":"This comment has changed. Cancel editing, refresh, and try again.","commentMissing":"This comment is no longer available. Refresh and try again.","commentInvalid":"Enter a comment of up to 10,000 characters.","commentDenied":"You cannot change comments here. Check your GitHub permissions.","commentsClosed":"Comments are closed for this config.","commentSendFailed":"Could not confirm your comment was posted. Refresh before posting again.","noRatings":"No ratings yet","ratingCount":"${count} ratings","yourRating":"Your rating","ratingStars":"${score} stars","ratingSignIn":"Sign in to rate","removeRating":"Remove rating","ratingSaved":"Rating saved.","ratingRemoved":"Rating removed.","ratingFailed":"Could not confirm your rating was saved. Refresh to check.","ratingInvalid":"Choose 1 to 5 stars.","ratingsClosed":"Ratings are closed for this config.","ratingDenied":"You cannot rate this config. Check your GitHub permissions.","ratingChanged":"Your rating changed elsewhere. Refresh and try again.","ratingsTooMany":"Too many comments to load your rating. Open this config on GitHub.","ratingCountOne":"1 rating","downloadCount":"${count} downloads","downloadsUnavailable":"Downloads unavailable","rules":"Rules"}}; const t = key => { const name = key.replace(/^cStore\./, ''); const pack = host.jpxI18N?.cStore?.[name]; if (typeof pack === 'string') return pack; const external = translate?.(key); const missing = name.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/_/g, ' ').toLowerCase().replace(/^./, c => c.toUpperCase()); if (typeof external === 'string' && external !== key && external !== name && external !== missing) return external; const fallback = translations.en; return fallback[name] || name; }; // Only this public app identifier is embedded. Tokens stay in userscript-manager storage. const JPX_CONFIG_STORE = Object.freeze({ repository: 'MeiYongAI/JPX-PLUS-Configs', clientId: 'Iv23liGY2o8zyCDWgKBV' }); const styles = ['OneHanded', '1H_Mage', 'TwoHanded', '2H_Mage', 'DualWielding', 'DW_Mage', 'NitenIchiryu', 'NI_Mage', 'Staff', 'Unarmed']; const battleTypes = ['General', 'Arena', 'Encounter', 'Colosseum', 'Battle1000', 'Item', 'Tower']; const ratingTotals = new Map(); const downloadCounts = createJpxStoreDownloads(); const clone = value => JSON.parse(JSON.stringify(value)); const jpxConfigStore = (() => { const repository = JPX_CONFIG_STORE.repository, api = 'https://api.github.com', raw = 'https://raw.githubusercontent.com/' + repository + '/main/'; const tokenKey = 'jpx-config-store-auth-v1', marker = '\n```json\n'; const archivedMarker = '\n```json\n'; const ratingPrefix = '\nRating: ' + score + '/5'; const ratingScore = body => [1, 2, 3, 4, 5].find(score => body === ratingBody(score)) || null; const kinds = ['battle-mode', 'battle', 'stats'], worlds = ['Persistent', 'Isekai', 'Any']; const modes = styles.flatMap(style => battleTypes.map(type => style + '_' + type)); const ruleTypes = { supports: ['spellSupport', 'item', 'toggle', 'stop'], attacks: ['target', 'toggle', 'smartDebuff', 'spellDebuff', 'spellDamage', 'skill', 'normalAttack', 'kamisamaniNattaHi'], keys: ['target', 'spellSupport', 'item', 'toggle', 'stop', 'smartDebuff', 'spellDebuff', 'spellDamage', 'skill', 'normalAttack', 'kamisamaniNattaHi'] }; const conditionKeys = new Set('world pLevel pMaxSpellType battleTypes difficulty roundCurrent roundLeft roundTotal floor pActionCooldown pActionHistory pActionCounts pTotalActionCounts pHP pMP pSP pOC pSpiritStatus pEffects pIgnoredEffects pEffectStacks monsters activeMonsters defeatedMonsters bosses activeBosses defeatedBosses mLevel mWithoutEffects tName tTypes tClasses tPowerLevel tIndex tHP tMP tSP tEffects tIgnoredEffects tEffectStacks tDaysSinceUpdate'.split(' ')); const encode = value => new TextEncoder().encode(value); let cache, loginPending, refreshing, sessionGeneration = 0; const pendingSubmissions = new Map(); const error = code => Object.assign(new Error(code), { code }); const fail = code => { throw error(code); }; const object = value => value && typeof value === 'object' && !Array.isArray(value); const integer = value => Number.isSafeInteger(value) && value > 0; const validToken = value => typeof value === 'string' && /^[A-Za-z0-9_]{1,512}$/.test(value); const text = (value, max, empty = false) => typeof value === 'string' && (empty || value.trim().length > 0) && value.length <= max && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value); const issueURL = id => 'https://github.com/' + repository + '/issues/' + id, issuesPath = '/repos/' + repository + '/issues'; const person = value => ({ id: value.id, login: value.login }); function inspect(value, depth = 0, budget = { nodes: 0, stringLimit: Infinity }) { if (++budget.nodes > (budget.nodeLimit || 12000) || depth > 24) fail('invalidConfig'); if (typeof value === 'string') { if (value.length > budget.stringLimit) fail('tooLarge'); return; } if (value === null || typeof value === 'boolean') return; if (typeof value === 'number' && Number.isFinite(value)) return; if (typeof value !== 'object') fail('invalidConfig'); const keys = Object.keys(value); if (budget.exactJSON && (Object.getOwnPropertySymbols(value).length || (Array.isArray(value) ? keys.length !== value.length || keys.some(key => !/^(0|[1-9]\d*)$/.test(key) || +key >= value.length) : Object.prototype.toString.call(value) !== '[object Object]'))) fail('invalidConfig'); for (const key of keys) { if (['__proto__', 'prototype', 'constructor'].includes(key)) fail('invalidConfig'); if (budget.exactJSON) { const property = Object.getOwnPropertyDescriptor(value, key); if (property.get || property.set) fail('invalidConfig'); } inspect(value[key], depth + 1, budget); } } function parse(source, max = 60000) { if (typeof source !== 'string' || encode(source).length > max) fail('tooLarge'); let value; try { value = JSON.parse(source); } catch { fail('invalidConfig'); } inspect(value); return value; } function validate(value) { inspect(value, 0, { nodes: 0, stringLimit: 30000 }); if (!object(value) || value.schemaVersion !== 1 || !kinds.includes(value.kind) || !worlds.includes(value.world) || !text(value.title, 100) || /[\r\n]/.test(value.title) || !text(value.description, 4000, true) || typeof value.scriptVersion !== 'string' || !/^[\d.\w-]{1,40}$/.test(value.scriptVersion) || !object(value.config)) fail('invalidConfig'); if (Object.keys(value).some(key => !['schemaVersion', 'kind', 'title', 'description', 'world', 'mode', 'scriptVersion', 'config'].includes(key))) fail('invalidConfig'); const config = value.config; if (value.kind === 'stats') { if ('columnGroups' in config && (!object(config.columnGroups) || Object.values(config.columnGroups).some(value => typeof value !== 'boolean'))) fail('invalidConfig'); if (!integer(config.statsVersion) || config.statsVersion < 20260109 || value.mode !== undefined) fail('invalidConfig'); let count = 0; for (const name of ['combatRows', 'revenueRows', 'statsColumns']) if (name in config) { if (!Array.isArray(config[name]) || config[name].length > 500) fail('invalidConfig'); const ids = new Set(); count++; for (const row of config[name]) { if (!object(row) || !text(row.id, 100) || ids.has(row.id) || ('disabled' in row && typeof row.disabled !== 'boolean')) fail('invalidConfig'); for (const field of ['customName', 'styleText', 'colorThresholds', ...Object.keys(row).filter(key => key.startsWith('s_'))]) if (field in row && typeof row[field] !== 'string') fail('invalidConfig'); ids.add(row.id); } } if (!count) fail('invalidConfig'); } else { // Match the original JPX aliases on this detached submission only. if (!config.battleVersion && config.version) config.battleVersion = config.version; delete config.version; if (!config['1H_Mage_General'] && config.Battlecaster_General) config['1H_Mage_General'] = config.Battlecaster_General; delete config.Battlecaster_General; if (value.mode === 'Battlecaster_General') value.mode = '1H_Mage_General'; if (!integer(config.battleVersion) || config.battleVersion < 20251216) fail('invalidConfig'); const selected = modes.filter(mode => mode in config); if (!selected.length) fail('invalidConfig'); let ruleCount = 0; for (const mode of selected) { if (value.kind === 'battle' && object(config[mode]) && !Object.keys(config[mode]).length) continue; if (!object(config[mode]) || (Object.hasOwn(config[mode], 'rules') ? !Array.isArray(config[mode].rules) : !Array.isArray(config[mode].supports) || !Array.isArray(config[mode].attacks))) fail('invalidConfig'); for (const group of [...(Array.isArray(config[mode].rules) ? ['rules'] : ['supports', 'attacks']), ...Object.keys(config[mode]).filter(key => key.startsWith('kb_'))]) { const rules = config[mode][group], allowed = ruleTypes[group] || ruleTypes.keys; if (!Array.isArray(rules)) fail('invalidConfig'); if ((ruleCount += rules.length) > 2000) fail('tooLarge'); for (const rule of rules) { if (object(rule) && ['spellInstant', 'spellDuration'].includes(rule.type)) rule.type = 'spellSupport'; if (object(rule) && ['itemInstant', 'itemDuration'].includes(rule.type)) rule.type = 'item'; if (!object(rule) || !allowed.includes(rule.type) || ('conditions' in rule && !Array.isArray(rule.conditions))) fail('invalidConfig'); for (const condition of rule.conditions || []) { if (!object(condition) || !conditionKeys.has(condition.key)) fail('invalidConfig'); if (condition.key === 'pSpiritStatus' ? typeof condition.value !== 'boolean' : condition.key === 'tName' ? typeof condition.value !== 'string' : !Array.isArray(condition.value)) fail('invalidConfig'); } } } } if (value.kind === 'battle-mode' && (!modes.includes(value.mode) || selected.length !== 1 || selected[0] !== value.mode || Object.keys(config).some(key => key !== 'battleVersion' && key !== value.mode))) fail('invalidConfig'); if (value.kind === 'battle' && value.mode !== undefined) fail('invalidConfig'); } const serialized = JSON.stringify(value) + '\n'; if (encode(serialized).length + 50 > 60000) fail('tooLarge'); return value; } function parseSubmission(body) { if (typeof body !== 'string' || !body.startsWith(marker) || !body.endsWith('\n```')) fail('invalidConfig'); return validate(parse(body.slice(marker.length, -4))); } const hash = async source => jpxStoreHex(await crypto.subtle.digest('SHA-256', encode(source))); function request(url, { method = 'GET', data, token, signal, limit = 6000000, accept = 'application/json' } = {}) { if (typeof GM_xmlhttpRequest !== 'function') return Promise.reject(error('managerUnavailable')); const target = new URL(url); if (target.protocol !== 'https:' || target.username || target.password || !['api.github.com', 'github.com', 'raw.githubusercontent.com'].includes(target.hostname) || (token && target.hostname !== 'api.github.com')) return Promise.reject(error('invalidResponse')); return new Promise((resolve, reject) => { let handle, done = false; const end = (callback, value) => { if (done) return; done = true; signal?.removeEventListener('abort', abort); callback(value); }; const abort = () => { handle?.abort(); end(reject, error('cancelled')); }; if (signal?.aborted) return abort(); const headers = { Accept: accept }; if (accept === 'application/vnd.github.raw+json') headers['Cache-Control'] = 'no-cache'; if (target.hostname === 'api.github.com') headers['X-GitHub-Api-Version'] = '2022-11-28'; if (token) headers.Authorization = 'Bearer ' + token; if (data !== undefined) headers['Content-Type'] = 'application/json'; signal?.addEventListener('abort', abort, { once: true }); try { handle = GM_xmlhttpRequest({ method, url, headers, data: data === undefined ? undefined : JSON.stringify(data), timeout: 25000, anonymous: true, redirect: 'error', onload(response) { if (response.finalUrl && response.finalUrl !== url) return end(reject, error('invalidResponse')); if (typeof response.responseText !== 'string' || encode(response.responseText).length > limit) return end(reject, error('tooLarge')); if (response.status < 200 || response.status >= 300) { const limited = response.status === 429 || (response.status === 403 && /(?:x-ratelimit-remaining:\s*0\b|retry-after:)/i.test(response.responseHeaders || '')); const code = response.status === 401 ? 'loginRequired' : response.status === 404 ? 'notFound' : limited ? 'rateLimited' : response.status === 403 ? 'accessDenied' : 'networkError'; return end(reject, Object.assign(error(code), { status: response.status })); } end(resolve, response.responseText); }, onerror: () => end(reject, error('networkError')), ontimeout: () => end(reject, error('networkError')), onabort: () => end(reject, error('cancelled')) }); } catch { end(reject, error('managerUnavailable')); } }); } const validIdentity = value => object(value) && integer(value.id) && typeof value.login === 'string' && /^[a-z\d](?:[a-z\d-]{0,38})$/i.test(value.login); const sameAuth = (left, right) => !!left && !!right && left.token === right.token && left.refreshToken === right.refreshToken; // Device-flow endpoints on github.com; every request carries the public client id first. const githubLogin = (path, data, signal) => request('https://github.com/login/' + path, { method: 'POST', signal, data: { client_id: JPX_CONFIG_STORE.clientId, ...data } }); function readAuth() { if (typeof GM_getValue !== 'function') fail('managerUnavailable'); return GM_getValue(tokenKey, null); } function authFromResponse(result) { if (!validToken(result.access_token) || result.token_type?.toLowerCase() !== 'bearer' || result.expires_in !== undefined && !integer(result.expires_in)) fail('invalidResponse'); const auth = { token: result.access_token, expiresAt: result.expires_in === undefined ? null : Date.now() + result.expires_in * 1000 }; if (result.refresh_token !== undefined) { if (!validToken(result.refresh_token) || !integer(result.refresh_token_expires_in)) fail('invalidResponse'); auth.refreshToken = result.refresh_token; auth.refreshExpiresAt = Date.now() + result.refresh_token_expires_in * 1000; } return auth; } function forgetAuth(expected) { // A late 401 from an old tab/request must not erase a renewed login. if (!sameAuth(readAuth(), expected)) return; if (typeof GM_deleteValue !== 'function') fail('managerUnavailable'); sessionGeneration++; pendingSubmissions.clear(); GM_deleteValue(tokenKey); } async function withAuthLock(action) { if (typeof GM_listValues !== 'function' || typeof GM_setValue !== 'function' || typeof GM_deleteValue !== 'function') fail('managerUnavailable'); // Bakery tickets in userscript storage also coordinate primary/alt hosts. // Each contender owns one key; a crashed tab's ticket expires. const prefix = tokenKey + ':lock:', key = prefix + crypto.randomUUID(); const expiresAt = Date.now() + 60000; const tickets = () => GM_listValues().filter(name => name.startsWith(prefix)).map(name => [name, GM_getValue(name, null)]) .filter(([, value]) => object(value) && Number.isFinite(value.expiresAt) && value.expiresAt > Date.now() && Number.isSafeInteger(value.ticket) && value.ticket >= 0); GM_setValue(key, { ticket: 0, expiresAt }); try { const ticket = Math.max(0, ...tickets().map(([, value]) => value.ticket)) + 1; GM_setValue(key, { ticket, expiresAt }); while (tickets().some(([name, value]) => name !== key && (value.ticket === 0 || value.ticket < ticket || value.ticket === ticket && name < key))) { if (Date.now() >= expiresAt - 26000) fail('networkError'); await pause(100); } if (Date.now() >= expiresAt - 26000) fail('networkError'); return await action(() => Date.now() < expiresAt); } finally { GM_deleteValue(key); } } async function renewAuth(expected) { if (refreshing) return refreshing; const generation = sessionGeneration; refreshing = withAuthLock(async leaseAlive => { let auth = readAuth(); if (generation !== sessionGeneration || !sameAuth(auth, expected)) return auth; if (!validToken(auth.refreshToken) || !Number.isFinite(auth.refreshExpiresAt) || auth.refreshExpiresAt <= Date.now()) return auth; // GitHub device-flow refresh does not require a client secret. // Never copy these credentials into page storage, exports or logs. const result = parse(await githubLogin('oauth/access_token', { grant_type: 'refresh_token', refresh_token: auth.refreshToken })); if (generation !== sessionGeneration || !sameAuth(readAuth(), auth)) return readAuth(); if (result.error) { // Retain the record: another process may have just rotated it, // and network/server errors are never a reason to sign out. if (['bad_refresh_token', 'expired_token', 'invalid_grant'].includes(result.error)) fail('loginRequired'); fail('networkError'); } const renewed = authFromResponse(result); if (renewed.expiresAt !== null && !renewed.refreshToken) fail('invalidResponse'); if (!leaseAlive()) fail('networkError'); if (validIdentity(auth.user)) renewed.user = auth.user; GM_setValue(tokenKey, renewed); return renewed; }).finally(() => { refreshing = null; }); return refreshing; } async function storedAuth() { let auth = await readAuth(); if (!object(auth) || !validToken(auth.token)) return null; if (Number.isFinite(auth.expiresAt) && auth.expiresAt <= Date.now() + 30000 && validToken(auth.refreshToken)) auth = await renewAuth(auth); // Older versions invented an eight-hour deadline even for permanent // tokens. Without a refresh token, let GitHub decide validity via 401. return object(auth) && validToken(auth.token) ? auth : null; } async function authenticated(path, options = {}, onSuccess) { const { rawResponse = false, expectedUserId, ...requestOptions } = options; let auth = await storedAuth(); if (!auth) fail('loginRequired'); for (let attempt = 0; attempt < 2; attempt++) { if (expectedUserId !== undefined && auth.user?.id !== expectedUserId) fail('loginRequired'); try { const response = await request(api + path, { ...requestOptions, token: auth.token }); const value = rawResponse ? response : parse(response, options.limit || 6000000); onSuccess?.(value, auth); return value; } catch (err) { if (err.code !== 'loginRequired') throw err; const current = readAuth(); if (!sameAuth(current, auth)) { if (options.method && options.method !== 'GET' && (!validIdentity(auth.user) || !validIdentity(current?.user) || auth.user.id !== current.user.id)) throw err; if (!attempt && current && validToken(current.token)) { auth = await storedAuth(); if (auth) continue; } throw err; } if (!attempt && validToken(auth.refreshToken) && auth.refreshExpiresAt > Date.now()) { auth = await renewAuth(auth); if (auth) continue; } else forgetAuth(auth); throw err; } } } async function user() { try { const identity = await authenticated('/user', {}, (value, auth) => { if (!validIdentity(value)) fail('invalidResponse'); const current = readAuth(); if (!sameAuth(current, auth)) fail('loginRequired'); if ((current.user?.id !== value.id || current.user?.login !== value.login) && typeof GM_setValue === 'function') { GM_setValue(tokenKey, { ...current, user: person(value) }); } }); return person(identity); } catch (err) { if (err.code === 'loginRequired') return null; const auth = readAuth(); if (['networkError', 'rateLimited'].includes(err.code) && validToken(auth?.token) && validIdentity(auth?.user)) return person(auth.user); throw err; } } async function logout() { sessionGeneration++; pendingSubmissions.clear(); if (typeof GM_deleteValue !== 'function') fail('managerUnavailable'); await GM_deleteValue(tokenKey); } function pause(milliseconds, signal) { return new Promise((resolve, reject) => { const abort = () => { clearTimeout(timer); reject(error('cancelled')); }; if (signal?.aborted) return reject(error('cancelled')); const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, milliseconds); signal?.addEventListener('abort', abort, { once: true }); }); } async function login(onDeviceCode, signal) { if (!JPX_CONFIG_STORE.clientId) fail('notConfigured'); if (loginPending) fail('loginPending'); if (typeof GM_setValue !== 'function') fail('managerUnavailable'); const generation = sessionGeneration, cancelled = () => generation !== sessionGeneration || signal?.aborted; loginPending = true; try { const device = parse(await githubLogin('device/code', {}, signal)); if (!text(device.device_code, 256) || !text(device.user_code, 64) || device.verification_uri !== 'https://github.com/login/device' || !integer(device.expires_in) || device.expires_in > 1800 || !integer(device.interval) || device.interval > 60) fail('invalidResponse'); onDeviceCode?.({ userCode: device.user_code, verificationUri: device.verification_uri, expiresIn: device.expires_in }); const expires = Date.now() + device.expires_in * 1000; let interval = Math.max(5, device.interval); while (Date.now() < expires) { await pause(Math.min(interval * 1000, expires - Date.now()), signal); if (cancelled()) fail('cancelled'); if (Date.now() >= expires) break; const result = parse(await githubLogin('oauth/access_token', { device_code: device.device_code, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }, signal)); if (result.error === 'authorization_pending') continue; if (result.error === 'slow_down') { interval += 5; continue; } if (result.error) fail(result.error === 'access_denied' ? 'accessDenied' : result.error === 'expired_token' ? 'loginExpired' : result.error === 'device_flow_disabled' ? 'notConfigured' : 'loginFailed'); const auth = authFromResponse(result); const identity = parse(await request(api + '/user', { token: result.access_token, signal })); if (!validIdentity(identity)) fail('invalidResponse'); if (cancelled()) fail('cancelled'); auth.user = person(identity); await GM_setValue(tokenKey, auth); if (cancelled()) { forgetAuth(auth); fail('cancelled'); } return person(identity); } fail('loginExpired'); } finally { loginPending = false; } } function entryValid(entry) { return object(entry) && integer(entry.id) && text(entry.author, 100) && text(entry.title, 100) && text(entry.description, 4000, true) && kinds.includes(entry.kind) && worlds.includes(entry.world) && text(entry.scriptVersion, 64) && text(entry.updatedAt, 64) && (entry.rating === undefined || object(entry.rating) && Number.isSafeInteger(entry.rating.count) && entry.rating.count >= 0 && Number.isSafeInteger(entry.rating.sum) && entry.rating.sum >= entry.rating.count && entry.rating.sum <= 5 * entry.rating.count) && /^[a-f0-9]{64}$/.test(entry.sha256) && entry.configPath === 'catalog/configs/' + entry.id + '-' + entry.sha256 + '.json' && entry.issueUrl === issueURL(entry.id) && (entry.kind === 'battle-mode' ? modes.includes(entry.mode) : entry.mode === undefined) && (entry.modes === undefined || Array.isArray(entry.modes) && entry.modes.length <= modes.length && new Set(entry.modes).size === entry.modes.length && entry.modes.every(mode => modes.includes(mode)) && (entry.kind === 'stats' ? !entry.modes.length : entry.kind !== 'battle-mode' || entry.modes.length === 1 && entry.modes[0] === entry.mode)); } async function catalog({ refresh = false } = {}) { if (!refresh && cache && Date.now() - cache.at < 60000) return clone(cache.value); // Raw GitHub can lag behind a publication even with a cache-busting query. const url = refresh ? api + '/repos/' + repository + '/contents/catalog/index.json?ref=main' : raw + 'catalog/index.json'; const value = parse(await request(url, refresh ? { accept: 'application/vnd.github.raw+json' } : {}), 6000000); if (!object(value) || value.schemaVersion !== 1 || !Array.isArray(value.entries) || value.entries.length > 5000 || !text(value.updatedAt, 64)) fail('invalidResponse'); const ids = new Set(); for (const entry of value.entries) { if (!entryValid(entry) || ids.has(entry.id)) fail('invalidResponse'); ids.add(entry.id); } cache = { at: Date.now(), value }; return clone(value); } async function load(entry) { if (!entryValid(entry)) fail('invalidResponse'); const source = await request(raw + entry.configPath, { limit: 60000 }); if (await hash(source) !== entry.sha256) fail('integrityFailed'); const value = validate(parse(source)); if (['kind', 'title', 'description', 'world', 'mode', 'scriptVersion'].some(key => value[key] !== entry[key])) fail('integrityFailed'); return value; } async function ownIssue(id) { if (!integer(id)) fail('invalidResponse'); const identity = await user(); if (!identity) fail('loginRequired'); const issue = await authenticated(issuesPath + '/' + id); if (issue.pull_request || issue.user?.id !== identity.id || issue.number !== id || issue.html_url !== issueURL(id)) fail('notOwner'); return issue; } // Walks 100-row pages until a short page; a full last page means the list is too long. async function eachPage(path, maxPages, tooMany, visit, options) { for (let page = 1; page <= maxPages; page++) { const rows = await authenticated(path + 'per_page=100&page=' + page, options); if (!Array.isArray(rows)) fail('invalidResponse'); visit(rows); if (rows.length < 100) return; } fail(tooMany); } async function mine() { const identity = await user(); if (!identity) fail('loginRequired'); const collected = []; await eachPage(issuesPath + '?state=all&creator=' + encodeURIComponent(identity.login) + '&', 10, 'tooManySubmissions', rows => { for (const row of rows) { if (row.pull_request || row.user?.id !== identity.id || !integer(row.number) || row.html_url !== issueURL(row.number) || typeof row.body !== 'string' || !row.body.startsWith(marker)) continue; collected.push({ id: row.number, title: row.title, state: row.state, labels: (row.labels || []).map(label => typeof label === 'string' ? label : label.name).filter(label => typeof label === 'string'), body: row.body, url: row.html_url, updatedAt: row.updated_at, pending: pendingSubmissions.get(row.number) === row.body }); } }); return collected; } async function submit(input, issueNumber, expectedBody) { const value = validate(clone(input)); const generation = sessionGeneration; if (issueNumber !== undefined) { const existing = await ownIssue(issueNumber); if (existing.state !== 'open') fail('submissionClosed'); if (!existing.body?.startsWith(marker)) fail('invalidConfig'); if (typeof expectedBody !== 'string' || existing.body !== expectedBody) fail('shareChanged'); } if (generation !== sessionGeneration) fail('loginRequired'); const body = marker + JSON.stringify(value) + '\n```'; if (encode(body).length > 60000) fail('tooLarge'); const result = await authenticated(issuesPath + (issueNumber === undefined ? '' : '/' + issueNumber), { method: issueNumber === undefined ? 'POST' : 'PATCH', data: { title: '[Config] ' + value.title, body } }); if (!integer(result.number) || result.html_url !== issueURL(result.number) || result.body !== body || result.state !== 'open' || issueNumber !== undefined && result.number !== issueNumber) fail('invalidResponse'); pendingSubmissions.set(result.number, body); return { id: result.number, url: result.html_url }; } async function withdraw(id) { const issue = await ownIssue(id); if (!issue.body?.startsWith(marker)) fail('invalidConfig'); await authenticated(issuesPath + '/' + id, { method: 'PATCH', data: { state: 'closed' } }); cache = null; } async function archive(id) { const generation = sessionGeneration, issue = await ownIssue(id); if (generation !== sessionGeneration) fail('loginRequired'); if (issue.state !== 'closed') fail('withdrawFirst'); if (issue.body?.startsWith(archivedMarker)) return; if (!issue.body?.startsWith(marker)) fail('invalidConfig'); // Keep the issue and exact configuration as an audit record. A distinct // marker removes it from Shared on every device without admin privileges. const body = archivedMarker + issue.body.slice(marker.length); const result = await authenticated(issuesPath + '/' + id, { method: 'PATCH', data: { state: 'closed', body } }); if (result.number !== id || result.html_url !== issueURL(id) || result.user?.id !== issue.user.id || result.state !== 'closed' || result.body !== body) fail('invalidResponse'); cache = null; } async function feedback(id) { const issue = await ownIssue(id), envelope = parseSubmission(issue.body), revision = await hash(JSON.stringify(envelope) + '\n'); let latest = null; await eachPage(issuesPath + '/' + id + '/comments?', 10, 'tooManySubmissions', rows => { for (const row of rows) { if (row.user?.login !== 'github-actions[bot]' || row.user.type !== 'Bot' || typeof row.body !== 'string') continue; const match = row.body.match(//); if (!match) continue; try { const value = parse(match[1], 24000); if (value.revision !== revision || !['published', 'changes-requested', 'needs-review', 'unavailable', 'pending'].includes(value.status) || !object(value.summary) || !text(value.summary.en, 3000, true) || !text(value.summary.zh, 3000, true) || !Array.isArray(value.findings) || value.findings.length > 50) continue; if (value.findings.some(item => !object(item) || !['info', 'warning', 'error'].includes(item.severity) || !text(item.path, 300, true) || !text(item.en, 3000, true) || !text(item.zh, 3000, true))) continue; latest = value; } catch { /* Ignore malformed, unrelated, or stale comments. */ } } }); if (latest && latest.status !== 'pending' && pendingSubmissions.get(id) === issue.body) pendingSubmissions.delete(id); return latest; } function commentRecord(row, issue) { if (!object(row) || !integer(row.id) || !validIdentity(row.user) || row.user.type !== 'User' || !text(row.body, 65536, true) || row.html_url !== issueURL(issue) + '#issuecomment-' + row.id || row.issue_url !== api + issuesPath + '/' + issue || !Number.isFinite(Date.parse(row.created_at)) || !Number.isFinite(Date.parse(row.updated_at))) return null; return { id: row.id, body: row.body, author: { id: row.user.id, login: row.user.login }, createdAt: row.created_at, updatedAt: row.updated_at, url: row.html_url }; } async function comments(issue, page = 1) { if (!integer(issue) || !integer(page) || page > 1000) fail('invalidResponse'); const path = issuesPath + '/' + issue + '/comments?per_page=30&page=' + page; let rows; try { rows = await authenticated(path); } catch (error) { if (error.code !== 'loginRequired') throw error; rows = parse(await request(api + path), 6000000); } if (!Array.isArray(rows) || rows.length > 30) fail('invalidResponse'); return { items: rows.map(row => commentRecord(row, issue)).filter(row => row && !row.body.startsWith(ratingPrefix)), nextPage: rows.length === 30 ? page + 1 : null }; } function commentBody(value) { if (!text(value, 10000) || encode(value).length > 60000 || value.trim().startsWith(ratingPrefix)) fail('commentInvalid'); return value.trim(); } async function commentIdentity(expectedUserId) { if (!integer(expectedUserId)) fail('loginRequired'); const identity = await user(); if (identity?.id !== expectedUserId) fail('loginRequired'); return identity; } async function commentMutation(action) { try { return await action(); } catch (error) { if (error.code === 'rateLimited') throw error; if (error.status === 403) fail('commentDenied'); if (error.status === 404) fail('commentMissing'); if (error.status === 422) fail('commentInvalid'); throw error; } } async function commentIssue(issue, expectedUserId) { const path = issuesPath + '/' + issue; const current = await authenticated(path, { expectedUserId }); if (current.number !== issue || current.html_url !== issueURL(issue) || current.pull_request || !current.body?.startsWith(marker)) fail('invalidResponse'); if (current.locked || current.state !== 'open' || current.labels?.some(label => (label.name || label) === 'store:hide')) fail('commentsClosed'); return path; } async function addComment(issue, input, expectedUserId) { if (!integer(issue)) fail('invalidResponse'); const body = commentBody(input), identity = await commentIdentity(expectedUserId); return commentMutation(async () => { const path = await commentIssue(issue, expectedUserId); const result = commentRecord(await authenticated(path + '/comments', { method: 'POST', data: { body }, expectedUserId }), issue); if (!result || result.author.id !== identity.id || result.body !== body) fail('invalidResponse'); return result; }); } async function ownComment(issue, expected, expectedUserId, rating = false) { if (!integer(issue) || !integer(expected?.id) || !text(expected.body, 65536, true) || !text(expected.updatedAt, 64)) fail('invalidResponse'); const identity = await commentIdentity(expectedUserId); const path = issuesPath + '/comments/' + expected.id; const current = commentRecord(await authenticated(path, { expectedUserId }), issue); if (!current || current.author.id !== identity.id) fail('commentNotOwner'); if (rating ? !ratingScore(current.body) : current.body.startsWith(ratingPrefix)) fail('invalidResponse'); if (current.body !== expected.body || current.updatedAt !== expected.updatedAt) fail('commentChanged'); return { current, path }; } async function updateComment(issue, expected, input, expectedUserId) { const body = commentBody(input); return commentMutation(async () => { const { current, path } = await ownComment(issue, expected, expectedUserId); if (current.body === body) return current; const result = commentRecord(await authenticated(path, { method: 'PATCH', data: { body }, expectedUserId }), issue); if (!result || result.id !== current.id || result.author.id !== current.author.id || result.body !== body) fail('invalidResponse'); return result; }); } async function deleteComment(issue, expected, expectedUserId) { return commentMutation(async () => { const { path } = await ownComment(issue, expected, expectedUserId); await authenticated(path, { method: 'DELETE', rawResponse: true, expectedUserId }); return true; }); } async function ratingRecords(issue, expectedUserId) { if (!integer(issue)) fail('invalidResponse'); await commentIdentity(expectedUserId); const records = []; await eachPage(issuesPath + '/' + issue + '/comments?', 100, 'ratingsTooMany', rows => { if (rows.length > 100) fail('invalidResponse'); for (const row of rows) { const value = commentRecord(row, issue); if (value && ratingScore(value.body)) records.push(value); } }, { expectedUserId }); return records; } function ratingState(records, expectedUserId) { const votes = new Map(); for (const record of records.slice().sort((a, b) => Date.parse(a.updatedAt) - Date.parse(b.updatedAt) || a.id - b.id)) votes.set(record.author.id, record); return { score: ratingScore(votes.get(expectedUserId)?.body), count: votes.size, sum: [...votes.values()].reduce((sum, row) => sum + ratingScore(row.body), 0) }; } async function rating(issue, expectedUserId) { return ratingState(await ratingRecords(issue, expectedUserId), expectedUserId); } async function setRating(issue, score, expectedUserId) { if (!integer(issue) || score !== null && (!Number.isInteger(score) || score < 1 || score > 5)) fail('ratingInvalid'); return commentMutation(async () => { let records = await ratingRecords(issue, expectedUserId); const own = records.filter(row => row.author.id === expectedUserId).sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt) || b.id - a.id); if (score === null) { // Remove older duplicates first so withdrawing never resurrects an old vote. for (const row of own.slice().reverse()) { const { path } = await ownComment(issue, row, expectedUserId, true); await authenticated(path, { method: 'DELETE', rawResponse: true, expectedUserId }); } records = records.filter(row => row.author.id !== expectedUserId); } else { const path = await commentIssue(issue, expectedUserId), body = ratingBody(score); const current = own[0]; if (!current || current.body !== body) { const target = current ? (await ownComment(issue, current, expectedUserId, true)).path : path + '/comments'; const saved = commentRecord(await authenticated(target, { method: current ? 'PATCH' : 'POST', data: { body }, expectedUserId }), issue); if (!saved || saved.author.id !== expectedUserId || saved.body !== body || current && saved.id !== current.id) fail('invalidResponse'); records = records.filter(row => row.id !== saved.id); records.push(saved); } } cache = null; return ratingState(records, expectedUserId); }); } return Object.freeze({ catalog, load, user, login, logout, mine, submit, withdraw, archive, parseSubmission, feedback, comments, addComment, updateComment, deleteComment, rating, setRating, prepare: input => validate(clone(input)) }); })(); function renderConfigStore(parent, hooks, options = {}) { const doc = parent.ownerDocument; const tr = key => t('cStore.' + key); const el = (tag, text, className) => { const node = doc.createElement(tag); if (text !== undefined) node.textContent = text; if (className) node.className = className; return node; }; const div = className => el('div', undefined, className); const root = el('section', undefined, 'jpx-store'); const toolbar = div('jpx-store-toolbar'); const navigation = div('jpx-store-navigation'); const account = div('jpx-store-account'); const status = el('p', '', 'jpx-store-status'); status.setAttribute('role', 'status'); status.hidden = true; const viewHeader = div('jpx-store-view-header'); const stage = div('jpx-store-stage'); const layoutEvents = new AbortController(); let browseControls = null, commentView = null, ratingView = null; const commentDrafts = new Map(); const state = { view: 'browse', query: '', sharedQuery: '', kind: '', world: '', style: '', battleType: '', sort: 'updated', filtersOpen: false, visible: 30, browseScroll: 0, user: null, editor: null, request: 0, login: null, disposed: false, suspended: false, saved: new Set(), authGeneration: 0, currentEntry: null }; const alive = () => !state.disposed && !state.suspended && root.isConnected; const live = request => alive() && request === state.request; const labelled = (node, label) => { node.title = label; node.setAttribute('aria-label', label); return node; }; const icon = (path, size = 16, stroke = 1.7) => ''; function downloadCount(id) { const node = el('span', undefined, 'jpx-download-count'); node.dataset.downloadId = String(id); node.setAttribute('role', 'img'); node.innerHTML = icon('M12 3v12m-5-5 5 5 5-5M4 16v4h16v-4', 14, 1.6) + ''; paintDownloadCount(node); return node; } function paintDownloadCount(node) { const count = downloadCounts.peek(Number(node.dataset.downloadId)), text = count === null ? '—' : count.toLocaleString(); node.lastElementChild.textContent = text; labelled(node, tr(count === null ? 'downloadsUnavailable' : 'downloadCount').replace('${count}', text)); } function refreshDownloadCounts() { const nodes = [...stage.querySelectorAll('.jpx-download-count')]; const pending = []; for (let i = 0; i < nodes.length; i += 100) pending.push(downloadCounts.counts(nodes.slice(i, i + 100).map(node => Number(node.dataset.downloadId)))); Promise.all(pending).then(() => { if (alive()) nodes.filter(node => node.isConnected).forEach(paintDownloadCount); }).catch(() => {}); } function recordDownload(id) { downloadCounts.record(id).then(() => { if (alive()) stage.querySelectorAll('.jpx-download-count').forEach(paintDownloadCount); }).catch(() => {}); } function layoutBrowseControls() { if (!alive() || !browseControls) return; const { queryBar, results, refresh, clear, sort } = browseControls; const mobile = root.closest('.jpx-settings-mobile'); const focused = doc.activeElement; if (options.toolbarHost) { if (mobile) { if (queryBar.parentElement !== options.toolbarHost || queryBar.previousElementSibling !== toolbar) options.toolbarHost.append(queryBar); if (refresh.parentElement !== queryBar) queryBar.append(refresh); if (clear && clear.parentElement !== results) results.insertBefore(clear, sort); } else { if (queryBar.parentElement !== options.toolbarHost || queryBar.nextElementSibling !== toolbar) options.toolbarHost.insertBefore(queryBar, toolbar); const refreshHost = results || queryBar; if (refresh.parentElement !== refreshHost) refreshHost.append(refresh); if (clear && clear.parentElement !== queryBar) queryBar.append(clear); } if (results && results.parentElement !== viewHeader) viewHeader.append(results); } else if (mobile) { if (results.parentElement !== viewHeader) viewHeader.append(results); } else if (results.parentElement !== queryBar) queryBar.insertBefore(results, queryBar.lastElementChild); if (focused?.isConnected && focused !== doc.activeElement) focused.focus({ preventScroll: true }); } doc.defaultView.addEventListener('resize', layoutBrowseControls, { signal: layoutEvents.signal }); doc.defaultView.visualViewport?.addEventListener('resize', layoutBrowseControls, { signal: layoutEvents.signal }); function message(text, error = false) { status.textContent = text || ''; status.hidden = !text; status.dataset.error = String(error); } // Error codes that share their message key; anything else is a generic failure. const messageCodes = new Set(['loginRequired', 'notConfigured', 'networkError', 'invalidConfig', 'tooLarge', 'accessDenied', 'loginExpired', 'managerUnavailable', 'notOwner', 'submissionClosed', 'withdrawFirst', 'shareChanged', 'localChanged', 'tooManySubmissions', 'storageCorrupt', 'storageError', 'localNotFound']); function errorMessage(error) { const code = error?.code, renamed = { rateLimited: 'rateLimit', integrityFailed: 'integrityError' }; if (Object.hasOwn(renamed, code)) return tr(renamed[code]); return tr(messageCodes.has(code) ? code : 'requestFailed'); } function button(text, action, className) { const node = el('button', text, className); node.type = 'button'; node.addEventListener('click', async () => { node.disabled = true; try { await action(node); } catch (error) { if (alive() && error?.name !== 'AbortError') message(errorMessage(error), true); } finally { if (node.isConnected) node.disabled = false; } }); return node; } const confirmShare = (title, description, action) => hooks.confirm ? hooks.confirm(title, description, action) : Promise.resolve(confirm([title, description].filter(Boolean).join('\n'))); function field(text, input) { const label = el('label', undefined, 'jpx-store-field'); input.setAttribute('aria-label', text); label.append(el('span', text), input); return label; } function refreshControl(action) { const node = button(tr('refresh'), action); if (options.toolbarHost) { node.className = 'jpx-store-refresh'; labelled(node, tr('refresh')).innerHTML = icon('M3 11a9 9 0 0 1 15.6-5.4L21 8M21 3v5h-5M21 13A9 9 0 0 1 5.4 18.4L3 16M3 21v-5h5'); } return node; } function select(options, value) { const node = el('select'); for (const [key, name] of options) { const option = el('option', name); option.value = key; node.append(option); } node.value = value; return node; } const kinds = () => [['battle-mode', tr('currentMode')], ['battle', tr('allBattle')], ['stats', tr('stats')]]; const kindName = kind => kinds().find(([key]) => key === kind)?.[1] || kind; const worldName = world => tr(world === 'Isekai' ? 'isekai' : world === 'Persistent' ? 'persistent' : 'anyWorld'); const styleName = style => host.jpxI18N?.cB?.[style] || host.jpxI18N?.cW?.[style] || tr(style); const battleName = battle => host.jpxI18N?.cB?.[battle] || tr(battle); const splitMode = mode => { const split = mode.lastIndexOf('_'); return [mode.slice(0, split), mode.slice(split + 1)]; }; function modeName(mode) { if (!mode) return ''; const [style, battle] = splitMode(mode); return styleName(style) + ' · ' + battleName(battle); } function info(envelope, author) { return [author ? '@' + author : '', kindName(envelope.kind), worldName(envelope.world), modeName(envelope.mode)].filter(Boolean).join(' · '); } function tags(envelope, author, choose) { if (!hooks.renderTags) return el('p', info(envelope, author), 'jpx-store-meta'); const group = hooks.renderTags(envelope, choose); if (author) group.prepend(el('span', '@' + author, 'jpx-config-tag-author')); return group; } const browseButton = button(tr('browse'), () => browse()); const mineButton = button(tr('shared'), () => options.toolbarHost && state.view === 'mine' ? browse() : mine()); navigation.append(...(options.toolbarHost ? [mineButton] : [browseButton, mineButton])); toolbar.append(navigation, account); root.append(toolbar, viewHeader, status, stage); parent.append(root); if (options.toolbarHost) options.toolbarHost.append(toolbar); function accountControls() { account.replaceChildren(); if (state.user) { const logout = button('@' + state.user.login, async node => { const user = state.user, previousGeneration = state.authGeneration; const confirmed = await confirmShare(tr('signOut') + '?', '@' + user.login, tr('signOut')); if (!alive() || state.user !== user || state.authGeneration !== previousGeneration) return; if (!confirmed) { node.disabled = false; node.focus({ preventScroll: true }); return; } const generation = ++state.authGeneration; await jpxConfigStore.logout(); if (!alive() || generation !== state.authGeneration) return; state.user = null; accountControls(); if (state.view === 'mine') await mine(); message(tr('signedOut')); account.querySelector('button')?.focus({ preventScroll: true }); }); logout.title = tr('signOut'); logout.setAttribute('aria-label', tr('signOut') + ' · ' + state.user.login); account.append(logout); } else account.append(button(tr('signIn'), () => login())); commentView?.authChanged(); ratingView?.authChanged(); } const closeViews = () => { commentView?.dispose(); ratingView?.dispose(); commentView = ratingView = null; }; function open(view) { closeViews(); browseControls?.queryBar.remove(); browseControls = null; state.login?.abort(); state.login = null; if (view !== 'edit' && view !== 'login') state.editor = null; if (view !== 'detail') state.currentEntry = null; state.view = view; state.back = null; const browsing = !!options.toolbarHost && view === 'browse'; root.classList.toggle('jpx-store-browsing', browsing); viewHeader.classList.toggle('jpx-store-browse-header', browsing); viewHeader.classList.toggle('jpx-config-list-header', browsing); state.request++; browseButton.setAttribute('aria-pressed', String(view === 'browse' || view === 'detail')); mineButton.setAttribute('aria-pressed', String(view === 'mine' || view === 'edit')); viewHeader.replaceChildren(); stage.replaceChildren(); message(''); stage.scrollTop = 0; return state.request; } function heading(title, back) { const row = div('jpx-store-heading'); state.back = back || null; if (back) row.append(button(tr('back'), back, 'jpx-store-back')); row.append(el('h3', title)); viewHeader.append(row); } function empty(text, action, label = tr('retry'), target = stage) { const box = div('jpx-store-empty'); box.append(el('p', text)); if (action) box.append(button(label, action)); target.append(box); } function searchField(value, label) { const node = el('input'); node.type = 'search'; node.value = value; node.placeholder = label; node.setAttribute('aria-label', label); return node; } // Stats configs have no style or battle type, so choosing them clears both. function chooseFilter(key, value) { state[key === 'scenario' ? 'battleType' : key] = value; if (key === 'kind' && value === 'stats') state.style = state.battleType = ''; } async function browse(refresh = false) { const backEntry = state.view === 'detail' ? state.currentEntry?.id : null; const backScroll = backEntry ? state.browseScroll : 0; const request = open('browse'); const queryBar = div('jpx-store-querybar'); const search = searchField(state.query, tr('search')); const filters = div('jpx-store-filter-grid'); filters.id = 'jpx-store-catalog-filters'; const toggle = button(tr('filters'), () => { state.filtersOpen = !state.filtersOpen; updateFilters(); }, 'jpx-store-filter-toggle'); toggle.setAttribute('aria-controls', filters.id); const refreshButton = refreshControl(() => loadCatalog(true)); queryBar.append(search, toggle, refreshButton); const controls = {}; for (const [key, choices] of [ ['world', [['', tr('allWorlds')], ...['Persistent', 'Isekai'].map(value => [value, worldName(value)])]], ['style', [['', tr('allStyles')], ...styles.map(value => [value, styleName(value)])]], ['battleType', [['', tr('allBattles')], ...battleTypes.map(value => [value, battleName(value)])]], ['kind', [['', tr('allTypes')], ...kinds()]] ]) { const control = select(choices, state[key]); controls[key] = control; control.setAttribute('aria-label', tr(key === 'kind' ? 'type' : key)); control.dataset.storeFilter = key; control.addEventListener('change', () => { chooseFilter(key, control.value); render(true); }); filters.append(control); } const results = div('jpx-store-results'); const count = el('span', '', 'jpx-store-result-count'); count.setAttribute('role', 'status'); count.setAttribute('aria-live', 'polite'); const reset = () => { state.query = state.kind = state.world = state.style = state.battleType = ''; search.value = ''; render(true); }; const clear = button(tr('clearFilters'), reset, 'jpx-store-clear'); const sort = select([['updated', tr('latest')], ['name', tr('nameSort')], ...(hooks.compareTypes ? [['type', t('cM.typeSort')]] : [])], state.sort); sort.setAttribute('aria-label', tr('sort')); sort.dataset.storeSort = ''; sort.addEventListener('change', () => { state.sort = sort.value; render(true); }); results.append(count, clear, sort); const list = div('jpx-store-list'); list.setAttribute('aria-busy', 'true'); const focusEntry = id => list.querySelector('[data-store-id="' + id + '"] .jpx-store-title')?.focus({ preventScroll: true }); browseControls = { queryBar, results, refresh: refreshButton, clear, sort }; viewHeader.append(queryBar, filters, results); stage.append(list); layoutBrowseControls(); // Normalize catalog metadata once, then filter locally without more requests. const normalize = value => String(value || '').normalize('NFKC').toLocaleLowerCase().replace(/[@_·/\-]+/g, ' ').replace(/\s+/g, ' ').trim(); const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); let index = null, orderedBy = null; function updateFilters() { const active = ['world', 'style', 'battleType', 'kind'].filter(key => state[key]).length; toggle.textContent = tr('filters') + (active ? ' (' + active + ')' : ''); toggle.setAttribute('aria-expanded', String(state.filtersOpen)); filters.dataset.open = String(state.filtersOpen); clear.hidden = !active && !state.query; for (const [key, control] of Object.entries(controls)) { control.value = state[key]; control.disabled = ['style', 'battleType'].includes(key) && state.kind === 'stats'; } } filters.addEventListener('keydown', event => { if (event.key === 'Escape' && state.filtersOpen && root.closest('.jpx-settings-mobile')) { event.stopPropagation(); state.filtersOpen = false; updateFilters(); toggle.focus(); } }); function render(resetPosition = false) { updateFilters(); if (!index) return; if (orderedBy !== state.sort) { const byTitle = (a, b) => collator.compare(a.entry.title, b.entry.title) || a.entry.id - b.entry.id; index.sort((a, b) => state.sort === 'type' ? hooks.compareTypes(a.entry, b.entry) || byTitle(a, b) : state.sort === 'name' ? byTitle(a, b) : b.updated - a.updated || b.entry.id - a.entry.id); orderedBy = state.sort; } if (resetPosition) { state.visible = 30; state.browseScroll = 0; stage.scrollTop = 0; } list.replaceChildren(); const words = normalize(state.query).split(' ').filter(Boolean); const matches = index.filter(({ entry, modes, text }) => (!state.kind || entry.kind === state.kind) && (!state.world || entry.world === state.world || entry.world === 'Any') && ((!state.style && !state.battleType) || modes.some(mode => { const [style, battle] = splitMode(mode); return (!state.style || style === state.style) && (!state.battleType || battle === state.battleType); })) && words.every(word => text.includes(word))); count.textContent = tr('resultCount').replace('${count}', String(matches.length)); if (!matches.length) return empty(tr(index.length ? 'noMatches' : 'noConfigs'), clear.hidden ? null : () => { reset(); search.focus(); }, tr('clearFilters'), list); const fragment = doc.createDocumentFragment(); for (const { entry, updated } of matches.slice(0, state.visible)) { const row = el('article', undefined, 'jpx-store-row'); row.dataset.storeId = String(entry.id); const title = button(entry.title, () => { state.browseScroll = stage.scrollTop; return details(entry); }, 'jpx-store-title'); row.append(title); const tools = div('jpx-store-row-tools'); if (updated) { const date = el('time', new Date(updated).toLocaleDateString(), 'jpx-store-date'); date.dateTime = entry.updatedAt; date.title = tr('latest'); tools.append(date); } const download = button('', async node => { node.setAttribute('aria-busy', 'true'); try { const envelope = await jpxConfigStore.load(entry); if (!live(request) || !node.isConnected) return; if (!await saveConfig(envelope, entry)) return; if (live(request) && node.isConnected) { node.title = tr('saved'); node.setAttribute('aria-label', tr('saved') + ': ' + entry.title); node.innerHTML = icon('m5 12 4 4L19 6'); } } catch (error) { if (live(request) && node.isConnected) throw error; } finally { node.removeAttribute('aria-busy'); } }, 'jpx-store-download'); download.title = tr('save'); download.setAttribute('aria-label', tr('save') + ': ' + entry.title); download.innerHTML = icon('M12 3v12m-5-5 5 5 5-5M4 16v4a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-4'); tools.prepend(download); row.append(tools); row.append(tags(entry, entry.author, (key, value) => { chooseFilter(key, value); render(true); })); const metrics = el('p', undefined, 'jpx-store-rating-summary'); metrics.append(el('span', jpxStoreRatingText(ratingTotals.get(entry.id) || entry.rating, tr)), downloadCount(entry.id)); row.append(metrics); if (entry.description) row.append(el('p', entry.description, 'jpx-store-excerpt')); fragment.append(row); } if (matches.length > state.visible) fragment.append(button(tr('showMore'), () => { const position = stage.scrollTop, next = matches[state.visible]?.entry.id; state.visible += 30; render(); focusEntry(next); stage.scrollTop = position; }, 'jpx-store-show-more')); list.append(fragment); refreshDownloadCounts(); } search.addEventListener('input', event => { state.query = search.value; if (!event.isComposing) render(true); }); search.addEventListener('compositionend', () => { state.query = search.value; render(true); }); updateFilters(); async function loadCatalog(force) { refreshButton.disabled = true; refreshButton.setAttribute('aria-busy', 'true'); labelled(refreshButton, tr('loading')); list.setAttribute('aria-busy', 'true'); message(''); try { const catalog = await jpxConfigStore.catalog({ refresh: force }); if (!live(request)) return; if (force) ratingTotals.clear(); orderedBy = null; index = catalog.entries.map(entry => { const modes = entry.mode ? [entry.mode] : entry.modes || []; const labels = modes.flatMap(mode => { const [style, battle] = splitMode(mode); return [mode, modeName(mode), tr(style), tr(battle), translations.en[style], translations.en[battle]]; }); return { entry, modes, updated: Date.parse(entry.updatedAt) || 0, text: normalize([entry.title, entry.description, entry.author, entry.kind, kindName(entry.kind), entry.world, worldName(entry.world), entry.world === 'Any' ? t('cM.anyWorld') : '', entry.kind === 'stats' ? t('cM.stats') : entry.kind === 'battle' ? modes.length ? t('cM.groupCount').replace('${count}',String(modes.length)) : t('cM.allBattle') : '', ...labels].join(' ')) }; }); const scroll = stage.scrollTop; render(); stage.scrollTop = scroll; } catch (error) { if (!live(request)) return; message(errorMessage(error), true); } finally { refreshButton.disabled = false; refreshButton.removeAttribute('aria-busy'); labelled(refreshButton, tr('refresh')); list.setAttribute('aria-busy', 'false'); } } await loadCatalog(refresh); if (backEntry && live(request)) { focusEntry(backEntry); stage.scrollTop = backScroll; } } function configSummary(envelope) { const values = envelope.config; const counts = []; if (envelope.kind === 'stats') { for (const [key, name] of [['statsColumns', 'columns'], ['combatRows', 'combatRows'], ['revenueRows', 'revenueRows']]) if (Array.isArray(values[key])) counts.push(tr(name) + ': ' + values[key].filter(item => item.disabled !== true).length); } else { let count = 0, code = 0; for (const mode of Object.values(values)) { const rules = Array.isArray(mode?.rules) ? mode.rules : Array.isArray(mode?.supports) && Array.isArray(mode.attacks) ? [...mode.supports, ...mode.attacks] : []; count += rules.length; code += rules.filter(rule => rule.type === 'kamisamaniNattaHi').length; } counts.push(tr('rules') + ': ' + count); if (code) counts.push(tr('customCode') + ': ' + code); } return counts.join(' · '); } function rawPreview(envelope) { const details = el('details', undefined, 'jpx-store-raw'); details.append(el('summary', tr('viewConfig'))); details.addEventListener('toggle', () => { if (details.open && details.childElementCount === 1) details.append(el('pre', JSON.stringify(envelope.config, null, 2))); }); return details; } function downloadConfig(envelope, id) { const blob = new Blob([JSON.stringify(envelope.config, null, 2)], { type: 'application/json;charset=utf-8' }); const url = URL.createObjectURL(blob), link = el('a'); link.href = url; link.download = 'jpx-config-' + id + '.json'; link.click(); recordDownload(id); setTimeout(() => URL.revokeObjectURL(url), 1000); } async function saveConfig(envelope, entry) { if (typeof hooks.saveConfig !== 'function') throw new Error('Save unavailable'); const saved = await hooks.saveConfig(clone(envelope), { id: entry.id, author: entry.author, source: { repository: JPX_CONFIG_STORE.repository, id: entry.id, author: entry.author, sha256: entry.sha256, url: entry.issueUrl } }); if (saved === false) return false; state.saved.add(entry.id); recordDownload(entry.id); return true; } async function details(entry) { const request = open('detail'); heading(entry.title, () => browse()); message(tr('loading')); state.currentEntry = entry; try { const envelope = await jpxConfigStore.load(entry); if (!live(request)) return; message(''); stage.append(tags(envelope, entry.author, (key, value) => { chooseFilter(key, value); return browse(); })); if (envelope.description) stage.append(el('p', envelope.description, 'jpx-store-description')); stage.append(el('p', configSummary(envelope), 'jpx-store-meta'), el('p', tr('scriptVersion') + ': ' + envelope.scriptVersion, 'jpx-store-meta')); const actions = div('jpx-store-actions'); const save = button(tr(state.saved.has(entry.id) ? 'saved' : 'save'), async node => { if (!await saveConfig(envelope, entry)) return; if (!live(request)) return; node.textContent = tr('saved'); message(tr('savedConfig')); }, 'jpx-store-primary'); actions.append(save); if (typeof hooks.applyConfig === 'function') actions.append(button(tr('apply'), () => hooks.applyConfig(clone(envelope)))); actions.append(button(tr('download'), () => downloadConfig(envelope, entry.id))); stage.append(actions, rawPreview(envelope)); const reopen = () => details(entry), community = { service: jpxConfigStore, entry, tr, el, signIn: () => login(reopen, reopen), user: () => state.user, isCurrent: () => live(request) }; ratingView = renderJpxStoreRating(stage, { ...community, summary: ratingTotals.get(entry.id) || entry.rating, onChange: value => ratingTotals.set(entry.id, value) }); stage.querySelector('.jpx-rating-heading strong').after(downloadCount(entry.id)); refreshDownloadCounts(); const draft = commentDrafts.get(entry.id) || { body: '', edits: {} }; commentDrafts.set(entry.id, draft); commentView = renderJpxStoreComments(stage, { ...community, confirm: confirmShare, draft }); } catch (error) { if (!live(request)) return; message(errorMessage(error), true); empty(tr('cannotLoad'), () => details(entry)); } } async function login(after = () => browse(), cancel = () => browse()) { const generation = ++state.authGeneration; const request = open('login'); heading(tr('signIn'), cancel); const panel = div('jpx-store-auth'); stage.append(panel); const controller = new AbortController(); state.login = controller; message(tr('connecting')); try { const user = await jpxConfigStore.login(code => { if (!live(request)) return; message(''); panel.replaceChildren(el('p', tr('authHint'))); const copyCode = async text => { try { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(text); return true; } } catch {} const area = doc.createElement('textarea'); const focused = doc.activeElement; try { area.value = text; area.setAttribute('readonly', ''); area.style.cssText = 'position:fixed;top:-1000px;opacity:0'; // A modal dialog makes nodes outside it inert, including clipboard helpers. panel.appendChild(area); area.focus({ preventScroll: true }); area.select(); return doc.execCommand('copy'); } catch { return false; } finally { area.remove(); if (focused?.isConnected) focused.focus({ preventScroll: true }); } }; const codeRow = div('jpx-store-auth-code-row'); const codeEl = el('code', code.userCode, 'jpx-store-auth-code'); const copy = button(tr('copyCode'), async node => { const copied = await copyCode(code.userCode); node.textContent = tr(copied ? 'copied' : 'copyFailed'); node.disabled = false; if (node.isConnected && alive()) node.focus({ preventScroll: true }); setTimeout(() => { if (node.isConnected) node.textContent = tr('copyCode'); }, 1400); }, 'jpx-store-auth-copy'); codeRow.append(codeEl, copy); panel.append(codeRow); const link = el('a', tr('authorize'), 'jpx-store-link'); // Device authorization is the only external navigation in the publishing flow. const url = new URL(code.verificationUri); if (url.origin !== 'https://github.com' || url.pathname !== '/login/device') throw new Error('Invalid authorization URL'); link.href = url.href; link.target = '_blank'; link.rel = 'noopener noreferrer'; panel.append(link, el('p', tr('waitingAuth'), 'jpx-store-meta'), button(tr('cancel'), cancel)); }, controller.signal); if (!live(request) || generation !== state.authGeneration) return; state.user = user || await jpxConfigStore.user(); state.login = null; accountControls(); await after(); } catch (error) { if (!live(request) || error?.name === 'AbortError') return; message(errorMessage(error), true); panel.replaceChildren(button(tr('retry'), () => login(after, cancel))); } } async function edit(model) { if (!model?.envelope) return options.onBack?.(); if (model.id && !model.originalEnvelope) model.originalEnvelope = clone(model.envelope); state.editor = model; const request = open('edit'); heading(tr(model.id ? 'updateShare' : 'share'), model.back || options.onBack || (() => mine())); const form = el('form', undefined, 'jpx-store-form'); form.dataset.storeEditor = 'share'; const envelope = model.envelope; const world = model.id ? select(['Persistent', 'Isekai', 'Any'].map(value => [value, worldName(value)]), envelope.world) : null; const title = el('input'); title.type = 'text'; title.required = true; title.maxLength = 100; title.value = envelope.title || ''; const description = el('textarea'); description.rows = 4; description.maxLength = 4000; description.value = envelope.description || ''; const metadata = el('p', info(envelope), 'jpx-store-meta'); form.append(metadata); let preview = rawPreview(envelope); if (model.id && typeof hooks.listShareConfigs === 'function' && typeof hooks.getShareConfig === 'function') { const matches = entry => entry?.envelope?.kind === model.originalEnvelope.kind && entry.envelope.mode === model.originalEnvelope.mode; const entries = hooks.listShareConfigs().filter(matches); const content = select([['', tr('keepSharedConfig')], ...entries.map(entry => [entry.id, entry.envelope.title + ' · ' + worldName(entry.envelope.world)])], model.localSource?.id || ''); content.dataset.shareSource = ''; if (!entries.length) { const option = el('option', tr('noMatchingLocal')); option.disabled = true; content.append(option); } // A source deleted in another tab stays visible until the user selects // a replacement; never silently submit its stale snapshot as current. if (model.localSource && !entries.some(entry => entry.id === model.localSource.id)) { const option = el('option', model.localSource.title); option.value = model.localSource.id; content.append(option); content.value = option.value; } content.addEventListener('change', () => { const previous = model.localSource?.id || ''; try { const entry = content.value ? hooks.getShareConfig(content.value) : null; if (content.value && !matches(entry)) { content.value = previous; message(tr('localChanged'), true); return; } const chosen = jpxConfigStore.prepare(entry?.envelope || model.originalEnvelope); envelope.config = chosen.config; envelope.scriptVersion = chosen.scriptVersion; model.localSource = entry ? { id: entry.id, revision: entry.revision, title: entry.envelope.title } : null; const replacement = rawPreview(envelope), expanded = preview.open; preview.replaceWith(replacement); preview = replacement; preview.open = expanded; message(''); } catch (error) { content.value = previous; message(errorMessage(error), true); } }); form.append(field(tr('configContents'), content)); } if (world) form.append(field(tr('appliesTo'), world)); form.append(field(tr('title'), title), field(tr('description'), description)); const actions = div('jpx-store-actions'); const publish = el('button', tr(model.id ? 'submitUpdate' : 'submit'), 'jpx-store-primary'); publish.type = 'submit'; actions.append(publish); form.append(preview, actions, el('p', tr('reviewHint'), 'jpx-store-meta')); for (const [control, key] of [[title, 'title'], [description, 'description'], ...(world ? [[world, 'world']] : [])]) control.addEventListener('input', () => { envelope[key] = control.value; if (key === 'world') metadata.textContent = info(envelope); }); form.addEventListener('submit', async event => { event.preventDefault(); if (!form.reportValidity()) return; envelope.title = title.value.trim(); envelope.description = description.value.trim(); if (world) envelope.world = world.value; if (!envelope.title) { title.focus(); return; } if (model.localSource && hooks.getShareConfig(model.localSource.id)?.revision !== model.localSource.revision) { message(tr('localChanged'), true); return; } if (!state.user) { await login(() => edit(model), () => edit(model)); return; } publish.disabled = true; message(tr('submitting')); try { await jpxConfigStore.submit(envelope, model.id, model.originalBody); state.editor = null; if (!alive()) { state.view = 'mine'; return; } if (request !== state.request) { hooks.notify?.(tr('submitted')); return; } await mine(); const done = tr(model.id ? 'updateSubmitted' : 'submitted'); if (hooks.notify) hooks.notify(done); else message(done); } catch (error) { if (alive()) message(errorMessage(error), true); } finally { if (publish.isConnected) publish.disabled = false; } }); stage.append(form); } // Review status -> message key; the order is the label priority on an issue. const reviewStatus = { pending: 'pending', 'changes-requested': 'changes', 'needs-review': 'needsReview', unavailable: 'unavailable', published: 'publishedVersion' }; function issueStatus(issue) { if (issue.state === 'closed') return 'withdrawn'; if (issue.labels.includes('store:hide')) return 'hidden'; if (issue.pending) return 'pending'; for (const [status, key] of Object.entries(reviewStatus)) if (issue.labels.includes('store:' + status)) return key; return 'pending'; } async function mine() { const request = open('mine'); let search; const filterShares = () => { const words = state.sharedQuery.normalize('NFKC').toLocaleLowerCase().trim().split(/\s+/).filter(Boolean); for (const row of stage.querySelectorAll('.jpx-store-row')) row.hidden = !words.every(word => (row.dataset.searchText || row.textContent).normalize('NFKC').toLocaleLowerCase().includes(word)); }; if (options.toolbarHost) { const queryBar = div('jpx-store-querybar'); search = searchField(state.sharedQuery, t('cM.search')); search.disabled = !state.user; search.addEventListener('input', () => { state.sharedQuery = search.value; filterShares(); }); const refresh = refreshControl(() => mine()); refresh.disabled = !state.user; queryBar.append(search, refresh); browseControls = { queryBar, refresh }; layoutBrowseControls(); } if (!state.user) { empty(tr('loginRequired'), () => login(() => mine()), tr('signIn')); return; } if (!options.toolbarHost) viewHeader.append(button(tr('refresh'), () => mine())); message(tr('loading')); try { const issues = await jpxConfigStore.mine(); if (!live(request)) return; message(''); if (!issues.length) { empty(tr('noShares')); return; } const list = div('jpx-store-list'); stage.append(list); for (const issue of issues) { const row = el('article', undefined, 'jpx-store-row'); row.dataset.sharedId = issue.id; const title = el('strong', issue.title.replace(/^\[Config\]\s*/, '')); const badge = el('span', tr(issueStatus(issue)), 'jpx-store-badge'), listed = issue.state !== 'closed' && !issue.labels.includes('store:hide'); row.append(title, badge); try { const envelope = jpxConfigStore.parseSubmission(issue.body); const group = tags(envelope, null, (key, value, label) => { state.sharedQuery = label; if (search) search.value = label; filterShares(); }); row.append(group); row.dataset.searchText = [title.textContent, info(envelope), ...group.querySelectorAll('[title]')].map(value => typeof value === 'string' ? value : value.title).join(' ') + ' ' + group.textContent; } catch { /* Keep malformed submissions manageable. */ } const actions = div('jpx-store-actions'); if (issue.state !== 'closed') { actions.append(button(tr('updateShare'), () => edit({ id: issue.id, envelope: jpxConfigStore.parseSubmission(issue.body), originalBody: issue.body, back: () => mine() })), button(tr('withdraw'), async () => { if (!await confirmShare(tr('withdraw'), tr('withdrawConfirm'), tr('withdraw'))) return; if (!live(request)) return; await jpxConfigStore.withdraw(issue.id); await mine(); })); } else { actions.append(button(tr('removeShare'), async () => { if (!await confirmShare(tr('removeShare'), tr('removeShareConfirm'), tr('removeShare'))) return; if (!live(request)) return; message(''); await jpxConfigStore.archive(issue.id); if (!live(request)) return; const visible = [...list.children].filter(item => !item.hidden), index = visible.indexOf(row); const neighbor = visible[index + 1] || visible[index - 1]; row.remove(); if (!list.children.length) { list.remove(); empty(tr('noShares')); } (neighbor?.querySelector('button:not(:disabled)') || search || browseControls?.refresh)?.focus({ preventScroll: true }); }, 'jpx-store-remove-share')); } actions.append(button(tr('review'), async node => { const old = row.querySelector('.jpx-store-feedback'); if (old) { old.remove(); node.setAttribute('aria-expanded', 'false'); return; } const feedback = await jpxConfigStore.feedback(issue.id); if (!live(request)) return; if (listed) badge.textContent = tr(feedback ? reviewStatus[feedback.status] : 'pending'); const box = div('jpx-store-feedback'); const language = tr('browse') === '浏览' ? 'zh' : 'en'; box.append(el('p', feedback?.summary?.[language] || tr('noReview'))); for (const finding of feedback?.findings || []) box.append(el('p', [finding.path, finding[language]].filter(Boolean).join(' — '))); row.append(box); node.setAttribute('aria-expanded', 'true'); })); row.append(actions); list.append(row); // Reconcile only this session's submissions when the user opens // or refreshes Shared. No battle-time polling or per-row timers. if (issue.pending && listed) jpxConfigStore.feedback(issue.id).then(feedback => { if (!live(request) || !feedback) return; badge.textContent = tr(reviewStatus[feedback.status]); }).catch(() => { /* Keep pending until a later refresh succeeds. */ }); } filterShares(); } catch (error) { if (!live(request)) return; message(errorMessage(error), true); empty(tr('cannotLoad'), () => mine()); } } const dispose = () => { state.disposed = true; closeViews(); state.login?.abort(); layoutEvents.abort(); browseControls?.queryBar.remove(); toolbar.remove(); observer.disconnect(); }; const observer = new MutationObserver(() => { if (!root.isConnected) dispose(); }); // The core removes its dialog directly from body; ignore battle-content mutations. observer.observe(doc.body, { childList: true }); observer.observe(parent, { childList: true }); accountControls(); const authGeneration = state.authGeneration; jpxConfigStore.user().then(user => { if (!state.disposed && authGeneration === state.authGeneration) { state.user = user; if (alive()) accountControls(); } }).catch(cause => { if (alive() && authGeneration === state.authGeneration) message(errorMessage(cause), true); }); if (options.share) edit({ envelope: clone(options.share), back: options.onBack }); else browse(); dispose.back = () => { if (!alive() || !state.back) return false; Promise.resolve().then(state.back).catch(error => { if (alive()) message(errorMessage(error), true); }); return true; }; dispose.suspend = () => { if (state.disposed || state.suspended) return; state.suspended = true; state.request++; closeViews(); if (state.login) { state.authGeneration++; state.login.abort(); state.login = null; } }; dispose.resume = () => { if (state.disposed || !state.suspended) return; state.suspended = false; accountControls(); if (state.editor) edit(state.editor); else if (state.view === 'mine') mine(); else if (state.view === 'detail' && state.currentEntry) details(state.currentEntry); else browse(); }; return dispose; } return Object.freeze({ service: jpxConfigStore, render(parent, hooks, options = {}) { const doc = parent.ownerDocument; if (!doc.getElementById('jpx-integrated-store-style')) { const style = doc.createElement('style'); style.id = 'jpx-integrated-store-style'; style.textContent = ` #settings-container #panel_configStore { overflow: hidden; } #settings-container .jpx-store { display: flex; flex: 1; flex-direction: column; gap: 12px; width: 100%; min-width: 0; min-height: 0; color: var(--jpx-theme-text, #392d25); font: 13px/1.45 Arial, Helvetica, sans-serif; } #settings-container .jpx-store * { box-sizing: border-box; } #settings-container .jpx-store [hidden] { display: none !important; } #settings-container :is(.jpx-store-toolbar, .jpx-store-navigation, .jpx-store-account, .jpx-store-actions, .jpx-store-heading) { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; } #settings-container .jpx-store-toolbar { flex: none; justify-content: space-between; padding-bottom: 8px; border-bottom: 1px solid var(--jpx-theme-border, #c8b49b); } #settings-container .jpx-store-view-header { display: grid; flex: none; gap: 12px; min-width: 0; } #settings-container .jpx-store-view-header:empty { display: none; } #settings-container .jpx-store button, #settings-container .jpx-store-link { min-height: 32px; max-width: 100%; margin: 0; padding: 4px 10px; border: 1px solid var(--jpx-theme-border, #c8b49b); border-radius: 6px; background: var(--jpx-theme-surface, #f9f6ec); color: var(--jpx-theme-accent, #5c0d11); font: inherit; font-weight: 400; line-height: 1.4; text-decoration: none; cursor: pointer; overflow-wrap: anywhere; } #settings-container .jpx-store button:hover, #settings-container .jpx-store-link:hover { background: var(--jpx-theme-hover, #f1e2c5); } #settings-container .jpx-store button[aria-pressed=true], #settings-container .jpx-store .jpx-store-primary { border-color: var(--jpx-theme-accent, #5c0d11); background: var(--jpx-theme-selected, #ead9b8); } #settings-container .jpx-store button:disabled { opacity: .55; cursor: default; } #settings-container .jpx-store :is(a, summary, button, input, select, textarea):focus-visible { outline: 1px solid var(--jpx-theme-accent, #9b4e03); outline-offset: -1px; } #settings-container .jpx-store :is(a, summary):focus-visible { box-shadow: 0 0 0 2px color-mix(in srgb, var(--jpx-theme-accent, #9b4e03) 12%, transparent); } #settings-container .jpx-store p { margin: 0; } #settings-container :is(.jpx-store-status, .jpx-store-empty) { padding: 12px; border: 1px solid var(--jpx-theme-border, #c8b49b); background: var(--jpx-theme-surface, #f9f6ec); } #settings-container .jpx-store-status[data-error=true] { border-left: 3px solid var(--jpx-theme-accent, #5c0d11); } #settings-container .jpx-store-status { flex: none; } #settings-container .jpx-store-empty p { margin-bottom: 8px; } #settings-container .jpx-store-stage { display: grid; align-content: start; flex: 1; gap: 12px; min-width: 0; min-height: 0; overflow: auto; padding-right: 4px; overscroll-behavior: contain; scrollbar-width: var(--jpx-scrollbar-width, thin); scrollbar-color: inherit; } #settings-container .jpx-store :is(input, select, textarea) { min-width: 0; max-width: 100%; min-height: 32px; margin: 0; padding: 5px 8px; border: 1px solid var(--jpx-theme-border, #c8b49b); border-radius: 4px; background: var(--jpx-theme-field, #fffdf7); color: var(--jpx-theme-text, #392d25); font: inherit; } #settings-container .jpx-store-list { display: grid; min-width: 0; border-top: 1px solid var(--jpx-theme-border, #c8b49b); } #settings-container .jpx-store-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 8px; padding: 10px 0; border-bottom: 1px solid var(--jpx-theme-border, #c8b49b); } #settings-container .jpx-store-row > p, #settings-container .jpx-store-row > .jpx-store-actions, #settings-container .jpx-store-feedback { grid-column: 1 / -1; } #settings-container .jpx-store .jpx-store-title { width: fit-content; padding: 0; min-height: 24px; border: 0; background: transparent; text-align: left; font-weight: 600; } #settings-container .jpx-store .jpx-store-title:hover { text-decoration: underline; } #settings-container .jpx-store-meta { color: var(--jpx-theme-muted, #71634f); font-size: 12px; overflow-wrap: anywhere; } #settings-container .jpx-store-excerpt { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; white-space: pre-wrap; overflow-wrap: anywhere; } #settings-container .jpx-store-description { white-space: pre-wrap; overflow-wrap: anywhere; } #settings-container .jpx-store-heading h3 { flex: 1; margin: 0; color: var(--jpx-theme-accent, #5c0d11); font-size: 14px; overflow-wrap: anywhere; } #settings-container .jpx-store-form { display: grid; gap: 12px; min-width: 0; } #settings-container .jpx-store-row-tools { display: flex; flex-wrap: wrap; justify-content: end; align-items: start; gap: 6px; } #settings-container .jpx-store-field { display: grid; gap: 4px; min-width: 0; } #settings-container .jpx-store textarea { width: 100%; resize: vertical; } #settings-container .jpx-store-raw { min-width: 0; border: 1px solid var(--jpx-theme-border, #c8b49b); background: var(--jpx-theme-field, #fffdf7); } #settings-container .jpx-store-raw summary { padding: 8px; cursor: pointer; color: var(--jpx-theme-accent, #5c0d11); } #settings-container .jpx-store pre { max-height: 280px; margin: 0; padding: 8px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px/1.5 Consolas, monospace; border-top: 1px solid var(--jpx-theme-border, #c8b49b); } #settings-container .jpx-store-auth { display: grid; justify-items: start; gap: 12px; padding: 16px; border: 1px solid var(--jpx-theme-border, #c8b49b); background: var(--jpx-theme-surface, #f9f6ec); } #settings-container .jpx-store-auth-code { font: 600 22px/1.4 Consolas, monospace; user-select: all; letter-spacing: 2px; } #settings-container .jpx-store-auth-code-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } #settings-container .jpx-store-auth-copy { flex: none; white-space: nowrap; } #settings-container .jpx-store-badge { align-self: start; padding: 2px 8px; border: 1px solid var(--jpx-theme-border, #c8b49b); border-radius: 12px; color: var(--jpx-theme-accent, #5c0d11); font-size: 12px; white-space: nowrap; } #settings-container .jpx-store-feedback { display: grid; gap: 8px; padding: 8px 12px; border-left: 2px solid var(--jpx-theme-border, #c8b49b); background: var(--jpx-theme-surface, #f9f6ec); overflow-wrap: anywhere; white-space: pre-wrap; } @media (max-width: 650px) { #settings-container :is(.jpx-store-navigation, .jpx-store-account) { gap: 6px; } #settings-container .jpx-store button, #settings-container .jpx-store-link { padding: 5px 8px; } #settings-container .jpx-store :is(button, input, select), #settings-container .jpx-store-link { min-height: 44px; } } `; doc.head.append(style); } return renderConfigStore(parent, hooks, options); } }); } // Configuration ownership is separate from the native battle settings and editor drafts. let jpxConfigLibrary = null; let jpxConfigManagerView = null; let jpxEmbeddedStore = null; const jpxConfigLibraryKey = 'jpx_configLibrary_v1'; const jpxConfigApplyKey = 'jpx_configApplySignal_v1'; const jpxConfigClone = value => JSON.parse(JSON.stringify(value)); const jpxConfigWorld = () => isekaiSuffix ? 'Isekai' : 'Persistent'; const jpxConfigHasRules = value => value && (Object.hasOwn(value, 'rules') ? Array.isArray(value.rules) : Array.isArray(value.supports) && Array.isArray(value.attacks)); const jpxConfigHasContent = value => jpxConfigHasRules(value) && Object.entries(value).some(([key, rules]) => (key === 'rules' || !Array.isArray(value.rules) && (key === 'supports' || key === 'attacks') || key.startsWith('kb_')) && Array.isArray(rules) && rules.length); let jpxSelectedConfig; let jpxSceneRuntime = { scenes: {} }; const jpxConfigSceneLabel = scene => scene === 'Battle1000' ? t('cM.grindfest') : t('cB.' + scene); const jpxConfigModeLabel = mode => { const split = mode.lastIndexOf('_'); return t('cB.' + mode.slice(0, split)) + ' · ' + jpxConfigSceneLabel(mode.slice(split + 1)); }; function getJpxConfigLibrary() { return jpxConfigLibrary ||= createJpxConfigLibrary({ storage: localStorage, key: jpxConfigLibraryKey, modes: BATTLE_MODES, battleVersion: defaultCfgBattle.battleVersion, statsVersion: defaultCfgStats.statsVersion }); } async function migrateJpxLegacyConfigs(entries) { if (!Array.isArray(entries) || entries.length > 1000) throw new Error('Invalid configuration archive'); // The legacy plugin owns its GM store. Only configuration records cross this boundary. const copied = jpxConfigClone(entries).map(entry => ({ id: entry.id, savedAt: entry.savedAt, envelope: entry.envelope, ...(entry.source ? { source: entry.source } : {}) })); const library = getJpxConfigLibrary(); // A source revision is imported once, even if its local copy was subsequently // edited. A changed legacy source gets a new copy rather than replacing edits. for (const entry of copied) { const source = JSON.stringify({ id: entry.id, envelope: entry.envelope, ...(entry.source ? { source: entry.source } : {}) }); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(source)); const fingerprint = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''); library.migrate([entry], 'legacy-backpack:' + fingerprint); } window.dispatchEvent(new Event('jpx:config-library')); return library.readState(); } function seedJpxConfigLibrary() { const library = getJpxConfigLibrary(); for (const world of ['Persistent', 'Isekai']) { const marker = 'native-configs-v1:' + world; if (library.readState().migrations.includes(marker)) continue; const raw = localStorage.getItem(prefix + 'cfgBattle' + (world === 'Isekai' ? '_isekai' : '')); let config; try { config = raw ? JSON.parse(raw) : null; } catch { /* Keep the original malformed storage untouched. */ } const valid = config && typeof config === 'object' && !Array.isArray(config) && Number(config.battleVersion || config.version || 0) >= defaultCfgBattle.battleVersion; if (!valid) continue; // Never split away a user's original multi-mode file during file import. These // entries are snapshots of the already-applied native mode slots, not an import. const normal = {}, entries = []; mergeCfg(jpxConfigClone(config), { battleVersion: defaultCfgBattle.battleVersion }, normal, 'battle'); for (const mode of BATTLE_MODES) if (jpxConfigHasContent(normal[mode])) entries.push({ id: 'native-' + world + '-' + mode, source: { type: 'native' }, envelope: { schemaVersion: 1, kind: 'battle-mode', title: jpxConfigModeLabel(mode), description: '', world, mode, scriptVersion: window.JPXPlus.version, config: { battleVersion: normal.battleVersion, [mode]: normal[mode] } } }); // Entries, initial applied snapshots and the completion marker are committed // together. A failed write can be retried without losing an applied label. library.migrate(entries, marker, { applied: entries.map(entry => ({ world, id: entry.id, scopes: [entry.envelope.mode] })) }); } return library; } // Cache the explicit selection once, outside the battle action loop. The active // snapshot belongs to the library; native exports still contain only JPX rules. function refreshJpxSelectedConfig() { jpxSelectedConfig = null; jpxSceneRuntime = { scenes: {} }; try { const runtime = getJpxConfigLibrary().readRuntime(jpxConfigWorld()), record = runtime.selection; jpxSceneRuntime = runtime; if (record?.mode) normalizeJpxBattleMode(cfgBattle[record.mode]); if (record?.mode && BATTLE_MODES.includes(record.mode) && jpxConfigHasRules(cfgBattle[record.mode]) && JSON.stringify(cfgBattle[record.mode]) === JSON.stringify(record.config[record.mode])) { jpxSelectedConfig = { mode: record.mode, rules: cfgBattle[record.mode] }; } } catch (error) { jpxSceneRuntime.failed = true; console.warn('JPX-PLUS selected configuration could not be loaded.', error); } } function getJpxSelectedBattleMode() { if (jpxSelectedConfig === undefined || jpxSelectedConfig && cfgBattle[jpxSelectedConfig.mode] !== jpxSelectedConfig.rules) refreshJpxSelectedConfig(); return jpxSelectedConfig?.mode || ''; } function resolveJpxScene(style, scene, routes = jpxSceneRuntime.scenes, config = cfgBattle) { if (!style) return { mode: '', rules: null, id: '', inherited: false, assigned: false }; const direct = style + '_' + scene, general = style + '_General'; for (const mode of direct === general ? [general] : [direct, general]) { const assigned = Object.hasOwn(routes, mode), route = routes[mode]; const rules = assigned ? route?.rules : config[mode]; if (jpxConfigHasContent(rules)) return { mode, rules, id: route?.id || '', inherited: mode !== direct, assigned }; } return { mode: general, rules: null, id: '', inherited: scene !== 'General', assigned: false }; } function getJpxBattleRules(defaultStyle = '') { const selected = getJpxSelectedBattleMode(); if (selected) return cfgBattle[selected]; if (jpxSceneRuntime.failed) return null; const mode = resolveJpxScene(battleStyle || defaultStyle, battleType).rules; if (mode && !Array.isArray(mode.rules)) normalizeJpxBattleMode(mode); return mode; } function syncJpxSceneRuntime() { // Compare only the effective selection, outside the action loop. Other // scenes, saved copies and assignment metadata cannot interrupt this battle. const snapshot = () => JSON.stringify([getJpxSelectedBattleMode(), getBattleMode(), getJpxBattleRules(), !!jpxSceneRuntime.failed]); const before = log ? snapshot() : ''; refreshJpxSelectedConfig(); if (log && before !== snapshot()) pauseForJpxConfigApplication(); } function restoreJpxAutomaticSelection(world = jpxConfigWorld()) { getJpxConfigLibrary().clearSelection(world); if (world === jpxConfigWorld()) syncJpxSceneRuntime(); localStorage.setItem(jpxConfigApplyKey, JSON.stringify({ world, scopes: [], nonce: Date.now() + ':' + Math.random() })); window.dispatchEvent(new Event('jpx:config-library')); } // Explicit PLUS choices live with their rules, never in the detected magic-damage cache. function getManagedBattleStyle(detected) { const selected = getJpxSelectedBattleMode(); if (selected) return selected.slice(0, selected.lastIndexOf('_')); // Automatic routing belongs to the detected style. Metadata on another // style's saved rules must not turn a physical build into a mage or vice versa. return detected; } function getManagedSpellType() { const mode = getBattleMode(), rules = getJpxBattleRules(); // Empty native groups can still provide an explicit element for manual spells. const metadata = rules || (!jpxSceneRuntime.failed && !Object.hasOwn(jpxSceneRuntime.scenes, mode) ? cfgBattle[mode] : null); const element = metadata?.jpxPlusExecution?.element; return ['fire', 'cold', 'wind', 'elec', 'holy', 'dark'].includes(element) ? element : spellDamageBonus.maxType; } function pauseForJpxConfigApplication() { if (!log) return false; cancelBattleDecision(); jpxPanelManager.roundHoverResume = null; if (cfgBattle.ctrlWidgetMouseEnter) jpxPanelManager.ready = false; isActiveBattle = false; readyNext = 0; jpxPanelManager.updateContent('battle'); jpxPanelManager.setBackground('#fef'); jpxPanelManager.dispatchState(); return true; } // A changed effective strategy must stop battle before its next action. window.addEventListener('storage', event => { if (event.key === jpxConfigLibraryKey) { syncJpxSceneRuntime(); return; } if (event.key !== jpxConfigApplyKey || !event.newValue) return; try { const signal = JSON.parse(event.newValue), stats = signal.world === 'Any'; if (!stats && signal.world !== jpxConfigWorld() || !Array.isArray(signal.scopes)) return; if (!stats && !signal.scopes.length) { syncJpxSceneRuntime(); window.dispatchEvent(new Event('jpx:config-library')); return; } const key = stats ? prefix + 'cfgStats' : prefix + 'cfgBattle' + isekaiSuffix; const data = JSON.parse(localStorage.getItem(key) || 'null'); if (!data || typeof data !== 'object' || Array.isArray(data)) return; if (stats) { validateStatsConfig(data); cfgStats = jpxConfigClone(data); document.getElementById('settings-container')?.jpxConfigApplied?.(data, 'stats'); } else { if ((data.battleVersion || 0) < defaultCfgBattle.battleVersion) return; pauseForJpxConfigApplication(); const patch = {}; for (const key of signal.scopes) if (BATTLE_MODES.includes(key) || Object.hasOwn(defaultCfgBattle,key)) { if (Object.hasOwn(data,key)) patch[key] = jpxConfigClone(data[key]); } Object.assign(cfgBattle,patch); refreshJpxSelectedConfig(); document.getElementById('settings-container')?.jpxConfigApplied?.(patch,'battle'); jpxPanelManager.refreshAppearance?.(); } window.dispatchEvent(new Event('jpx:config-library')); } catch (error) { console.warn('JPX-PLUS configuration update could not be loaded.', error); } }); function commitJpxConfigEntry(entry, world, onApplied = (patch, scope) => document.getElementById("settings-container")?.jpxConfigApplied?.(patch, scope)) { const library = getJpxConfigLibrary(), envelope = entry.envelope, stats = envelope.kind === "stats"; if (!["Persistent", "Isekai", "Any"].includes(world) || stats !== (world === "Any")) throw Object.assign(new Error(), { code: "invalidConfig" }); if (library.get(entry.id)?.revision !== entry.revision) throw Object.assign(new Error(), { code: "libraryChanged" }); const key=stats?prefix+'cfgStats':prefix+'cfgBattle'+(world==='Isekai'?'_isekai':''); const original=localStorage.getItem(key), originalLibrary=localStorage.getItem(jpxConfigLibraryKey); let current=original?JSON.parse(original):null; const versionKey=stats?'statsVersion':'battleVersion',defaults=stats?defaultCfgStats:defaultCfgBattle; if(!current||typeof current!=='object'||Array.isArray(current)||Number(current[versionKey]||(!stats&¤t.version)||0)Object.hasOwn(envelope.config,mode))) patch[mode]=normalized[mode]||jpxConfigClone(envelope.config[mode]); if(envelope.kind==='battle')for(const key of Object.keys(envelope.config))if(!BATTLE_MODES.includes(key)&&Object.hasOwn(defaultCfgBattle,key))patch[key]=jpxConfigClone(envelope.config[key]); patch.battleVersion=defaultCfgBattle.battleVersion; } const result=stats?patch:{...current,...patch}; const paused=world===jpxConfigWorld()&&!!log; if(paused)pauseForJpxConfigApplication(); try{ if(original!==null&&localStorage.getItem(key+':configManagerBackup')===null)localStorage.setItem(key+':configManagerBackup',original); localStorage.setItem(key,JSON.stringify(result)); library.setApplied(world,{id:entry.id,revision:entry.revision,scopes:stats?['stats']:Object.keys(patch).filter(key=>key!=='battleVersion'),config:stats?result:patch, ...(envelope.kind==='battle-mode'?{mode:envelope.mode}:{})},{activate:true}); localStorage.setItem(jpxConfigApplyKey,JSON.stringify({world,scopes:stats?['stats']:Object.keys(patch),nonce:Date.now()+':'+Math.random()})); }catch(cause){ if(original===null)localStorage.removeItem(key);else localStorage.setItem(key,original); if(originalLibrary===null)localStorage.removeItem(jpxConfigLibraryKey);else localStorage.setItem(jpxConfigLibraryKey,originalLibrary); throw cause; } if(stats){cfgStats=jpxConfigClone(result);onApplied?.(patch,'stats');} else if(world===jpxConfigWorld()){Object.assign(cfgBattle,jpxConfigClone(patch));refreshJpxSelectedConfig();onApplied?.(patch,'battle');jpxPanelManager.refreshAppearance?.();} return paused; } const jpxConfigElements = ['fire', 'cold', 'wind', 'elec', 'holy', 'dark']; const jpxModeStyle = mode => mode.slice(0, mode.lastIndexOf('_')); const jpxModeScene = mode => mode.slice(mode.lastIndexOf('_') + 1); const jpxConfigText = (key, args) => t('cM.' + key, args); const jpxConfigError = code => Object.assign(new Error(), { code }); const announceJpxConfigLibrary = () => window.dispatchEvent(new Event('jpx:config-library')); const signalJpxConfigWorld = world => localStorage.setItem(jpxConfigApplyKey, JSON.stringify({ world, scopes: [], nonce: Date.now() + ':' + Math.random() })); function jpxConfigEl(tag, text, className) { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; if (className) node.className = className; return node; } const jpxConfigDiv = className => jpxConfigEl('div', undefined, className); // Keeps Tab inside a modal; the control list is only collected when Tab is pressed. function trapJpxDialogFocus(event, collect) { if (event.key !== 'Tab') return; const controls = collect(), first = controls[0], last = controls.at(-1); if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } } function ensureJpxConfigManagerStyle() { if (!document.getElementById('jpx-config-manager-style')) { const style = document.createElement('style'); style.id = 'jpx-config-manager-style'; style.textContent = JPX_CONFIG_MANAGER_CSS; document.head.append(style); } } function chooseJpxBattleExport(parent, config) { if (parent.querySelector('#jpx-battle-export')) return Promise.resolve(null); ensureJpxConfigManagerStyle(); const tr = jpxConfigText, el = jpxConfigEl, div = jpxConfigDiv, data = jpxConfigClone(config); const activeMode = getJpxSelectedBattleMode(); const detected = activeMode ? '' : log ? battleStyle : getDetectedJpxBattleStyle(); const mode = activeMode || (detected ? getBattleMode(detected) : ''); const routed = !activeMode && detected && getManagedBattleStyle(detected); const assignedRules = routed ? resolveJpxScene(routed, battleType) : null; const hasSceneRoute = assignedRules && [routed + '_' + battleType, routed + '_General'].some(key => Object.hasOwn(jpxSceneRuntime.scenes, key)); const currentRules = assignedRules?.assigned || hasSceneRoute && !assignedRules.rules ? assignedRules.rules : data[mode]; const current = jpxConfigHasRules(currentRules) ? mode : ''; const modes = BATTLE_MODES.filter(key => jpxConfigHasContent(data[key]) || key === current && jpxConfigHasRules(data[key])); let scope = current ? 'current' : 'all', update = () => {}; const dialog = el('dialog', undefined, 'jpx-export-dialog'); dialog.id = 'jpx-battle-export'; const title = el('h3', t('cB.exportBattleConfig')); title.id = getUniqueId('export-title'); dialog.setAttribute('aria-labelledby', title.id); const nav = div('jpx-rule-section-tabs'); nav.setAttribute('role', 'group'); nav.setAttribute('aria-label', title.textContent); const summary = el('p', undefined, 'jpx-export-summary'), fields = div('jpx-export-fields'), footer = div('jpx-export-footer'); const button = (host, text, action) => { const node = jpxUtils.createButton(host, { text, history: false, onClick: action }); node.type = 'button'; return node; }; const switches = ['current', 'all', 'choose'].map(value => { const node = button(nav, tr({ current: 'exportCurrent', all: 'exportAll', choose: 'exportChoose' }[value]), () => { scope = value; update(); }); node.dataset.exportScope = value; node.disabled = value === 'current' && !current || value === 'choose' && !modes.length; if (value === 'current' && !current) node.title = tr('exportUnknown'); return node; }); const style = el('select'), scene = el('select'); style.dataset.exportStyle = ''; scene.dataset.exportScene = ''; const addOption = (select, value) => { const option = el('option', t('cB.' + value)); option.value = value; select.append(option); }; new Set(modes.map(jpxModeStyle)).forEach(value => addOption(style, value)); if (current && [...style.options].some(option => option.value === jpxModeStyle(current))) style.value = jpxModeStyle(current); function updateScenes() { const previous = scene.value || jpxModeScene(current); scene.replaceChildren(); modes.filter(key => jpxModeStyle(key) === style.value).forEach(key => addOption(scene, jpxModeScene(key))); if ([...scene.options].some(option => option.value === previous)) scene.value = previous; update(); } style.addEventListener('change', updateScenes); scene.addEventListener('change', () => update()); updateScenes(); for (const [key, input] of [['style', style], ['scenario', scene]]) { const label = el('label'); label.append(el('span', tr(key)), input); fields.append(label); } dialog.append(title, nav, summary, fields, footer); const focused = document.activeElement; return new Promise(resolve => { let settled = false; const finish = result => { if (settled) return; settled = true; parent.removeEventListener('close', parentClosed); if (dialog.open) dialog.close(); dialog.remove(); if (focused?.isConnected) focused.focus({ preventScroll: true }); resolve(result); }; const parentClosed = () => finish(null); button(footer, tr('cancel'), () => finish(null)); const submit = button(footer, tr('export'), () => { const key = scope === 'current' ? current : style.value + '_' + scene.value; const output = scope === 'all' ? data : { battleVersion: data.battleVersion, [key]: scope === 'current' ? currentRules : data[key] }; const suffix = scope === 'all' ? '' : '_' + key; finish({ data: output, fileName: `cfgBattle_${jpxConfigWorld()}${suffix}.txt`, depth: 3 }); }); submit.className = 'jpx-export-submit'; update = () => { switches.forEach(node => node.setAttribute('aria-pressed', String(node.dataset.exportScope === scope))); fields.hidden = scope !== 'choose'; summary.hidden = scope === 'choose'; summary.textContent = scope === 'current' ? jpxConfigModeLabel(current) : t('cB.basicSettings') + ' · ' + tr('groupCount', { count: BATTLE_MODES.filter(key => jpxConfigHasRules(data[key])).length }); submit.disabled = scope === 'choose' && !modes.includes(style.value + '_' + scene.value); }; dialog.addEventListener('cancel', event => { event.preventDefault(); finish(null); }); dialog.addEventListener('keydown', event => trapJpxDialogFocus(event, () => [...dialog.querySelectorAll('button,select')].filter(node => !node.disabled && node.getClientRects().length))); dialog.addEventListener('close', () => finish(null)); parent.addEventListener('close', parentClosed); parent.append(dialog); update(); dialog.showModal(); switches.find(node => node.dataset.exportScope === scope).focus(); }); } // Import results stay visible until dismissed or the user leaves this view. // Keep them in the layout so long file names never cover actions or fields. function jpxImportDisplayName(name) { const chars = Array.from(String(name)); return chars.length > 64 ? chars.slice(0, 40).join('') + '…' + chars.slice(-16).join('') : String(name); } function createJpxImportFeedback() { ensureJpxConfigManagerStyle(); const node = jpxConfigDiv('jpx-import-feedback'); node.hidden = true; const message = jpxConfigEl('p'); message.setAttribute('role', 'status'); message.setAttribute('aria-atomic', 'true'); const close = jpxConfigEl('button', '×'); close.type = 'button'; close.setAttribute('aria-label', t('cM.close')); close.title = t('cM.close'); const clear = () => { node.hidden = true; message.textContent = ''; delete node.dataset.stage; }; close.addEventListener('click', clear); node.append(message, close); return { node, clear, show(text, stage = 'success', fullName = '') { node.dataset.stage = stage; node.hidden = false; message.title = fullName; message.setAttribute('role', stage === 'error' ? 'alert' : 'status'); message.textContent = text; } }; } function renderJpxConfigManager(parent, hooks = {}) { ensureJpxConfigManagerStyle(); const el = jpxConfigEl, div = jpxConfigDiv, tr = jpxConfigText; const root = el('section', undefined, 'jpx-config-manager'); parent.append(root); const sortKey = 'jpx_configListSort_v1'; let savedSort; try { savedSort = localStorage.getItem(sortKey); } catch {} const state = { query: '', world: '', style: '', scenario: '', kind: '', sort: ['type', 'updated', 'name', 'manual'].includes(savedSort) ? savedSort : 'type', filtersOpen: false, scroll: 0, editor: null, page: 'mine', storeDispose: null, disposed: false, dialog: null }; const library = getJpxConfigLibrary(); const notice = el('p', '', 'jpx-config-notice'); notice.setAttribute('role', 'status'); const importFeedback = createJpxImportFeedback(); let body, list, noticeTimer, listVersion, contextVersion, cachedContext, resultCount, orderedContext, orderedBy, orderedEntries, refreshFilters, cancelListDrag; let importGeneration = 0; const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); const clearNotice = () => { clearTimeout(noticeTimer); noticeTimer = null; notice.textContent = ''; }; const notify = (message, persistent = false) => { clearNotice(); if (state.disposed) return; notice.textContent = message; if (!persistent) noticeTimer = setTimeout(clearNotice, 4000); }; const messageKey = (cause, fallback) => cause?.code && Object.hasOwn(I18N.cM, cause.code) ? cause.code : fallback; const error = cause => notify(tr(messageKey(cause, 'error')), true); function button(label, action, cls = '') { const node = el('button', label, cls); node.type = 'button'; node.addEventListener('click', async () => { if (node.disabled) return; try { await action(node); } catch (cause) { error(cause); } }); return node; } function backButton(action) { state.back = action; return button(tr('back'), action, 'jpx-config-back'); } const addOptions = (node, values) => { for (const [value, label] of values) { const option = el('option', label); option.value = value; node.append(option); } }; function select(values, selected) { const node = el('select'); addOptions(node, values); node.value = selected; return node; } function field(label, input, wide = false) { const node = el('label', undefined, wide ? 'jpx-config-wide' : ''); node.append(el('span', label), input); return node; } const worlds = [['Persistent', t('cB.Persistent')], ['Isekai', t('cB.Isekai')], ['Any', tr('anyWorld')]]; const worldIds = worlds.map(([world]) => world), worldLabel = value => worlds.find(([world]) => world === value)?.[1]; const nativeChoices = values => values.map(value => [value, t('cB.' + value)]); const modesOf = envelope => BATTLE_MODES.filter(mode => jpxConfigHasRules(envelope.config[mode])); function meta(envelope) { const detail = envelope.kind === 'stats' ? tr('stats') : envelope.mode ? jpxConfigModeLabel(envelope.mode) : tr('groupCount', { count: modesOf(envelope).length }); const execution = envelope.mode && envelope.config[envelope.mode]?.jpxPlusExecution; return [envelope.title === detail ? '' : detail, execution?.element && execution.element !== 'auto' ? tr(execution.element) : '', worldLabel(envelope.world)].filter(Boolean).join(' · '); } const classifications = new WeakMap(), scenarios = ['General', ...BATTLE_TYPES]; function classify(envelope) { if (classifications.has(envelope)) return classifications.get(envelope); const modes = envelope.kind === 'battle-mode' ? [envelope.mode] : envelope.config ? modesOf(envelope).filter(mode => jpxConfigHasContent(envelope.config[mode])) : (envelope.modes || []); const styles = [...new Set(modes.map(jpxModeStyle))], battles = [...new Set(modes.map(jpxModeScene))]; const elements = [...new Set(modes.map(mode => envelope.config?.[mode]?.jpxPlusExecution?.element).filter(value => jpxConfigElements.includes(value)))]; const result = { modes, styles, battles, elements }; classifications.set(envelope, result); return result; } function typeOrder(a, b) { const rank = entry => { const data = classify(entry.envelope); return [entry.envelope.kind === 'stats' ? BATTLE_STYLES.length + 2 : data.styles.length === 1 ? BATTLE_STYLES.indexOf(data.styles[0]) : BATTLE_STYLES.length, data.battles.length === 1 ? scenarios.indexOf(data.battles[0]) : scenarios.length, worlds.findIndex(([world]) => world === entry.envelope.world)]; }; const left = rank(a), right = rank(b); return left.reduce((order, value, index) => order || value - right[index], 0); } function setFilter(key, value) { state[key] = value; if (key === 'kind' && value === 'stats') state.style = state.scenario = ''; refreshFilters(); } function tags(envelope, choose = setFilter) { const data = classify(envelope), group = div('jpx-config-tags'); const add = (label, kind, key, value, title) => { const tag = key && choose ? button(label, () => choose(key, value, label)) : el('span', label); tag.className = 'jpx-config-tag'; tag.dataset.tagKind = kind; if (value) tag.dataset.tagValue = value; if (title) tag.title = title; group.append(tag); }; if (envelope.kind === 'stats') add(tr('stats'), 'kind', 'kind', 'stats'); else { for (const [values, kind, key, summary] of [[data.styles, 'style', 'style', 'multiStyle'], [data.battles, 'scenario', 'scenario', 'multiBattle']]) { if (values.length > 3) add(tr(summary), kind, null, 'mixed', values.map(value => t('cB.' + value)).join(' · ')); else for (const value of values) add(t('cB.' + value), kind, key, value); } for (const value of data.elements) add(tr(value), 'element', null, value); if (envelope.kind === 'battle') add(data.modes.length ? tr('groupCount', { count: data.modes.length }) : tr('allBattle'), 'kind', null, 'battle'); } add(worldLabel(envelope.world), 'world', envelope.world === 'Any' ? null : 'world', envelope.world); return group; } const matchesApplied = (saved, current) => saved && current && (saved.mode ? [saved.mode] : saved.scopes).every(scope => JSON.stringify(scope === 'stats' ? current : current[scope]) === JSON.stringify(scope === 'stats' ? saved.config : saved.config[scope])); function appliedContext() { const storageKey = world => world === 'Any' ? prefix + 'cfgStats' : prefix + 'cfgBattle' + (world === 'Isekai' ? '_isekai' : ''); const version = [jpxConfigLibraryKey, ...worldIds.map(storageKey)].map(key => localStorage.getItem(key)); if (contextVersion?.every((raw, index) => raw === version[index])) return cachedContext; const state = library.readState(), native = {}, saved = {}; for (const world of worldIds) { let current; try { current = JSON.parse(localStorage.getItem(storageKey(world)) || 'null'); } catch { continue; } saved[world] = current; current ||= world === jpxConfigWorld() ? cfgBattle : world === 'Any' ? cfgStats : {}; if (world !== 'Any') { const normalized = {}; mergeCfg(jpxConfigClone(current), defaultCfgBattle, normalized, 'battle'); // Explicit empty modes deliberately clear a scene and must stay empty. for (const mode of BATTLE_MODES) if (current[mode] && !Object.keys(current[mode]).length) normalized[mode] = {}; current = normalized; } native[world] = current; } const active = {}; for (const world of worldIds) { const id = state.active?.[world]; if (id && matchesApplied(state.applied[world]?.[id], native[world])) active[world] = id; } contextVersion = version; return cachedContext = { state, native, active, saved }; } const currentApplied = (entry, context = appliedContext()) => worldIds.flatMap(world => { const saved = context.state.applied[world]?.[entry.id]; return matchesApplied(saved, context.native[world]) ? [{ ...saved, world }] : []; }); function resetPage(page) { importGeneration++; cancelListDrag?.(); cancelListDrag = null; state.storeDispose?.(); state.storeDispose = null; root.querySelectorAll('.jpx-config-menu').forEach(node => node.remove()); state.page = page; state.back = null; clearNotice(); importFeedback.clear(); root.replaceChildren(); } async function confirmAction(title, options, content, { validate, focus } = {}) { if (state.dialog) return null; const focused = document.activeElement, overlay = div('jpx-config-overlay'); const box = el('section', undefined, 'jpx-config-confirm'); box.setAttribute('role', 'dialog'); box.setAttribute('aria-modal', 'true'); const heading = el('h3', title); heading.id = getUniqueId('config-confirm'); box.setAttribute('aria-labelledby', heading.id); box.append(heading); if (content) box.append(content); const actions = div('jpx-config-actions'); box.append(actions); overlay.append(box); const siblings = [...root.children]; siblings.forEach(node => node.inert = true); root.append(overlay); return new Promise(resolve => { const finish = value => { overlay.remove(); state.dialog = null; siblings.forEach(node => node.inert = false); if (focused?.isConnected) focused.focus({ preventScroll: true }); resolve(value); }; state.dialog = finish; for (const [value, label, primary] of options) actions.append(button(label, () => { if (!validate || validate(value)) finish(value); }, primary ? 'jpx-config-primary' : '')); overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); event.preventDefault(); finish(null); } trapJpxDialogFocus(event, () => [...box.querySelectorAll('button,select,input')].filter(node => !node.disabled)); }); (focus || actions.querySelector('button'))?.focus(); }); } // A cancel/confirm pair; resolves true only for the primary action. const confirmed = async (title, label, content) => await confirmAction(title, [['cancel', tr('cancel')], ['confirm', label, true]], content) === 'confirm'; function pageTabs(mineActive, onMine, onStore) { const nav = div('jpx-config-nav'); for (const [label, action, pressed] of [['mine', onMine, mineActive], ['store', onStore, !mineActive]]) { const tab = button(tr(label), action); tab.setAttribute('aria-pressed', String(pressed)); nav.append(tab); } return nav; } function titleInput(value) { const input = el('input'); input.type = 'text'; input.required = true; input.maxLength = 100; input.value = value; return input; } function pageHeader(back, title) { const header = div('jpx-config-editor-header'); header.append(back, el('strong', title)); return header; } function captureList() { if (state.page === 'mine' && body) state.scroll = body.scrollTop; } function showMine() { resetPage('mine'); listVersion = null; const toolbar = div('jpx-config-toolbar'); const nav = pageTabs(true, () => {}, () => { captureList(); showStore(); }); nav.setAttribute('role', 'group'); nav.setAttribute('aria-label', tr('name')); root.append(renderSelection()); const search = el('input'); search.type = 'search'; search.placeholder = tr('search'); search.setAttribute('aria-label', tr('search')); search.value = state.query; search.addEventListener('input', () => { state.query = search.value; refresh(); }); const queryBar = div('jpx-store-querybar'); const filters = div('jpx-store-filter-grid'); filters.id = getUniqueId('config-filters'); const toggle = button(tr('filters'), () => { state.filtersOpen = !state.filtersOpen; updateFilters(); }, 'jpx-store-filter-toggle'); toggle.setAttribute('aria-controls', filters.id); queryBar.append(search, toggle); const controls = {}; for (const [key, label, choices] of [ ['world', 'world', [['', tr('allWorlds')], ...worlds.filter(([value]) => value !== 'Any')]], ['style', 'style', [['', tr('allStyles')], ...nativeChoices(BATTLE_STYLES)]], ['scenario', 'scenario', [['', tr('allBattles')], ...nativeChoices(scenarios)]], ['kind', 'type', [['', tr('allTypes')], ['battle-mode', tr('singleMode')], ['battle', tr('allBattle')], ['stats', tr('stats')]]] ]) { const control = select(choices, state[key]); controls[key] = control; control.setAttribute('aria-label', tr(label)); control.dataset.configFilter = key; control.addEventListener('change', () => setFilter(key, control.value)); filters.append(control); } const results = div('jpx-store-results'); resultCount = el('span', '', 'jpx-store-result-count'); resultCount.setAttribute('role', 'status'); const clear = button(tr('clearFilters'), () => { state.query = state.world = state.style = state.scenario = state.kind = ''; search.value = ''; refresh(); }, 'jpx-store-clear'); const sort = select([['type', tr('typeSort')], ['updated', tr('latest')], ['name', tr('nameSort')], ['manual', tr('manualSort')]], state.sort); sort.setAttribute('aria-label', tr('sort')); sort.dataset.configSort = ''; sort.addEventListener('change', () => { state.sort = sort.value; refresh(); try { localStorage.setItem(sortKey, state.sort); } catch { error({ code: 'storageError' }); } }); results.append(resultCount, clear, sort); const header = div('jpx-config-list-header jpx-store-browse-header jpx-store-view-header'); header.append(filters, results); function updateFilters() { const active = Object.keys(controls).filter(key => state[key]).length; toggle.textContent = tr('filters') + (active ? ' (' + active + ')' : ''); toggle.setAttribute('aria-expanded', String(state.filtersOpen)); filters.dataset.open = String(state.filtersOpen); clear.hidden = !active && !state.query; for (const [key, control] of Object.entries(controls)) { control.value = state[key]; control.disabled = ['style', 'scenario'].includes(key) && state.kind === 'stats'; } } function refresh() { updateFilters(); state.scroll = 0; renderList(); body.scrollTop = 0; } refreshFilters = refresh; filters.addEventListener('keydown', event => { if (event.key === 'Escape' && state.filtersOpen && root.closest('.jpx-settings-mobile')) { event.preventDefault(); event.stopPropagation(); state.filtersOpen = false; updateFilters(); toggle.focus(); } }); const actions = div('jpx-config-actions'); actions.append(button(tr('new'), () => { captureList(); showSettings(); }, 'jpx-config-primary'), button(tr('import'), () => importFile())); toolbar.append(nav, queryBar, actions); body = div('jpx-config-body'); list = div('jpx-config-list'); body.append(list); root.append(toolbar, header, importFeedback.node, notice, body); updateFilters(); renderList(); body.scrollTop = state.scroll; cancelListDrag = bindStatsListDrag(list, moveEntry, { row: '.jpx-config-row', handle: '.jpx-config-grip', idKey: 'configId', scroller: body, previewClass: 'jpx-config-drag-preview', preview: row => [createSettingsIcon('grip'), el('strong', row.querySelector('.jpx-config-title strong').textContent)], afterMove: () => {} }); } function renderSelection(selection = div('jpx-config-selection')) { selection.replaceChildren(); const selected = getJpxSelectedBattleMode(); const summary = div('jpx-selection-summary'); const mode = el('span', tr(selected ? 'fixedMode' : 'automaticMode'), 'jpx-selection-mode'); mode.dataset.fixed = String(!!selected); if (selected) mode.title = tr('fixedHint'); summary.append(mode); if (selected) summary.append(el('span', jpxConfigModeLabel(selected), 'jpx-selection-name')); else summary.append(el('span', t('cB.' + jpxConfigWorld()), 'jpx-selection-world')); const actions = div('jpx-selection-actions'); if (state.page !== 'scenes') actions.append(button(tr('sceneAssignments'), () => { captureList(); showScenes(); }, 'jpx-scene-open')); if (selected) actions.append(button(tr('restoreAutomatic'), () => { restoreJpxAutomaticSelection(); state.page === 'scenes' ? showScenes() : showMine(); })); selection.append(summary, actions); return selection; } function showScenes() { resetPage('scenes'); state.back = showMine; state.sceneWorld ||= jpxConfigWorld(); state.sceneStyle ||= getDetectedJpxBattleStyle() || BATTLE_STYLES[0]; const top = div('jpx-config-toolbar'); top.append(backButton(showMine), el('strong', tr('sceneAssignments'))); const selectedMode = getJpxSelectedBattleMode(); const controls = div('jpx-config-form jpx-scene-context'); const world = select(worlds.slice(0, 2), state.sceneWorld), style = select(nativeChoices(BATTLE_STYLES), state.sceneStyle); world.dataset.sceneWorld = ''; style.dataset.sceneStyle = ''; controls.append(field(tr('world'), world), field(tr('style'), style)); world.addEventListener('change', () => { state.sceneWorld = world.value; showScenes(); }); style.addEventListener('change', () => { state.sceneStyle = style.value; showScenes(); }); const content = div('jpx-config-body jpx-scenes-body'); root.append(top); if (selectedMode) root.append(renderSelection()); content.append(controls); root.append(notice, content); const application = appliedContext(), routes = application.state.scenes?.[state.sceneWorld] || {}, native = application.native[state.sceneWorld] || {}; const detected = getManagedBattleStyle(battleStyle || getDetectedJpxBattleStyle()); const execution = selectedMode ? { mode: selectedMode, id: application.state.active?.[jpxConfigWorld()] } : resolveJpxScene(detected, battleType); const entryById = id => application.state.entries.find(entry => entry.id === id); const strategyName = (resolved, world, config) => entryById(resolved.id)?.envelope.title || application.state.entries.find(entry => application.state.applied[world]?.[entry.id]?.scopes.includes(resolved.mode) && matchesApplied(application.state.applied[world][entry.id], config))?.envelope.title || tr('current'); const viewingCurrent = state.sceneWorld === jpxConfigWorld() && state.sceneStyle === detected; if (selectedMode || !viewingCurrent) { const executingName = execution.rules || selectedMode ? strategyName(execution, jpxConfigWorld(), application.native[jpxConfigWorld()]) : tr('unassigned'); const current = div('jpx-scene-executing'); current.append(el('span', tr('executing'), 'jpx-scene-badge'), el('span', detected ? jpxConfigModeLabel(detected + '_' + battleType) : '—'), el('strong', executingName)); content.append(current); } const table = div('jpx-scenes-table'); content.append(table); const candidates = application.state.entries.filter(entry => entry.envelope.kind !== 'stats' && ['Any', state.sceneWorld].includes(entry.envelope.world) && visibleSavedEntry(entry, application)); const options = candidates.flatMap(entry => BATTLE_MODES.filter(mode => jpxModeStyle(mode) === state.sceneStyle && jpxConfigHasContent(entry.envelope.config[mode])).map(mode => ({ entry, mode }))); const general = resolveJpxScene(state.sceneStyle, 'General', routes, native); const inheritLabel = tr('inheritGeneral') + (general.rules ? ' · ' + strategyName(general, state.sceneWorld, native) : ''); for (const scene of ['General', 'Arena', 'Item', state.sceneWorld === 'Isekai' ? 'Tower' : 'Encounter', 'Battle1000']) { const target = state.sceneStyle + '_' + scene, route = routes[target]; const resolved = resolveJpxScene(state.sceneStyle, scene, routes, native); const row = el('article', undefined, 'jpx-scene-row'); row.dataset.scene = scene; const info = el('label', undefined, 'jpx-scene-label'), name = strategyName(resolved, state.sceneWorld, native); info.append(el('strong', jpxConfigSceneLabel(scene))); row.dataset.general = String(scene === 'General'); row.dataset.inherited = String(resolved.inherited); if (!selectedMode && viewingCurrent && scene === battleType && resolved.rules) { row.dataset.executing = 'true'; info.append(el('span', tr('inUse'), 'jpx-scene-badge')); } const choices = [['', scene === 'General' ? tr('unassigned') : inheritLabel]]; if (!Object.hasOwn(routes, target) && jpxConfigHasContent(native[target])) choices.push(['native', name]); for (const {entry, mode} of options) choices.push([JSON.stringify([entry.id, mode]), entry.envelope.title + (entry.envelope.kind === 'battle' ? ' · ' + jpxConfigSceneLabel(jpxModeScene(mode)) : '')]); const selected = route ? JSON.stringify([route.id, route.mode]) : choices.some(([value]) => value === 'native') ? 'native' : ''; if (route && !choices.some(([value]) => value === selected)) choices.push([selected, name]); const picker = select(choices, selected); picker.id = getUniqueId('scene-strategy'); info.htmlFor = picker.id; if (CSS.supports('appearance', 'base-select')) { const face = el('button'); face.type = 'button'; face.append(el('selectedcontent')); picker.prepend(face); } picker.setAttribute('aria-label', jpxConfigSceneLabel(scene)); const outdated = route && entryById(route.id)?.revision !== route.revision; if (outdated) info.append(el('span', tr('assignmentOlder'), 'jpx-scene-update')); const save = button(tr('assign'), async () => { if (picker.value === 'native') return; const pair = picker.value ? JSON.parse(picker.value) : null; const candidate = pair && candidates.find(entry => entry.id === pair[0]); if (pair && !candidate) throw jpxConfigError('worldMismatch'); if (candidate && jpxConfigContainsCode(candidate.envelope) && !await confirmed(tr('customCode'), tr('assign'))) return; library.assignScene(state.sceneWorld, target, candidate?.id || null, pair?.[1], candidate?.revision, route || null); if (state.sceneWorld === jpxConfigWorld()) syncJpxSceneRuntime(); signalJpxConfigWorld(state.sceneWorld); const scrollTop = content.scrollTop; announceJpxConfigLibrary(); showScenes(); notify(tr('assigned')); root.querySelector('.jpx-scenes-body').scrollTop = scrollTop; root.querySelector('[data-scene="' + scene + '"] select')?.focus({ preventScroll: true }); }, 'jpx-config-primary'); const cancel = button(tr('cancel'), () => { picker.value = selected; updatePending(); picker.focus({ preventScroll: true }); }); const pending = div('jpx-scene-pending'); pending.append(cancel, save); function updatePending() { const changed = picker.value !== selected || !!outdated && picker.value !== 'native'; pending.hidden = !changed; row.dataset.pending = String(changed); picker.title = picker.selectedOptions[0]?.textContent || ''; } picker.addEventListener('change', updatePending); updatePending(); const actions = div('jpx-scene-controls'); actions.append(picker, pending); row.append(info, actions); table.append(row); } } const sceneAssigned = (entry, application) => Object.values(application.state.scenes || {}).some(routes => Object.values(routes).some(route => route?.id === entry.id)); function visibleSavedEntry(entry, application = appliedContext()) { // Hide only untouched placeholders from older migrations, in every picker. if (entry.source?.type === 'native' && entry.revision === 1 && !Object.values(application.state.active || {}).includes(entry.id) && !sceneAssigned(entry, application)) { const mode = entry.envelope.mode, saved = application.saved[entry.envelope.world]; const rules = saved?.[mode] || (mode === '1H_Mage_General' ? saved?.Battlecaster_General : null); return !!(jpxConfigHasContent(entry.envelope.config[mode]) && jpxConfigHasContent(rules)); } return true; } function renderList() { cancelListDrag?.(); const normalize = value => String(value || '').normalize('NFKC').toLocaleLowerCase().replace(/[_·/\-]+/g, ' ').replace(/\s+/g, ' ').trim(); const query = normalize(state.query), words = query.split(' ').filter(Boolean); const application = appliedContext(); const selection = root.querySelector('.jpx-config-selection'); if (selection) renderSelection(selection); const detectedStyle = getDetectedJpxBattleStyle(); const detectedMode = detectedStyle ? getBattleMode(detectedStyle) : ''; const version = [application, query, detectedStyle, detectedMode, getJpxSelectedBattleMode(), state.world, state.style, state.scenario, state.kind, state.sort, localStorage.getItem(jpxLoadoutKey('Persistent')), localStorage.getItem(jpxLoadoutKey('Isekai'))]; if (listVersion?.every((value, index) => value === version[index])) { ensureJpxModeDetection(); return; } const fragment = document.createDocumentFragment(); const loadouts = new Map(), entryBindings = new Map(); for (const binding of application.state.bindings || []) { if (!loadouts.has(binding.world)) loadouts.set(binding.world, getJpxLoadoutCatalog(binding.world)); if (!entryBindings.has(binding.id)) entryBindings.set(binding.id, []); entryBindings.get(binding.id).push(binding); } if (orderedContext !== application || orderedBy !== state.sort) { orderedEntries = [...application.state.entries]; if (state.sort !== 'manual') orderedEntries.sort((a, b) => (state.sort === 'type' ? typeOrder(a, b) : state.sort === 'updated' ? Date.parse(b.updatedAt) - Date.parse(a.updatedAt) : 0) || collator.compare(a.envelope.title, b.envelope.title) || a.id.localeCompare(b.id)); orderedContext = application; orderedBy = state.sort; } const entries = orderedEntries.filter(entry => { if (!visibleSavedEntry(entry, application)) return false; const envelope = entry.envelope, data = classify(envelope); const matches = (!state.world || envelope.world === state.world || envelope.world === 'Any') && (!state.kind || envelope.kind === state.kind) && ((!state.style && !state.scenario) || data.modes.some(mode => (!state.style || jpxModeStyle(mode) === state.style) && (!state.scenario || jpxModeScene(mode) === state.scenario))); if (!matches || !words.length) return matches; const text = normalize([envelope.title, meta(envelope), ...data.modes, ...[...data.styles, ...data.battles].map(value => t('cB.' + value)), ...data.elements.map(value => tr(value))].join(' ')); return words.every(word => text.includes(word)); }); const routedStyle = getManagedBattleStyle(battleStyle || detectedStyle), sceneSelection = resolveJpxScene(routedStyle, battleType); const fixedMode = getJpxSelectedBattleMode(); const hasSceneRoute = [routedStyle + '_' + battleType, routedStyle + '_General'].some(mode => Object.hasOwn(jpxSceneRuntime.scenes, mode)); for (const entry of entries) { const row = el('article', undefined, 'jpx-config-row'); row.dataset.configId = entry.id; const applied = currentApplied(entry, application), current = entry.envelope.kind !== 'stats' && !fixedMode && hasSceneRoute && (sceneSelection.id || !sceneSelection.rules) ? sceneSelection.id === entry.id : applied.some(item => { if (item.world !== 'Any' && item.world !== jpxConfigWorld()) return false; const selected = item.world === 'Any' || fixedMode || !hasSceneRoute ? application.active[item.world] : null; return selected ? selected === entry.id : item.world === 'Any' || !!detectedMode && item.scopes.includes(detectedMode); }), outdated = applied.some(item => item.revision !== entry.revision); row.dataset.active = String(current); const info = div('jpx-config-info'), title = div('jpx-config-title'); if (state.sort === 'manual') { const dragLabel = t('cGen.dragRule'), grip = button(dragLabel, () => {}, 'jpx-config-grip'); grip.replaceChildren(createSettingsIcon('grip')); grip.title = dragLabel; grip.setAttribute('aria-label', dragLabel + ': ' + entry.envelope.title); grip.addEventListener('keydown', event => { if (!['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return; event.preventDefault(); event.stopPropagation(); const rows = listRows(), from = rows.findIndex(row => row.dataset.configId === entry.id); const to = event.key === 'Home' ? 0 : event.key === 'End' ? rows.length - 1 : from + (event.key === 'ArrowUp' ? -1 : 1); moveEntry(entry.id, Math.max(0, Math.min(rows.length - 1, to))); }); title.append(grip); } title.append(el('strong', entry.envelope.title)); if (current) title.append(el('span', tr('inUse'), 'jpx-config-status')); if (sceneAssigned(entry, application)) title.append(el('span', tr('assigned'), 'jpx-config-assigned')); if (detectedStyle && classify(entry.envelope).styles.includes(detectedStyle) && ['Any', jpxConfigWorld()].includes(entry.envelope.world)) title.append(el('span', tr('currentStyle'), 'jpx-config-detected')); info.append(title, tags(entry.envelope)); const bindings = entryBindings.get(entry.id) || []; if (bindings.length) { const label = bindings.map(binding => bindingLabel(binding, loadouts.get(binding.world))).join(' / '); const bound = button(label, () => showBindings(entry), 'jpx-config-binding'); bound.title = tr('bind') + ': ' + label; info.append(bound); } const actions = div('jpx-config-actions'); if (!current || outdated || entry.envelope.kind === 'battle-mode' && !fixedMode && sceneSelection.id === entry.id) { const apply = button(tr(outdated ? 'updateApply' : 'apply'), () => applyEntry(entry), 'jpx-config-primary'); if (entry.envelope.kind === 'battle-mode') apply.title = tr('fixedHint'); actions.append(apply); } actions.append(button(tr('edit'), () => { captureList(); chooseEditor(entry); })); const more = button(tr('more'), () => showMore(more, entry), 'jpx-config-more'); more.replaceChildren(createSettingsIcon('more')); more.setAttribute('aria-label', tr('more') + ': ' + entry.envelope.title); more.title = tr('more'); actions.append(more); row.append(info, actions); fragment.append(row); } resultCount.textContent = tr('resultCount', { count: entries.length }); if (!entries.length) fragment.append(el('p', tr(query || state.world || state.style || state.scenario || state.kind ? 'noMatches' : 'empty'), 'jpx-config-empty')); list.replaceChildren(fragment); listVersion = version; ensureJpxModeDetection(); } const listRows = () => [...list.querySelectorAll('.jpx-config-row')], rowOf = id => listRows().find(row => row.dataset.configId === id); function moveEntry(id, destination) { if (state.sort !== 'manual') return; const ids = listRows().map(row => row.dataset.configId), from = ids.indexOf(id); if (from < 0 || destination < 0 || destination >= ids.length || destination === from) return; const reordered = [...ids]; reordered.splice(from, 1); reordered.splice(destination, 0, id); try { captureList(); library.reorder(reordered, ids); renderList(); body.scrollTop = state.scroll; rowOf(id)?.querySelector('.jpx-config-grip')?.focus({ preventScroll: true }); } catch (cause) { error(cause); } } function showMore(anchor, entry) { if (anchor.popoverTargetElement?.isConnected) return; root.querySelectorAll('.jpx-config-menu').forEach(node => node.remove()); const menu = div('jpx-config-menu'); menu.setAttribute('popover', 'auto'); menu.setAttribute('role', 'group'); const add = (label, action, disabled = false) => { const item = button(label.startsWith('cGen.') ? t(label) : tr(label), async () => { menu.hidePopover(); await action(); }); item.disabled = disabled; menu.append(item); }; if (state.sort === 'manual') { const rows = listRows(), index = rows.findIndex(row => row.dataset.configId === entry.id); for (const [label, destination] of [['moveTop', 0], ['moveUp', index - 1], ['moveDown', index + 1], ['moveBottom', rows.length - 1]]) add('cGen.' + label, () => moveEntry(entry.id, destination), destination < 0 || destination >= rows.length || destination === index); } add('rename', () => renameEntry(entry, anchor)); if (entry.envelope.kind !== 'stats') add('bind', () => showBindings(entry)); add('settings', () => { captureList(); showSettings(entry); }); add('duplicate', () => { const envelope = jpxConfigClone(entry.envelope); envelope.title = (envelope.title + ' · ' + tr('copySuffix')).slice(0,100); library.save(envelope, { source: entry.source }); showMine(); }); add('export', () => exportEntry(entry)); if (entry.envelope.kind === 'battle-mode') add('reset', async () => { if (!await confirmed(tr('resetConfirm'), tr('reset'))) return; captureList(); openEditor(entry, entry.envelope.mode); state.editor.history.run(tr('reset'), () => { const mode = entry.envelope.mode, config = state.editor.draft.envelope.config, execution = config[mode].jpxPlusExecution; config[mode] = jpxConfigClone(defaultCfgBattle[mode] || { rules: [] }); if (execution) config[mode].jpxPlusExecution = execution; state.editor.redraw(); }); }); add('share', () => { captureList(); showStore(entry.envelope); }); if (referenced(library.references(entry.id))) add('detach', () => detachEntry(entry, false)); add('delete', () => detachEntry(entry, true)); // Keep the opener linked so native light-dismiss and a second click agree. menu.style.visibility = 'hidden'; root.append(menu); anchor.popoverTargetElement = menu; menu.addEventListener('toggle', () => { if (menu.matches(':popover-open')) { positionSettingsPopover(anchor, menu); menu.style.removeProperty('visibility'); menu.querySelector('button')?.focus({ preventScroll: true }); } else { menu.remove(); if (anchor.popoverTargetElement === menu) anchor.popoverTargetElement = null; } }); } const stale = entry => library.get(entry.id)?.revision !== entry.revision; const referenced = refs => refs.applied.length || refs.bindings.length || refs.scenes.length; async function detachEntry(entry, removeEntry) { const refs = library.references(entry.id), content = el('div'); content.append(el('p', tr('detachHint'))); const locations = el('ul'); for (const ref of refs.applied) locations.append(el('li', t('cB.' + ref.world) + ' · ' + (ref.selected ? tr('fixedMode') + ' · ' : '') + ref.scopes.map(scope => BATTLE_MODES.includes(scope) ? jpxConfigModeLabel(scope) : scope).join(', '))); for (const ref of refs.bindings) locations.append(el('li', bindingLabel(ref))); for (const ref of refs.scenes) locations.append(el('li', tr('sceneAssignments') + ' · ' + t('cB.' + ref.world) + ' · ' + jpxConfigModeLabel(ref.mode))); content.append(locations); const label = removeEntry ? referenced(refs) ? 'detachDelete' : 'delete' : 'detach'; if (!await confirmed(tr(removeEntry ? 'deleteConfirm' : 'detach'), tr(label), content)) return; library.detach(entry.id, entry.revision, removeEntry, refs); syncJpxSceneRuntime(); for (const world of new Set([...refs.applied, ...refs.scenes].map(ref => ref.world))) signalJpxConfigWorld(world); announceJpxConfigLibrary(); showMine(); notify(tr(removeEntry ? 'deleted' : 'detached')); } async function renameEntry(entry, anchor) { captureList(); anchor.focus({ preventScroll: true }); const input = titleInput(entry.envelope.title); input.pattern = '.*\\S.*'; input.setAttribute('aria-label', tr('title')); const content = div('jpx-config-rename'); content.append(input); input.addEventListener('keydown', event => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); input.closest('.jpx-config-confirm').querySelector('.jpx-config-primary').click(); } }); const answer = confirmAction(tr('rename'), [['cancel', tr('cancel')], ['save', tr('save'), true]], content, { validate: value => value !== 'save' || input.reportValidity(), focus: input }); input.select(); if (await answer !== 'save' || state.disposed || state.page !== 'mine') return; library.rename(entry.id, input.value, entry.revision); renderList(); body.scrollTop = state.scroll; rowOf(entry.id)?.querySelector('.jpx-config-more')?.focus({ preventScroll: true }); notify(tr('saved')); } function exportEntry(entry) { const blob = new Blob([JSON.stringify(entry.envelope.config, null, 2)], { type: 'application/json;charset=utf-8' }); const url = URL.createObjectURL(blob), anchor = el('a'); anchor.href = url; anchor.download = entry.envelope.title.replace(/[\\/:*?"<>|]/g, '_') + '.json'; anchor.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); } function showSettings(entry, imported) { resetPage('settings'); const header = pageHeader(backButton(showMine), tr(entry ? 'settings' : imported ? 'importWorld' : 'new')); body = div('jpx-config-body'); const form = el('form', undefined, 'jpx-config-form'); const envelope = entry ? jpxConfigClone(entry.envelope) : imported; const title = titleInput(envelope?.title || ''); const mode = envelope?.mode || getBattleMode('OneHanded'); const existing = envelope?.mode ? envelope.config[envelope.mode]?.jpxPlusExecution : null; const style = select([['auto', tr('auto')], ...nativeChoices(BATTLE_STYLES)], existing?.style || (entry ? 'auto' : jpxModeStyle(mode))); const element = select([['auto', tr('auto')], ...jpxConfigElements.map(value => [value, tr(value)])], existing?.element || 'auto'); const world = select(worlds, envelope?.world || jpxConfigWorld()); const scenario = select(nativeChoices(scenarios), jpxModeScene(mode)); const single = !envelope || envelope.kind === 'battle-mode'; form.append(field(tr('title'), title, true)); if (single) form.append(field(tr('style'), style), field(tr('element'), element)); form.append(field(tr('world'), world)); if (single) form.append(field(tr('scenario'), scenario)); if (envelope?.kind === 'stats') { world.value = 'Any'; world.disabled = true; } // An imported mode keeps its exact key. Changing a saved key is an explicit // config-setting action, never an automatic remapping during import. if (imported && single) { style.value = 'auto'; style.disabled = scenario.disabled = element.disabled = true; } const actions = div('jpx-config-actions jpx-config-wide'); actions.append(button(tr('cancel'), showMine)); const submit = el('button', tr(entry || imported ? 'save' : 'create'), 'jpx-config-primary'); submit.type = 'submit'; actions.append(submit); form.append(actions); form.addEventListener('submit', event => { event.preventDefault(); if (!form.reportValidity()) return; try { let next = envelope ? jpxConfigClone(envelope) : { schemaVersion:1, kind:'battle-mode', title:'', description:'', world:world.value, scriptVersion:window.JPXPlus.version, config:{battleVersion:defaultCfgBattle.battleVersion} }; next.title = title.value.trim(); if (!next.title) { title.focus(); return; } next.world = world.value; if (single && !imported) { const selectedStyle = style.value === 'auto' ? jpxModeStyle(mode) : style.value; const nextMode = selectedStyle + '_' + scenario.value; const rules = next.mode ? next.config[next.mode] : jpxConfigClone(defaultCfgBattle[nextMode] || defaultCfgBattle[selectedStyle + '_General'] || { rules:[] }); if (next.mode && next.mode !== nextMode) delete next.config[next.mode]; if (style.value !== 'auto' || element.value !== 'auto') rules.jpxPlusExecution = { style:style.value, element:element.value }; else delete rules.jpxPlusExecution; next.mode = nextMode; next.config[nextMode] = rules; } const saved = library.save(next, entry ? { id:entry.id, source:entry.source } : {}); if (!entry && !imported) chooseEditor(saved); else { showMine(); if (imported) importFeedback.show(tr('importAdded', { name: jpxImportDisplayName(saved.envelope.title) }), 'success', saved.envelope.title); else notify(tr('saved')); } } catch (cause) { if (imported) importFeedback.show(tr(messageKey(cause, 'storageError')), 'error'); else error(cause); } }); body.append(form); root.append(header,importFeedback.node,notice,body); if (imported) importFeedback.show(tr('importReady'), 'draft'); title.focus(); } function importFile() { const generation = ++importGeneration; if (importFeedback.node.dataset.stage === 'reading') importFeedback.clear(); const current = () => generation === importGeneration && !state.disposed && root.isConnected && state.page === 'mine'; const input = el('input'); input.type = 'file'; input.accept = '.txt,.json'; input.addEventListener('change', async () => { const file = input.files[0]; if (!file || !current()) return; clearNotice(); importFeedback.show(tr('importReading', { name: jpxImportDisplayName(file.name) }), 'reading', file.name); let reading = false; try { if (file.size > 2 * 1024 * 1024) throw jpxConfigError('tooLarge'); reading = true; const fileText = await file.text(); reading = false; // A newer selection, closed dialog or navigation owns the UI now. if (!current()) return; const value = JSON.parse(fileText, (key,value) => { if (['__proto__','prototype','constructor'].includes(key)) throw new Error('Invalid key'); return value; }); let envelope; if (value?.schemaVersion === 1 && value.config) envelope = value; else { const config = value, modes = BATTLE_MODES.filter(mode => Object.hasOwn(config,mode)); if (config.Battlecaster_General && !modes.includes('1H_Mage_General')) modes.push('Battlecaster_General'); const stats = !!config.statsVersion; const mode = modes.length === 1 && Object.keys(config).every(key => ['battleVersion','version',modes[0]].includes(key)) ? modes[0] : null; envelope = { schemaVersion:1, kind:stats?'stats':mode?'battle-mode':'battle', title:file.name.replace(/\.(json|txt)$/i,'').slice(0,100), description:'', world:stats?'Any':jpxConfigWorld(), scriptVersion:window.JPXPlus.version, ...(mode?{mode}:{}), config }; } // Validate in a detached temporary store so the naming form never // writes a malformed archive to the real library. const temporary = new Map(); const validator = createJpxConfigLibrary({ storage:{getItem:key=>temporary.get(key)||null,setItem:(key,value)=>temporary.set(key,value)}, key:'check', modes:BATTLE_MODES,battleVersion:defaultCfgBattle.battleVersion,statsVersion:defaultCfgStats.statsVersion }); envelope = validator.save(envelope).envelope; captureList(); showSettings(null,envelope); } catch(cause) { if (current()) importFeedback.show(tr('importFailed', { name: jpxImportDisplayName(file.name), reason: tr(reading ? 'importReadError' : messageKey(cause, 'invalidConfig')) }), 'error', file.name); } }); input.click(); } function bindingLabel(binding, catalog = getJpxLoadoutCatalog(binding.world)) { const persona = catalog.personas.find(item => item.id === binding.personaId); const set = persona?.sets.find(item => item.id === binding.setId); return [t('cB.' + binding.world), persona?.name || tr('personaNumber', { id: binding.personaId }), set?.name || tr('setNumber', { id: binding.setId })].join(' · '); } async function showBindings(entry) { if (stale(entry)) throw jpxConfigError('libraryChanged'); initJpxLoadoutBindings(); if (state.disposed || !root.isConnected) return; const content = div('jpx-config-bindings'), assignments = div('jpx-config-binding-list'); const world = select(worlds.slice(0, 2), entry.envelope.world === 'Any' ? jpxConfigWorld() : entry.envelope.world); const persona = select([], ''), set = select([], ''), hint = el('p', undefined, 'jpx-config-binding-hint'); const form = div('jpx-config-binding-fields'); world.dataset.bindingWorld = ''; persona.dataset.bindingPersona = ''; set.dataset.bindingSet = ''; form.append(field(tr('world'), world), field(tr('persona'), persona), field(tr('equipSet'), set)); const fill = (select, values, value) => { select.replaceChildren(); addOptions(select, values); if (values.some(([id]) => id === value)) select.value = value; select.disabled = !values.length; }; function updateSets() { const catalog = getJpxLoadoutCatalog(world.value), known = catalog.personas.find(item => item.id === persona.value); const ids = [...new Set(known?.sets.length ? known.sets.map(item => item.id) : catalog.sets)].sort((a, b) => Number(a) - Number(b)); fill(set, ids.map(id => [id, known?.sets.find(item => item.id === id)?.name || tr('setNumber', { id })]), catalog.current?.personaId === persona.value ? catalog.current.setId : known?.lastSetId || set.value); hint.hidden = !!persona.value && !!set.value; hint.textContent = tr(log || document.querySelector('#riddlemaster') ? 'bindingUnavailable' : 'bindingUnknown'); const submit = root.querySelector('.jpx-config-confirm .jpx-config-primary'); if (submit) submit.disabled = !persona.value || !set.value; } function updatePersonas() { const catalog = getJpxLoadoutCatalog(world.value); fill(persona, catalog.personas.map(item => [item.id, item.name || tr('personaNumber', { id: item.id })]), catalog.current?.personaId || persona.value); updateSets(); } function drawAssignments() { assignments.replaceChildren(); for (const binding of library.readState().bindings?.filter(item => item.id === entry.id) || []) { const row = div('jpx-config-binding-item'); row.append(el('span', bindingLabel(binding)), button(tr('unbind'), () => { library.removeBinding(binding, entry.id); drawAssignments(); (assignments.querySelector('button') || (persona.disabled ? world : persona)).focus({ preventScroll: true }); announceJpxConfigLibrary(); })); assignments.append(row); } } world.addEventListener('change', updatePersonas); persona.addEventListener('change', updateSets); updatePersonas(); drawAssignments(); content.append(assignments, form, hint); if (entry.envelope.kind === 'battle') content.append(el('p', tr('applyAll'))); if (jpxConfigContainsCode(entry.envelope)) content.append(el('p', tr('customCode'))); const choicePromise = confirmAction(tr('bind'), [['close', tr('close')], ['bind', tr('bind'), true]], content, { focus: persona.disabled ? world : persona, validate: value => value !== 'bind' || !!persona.value && !!set.value }); updateSets(); if (!jpxLoadoutConfirmed) { ensureJpxModeDetection(true).then(() => { if (content.isConnected) updatePersonas(); }); } const choice = await choicePromise; if (choice !== 'bind') return; const context = { world: world.value, personaId: persona.value, setId: set.value }; const previous = library.readState().bindings?.find(item => jpxLoadoutSame(item, context)); if (previous && previous.id !== entry.id) { const previousName = library.get(previous.id)?.envelope.title || ''; if (!await confirmed(tr('replaceBinding', { name: previousName }), tr('bind'))) return; } library.setBinding(context, entry.id, entry.revision, previous?.id || null); if (jpxLoadoutSame(jpxLoadoutConfirmed, context)) applyJpxLoadoutBinding(context, true); announceJpxConfigLibrary(); notify(tr('bound')); } async function applyEntry(entry) { if (stale(entry)) { notify(tr('libraryChanged'), true); return; } const envelope = entry.envelope, stats = envelope.kind === 'stats'; if (envelope.kind === 'battle-mode' && !jpxConfigHasRules(envelope.config[envelope.mode])) throw jpxConfigError('invalidConfig'); let world = stats ? 'Any' : envelope.world === 'Any' ? jpxConfigWorld() : envelope.world; const content = el('div'); if (envelope.kind === 'battle') content.append(el('p', tr('applyAll'))); if (!stats) { const target = select(worlds.slice(0,2),world); content.append(field(tr('applyWorld'),target)); target.addEventListener('change',()=>{world=target.value;}); } const custom = jpxConfigContainsCode(envelope); if(custom) content.append(el('p',tr('customCode'))); if ((envelope.kind==='battle'||envelope.world==='Any'||world!==jpxConfigWorld()||custom) && !await confirmed(tr('applyScope'),tr('apply'),content)) return; if (stale(entry)) { notify(tr('libraryChanged'), true); return; } const paused = commitJpxConfigEntry(entry, world, hooks.onApplied); captureList();showMine();notify(tr(paused?'applyPaused':'applied')); } function chooseEditor(entry) { // A detached schema editor uses the same fields without touching live cfgStats. if(entry.envelope.kind==='stats'){openEditor(entry,null);return;} const modes=modesOf(entry.envelope); if(modes.length===1){openEditor(entry,modes[0]);return;} resetPage('groups');const header=pageHeader(backButton(showMine),entry.envelope.title); body=div('jpx-config-body'); for(const mode of modes)body.append(button(jpxConfigModeLabel(mode),()=>openEditor(entry,mode),'jpx-config-group')); root.append(header,notice,body); } function openEditor(entry,mode){ resetPage('editor'); const draft=jpxConfigClone(entry),editor=div('jpx-config-editor'); const back=backButton(()=>leave(showMine)),header=pageHeader(back,entry.envelope.title); const content=div('jpx-config-editor-content'), footer=div('jpx-config-editor-footer'); const undoButton=button(tr('undo'),()=>history.undo()),redoButton=button(tr('redo'),()=>history.redo()); const saveButton=button(tr('save'),()=>saveEditor(),'jpx-config-primary'); footer.append(undoButton,redoButton,saveButton);editor.append(header,content,footer); const previousHistory=settingsEditHistory; state.editor={draft,mode,baseline:'',previousHistory,revision:entry.revision,history:null}; const draw=()=>{ content.replaceChildren(); if(mode){const section=el('div');content.append(section);renderBattleRuleSections(section,getSettingsSchemas().cfgBattleSchema.properties.find(field=>field.key==='modes').itemSchema,draft.envelope.config[mode],mode);} else{content.classList.add('jpx-config-stats-editor');content.style.overflow='auto';renderSchema(content,getSettingsSchemas().cfgStatsSchema,draft.envelope.config);} }; state.editor.redraw=draw; draw();state.editor.baseline=JSON.stringify(draft.envelope); const capture=()=>{ const expanded=[]; const visit=(value,path)=>{ if(!value||typeof value!=='object')return; if(fieldRenderers.expandedRuleItems.has(value))expanded.push(path); Object.entries(value).forEach(([key,child])=>visit(child,[...path,key])); }; visit(draft.envelope.config,[]); for(const panel of content.querySelectorAll('.jpx-rule-section:not([hidden])')) battleRulesView.scroll[mode+':'+panel.dataset.fieldKey]=panel.querySelector('.jpx-rule-scroll').scrollTop; return {value:JSON.stringify(draft.envelope),view:jpxConfigClone(battleRulesView),expanded, scroll:[...content.querySelectorAll('.jpx-rule-scroll')].map(node=>node.scrollTop)}; }; const entries=[];let position=0,restoring=false,pending=null,typing=null,typedAt=0; const update=()=>{undoButton.disabled=position===0;redoButton.disabled=position===entries.length;saveButton.disabled=!dirty();}; const finish=(before,key)=>{ if(restoring||!before)return;const after=capture();if(before.value===after.value)return; if(key&&typing===key&&position===entries.length&&Date.now()-typedAt<700)entries.at(-1).after=after; else{entries.splice(position);entries.push({before,after});if(entries.length>60)entries.shift();position=entries.length;} typing=key;typedAt=Date.now();update(); }; const restore=snapshot=>{ restoring=true;draft.envelope=JSON.parse(snapshot.value);battleRulesView=jpxConfigClone(snapshot.view); fieldRenderers.expandedRuleItems=new WeakSet(); for(const path of snapshot.expanded){const value=path.reduce((item,key)=>item?.[key],draft.envelope.config);if(value&&typeof value==='object')fieldRenderers.expandedRuleItems.add(value);} try{draw();[...content.querySelectorAll('.jpx-rule-scroll')].forEach((node,index)=>node.scrollTop=snapshot.scroll[index]||0);}finally{restoring=false;typing=null;update();} }; const beforeInput=event=>{if(event.target.matches('input,select,textarea'))pending=capture();}; const afterInput=event=>{finish(pending,event.type==='input'?event.target:null);pending=null;}; for(const type of ['input','change']){editor.addEventListener(type,beforeInput,true);editor.addEventListener(type,afterInput);} const history={ run(label,action){const before=capture();try{return action();}finally{finish(before,null);}}, undo(){if(position>0)restore(entries[--position].before);},redo(){if(position{ if(!(event.ctrlKey||event.metaKey)||event.altKey||event.isComposing||jpxUtils.keyCaptureController||event.target.closest('input,textarea,[contenteditable=true]'))return; if(!['z','y'].includes(event.key.toLowerCase()))return;event.preventDefault();event.stopPropagation(); if(event.key.toLowerCase()==='y'||event.shiftKey)history.redo();else history.undo(); }); state.editor.history=history;settingsEditHistory=history;update();root.append(notice,editor); (root.closest('.jpx-settings-mobile') ? document.getElementById('close-button') : back).focus({preventScroll:true}); } const dirty=()=>!!state.editor&&JSON.stringify(state.editor.draft.envelope)!==state.editor.baseline; function disposeEditor(){ if(!state.editor)return;fieldRenderers.dragState.cancel?.();jpxUtils.keyCaptureController?.abort(); state.editor.history.dispose();settingsEditHistory=state.editor.previousHistory;state.editor=null; } function saveEditor(){ const edit=state.editor;if(!edit)return true; const current=library.get(edit.draft.id); if(!current||current.revision!==edit.revision){notify(tr('libraryChanged'));return false;} try{library.save(edit.draft.envelope,{id:edit.draft.id,source:edit.draft.source});disposeEditor();showMine();notify(tr('saved'));return true;} catch(cause){error(cause);return false;} } async function leave(next){ if(state.dialog)return; if(dirty()){ const choice=await confirmAction(tr('saveChanges'),[['keep',tr('keepEditing')],['discard',tr('discard')],['save',tr('save'),true]]); if(!choice||choice==='keep')return; if(choice==='save'&&!saveEditor())return; } disposeEditor();if(state.page==='editor')showMine();next(); } function showStore(share){ resetPage('store'); root.append(renderSelection()); const top=div('jpx-config-toolbar jpx-config-store-header'); top.append(pageTabs(false,showMine,()=>showStore()));root.append(top,notice); const mount=el('div');mount.style.cssText='display:flex;flex:1;min-height:0;min-width:0;overflow:hidden';root.append(mount); jpxEmbeddedStore ||= createJpxIntegratedStore(window,t); state.storeDispose=jpxEmbeddedStore.render(mount,{ notify, renderTags:(envelope,choose)=>tags(envelope,choose||null), compareTypes:(a,b)=>typeOrder({envelope:a},{envelope:b}), confirm:(title,description,action)=>confirmed(title,action,el('p',description)), listShareConfigs(){ const application=appliedContext(); return application.state.entries.filter(entry=>visibleSavedEntry(entry,application)) .sort((a,b)=>Date.parse(b.updatedAt)-Date.parse(a.updatedAt)||collator.compare(a.envelope.title,b.envelope.title)); }, getShareConfig:id=>library.get(id), async saveConfig(envelope,origin){ const source=origin?.source,previous=source&&library.list().find(entry=>entry.source?.repository===source.repository&&entry.source?.id===source.id); let id; if(previous){const choice=await confirmAction(tr('sourceExists'),[['cancel',tr('cancel')],['copy',tr('keepCopy')],['update',tr('updateCopy'),true]]);if(!choice||choice==='cancel')return false;if(choice==='update'){ if(stale(previous)){notify(tr('libraryChanged'));return false;} id=previous.id; }} library.save(envelope,{...(id?{id}:{}),...(source?{source}:{})});notify(tr('savedFromStore'));return true; } },{...(share?{share:jpxConfigClone(share)}:{}),onBack:showMine,toolbarHost:top}); } const beforeUnload=event=>{if(dirty()){event.preventDefault();event.returnValue='';}}; const changed=()=>{try{if(state.page==='mine'){const scroll=body.scrollTop;renderList();body.scrollTop=scroll;}else if(state.page==='scenes'&&!state.dialog)showScenes();}catch(cause){error(cause);}}; const onStorage=event=>{if(event.key===jpxConfigLibraryKey)changed();}; const migrationError=()=>notify(tr('storageError')); const listeners=[['beforeunload',beforeUnload],['storage',onStorage],['jpx:config-library',changed],['jpx:legacy-config-error',migrationError],['jpx:mode-detected',changed],['jpx:loadout-detected',changed]]; for(const [type,listener] of listeners)window.addEventListener(type,listener); const controller={ isEditing:()=>!!state.editor,leave, back(){ if(state.dialog)return true; if(state.page==='store')return state.storeDispose?.back?.()||false; if(!state.back)return false; Promise.resolve().then(state.back).catch(error);return true; }, onHidden(){importGeneration++;cancelListDrag?.();clearNotice();importFeedback.clear();state.dialog?.(null);state.storeDispose?.suspend?.();}, onShown(){state.storeDispose?.resume?.();changed();}, dispose(){if(state.disposed)return;state.disposed=true;cancelListDrag?.();clearNotice();state.dialog?.(null);disposeEditor();state.storeDispose?.();for(const [type,listener] of listeners)window.removeEventListener(type,listener);if(jpxConfigManagerView===controller)jpxConfigManagerView=null;} }; jpxConfigManagerView=controller; try{seedJpxConfigLibrary();showMine();window.dispatchEvent(new Event('jpx:legacy-config-request'));} catch(cause){root.append(notice);error(cause);} return controller; } // Persona/set observations stay outside native rules and exported configs. const jpxLoadoutSlot = value => /^[1-9]\d{0,5}$/.test(String(value || '')) ? String(value) : ''; const jpxLoadoutKey = (world = jpxConfigWorld()) => prefix + 'loadouts_v1' + (world === 'Isekai' ? '_isekai' : ''); const jpxLoadoutSame = (a, b) => !!a && !!b && a.world === b.world && a.personaId === b.personaId && a.setId === b.setId; let jpxLoadoutConfirmed = null, jpxLoadoutPending = false, jpxLoadoutBusy = false, jpxLoadoutInitialized = false; function readJpxLoadoutCatalog(world = jpxConfigWorld()) { let saved; try { const raw = localStorage.getItem(jpxLoadoutKey(world)); if (raw?.length < 100000) saved = JSON.parse(raw); } catch { /* Missing observations can be recovered from the game. */ } const catalog = { version: 1, personas: [], sets: [] }; if (saved?.version !== 1) return catalog; if (Array.isArray(saved.sets)) catalog.sets = [...new Set(saved.sets.map(jpxLoadoutSlot).filter(Boolean))].slice(0, 100); if (Array.isArray(saved.personas)) for (const item of saved.personas.slice(0, 100)) { if (!jpxLoadoutSlot(item?.id) || catalog.personas.some(persona => persona.id === String(item.id))) continue; const persona = { id: String(item.id), name: String(item.name || '').slice(0, 100), sets: [] }; if (Array.isArray(item.sets)) for (const set of item.sets.slice(0, 100)) { if (jpxLoadoutSlot(set?.id)) persona.sets.push({ id: String(set.id), name: String(set.name || '').slice(0, 100) }); } if (persona.sets.some(set => set.id === jpxLoadoutSlot(item.lastSetId))) persona.lastSetId = String(item.lastSetId); catalog.personas.push(persona); } if (saved.current?.world === world && jpxLoadoutSlot(saved.current.personaId) && jpxLoadoutSlot(saved.current.setId)) catalog.current = { world, personaId: String(saved.current.personaId), setId: String(saved.current.setId) }; return catalog; } function readJpxHvutLoadout(world = jpxConfigWorld()) { try { const raw = localStorage.getItem((world === 'Isekai' ? 'hvuti' : 'hvut') + '_persona'); if (!raw || raw.length > 100000) return null; const data = JSON.parse(raw), personas = []; if (!data || typeof data !== 'object' || Array.isArray(data)) return null; for (const [id, item] of Object.entries(data)) { if (!jpxLoadoutSlot(id) || !item || typeof item !== 'object') continue; const sets = Object.entries(item).filter(([id]) => jpxLoadoutSlot(id)) .slice(0, 100).map(([id, set]) => ({ id, name: typeof set?.name === 'string' ? set.name.slice(0, 100) : '' })); personas.push({ id, name: typeof item.name === 'string' ? item.name.slice(0, 100) : '', sets }); if (personas.length >= 100) break; } const personaId = jpxLoadoutSlot(data.pset), setId = jpxLoadoutSlot(data.eset); return { personas, sets: [...new Set(personas.flatMap(item => item.sets.map(set => set.id)))], current: personaId && setId ? { world, personaId, setId } : null }; } catch { return null; } } function getJpxLoadoutCatalog(world = jpxConfigWorld()) { const catalog = readJpxLoadoutCatalog(world), hvut = readJpxHvutLoadout(world); // HVUT's cache supplies names/options, never proof of a completed switch. for (const item of hvut?.personas || []) { const previous = catalog.personas.find(persona => persona.id === item.id); if (!previous) catalog.personas.push(item); else { if (item.name) previous.name = item.name; for (const set of item.sets) { const known = previous.sets.find(value => value.id === set.id); if (!known) previous.sets.push(set); else if (set.name) known.name = set.name; } } } catalog.sets = [...new Set([...catalog.sets, ...(hvut?.sets || [])])].sort((a, b) => Number(a) - Number(b)); return catalog; } function jpxConfigContainsCode(envelope) { return BATTLE_MODES.some(mode => Object.entries(envelope.config[mode] || {}).some(([key, rules]) => (key === 'rules' || key === 'supports' || key === 'attacks' || key.startsWith('kb_')) && Array.isArray(rules) && rules.some(rule => rule.type === 'kamisamaniNattaHi'))); } function applyJpxLoadoutBinding(context, force = false, notify = true) { if (!context || context.world !== jpxConfigWorld() || jpxLoadoutPending || jpxLoadoutBusy || log || document.querySelector('#textlog, #battle_main, #riddlemaster')) return false; const library = getJpxConfigLibrary(); if (!library.hasBinding(context.world, context.personaId, context.setId)) return false; const state = library.readState(); const binding = state.bindings?.find(item => jpxLoadoutSame(item, context)); if (!binding) return false; const entry = state.entries.find(item => item.id === binding.id); // A later imported update cannot acquire permission to run custom code. if (!entry || jpxConfigContainsCode(entry.envelope) && binding.trustedRevision !== entry.revision) return false; const applied = state.applied[context.world]?.[entry.id]; if (!force && state.active?.[context.world] === entry.id && applied?.revision === entry.revision && applied.scopes.every(scope => JSON.stringify(cfgBattle[scope]) === JSON.stringify(applied.config[scope]))) return false; commitJpxConfigEntry(entry, context.world); if (notify) window.dispatchEvent(new Event('jpx:config-library')); return true; } function confirmJpxLoadout(current, catalog, livePage = false) { if (jpxLoadoutBusy || log || document.querySelector('#textlog, #battle_main, #riddlemaster') || current.world !== jpxConfigWorld()) return; const previous = readJpxLoadoutCatalog().current; const pending = jpxLoadoutPending; let applied = false; jpxLoadoutPending = false; try { if (!jpxLoadoutSame(previous, current)) applied = applyJpxLoadoutBinding(current, false, false); } catch (error) { jpxLoadoutPending = pending; throw error; } const persona = catalog.personas.find(item => item.id === current.personaId); if (!livePage && !jpxLoadoutSame(previous, current)) { localStorage.removeItem(jpxDetectedFamilyKey()); jpxDetectionSourceIgnored = true; } if (!jpxLoadoutSame(previous, current) && (!livePage || previous && !getJpxSpellDamageFromPage())) { const key = prefix + 'spellDamageBonus' + isekaiSuffix; localStorage.removeItem(key); localStorage.removeItem(key + ':context'); spellDamageBonus = { maxType: '', maxValue: 0 }; } localStorage.setItem(prefix + 'personaId' + isekaiSuffix, current.personaId); if (persona?.name) localStorage.setItem(prefix + 'persona' + isekaiSuffix, persona.name); catalog.current = current; if (persona?.sets.some(set => set.id === current.setId)) persona.lastSetId = current.setId; const raw = JSON.stringify(catalog), key = jpxLoadoutKey(); const changed = localStorage.getItem(key) !== raw || !jpxLoadoutSame(jpxLoadoutConfirmed, current); if (localStorage.getItem(key) !== raw) localStorage.setItem(key, raw); jpxLoadoutConfirmed = current; // Publish only after both configuration and persona/set state are ready. if (applied) window.dispatchEvent(new Event('jpx:config-library')); if (changed) window.dispatchEvent(new Event('jpx:loadout-detected')); } function rememberJpxLoadout(character = document, equipment = document) { if (jpxLoadoutPending && character === document) return; const equipmentPersona = equipment.querySelector('#persona_form select'); const selector = equipmentPersona || character.querySelector('#persona_form select'); const personaId = jpxLoadoutSlot(selector?.value); const characterPersona = character.querySelector('#persona_form select'); if (!personaId || characterPersona && characterPersona.value !== personaId) return; const active = equipment.querySelector('#eqsl img[src*="_on.png"]'); const setId = jpxLoadoutSlot(active?.getAttribute('src')?.match(/(?:^|\/)set(\d+)_on\.png(?:[?#]|$)/)?.[1]); const catalog = getJpxLoadoutCatalog(); for (const option of selector.options) { const id = jpxLoadoutSlot(option.value); if (!id) continue; const item = catalog.personas.find(persona => persona.id === id); if (item) item.name = option.textContent.trim().slice(0, 100); else catalog.personas.push({ id, name: option.textContent.trim().slice(0, 100), sets: [] }); } const sets = [...equipment.querySelectorAll('#eqsl img')].map(node => jpxLoadoutSlot(node.getAttribute('src')?.match(/(?:^|\/)set(\d+)_(?:on|off)\.png(?:[?#]|$)/)?.[1])).filter(Boolean); if (sets.length) catalog.sets = [...new Set(sets)]; if (!setId || !catalog.sets.includes(setId)) return; const persona = catalog.personas.find(item => item.id === personaId); if (!persona) return; // Keep the actual observed slots per persona as well as the legacy catalog. // No fixed persona/set count, and no borrowed selection from another world. persona.sets = sets.map(id => persona.sets.find(item => item.id === id) || { id, name: '' }); confirmJpxLoadout({ world: jpxConfigWorld(), personaId, setId }, catalog, character === document && equipment === document); } function initJpxLoadoutBindings() { if (jpxLoadoutInitialized) return; jpxLoadoutInitialized = true; const unavailable = () => !!log || !!document.querySelector('#textlog, #battle_main, #riddlemaster'); if (unavailable()) return; const invalidate = () => { jpxLoadoutPending = true; jpxLoadoutConfirmed = null; jpxDetectionGeneration++; jpxDetectionRetryAt = 0; jpxDetectionSourceIgnored = true; localStorage.removeItem(jpxDetectedFamilyKey()); const key = prefix + 'spellDamageBonus' + isekaiSuffix; localStorage.removeItem(key); localStorage.removeItem(key + ':context'); spellDamageBonus = { maxType: '', maxValue: 0 }; }; let refreshTimer; const refresh = () => { clearTimeout(refreshTimer); refreshTimer = setTimeout(() => { if (jpxLoadoutPending && !jpxLoadoutBusy && !unavailable() && document.visibilityState !== 'hidden') ensureJpxModeDetection(true); }, 80); }; document.addEventListener('change', event => { if (event.target.closest?.('#persona_form, [name=equip_set]')) invalidate(); }, true); document.addEventListener('submit', event => { if (isJpxLoadoutSubmission(event.target, event.submitter)) invalidate(); }, true); document.addEventListener('click', event => { if (event.target.closest?.('#eqsl')) invalidate(); }, true); // Native navigation is handled on the next page. AJAX replacements need a // fresh server snapshot, not the dropdown's provisional selection. const nativeObserver = new MutationObserver(records => { if (unavailable()) { nativeObserver.disconnect(); return; } if (!jpxLoadoutPending || jpxLoadoutBusy) return; if (records.some(record => record.type === 'attributes' ? record.target.closest?.('#eqsl') : [...record.addedNodes].some(node => node.nodeType === 1 && (node.matches('#persona_form, #eqsl, #eqsb') || node.querySelector('#persona_form, #eqsl, #eqsb'))))) refresh(); }); nativeObserver.observe(document.getElementById('csp') || document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] }); let hvutPending = false; function watchHvut(top) { const isBusy = () => [...top.children].some(node => /^\([PE]\.\.\.\)$/.test(node.firstElementChild?.textContent?.trim())); if (isBusy()) { hvutPending = true; jpxLoadoutBusy = true; invalidate(); } new MutationObserver(records => { if (unavailable()) return; const busy = isBusy(); if (busy) { hvutPending = true; jpxLoadoutBusy = true; invalidate(); return; } // A cached/fast response can enter and leave P/E busy in one task. // Mutation records retain the removed busy text even then. const completed = records.some(record => /^\([PE]\.\.\.\)$/.test(record.oldValue?.trim()) || [...record.removedNodes].some(node => /^\([PE]\.\.\.\)$/.test(node.textContent?.trim()))); if (!hvutPending && !completed) return; if (!hvutPending) invalidate(); hvutPending = false; jpxLoadoutBusy = false; const observed = readJpxHvutLoadout(); if (!observed?.current || !observed.personas.some(persona => persona.id === observed.current.personaId && persona.sets.some(set => set.id === observed.current.setId))) { refresh(); return; } // HVUT writes persona first, set second. Its P/E indicator must finish // before the tuple is accepted; intermediate cache values are ignored. try { confirmJpxLoadout(observed.current, getJpxLoadoutCatalog()); window.dispatchEvent(new Event('jpx:mode-detected')); } catch (error) { console.warn('JPX-PLUS loadout binding failed.', error); } }).observe(top, { childList: true, subtree: true, characterData: true, characterDataOldValue: true }); } const top = document.getElementById('hvut-top'); if (top) watchHvut(top); else { const observer = new MutationObserver(() => { const top = document.getElementById('hvut-top'); if (top) { observer.disconnect(); clearTimeout(timeout); watchHvut(top); } }); observer.observe(document.getElementById('navbar')?.parentElement || document.body, { childList: true }); const timeout = setTimeout(() => observer.disconnect(), 10000); } window.addEventListener('storage', event => { if (event.key !== jpxLoadoutKey() && event.key !== (isekaiSuffix ? 'hvuti' : 'hvut') + '_persona') return; if (unavailable()) return; if (event.key === jpxLoadoutKey()) { // Another JPX tab has already confirmed and applied this tuple. // Share its observation; do not re-apply over a manual selection. const current = readJpxLoadoutCatalog().current; if (current && !jpxLoadoutBusy) { jpxDetectionGeneration++; jpxDetectionSourceIgnored = true; jpxLoadoutConfirmed = current; jpxLoadoutPending = false; window.dispatchEvent(new Event('jpx:loadout-detected')); return; } } invalidate(); refresh(); }); window.addEventListener('focus', () => { if (jpxLoadoutPending) refresh(); }); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && jpxLoadoutPending) refresh(); }); window.addEventListener('pagehide', () => clearTimeout(refreshTimer)); try { rememberJpxLoadout(); if (!hvutPending && !jpxLoadoutConfirmed && getJpxConfigLibrary().hasBinding(jpxConfigWorld())) ensureJpxModeDetection(true); } catch (error) { console.warn('JPX-PLUS loadout binding could not be read.', error); } } const JPX_STATS_DATA_CSS = ` #settings-container #panel_stats { scrollbar-gutter:stable; } .jpx-stats-data { --jpx-motion:160ms; color:#392d25; font:13px/1.45 Arial,Helvetica,sans-serif; min-width:0; max-width:100%; text-align:left; } .jpx-stats-data * { box-sizing:border-box; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) h3 { margin:0 0 12px; font-size:14px; color:#5c0d11; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) h4 { margin:0 0 8px; font-size:13px; font-weight:600; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) .jpx-stats-toolbar { display:flex; flex-wrap:wrap; gap:8px; margin:0; } .jpx-stats-data-section { padding:16px 0; } .jpx-stats-data .jpx-shared-data { border-top:1px solid #c8b49b; border-bottom:1px solid #c8b49b; min-width:0; } .jpx-shared-data > summary { display:flex; align-items:center; justify-content:space-between; gap:12px; min-height:48px; padding:8px 4px 8px 0; cursor:pointer; list-style:none; color:#5c0d11; font-weight:600; } .jpx-shared-data > summary::-webkit-details-marker { display:none; } .jpx-shared-data > summary svg { width:18px; height:18px; flex:none; transition:transform var(--jpx-motion) ease-out; } .jpx-shared-data[open] > summary svg { transform:rotate(180deg); } .jpx-shared-data-body { padding:0 0 16px; display:grid; gap:20px; } .jpx-shared-data-row { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:8px 16px; padding:8px 0; } .jpx-shared-data-actions { display:flex; gap:8px; flex:none; } .jpx-shared-data-source { min-width:0; overflow-wrap:anywhere; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) :is(button,select,input) { font:inherit; margin:0; min-height:36px; max-width:100%; border:1px solid #c8b49b; border-radius:2px; background:#fffdf7; color:#5c0d11; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) button { padding:7px 12px; cursor:pointer; white-space:normal; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) button:hover { background:#f1e2c5; } .jpx-stats-data button:disabled { opacity:.6; cursor:default; } .jpx-stats-data :focus-visible { outline:2px solid #9b4e03; outline-offset:2px; } .jpx-shared-data-row select { min-width:0; width:100%; padding:6px; } .jpx-shared-data-stamina label { display:grid; grid-template-columns:minmax(0,1fr) 96px; align-items:center; gap:12px; min-width:0; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) .jpx-shared-data-stamina input[type=number] { width:100%; min-width:0; min-height:36px; field-sizing:fixed; padding:6px; background:#fffdf7; color:#392d25; border-color:#c8b49b; } .jpx-stats-data-maintenance { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:20px 0; flex-wrap:wrap; border-top:1px solid #c8b49b; } .jpx-shared-data + .jpx-stats-data-maintenance { border-top:0; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) .jpx-stats-transfer { margin:16px 0 0; padding:12px 0 0; border:0; border-top:1px solid #c8b49b; background:transparent; } .jpx-stats-data .jpx-stats-transfer label { display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin:12px 0; } .jpx-stats-data .jpx-stats-transfer select { min-width:0; padding:6px; } @media(max-width:650px),(pointer:coarse) { :is(.jpx-stats-data,#settings-container .jpx-stats-data) :is(button,select,input) { min-height:44px; } .jpx-shared-data-row { gap:8px; } .jpx-shared-data-revision { grid-template-columns:minmax(0,1fr); } .jpx-shared-data-revision .jpx-shared-data-actions { justify-self:end; } .jpx-stats-data-section { padding-top:12px; } :is(.jpx-stats-data,#settings-container .jpx-stats-data) .jpx-shared-data-stamina input[type=number] { font-size:16px; min-height:44px; } } @media(prefers-reduced-motion:reduce) { .jpx-stats-data { --jpx-motion:0ms; } } `; function sharedText(key) { return t('cShared.' + key); } async function ensureJpxSharedRecords() { return jpxShared.ensureRecords(async () => { const db = await openDB(); try { return await new Promise((resolve, reject) => { const tx = db.transaction('battleRecords', 'readonly'); const request = tx.objectStore('battleRecords').getAll(); tx.oncomplete = () => resolve(request.result); tx.onabort = () => reject(tx.error || new Error('Legacy archive read failed')); }); } finally { db.close(); } }); } function onJpxSharedChange(change) { const key = change.key; if (key === 'jpx_recordsChanged') { window.dispatchEvent(new Event('jpx:records-changed')); return; } // Shared settings are authoritative, but never resume a running battle. if (key === 'jpx_configLibrary_v1') { // Saving/renaming an unused archive is not an instruction to apply it. // A changed active selection is relevant even if the native rules match. const before = jpxSelectedConfig?.mode || ''; refreshJpxSelectedConfig(); if (before !== (jpxSelectedConfig?.mode || '')) pauseForJpxConfigApplication(); window.dispatchEvent(new Event('jpx:config-library')); } if ([prefix + 'cfgBattle' + isekaiSuffix, prefix + 'userKeybinds' + isekaiSuffix].includes(key)) { pauseForJpxConfigApplication(); if (key === prefix + 'cfgBattle' + isekaiSuffix) loadBattleConfig(); else userKeybinds = JSON.parse(localStorage.getItem(prefix + 'userKeybinds' + isekaiSuffix) || 'null') || { ...KEYBINDS }; refreshJpxSelectedConfig(); jpxPanelManager.refreshAppearance?.(); document.getElementById('settings-container')?.jpxConfigApplied?.(key.includes('userKeybinds') ? { shortcuts: userKeybinds } : cfgBattle, 'battle'); } if (key === prefix + 'cfgStats') { loadStatsSettingsConfig(); document.getElementById('settings-container')?.jpxConfigApplied?.(cfgStats, 'stats'); } // Existing theme, apply-signal and cleanup listeners can consume the same // invalidation path; no native storage or third-party prototype is changed. window.dispatchEvent(new StorageEvent('storage', { key, oldValue: change.oldValue ?? null, newValue: change.newValue ?? null, storageArea: window.localStorage, url: location.href })); } function renderJpxSharedDataActions(parent) { if (!jpxShared.enabled) return; const section = document.createElement('details'); section.className = 'jpx-shared-data'; const title = document.createElement('summary'); title.textContent = sharedText('title'); title.append(createSettingsIcon('chevronDown')); const body = document.createElement('div'); body.className = 'jpx-shared-data-body'; section.append(title,body); parent.append(section); const group = (caption, tooltip) => { const block = document.createElement('section'), heading = document.createElement('h4'); heading.textContent = caption; if (tooltip) heading.title = tooltip; block.append(heading); body.append(block); return block; }; const download = (name, value) => { const url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: 'application/json' })); const link = document.createElement('a'); link.href = url; link.download = name; link.click(); URL.revokeObjectURL(url); }; const restore = snapshot => { if (!window.confirm(sharedText('confirm'))) return; pauseForJpxConfigApplication(); jpxShared.restore(snapshot); onJpxSharedChange({ key: prefix + 'cfgBattle' + isekaiSuffix }); loadStatsSettingsConfig(); jpxUtils.createToast(sharedText('saved')); }; // Recovery copies are stored packed; list them once restored, above the quota. const recovery = document.createComment('jpx-recovery'); body.append(recovery); Promise.all([jpxShared.backups(), jpxShared.revisions()]).then(([backups, revisions]) => { if (backups.length) { const block = group(sharedText('backupSection')); recovery.before(block); for (const snapshot of backups) { const row = document.createElement('div'); row.className = 'jpx-shared-data-row'; const label = document.createElement('span'); label.className = 'jpx-shared-data-source'; label.textContent = new URL(snapshot.origin).hostname; row.append(label); const actions = document.createElement('div'); actions.className = 'jpx-shared-data-actions'; row.append(actions); jpxUtils.createButton(actions, { text:t('cM.export'), history:false, onClick:() => download('jpx-before-sharing-' + new URL(snapshot.origin).hostname + '.json', snapshot) }).title = sharedText('backup'); jpxUtils.createButton(actions, { text:sharedText('restoreAction'), history:false, onClick:() => restore(snapshot) }).title = sharedText('restore'); block.append(row); } } if (revisions.length) { const block = group(sharedText('historySection')); recovery.before(block); const row = document.createElement('div'); row.className = 'jpx-shared-data-row jpx-shared-data-revision'; const select = document.createElement('select'); select.setAttribute('aria-label', sharedText('restoreRevision')); revisions.slice().reverse().forEach((revision, index) => { const option = document.createElement('option'); option.value = index; option.textContent = revision.key + ' · ' + revision.source + ' · ' + (revision.at ? new Date(revision.at).toLocaleString() : index + 1); select.append(option); }); row.append(select); const actions = document.createElement('div'); actions.className = 'jpx-shared-data-actions'; row.append(actions); jpxUtils.createButton(actions, { text:t('cM.export'), history:false, onClick:() => download('jpx-shared-settings-history.json', revisions) }).title = sharedText('history'); jpxUtils.createButton(actions, { text:sharedText('restoreAction'), history:false, onClick:() => { const revision = revisions.slice().reverse()[Number(select.value)]; restore({values:{[revision.key]:revision.value}}); } }).title = sharedText('restoreRevision'); block.append(row); } }).catch(error => console.warn('JPX shared recovery copies could not be read.', error)); const date = new Date().toISOString().slice(0, 10); const stamina = group(sharedText('quotaShort') + ' · ' + date + ' UTC', sharedText('quotaHelp')); for (const world of ['Persistent', 'Isekai']) { const row = document.createElement('div'); row.className = 'jpx-shared-data-row jpx-shared-data-stamina'; const label = document.createElement('label'); label.textContent = t('sP.' + world); const input = document.createElement('input'); input.type = 'number'; input.min = '0'; input.step = '0.01'; input.value = jpxShared.baseline(world, date); input.dataset.sharedStamina = world; label.append(input); row.append(label); jpxUtils.createButton(row, { text: sharedText('save'), history: false, onClick: () => { if (!input.value.trim() || !input.reportValidity()) return; jpxShared.setBaseline(world, date, Number(input.value)); window.dispatchEvent(new Event('jpx:records-changed')); return sharedText('saved'); } }); stamina.append(row); } } // END JPX CONFIG MANAGEMENT window.addEventListener('storage', event => { if (event.key !== cleanupKey || !event.newValue || cleanupInProgress) return; cleanupInProgress = true; isActiveBattle = false; sessionStorage.setItem(cleanupHoldKey, '1'); window.removeEventListener('beforeunload', storeTmp); window.location.reload(); }); window.dispatchEvent(new Event('jpx:ready')); initDo(); } })(typeof unsafeWindow === 'undefined' ? window : unsafeWindow);