Merge branch 'master' into fix/spine-start-anim
This commit is contained in:
577 files changed
+43650
-10558
No files matched your search
@@ -17,7 +17,9 @@
|
||||
// already did.
|
||||
// Watching a teammate (DESIGN §20.15, ui/watchBonds.js) the strip and the popup show THAT player's bonds and layers:
|
||||
// the strip carries an amber "👁 name" tag (`owner`, the observing pill's spelling, research 09 §3.1) and amber rings,
|
||||
// the popup a "👁 name 的盟约" line; its member list reads the teammate's operators on the field (no hand: never sent).
|
||||
// the popup a "👁 name 的盟约" line; its member list reads the teammate's operators on the field — in prep their bench
|
||||
// too, counted like their own popup counts it (ui/watchBonds.js ownerBoard: hand / temp by the scout's `area`, GitHub
|
||||
// #385); a battle sends no bench.
|
||||
// 0.2.0 补位: a member the player fields as its stand-in (the own m.private.standIns; a teammate's unit that says so —
|
||||
// UnitInfo `standInFor`) is drawn as the stand-in — avatar, name, a small 「替补」 mark on the thumbnail — and its row
|
||||
// opens the stand-in's card (gameLogic memberStandIn; the owner's recall of the official mode, 2026-10-06).
|
||||
|
||||
@@ -91,13 +91,13 @@ export function pickBusy(busyIdx, card, mine) {
|
||||
|
||||
/**
|
||||
* Whether I may pick a card right now: my turn (solo: always), no pick of mine yet, the card free and no pick in flight.
|
||||
* @param {any} sp normalizeSp(...) @param {{ idx: number, takenBy?: string|null } | null | undefined} card
|
||||
* @param {any} sp normalizeSp(...) @param {{ idx: number, takenBy?: string|null, soldOut?: boolean } | null | undefined} card
|
||||
* @param {{ myId: string, solo: boolean, busyIdx?: number|null }} o
|
||||
*/
|
||||
export function cardPickable(sp, card, { myId, solo, busyIdx = null }) {
|
||||
if (!sp || !card) return false;
|
||||
const myTurn = solo || sp.turnPid === myId;
|
||||
return myTurn && sp.pickOf.get(myId) == null && !card.takenBy && busyIdx == null;
|
||||
return myTurn && sp.pickOf.get(myId) == null && !card.takenBy && !card.soldOut && busyIdx == null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,7 +127,7 @@ export function armedCard(armed, sp, o) {
|
||||
|
||||
/**
|
||||
* The overlay: keeps the two-tap selection and renders ChoiceView. `onPick(idx)` sends the confirmed card (g.choice).
|
||||
* @param {{ pub:any, sp:any, myId:string, solo:boolean, onPick:(idx:number)=>void, busyIdx?:number|null, total?:number|null }} props
|
||||
* @param {{ pub:any, sp:any, myId:string, solo:boolean, personal?:boolean, onPick:(idx:number)=>void, busyIdx?:number|null, total?:number|null }} props
|
||||
*/
|
||||
export function ChoiceOverlay(props) {
|
||||
const { sp, myId, solo, busyIdx = null, onPick } = props;
|
||||
@@ -154,10 +154,10 @@ export function ChoiceOverlay(props) {
|
||||
|
||||
/**
|
||||
* The overlay's view (pure: no hooks — test/ui renders it as a function).
|
||||
* @param {{ pub:any, sp:any, myId:string, solo:boolean, busyIdx?:number|null, total?:number|null, armed?:number|null,
|
||||
* @param {{ pub:any, sp:any, myId:string, solo:boolean, personal?:boolean, busyIdx?:number|null, total?:number|null, armed?:number|null,
|
||||
* onTap?:(idx:number)=>void, onConfirm?:()=>void, onDisarm?:()=>void }} props
|
||||
*/
|
||||
export function ChoiceView({ pub, sp, myId, solo, busyIdx = null, total = null, armed = null, onTap = () => {}, onConfirm = () => {}, onDisarm = () => {} }) {
|
||||
export function ChoiceView({ pub, sp, myId, solo, personal = false, busyIdx = null, total = null, armed = null, onTap = () => {}, onConfirm = () => {}, onDisarm = () => {} }) {
|
||||
if (!sp) return null;
|
||||
const fam = data.get('choices')?.families?.[sp.family] || null;
|
||||
const rawFam = data.getRaw('choices')?.families?.[sp.family] || null;
|
||||
@@ -166,8 +166,8 @@ export function ChoiceView({ pub, sp, myId, solo, busyIdx = null, total = null,
|
||||
const mine = sp.pickOf.get(myId);
|
||||
const turnName = players.get(sp.turnPid)?.name || t('队友');
|
||||
const special = /_s$/.test(String(sp.family || ''));
|
||||
const order = solo ? [] : sp.order;
|
||||
const timed = !solo && !sp.untimed;
|
||||
const order = personal || solo ? [] : sp.order;
|
||||
const timed = personal ? pub?.deadline > 0 : !solo && !sp.untimed;
|
||||
const armedCardRec = armed != null ? sp.cards.find((c) => c && c.idx === armed) : null;
|
||||
const armedName = armedCardRec ? resolveSpCard(armedCardRec, sp.family).name : null;
|
||||
// a press anywhere but a card or the confirm button drops the selection
|
||||
@@ -177,17 +177,18 @@ export function ChoiceView({ pub, sp, myId, solo, busyIdx = null, total = null,
|
||||
if (t && typeof t.closest === 'function' && t.closest('.spcard, .spov__confirm')) return;
|
||||
onDisarm();
|
||||
};
|
||||
return html`<div class=${cx('spov', armed != null && 'has-armed')} role="dialog" aria-label=${t('机变阶段')} onPointerDown=${onDown}>
|
||||
return html`<div class=${cx('spov', armed != null && 'has-armed')} role="dialog" aria-label=${personal ? t('教鞭选择') : t('机变阶段')} onPointerDown=${onDown}>
|
||||
<div class="spov__veil" aria-hidden="true"></div>
|
||||
<div class="spov__inner">
|
||||
<header class="spov__head">
|
||||
<div class="spov__titles">
|
||||
<${MicroLabel} tone="mint">${t('CONTINGENCY // 机变阶段')}</${MicroLabel}>
|
||||
<${MicroLabel} tone="mint">${personal ? t('教鞭选择') : t('CONTINGENCY // 机变阶段')}</${MicroLabel}>
|
||||
<h2 class=${cx('spov__title', special && 'is-special')}>${sentText(sp.name, rawFam?.name, fam?.name) || fam?.name || t('机变')}<span class="spov__bar">|</span><span class="spov__desc"><${RichText} text=${sentText(sp.desc, rawFam?.desc, fam?.desc) || fam?.desc || t('选择一项')} /></span></h2>
|
||||
<p class="spov__sub">${timed ? t('倒计时结束后仍未选定将自动分配') : t('选择一项(无时间限制)')}${mine == null && myTurn ? t(' · 点击卡牌选中,再次点击确认') : ''}</p>
|
||||
<p class="spov__sub">${timed ? (personal ? t('休整期结束时未选择将自动选定') : t('倒计时结束后仍未选定将自动分配')) : t('选择一项(无时间限制)')}${mine == null && myTurn ? t(' · 点击卡牌选中,再次点击确认') : ''}</p>
|
||||
</div>
|
||||
<div class="spov__turn">
|
||||
${mine != null ? html`<span class="spov__turntxt is-done"><${Icon} name="check" />${t('已完成选择')}</span>`
|
||||
${personal ? html`<span class="spov__turntxt is-mine">${t('从候选中选择一项战术特训')}</span>`
|
||||
: mine != null ? html`<span class="spov__turntxt is-done"><${Icon} name="check" />${t('已完成选择')}</span>`
|
||||
: myTurn ? html`<span class="spov__turntxt is-mine">${t('当前轮到你决策')}</span>`
|
||||
: html`<span class="spov__turntxt">${t('{turnName} 正在决策…', { turnName })}<${Icon} name="hourglass" /></span>`}
|
||||
${armed != null ? html`<${Button} variant="primary" size="lg" icon="check" class="spov__confirm" data-testid="sp-confirm"
|
||||
@@ -217,7 +218,7 @@ export function ChoiceView({ pub, sp, myId, solo, busyIdx = null, total = null,
|
||||
const busy = pickBusy(busyIdx, card, mine);
|
||||
const isArmed = can && armed === card.idx;
|
||||
const takerName = taker ? (card.takenBy === myId ? t('你') : taker.name) : null;
|
||||
return html`<button key=${card.idx} type="button" class=${cx('spcard', `spcard--${r.kind}`, card.takenBy && 'is-taken', card.takenBy === myId && 'is-mine', can && 'is-pickable', isArmed && 'is-armed', busy && 'is-busy')}
|
||||
return html`<button key=${card.idx} type="button" class=${cx('spcard', `spcard--${r.kind}`, (card.takenBy || card.soldOut) && 'is-taken', card.takenBy === myId && 'is-mine', can && 'is-pickable', isArmed && 'is-armed', busy && 'is-busy')}
|
||||
aria-busy=${busy ? 'true' : undefined} aria-pressed=${can ? String(isArmed) : undefined} disabled=${!can} onClick=${() => can && onTap(card.idx)}
|
||||
aria-label=${isArmed ? t('{name},已选中,再次点击确认', { name: r.name }) : takerName ? t('{name},{takerName}已选择', { name: r.name, takerName }) : r.name} title=${`${r.name}\n${richTextPlain(r.desc)}`}>
|
||||
<span class="spcard__glow" aria-hidden="true"></span>
|
||||
@@ -232,6 +233,7 @@ export function ChoiceView({ pub, sp, myId, solo, busyIdx = null, total = null,
|
||||
</span>
|
||||
</span>
|
||||
<${RichText} text=${r.desc} class="spcard__desc" />
|
||||
${card.soldOut && !taker ? html`<span class="spcard__busy" role="status">${t('库存不足')}</span>` : null}
|
||||
${r.tier ? html`<${TierChip} tier=${r.tier} size="md" class="spcard__tier" />` : null}
|
||||
${taker ? html`<span class="spcard__taker" title=${t('{name} 已选择', { name: taker.name })}><${PlayerAvatar} player=${taker} size="sm" /></span>` : null}
|
||||
${isArmed ? html`<span class="spcard__confirm" role="status"><b>${t('确认选择')}</b><small>${t('再次点击')}</small></span>` : null}
|
||||
|
||||
+17
-20
@@ -1,35 +1,32 @@
|
||||
// Clipboard helper shared by the room screen (invite code / link) and 干员调配 (导出 / 导入 payloads).
|
||||
//
|
||||
// Lives here rather than in a screen: `screens/room.js` imports `screens/loadout.js` (the 干员调配 button), so loadout
|
||||
// importing the helper back from room would be a cycle.
|
||||
|
||||
/**
|
||||
* Copy text to the clipboard (async API with a textarea fallback for insecure contexts).
|
||||
* @param {string} text
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
// Shared by invite links, loadouts and settings exports, including LAN / insecure contexts.
|
||||
/** @param {string} text @returns {Promise<boolean>} */
|
||||
export async function copyText(text) {
|
||||
try {
|
||||
if (globalThis.navigator?.clipboard && globalThis.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
} catch { /* use the selected-text fallback */ }
|
||||
let ta, prev;
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
prev = document.activeElement;
|
||||
ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.setAttribute('readonly', '');
|
||||
// 16 px: iOS zooms into smaller focused fields; `readonly` keeps the keyboard away
|
||||
// Keep the temporary selection inside the active focus trap (#433). The 16 px readonly field avoids iOS zoom
|
||||
// and its keyboard; do not disable the dialog's focus protection or copy a selection redirected to another field.
|
||||
ta.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;font-size:16px';
|
||||
document.body.appendChild(ta);
|
||||
const host = prev?.closest?.('[role="dialog"][aria-modal="true"], .guide') || document.body;
|
||||
host.appendChild(ta);
|
||||
ta.focus({ preventScroll: true });
|
||||
ta.select();
|
||||
// iOS Safari ignores select() on a textarea: an explicit range is what it copies (LAN play over http has no
|
||||
// navigator.clipboard, so this path is the one iPhones / iPads take)
|
||||
try { ta.setSelectionRange(0, ta.value.length); } catch { /* ignore */ }
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
return ok;
|
||||
ta.setSelectionRange(0, ta.value.length); // iOS Safari ignores select() alone
|
||||
if (document.activeElement !== ta || ta.selectionStart !== 0 || ta.selectionEnd !== ta.value.length) return false;
|
||||
return !!document.execCommand('copy');
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
ta?.remove();
|
||||
if (prev?.isConnected) prev.focus?.({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ function ProgressList({ list }) {
|
||||
<b>${p.name}</b>
|
||||
${p.done
|
||||
? html`<span class="chud__prog__ok" aria-label=${t('作战结束')}>✓</span>`
|
||||
: html`<span class="num">${p.killed != null && p.total != null ? `${p.killed}/${p.total}` : '•••'}</span>`}
|
||||
: html`<span class="num">${(p.resolved ?? p.killed) != null && p.total != null ? `${p.resolved ?? p.killed}/${p.total}` : '•••'}</span>`}
|
||||
</span>`)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
+37
-11
@@ -55,6 +55,8 @@ export const ICONS = {
|
||||
users: { d: 'M9 4a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7zM2 20a7 6.5 0 0 1 14 0zM16.5 5a3 3 0 1 1 0 6 3 3 0 0 1 0-6zm.9 8.1A6.5 6 0 0 1 22.5 20H18a8.6 8 0 0 0-2.4-6.1 6 6 0 0 1 1.8-.8z' },
|
||||
rook: { d: 'M5 3h3v2h2V3h4v2h2V3h3v5l-2 2v7l2 2v2H5v-2l2-2v-7L5 8z' },
|
||||
signal: { d: 'M2 17h3v4H2zm6-4h3v8H8zm6-4h3v12h-3zm6-4h3v16h-3z' },
|
||||
// 统计 (the stats page's entry): three columns on a baseline — apart from `signal`, the ping bars
|
||||
chart: { d: 'M4 12h4v7H4zm6-6h4v13h-4zm6 3h4v10h-4zM3 20h18v2H3z' },
|
||||
refresh: { d: 'M12 4a8 8 0 0 1 7.4 5H17v2h6V5h-2v2.3A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8zm0 16a8 8 0 0 1-7.4-5H7v-2H1v6h2v-2.3A10 10 0 0 0 22 12h-2a8 8 0 0 1-8 8z' },
|
||||
snow: { d: 'M11 2h2v4.2l2.3-2.3 1.4 1.4-3.7 3.7v2h2l3.7-3.7 1.4 1.4-2.3 2.3H22v2h-4.2l2.3 2.3-1.4 1.4-3.7-3.7h-2v2l3.7 3.7-1.4 1.4-2.3-2.3V22h-2v-4.2l-2.3 2.3-1.4-1.4 3.7-3.7v-2H9l-3.7 3.7-1.4-1.4L6.2 13H2v-2h4.2L3.9 8.7l1.4-1.4L9 11h2V9L7.3 5.3l1.4-1.4L11 6.2z' },
|
||||
chevronRight: { d: 'M8.6 5 7.2 6.4 12.8 12l-5.6 5.6L8.6 19l7-7z' },
|
||||
@@ -74,6 +76,8 @@ export const ICONS = {
|
||||
wifiOff: { d: 'M2 17h3v4H2zm6-4h3v8H8zm6-4h3v12h-3zm6-4h3v16h-3zM2.4 1 23 21.6 21.6 23 1 2.4z' },
|
||||
expand: { d: 'M3 3h7v2H5v5H3zm11 0h7v7h-2V5h-5zM3 14h2v5h5v2H3zm16 0h2v7h-7v-2h5z' },
|
||||
collapse: { d: 'M8 3h2v7H3V8h5zm6 0h2v5h5v2h-7zM3 14h7v7H8v-5H3zm11 0h7v2h-5v5h-2z' },
|
||||
// 添加到桌面 (add to home screen): a house outline with a + inside
|
||||
homePlus: { d: 'M12 2 22 10.5V21H2V10.5zm0 2.6-8 6.8V19h16v-7.6zM11 10h2v2.5h2.5v2H13V17h-2v-2.5H8.5v-2H11z', eo: true },
|
||||
rotate: { d: 'M7 2h8a2 2 0 0 1 2 2v7h-2V4H7v16h4v2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2zm8 12h5a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2zm0 2v4h5v-4z', eo: true },
|
||||
book: { d: 'M2 4h7.5A3.5 3.5 0 0 1 12 5.1 3.5 3.5 0 0 1 14.5 4H22v16h-7.5a1.5 1.5 0 0 0-1.5 1.5h-2A1.5 1.5 0 0 0 9.5 20H2zm2 2v12h5.5c.5 0 1 .1 1.5.3V7.5A1.5 1.5 0 0 0 9.5 6zm10.5 0A1.5 1.5 0 0 0 13 7.5v10.8c.5-.2 1-.3 1.5-.3H20V6z', eo: true },
|
||||
// 观战 (spectator seats; the same eye as gameComponents.js GIcon 'eye')
|
||||
@@ -386,7 +390,7 @@ export function Countdown({ deadline, seconds, total, warnAt = 10, label = 'COUN
|
||||
|
||||
// ---- Modal & dialogs ---------------------------------------------------------------------------
|
||||
|
||||
const modalStack = []; // open modals, topmost last: only the topmost reacts to Escape
|
||||
const modalStack = []; // open modals, topmost last: only the topmost handles keyboard focus / Escape
|
||||
|
||||
/**
|
||||
* Modal dialog (declarative). Esc / backdrop click call onClose.
|
||||
@@ -397,24 +401,46 @@ export function Modal({ open, title, micro, tone = 'mint', onClose, actions, wid
|
||||
const boxRef = useRef(null);
|
||||
const closeRef = useRef(onClose);
|
||||
closeRef.current = onClose;
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return undefined;
|
||||
const token = {};
|
||||
modalStack.push(token);
|
||||
const prevFocus = typeof document !== 'undefined' ? document.activeElement : null;
|
||||
const box = boxRef.current;
|
||||
// The independent guide can open above SettingsModal (its z-index is higher than --z-modal).
|
||||
const topmost = () => modalStack[modalStack.length - 1] === token && !document.querySelector('.guide');
|
||||
const available = (el) => !el.matches(':disabled') && !el.closest('[inert]') && el.getClientRects().length > 0
|
||||
&& getComputedStyle(el).visibility !== 'hidden';
|
||||
const tabbable = () => [...box.querySelectorAll('button, [href], input, select, textarea, [tabindex], summary')]
|
||||
.filter((el) => el.tabIndex >= 0 && available(el));
|
||||
const focusFirst = () => (tabbable()[0] || box).focus();
|
||||
const onKey = (e) => {
|
||||
if (e.key !== 'Escape' || modalStack[modalStack.length - 1] !== token || !closeRef.current) return;
|
||||
e.stopPropagation();
|
||||
closeRef.current();
|
||||
if (!topmost()) return;
|
||||
if (e.key === 'Escape' && closeRef.current) {
|
||||
e.stopPropagation();
|
||||
closeRef.current();
|
||||
} else if (e.key === 'Tab') {
|
||||
const els = tabbable();
|
||||
const first = els[0] || box, last = els[els.length - 1] || box;
|
||||
if (!els.includes(document.activeElement) || document.activeElement === (e.shiftKey ? first : last)) {
|
||||
e.preventDefault();
|
||||
(e.shiftKey ? last : first).focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
const onFocus = (e) => {
|
||||
if (topmost() && !box.contains(e.target)) focusFirst();
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
const t = setTimeout(() => {
|
||||
const el = boxRef.current?.querySelector('[data-autofocus]') || boxRef.current?.querySelector('button, input');
|
||||
el?.focus?.();
|
||||
}, 30);
|
||||
window.addEventListener('focusin', onFocus);
|
||||
const autofocus = box.querySelector('[data-autofocus]');
|
||||
if (topmost()) {
|
||||
if (autofocus && available(autofocus)) autofocus.focus();
|
||||
else focusFirst();
|
||||
}
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
clearTimeout(t);
|
||||
window.removeEventListener('focusin', onFocus);
|
||||
const i = modalStack.indexOf(token);
|
||||
if (i >= 0) modalStack.splice(i, 1);
|
||||
prevFocus?.focus?.();
|
||||
@@ -423,7 +449,7 @@ export function Modal({ open, title, micro, tone = 'mint', onClose, actions, wid
|
||||
if (!open) return null;
|
||||
return html`<div class="modal" role="presentation"
|
||||
onMouseDown=${(e) => { if (closeOnBackdrop && e.target === e.currentTarget && onClose) onClose(); }}>
|
||||
<div ref=${boxRef} class=${cx('modal__box', 'brackets', `modal__box--${tone}`, cls)} role="dialog" aria-modal="true"
|
||||
<div ref=${boxRef} class=${cx('modal__box', 'brackets', `modal__box--${tone}`, cls)} role="dialog" aria-modal="true" tabindex="-1"
|
||||
style=${width ? `width:${width}` : undefined}>
|
||||
<div class="modal__stripe" aria-hidden="true"></div>
|
||||
${title || micro ? html`<header class="modal__head">
|
||||
|
||||
+77
-32
@@ -37,7 +37,7 @@
|
||||
import { useEffect } from '../../vendor/hooks.module.js';
|
||||
import { html, Icon, TierChip, MicroLabel, Button, confirmDialog, useTicker } from './components.js';
|
||||
import { Img, RichText, UnitThumb, BondGlyph, GIcon, diyToken } from './gameComponents.js';
|
||||
import { attackInterval, rangeGridBox, fmtNum, tileKey, chessLoadout, nextThreshold, bondTier, briefingBondTip, pieceBondIds, grantedBonds, morphPairings, ownStandIn, standInOf, standInLoadout, standInLabel, standInTip, standInForText, ownDiyRecord, ownDiyPick, diyRecordFor, pickGetter } from './gameLogic.js';
|
||||
import { attackInterval, rangeGridBox, fmtNum, tileKey, chessLoadout, nextThreshold, bondTier, briefingBondTip, pieceBondIds, grantedBonds, morphPairings, ownStandIn, standInOf, standInLoadout, standInLabel, standInTip, standInForText, ownDiyRecord, ownDiyPick, diyRecordFor, pickGetter, unitPick, unitCultivation } from './gameLogic.js';
|
||||
import { chessPortraitUrl, skillIconUrl, skillRecordIconUrl, profIconUrl, subProfIconUrl, itemIconUrl, enemyIconUrl, tokenAvatarUrl, factionIconUrl, uiUrl, moduleTypeIconUrl } from './assetUrls.js';
|
||||
import { abilityRows } from './abilityLines.js';
|
||||
import { data } from '../data.js';
|
||||
@@ -46,6 +46,7 @@ import { SKILL_SUMMON_START_DEPLOY } from '../../../shared/constants.js';
|
||||
import { moduleBadge, fullTraitText } from './loadoutModel.js';
|
||||
import { t, tc, N_ } from '../../../shared/i18n.js';
|
||||
import { audio } from '../audio.js';
|
||||
import { tokenVariantFor } from './gameLogic/loadout.js';
|
||||
|
||||
const cx = (...p) => p.flat().filter(Boolean).join(' ');
|
||||
|
||||
@@ -315,7 +316,7 @@ export function garrisonTypeIconKey(garrison) {
|
||||
}
|
||||
|
||||
/** The operator's own effect (特质, garrisons.json): trigger chip + description, compact. */
|
||||
function GarrisonBlock({ garrison, m }) {
|
||||
export function GarrisonBlock({ garrison, m }) {
|
||||
return html`<section class="dgarrison" aria-label=${t('特质')} data-garrison=${garrison.garrisonId || ''}>
|
||||
<div class="dgarrison__head">
|
||||
<span class="dgarrison__k">${t('特质')}</span>
|
||||
@@ -383,7 +384,7 @@ function skillTextNote(sk) {
|
||||
return note ? html`<p class="dhint dhint--rule" data-skill-note=${sk.skillId}><${Icon} name="info" />${t(note)}</p>` : null;
|
||||
}
|
||||
|
||||
export function ChessDetail({ chess, piece, unit, snapHp, editable, onSell, bonds, offBonds = null, loadout, onBond, live = null, hint = null, unitItems = null, standIn = null, diy = null }) {
|
||||
export function ChessDetail({ chess, piece, unit, snapHp, editable, onSell, bonds, offBonds = null, loadout, onBond, live = null, hint = null, unitItems = null, standIn = null, diy = null, cultOpts = null }) {
|
||||
const m = data.get('assets');
|
||||
const hp = hpOf(live, snapHp);
|
||||
// 0.2.0 自选编队: `chess` is then the composed 自选 record (the operator, the slot's tier / price); its skill and module are
|
||||
@@ -395,7 +396,9 @@ export function ChessDetail({ chess, piece, unit, snapHp, editable, onSell, bond
|
||||
// still apply (the owner's recall of the official mode, 2026-10-06)
|
||||
const si = standIn && standIn.standInFor ? standIn : null;
|
||||
const body = si || chess;
|
||||
const lo = si ? standInLoadout(si, getChess, data.get('backups')) : chessLoadout(chess, loadout, getChess);
|
||||
// 0.2.2: at the operator's 潜能 / 练度 — the player's settings (`cultOpts.ops`) or a teammate's unit's own
|
||||
// (`cultOpts.cultivation`); a stand-in has neither
|
||||
const lo = si ? standInLoadout(si, getChess, data.get('backups')) : chessLoadout(chess, loadout, getChess, { ...(cultOpts || {}), effects: data.get('effects') });
|
||||
const c = chess;
|
||||
// stats / talents the unit fights with: the chosen module's (or none — statsBase) for an elite (DESIGN §16)
|
||||
const fr = lo?.record || body;
|
||||
@@ -580,21 +583,6 @@ export function summonDeployHint(token, startDeploy = SKILL_SUMMON_START_DEPLOY)
|
||||
: t('所属干员发动技能时才在摆放的位置出现(未摆放则不会出现)');
|
||||
}
|
||||
|
||||
/**
|
||||
* The token variant of the summon's owner (tokens.json `variants`, keyed by owner chess id): a golden owner's `_b`
|
||||
* entry (精锐 赫默's drone ATK 114, 精锐 巫恋's doll −30%), else its normal `_a` entry, else the first one.
|
||||
* @param {any} token tokens.json record
|
||||
* @param {string|null} ownerId the owner's chess id (null: unknown, e.g. a teammate's summon)
|
||||
*/
|
||||
export function tokenVariantFor(token, ownerId = null) {
|
||||
const vs = token?.variants || {};
|
||||
if (typeof ownerId === 'string') {
|
||||
const v = vs[ownerId] || vs[ownerId.replace(/_b$/, '_a')];
|
||||
if (v) return v;
|
||||
}
|
||||
return Object.values(vs)[0] || null;
|
||||
}
|
||||
|
||||
/** Chess id of the operator owning a token piece (`ownerUid`), from the player's own pieces (indexPieces). */
|
||||
function tokenOwnerId(piece, pieces) {
|
||||
if (!piece || piece.kind !== 'token' || !Number.isInteger(piece.ownerUid)) return null;
|
||||
@@ -711,9 +699,36 @@ function TerrainDetail({ terrain }) {
|
||||
${Array.isArray(terrain.facts) && terrain.facts.length ? html`<${Section} title=${t('这一格')}><p class="dtext">${terrain.facts.join(' · ')}</p><//>` : null}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A stage device's tip (GitHub #228, PR #229: 阻隔工事 / “双眼皮” / 射击台 / 源石流发生装置 — the terrain tip's sibling). Opened
|
||||
* by a tap on the device itself: the game screen resolves it with `gameLogic.deviceInfo` (prep) or `deviceTipAt` (a battle)
|
||||
* from the stage the board on screen is built from, so the lines carry that stage's own numbers. In a battle the
|
||||
* crate / turret is a device unit: its live HP (`live` from the battle's own sim, else `snapHp` — the screen reads the latest
|
||||
* snapshot tuple through `unitId`) draws a HP bar like a unit card's.
|
||||
* @param {{ name:string, tag:string, lines:string[], facts?:string[], stats?:{k:string,v:any}[] }} device
|
||||
* @param {{ hp:number, max:number }|null} snapHp
|
||||
*/
|
||||
function DeviceDetail({ device, snapHp = null, live = null }) {
|
||||
const hp = hpOf(live, snapHp);
|
||||
return html`
|
||||
<div class="dhead">
|
||||
<div class="dhead__icon"><${Icon} name="info" /></div>
|
||||
<div class="dhead__info">
|
||||
<div class="dhead__chips"><span class="dtag-kind">${device.tag}</span></div>
|
||||
<h3 class="dhead__name">${device.name}</h3>
|
||||
${hp ? html`<div class="dhp"><i style=${`width:${Math.max(0, Math.min(100, (hp.hp / Math.max(1, hp.max)) * 100))}%`}></i><span class="num">${fmtNum(hp.hp)} / ${fmtNum(hp.max)}</span></div>` : null}
|
||||
</div>
|
||||
</div>
|
||||
<${Section} title=${t('装置机制')} micro="DEVICE">
|
||||
${device.lines.map((line, i) => html`<p class="dtext" key=${i}>${line}</p>`)}
|
||||
<//>
|
||||
${Array.isArray(device.stats) && device.stats.length ? html`<div class="dstats">${device.stats.map((x) => html`<${Stat} key=${x.k} k=${x.k} v=${x.v} />`)}</div>` : null}
|
||||
${Array.isArray(device.facts) && device.facts.length ? html`<${Section} title=${t('这一格')}><p class="dtext">${device.facts.join(' · ')}</p><//>` : null}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve what a detail target shows.
|
||||
* @param {{ kind:'piece'|'chess'|'item'|'enemy'|'unit'|'token'|'terrain', id?:string, uid?:number, unit?:any, count?:number }} target
|
||||
* @param {{ kind:'piece'|'chess'|'item'|'enemy'|'unit'|'token'|'terrain'|'device', id?:string, uid?:number, unit?:any, count?:number }} target
|
||||
* @param {Map<number, any>} pieces indexPieces(priv)
|
||||
* @param {{ priv?: any, backups?: any }} [opts] 0.2.0 补位: the player's own pieces and cards of a chess in
|
||||
* m.private.standIns — a unit carrying `standInFor`, and a teammate's bond popup row that says it (`target.standInFor`)
|
||||
@@ -726,6 +741,12 @@ export function resolveDetail(target, pieces, { priv = null, backups = data.get(
|
||||
if (!target) return null;
|
||||
// a special terrain tile (issue #184): the screen resolved the stage's own numbers already (gameLogic.terrainInfo)
|
||||
if (target.kind === 'terrain') return target.terrain && typeof target.terrain === 'object' ? { type: 'terrain', terrain: target.terrain } : null;
|
||||
// a stage device (#228): the screen resolved the device's stage entry (gameLogic.deviceInfo / deviceTipAt); in a battle
|
||||
// `unitId` is the crate / turret unit whose snapshot tuple gives the live HP
|
||||
if (target.kind === 'device') {
|
||||
const device = target.device && typeof target.device === 'object' ? target.device : null;
|
||||
return device ? { type: 'device', device, ...(Number.isInteger(device.unitId) ? { unitId: device.unitId } : {}) } : null;
|
||||
}
|
||||
const ownSi = (c) => ownStandIn(c, priv, backups);
|
||||
const dd = { chess: data.get('chess'), backups };
|
||||
/** the own card of chess `c`: its 自选 record and pick when the player filled that DIY slot */
|
||||
@@ -755,9 +776,14 @@ export function resolveDetail(target, pieces, { priv = null, backups = data.get(
|
||||
// (a teammate's 自选 row hands its unit's pick on, `target.diy`: their operator, not the empty 甄选干员 slot — 0.2.1)
|
||||
const mate = foreign && c && target.diy && typeof target.diy === 'object' ? diyRecordFor(c, target.diy, dd) : null;
|
||||
const d = mate ? { chess: mate, diy: target.diy } : foreign ? null : ownDiy(c);
|
||||
if (d) return { type: 'chess', chess: d.chess, hint: target.hint || null, standIn: null, diy: d.diy, ...(items.length ? { unitItems: items } : {}) };
|
||||
// `tap`: which card tap opened it (game.js numbers every shop / reward card it opens) — selectVoiceKey
|
||||
const tap = target.tap != null ? { tap: target.tap } : null;
|
||||
// 0.2.2: a teammate's member card reads its unit's 潜能 / 练度 when the row hands it on (`target.cultivation`), else
|
||||
// the defaults (never the viewer's own settings)
|
||||
const cv = foreign ? (target.cultivation !== undefined ? { cultivation: target.cultivation } : { ops: null }) : null;
|
||||
if (d) return { type: 'chess', chess: d.chess, hint: target.hint || null, standIn: null, diy: d.diy, ...(items.length ? { unitItems: items } : {}), ...(cv ? { cultOpts: cv } : {}), ...tap };
|
||||
const si = !c ? null : foreign ? (typeof target.standInFor === 'string' && target.standInFor ? standInOf(c, backups) : null) : ownSi(c);
|
||||
return c ? { type: 'chess', chess: c, hint: target.hint || null, standIn: si, ...(items.length ? { unitItems: items } : {}) } : null;
|
||||
return c ? { type: 'chess', chess: c, hint: target.hint || null, standIn: si, ...(items.length ? { unitItems: items } : {}), ...(cv ? { cultOpts: cv } : {}), ...tap } : null;
|
||||
}
|
||||
if (target.kind === 'item') { const it = data.lookup('items', target.id); return it ? { type: 'item', item: it } : null; }
|
||||
if (target.kind === 'enemy') { const en = data.lookup('enemies', target.id); return en ? { type: 'enemy', enemy: en, count: target.count } : null; }
|
||||
@@ -776,10 +802,13 @@ export function resolveDetail(target, pieces, { priv = null, backups = data.get(
|
||||
else if (c && own?.piece) si = ownSi(c);
|
||||
// 0.2.0 自选编队: a unit says itself which operator fills its DIY slot (UnitInfo diy); an own piece's unit follows
|
||||
// m.private.diy like the piece
|
||||
const pick = c && u.diy && typeof u.diy === 'object' ? u.diy : own?.piece ? ownDiyPick(priv, c) : null;
|
||||
const pick = c && u.diy && typeof u.diy === 'object' ? unitPick(u) : own?.piece ? ownDiyPick(priv, c) : null;
|
||||
const dr = pick ? diyRecordFor(c, pick, dd) : null;
|
||||
if (dr) return { type: 'chess', chess: dr, piece: own?.piece || null, unitId: u.id, unitItems: Array.isArray(u.items) ? u.items : null, standIn: null, diy: pick };
|
||||
if (c) return { type: 'chess', chess: c, piece: own?.piece || null, unitId: u.id, unitItems: Array.isArray(u.items) ? u.items : null, standIn: si };
|
||||
// 0.2.2: another player's unit says its 潜能 / 练度 itself (UnitInfo potential / cultivate); an own piece's unit follows
|
||||
// m.private.ops (the panel's `cultOpts`)
|
||||
const cv = own?.piece ? null : { cultOpts: { cultivation: unitCultivation(u) } };
|
||||
if (dr) return { type: 'chess', chess: dr, piece: own?.piece || null, unitId: u.id, unitItems: Array.isArray(u.items) ? u.items : null, standIn: null, diy: pick, ...cv };
|
||||
if (c) return { type: 'chess', chess: c, piece: own?.piece || null, unitId: u.id, unitItems: Array.isArray(u.items) ? u.items : null, standIn: si, ...cv };
|
||||
const t = data.lookup('tokens', u.defId) || diyToken(u.defId);
|
||||
if (t) return { type: 'token', token: t, unitId: u.id, ownerId: tokenOwnerId(own?.piece, pieces) };
|
||||
const en = data.lookup('enemies', u.defId);
|
||||
@@ -788,6 +817,18 @@ export function resolveDetail(target, pieces, { priv = null, backups = data.get(
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 选中干员 key of a resolved detail (null: nothing to say). The panel says the line once per opened operator and stays
|
||||
* mounted while its target changes, so the key carries what identifies the opening: the chess record, the piece / battle
|
||||
* unit, and the card tap (`tap`, game.js) — two shop / reward cards of one operator (the pool deals duplicates) carry the
|
||||
* same chess id and no piece, so without it the second card's tap said nothing, nor replaced the first one's line.
|
||||
* @param {any} detail resolveDetail's result
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function selectVoiceKey(detail) {
|
||||
return detail?.type === 'chess' ? `${detail.chess?.chessId || ''}:${detail.unitId ?? detail.piece?.uid ?? ''}:${detail.tap ?? ''}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel.
|
||||
* @param {{ detail:any, editable:boolean, snapHp?:{hp:number,max:number}|null, onClose:Function, onSell:(piece:any)=>void, onDestroy:(piece:any)=>void,
|
||||
@@ -795,18 +836,21 @@ export function resolveDetail(target, pieces, { priv = null, backups = data.get(
|
||||
* bonds: the owner's m.private.bonds (counts / tiers of the bond chips); offBonds: the bonds this mode never activates
|
||||
* (gameLogic modeOffBonds — their chips and the 变形同构体 pairing lines read 本局禁用); loadout: m.private.loadout (DESIGN §16) for
|
||||
* the player's own operators and shop cards; a teammate's unit gets its owner's choice (gameLogic unitLoadout); null
|
||||
* = the defaults
|
||||
* = the defaults; ops: m.private.ops (0.2.2 潜能 / 练度 of the player's own operators and cards — a unit the detail
|
||||
* resolved as another player's carries its own, `detail.cultOpts`)
|
||||
* live: the unit's live stats (unitStatsEntry + src 'battle' | 'prep') — an object, or a getter the panel re-reads 4×
|
||||
* a second (the battle's own sim, battle/runner.js unitStats); null ⇒ the record's numbers
|
||||
* voice: whether the panel may speak — 选中干员 (audio.voice 'select') plays only while a battle runs (user request:
|
||||
* 整备期不播干员语音), so the game screen passes its combat flag
|
||||
* voice: whether the panel may speak — 选中干员 (audio.voice 'select') when it opens on an operator the player tapped:
|
||||
* a piece on the field or in the hand, a shop / reward card, a bond member. The game screen passes true in every phase
|
||||
* (the owner's request of 2026-10-08 「添加一下干员点击上去的语气一样的语音」 lifted 2026-10-03's 「整备阶段不需要干员语音」
|
||||
* for this line only; [ASSUMED] the official prep tap says 选中干员 like the battle's FOCUS_CHAR)
|
||||
*/
|
||||
export function DetailPanel({ detail, editable, snapHp, onClose, onSell, onDestroy, bonds = [], offBonds = null, loadout = null, onBond = null, side = 'left', shopOpen = false, live = null, voice = false }) {
|
||||
export function DetailPanel({ detail, editable, snapHp, onClose, onSell, onDestroy, bonds = [], offBonds = null, loadout = null, ops = null, onBond = null, side = 'left', shopOpen = false, live = null, voice = false }) {
|
||||
const getter = typeof live === 'function' ? live : null;
|
||||
useTicker(detail && getter ? 250 : 0);
|
||||
// 选中干员 voice (audio.voice 'select'): once per opened operator — the panel stays mounted while the target changes,
|
||||
// so the key carries what identifies it (its chess record and its piece / battle unit id)
|
||||
const selectKey = voice && detail?.type === 'chess' ? `${detail.chess?.chessId || ''}:${detail.unitId ?? detail.piece?.uid ?? ''}` : null;
|
||||
// so the key carries what identifies it (its chess record, its piece / battle unit id, the card tap: selectVoiceKey)
|
||||
const selectKey = voice && detail?.type === 'chess' ? selectVoiceKey(detail) : null;
|
||||
// 0.2.0 补位: a chess fielded as its stand-in is spoken for by the stand-in (the operator on the field, whose model, name
|
||||
// and battle lines the card and audio.js show), never by the operator it replaces; a 自选 record is already the pick's
|
||||
const selectChar = voice && detail?.type === 'chess' ? detail.standIn?.charId || detail.chess?.charId || null : null;
|
||||
@@ -834,11 +878,12 @@ export function DetailPanel({ detail, editable, snapHp, onClose, onSell, onDestr
|
||||
<div class="dpanel__scroll">
|
||||
${detail.type === 'chess' ? html`<${ChessDetail} chess=${detail.chess} piece=${detail.piece} snapHp=${snapHp} editable=${editable} onSell=${sellIt}
|
||||
bonds=${bonds} offBonds=${offBonds} loadout=${loadout} onBond=${onBond} live=${liveNow} hint=${detail.hint || null} unitItems=${detail.unitItems || null}
|
||||
standIn=${detail.standIn || null} diy=${detail.diy || null} />` : null}
|
||||
standIn=${detail.standIn || null} diy=${detail.diy || null} cultOpts=${detail.cultOpts || { ops }} />` : null}
|
||||
${detail.type === 'item' ? html`<${ItemDetail} item=${detail.item} piece=${detail.piece} editable=${editable} onDestroy=${destroyIt} offBonds=${offBonds} />` : null}
|
||||
${detail.type === 'enemy' ? html`<${EnemyDetail} enemy=${detail.enemy} snapHp=${snapHp} count=${detail.count} live=${liveNow} />` : null}
|
||||
${detail.type === 'token' ? html`<${TokenDetail} token=${detail.token} piece=${detail.piece} ownerId=${detail.ownerId ?? null} snapHp=${snapHp} live=${liveNow} />` : null}
|
||||
${detail.type === 'terrain' ? html`<${TerrainDetail} terrain=${detail.terrain} />` : null}
|
||||
${detail.type === 'device' ? html`<${DeviceDetail} device=${detail.device} snapHp=${snapHp} live=${liveNow} />` : null}
|
||||
</div>
|
||||
</aside>`;
|
||||
}
|
||||
|
||||
+27
-1
@@ -20,7 +20,8 @@
|
||||
// CSS counterpart: public/css/devices.css (safe-area insets, touch-action, overscroll, tap-target expansion).
|
||||
|
||||
import { useEffect, useState } from '../../vendor/hooks.module.js';
|
||||
import { html, Icon } from './components.js';
|
||||
import { pwaInstall } from '../pwa.js';
|
||||
import { html, Icon, Button } from './components.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
|
||||
/** A touch held this long without moving opens the detail (contextmenu) on DOM controls. */
|
||||
@@ -162,6 +163,24 @@ export function FullscreenButton({ class: cls = '' }) {
|
||||
</button>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a browser-issued install offer shows a button; installed and unsupported environments stay quiet.
|
||||
* `square`: the glyph alone (the lobby's top bar, beside ⚙ / 📖), the name stays title / aria-label.
|
||||
*/
|
||||
export function PwaInstallButton({ class: cls = '', size = 'sm', square = false }) {
|
||||
const [available, setAvailable] = useState(pwaInstall.available);
|
||||
useEffect(() => pwaInstall.subscribe(setAvailable), []);
|
||||
if (!available) return null;
|
||||
return html`<${Button} variant="secondary" size=${size} icon="homePlus" square=${square} class=${cls}
|
||||
title=${t('添加到桌面')} aria-label=${t('添加到桌面')}
|
||||
data-testid="pwa-install" onClick=${() => pwaInstall.request()}>${square ? null : t('添加到桌面')}<//>`;
|
||||
}
|
||||
|
||||
export function updateRotateHintPwaI18n(doc = globalThis.document) {
|
||||
const btn = doc?.getElementById?.('rotate-hint-pwa');
|
||||
if (btn) btn.textContent = t('添加到桌面');
|
||||
}
|
||||
|
||||
// ---- boot-time installation ----------------------------------------------------------------------------------------
|
||||
|
||||
let installed = null;
|
||||
@@ -253,6 +272,13 @@ export function installDeviceSupport(win = globalThis) {
|
||||
if (lp.swallowUntil && Date.now() < lp.swallowUntil) { lp.swallowUntil = 0; e.preventDefault(); e.stopPropagation(); }
|
||||
}, { capture: true });
|
||||
|
||||
const pwaBtn = doc?.getElementById?.('rotate-hint-pwa');
|
||||
if (pwaBtn) {
|
||||
updateRotateHintPwaI18n(doc);
|
||||
offs.push(pwaInstall.subscribe((available) => { pwaBtn.hidden = !available; }));
|
||||
on(pwaBtn, 'click', () => { pwaInstall.request(); });
|
||||
}
|
||||
|
||||
installed = () => { for (const off of offs.splice(0)) { try { off(); } catch { /* ignore */ } } clearTimeout(rotTimer); installed = null; };
|
||||
return installed;
|
||||
}
|
||||
@@ -147,9 +147,9 @@ export function pickOptions(slotId, picks, data, kitted) {
|
||||
* The record a slot shows for a pick (shared/diy.js diyRecord: the operator at the slot's normal form, or the elite).
|
||||
* @param {string} slotId @param {any} pick @param {any} data @param {{ elite?: boolean }} [opts]
|
||||
*/
|
||||
export function slotRecord(slotId, pick, data, { elite = false } = {}) {
|
||||
export function slotRecord(slotId, pick, data, { elite = false, potential = null } = {}) {
|
||||
if (!isObj(pick)) return null;
|
||||
try { return diyRecord(slotId, pick, { elite, data }); } catch { return null; }
|
||||
try { return diyRecord(slotId, pick, { elite, data, potential }); } catch { return null; }
|
||||
}
|
||||
|
||||
/** Set (or with null, clear) one slot. Returns a new roster (the input is not changed). */
|
||||
|
||||
@@ -111,7 +111,8 @@ export function EquipReplaceDialog({ request, getItem = () => null, busy = false
|
||||
].join('');
|
||||
const confirmIcon = localAsset('ui/battle', 'equip_replace_comfirm_icon');
|
||||
const swapIcon = localAsset('ui/battle', 'equip_replace_replace_icon');
|
||||
return html`<div class="eqr-host" style=${style} onKeyDown=${(e) => { if (e.key === 'Enter' && chosen && !busy) { e.preventDefault(); onConfirm(chosen.uid); } }}>
|
||||
// A focused button owns Enter through its native click, including Cancel and the item options.
|
||||
return html`<div class="eqr-host" style=${style} onKeyDown=${(e) => { if (e.key === 'Enter' && e.target?.tagName !== 'BUTTON' && chosen && !busy) { e.preventDefault(); onConfirm(chosen.uid); } }}>
|
||||
<${Modal} open=${true} tone="red" class="eqr" width="min(7.6rem, 96vw)" micro="EQUIPMENT · REPLACE" title=${t('替换装备')} onClose=${onCancel}
|
||||
actions=${html`
|
||||
<${Button} variant="secondary" icon="close" class="eqr__cancel" onClick=${onCancel}>${t('取消')}<//>
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
// LEFT, facing.js boardDir): the chevrons follow the finger, the range / model / intent use the board direction;
|
||||
// * release outside the centre commits (g.move {uid, to, dir} / g.art {…, dir}); release inside the centre, a tap
|
||||
// on ✕, a press outside the diamond or Esc cancels (the piece returns to where it came from). Arrow keys preview a
|
||||
// direction and Enter commits it (keyboard alternative). Mouse, pen and touch all use pointer events.
|
||||
// direction and Enter commits it (keyboard alternative) — Enter on a focused ✕ cancels, on any other focused
|
||||
// button does nothing while the wheel is open (GitHub #394). Mouse, pen and touch all use pointer events.
|
||||
//
|
||||
// View bridge: the field view (render/app.js or the DOM fallback) may implement `tileScreen(row, col)`,
|
||||
// `holdPiece(uid, tile|null)` and `setPieceDir(uid, dir)` (render/app.js does, DESIGN §9); a view without them falls
|
||||
@@ -25,7 +26,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from '../../vendor/hooks
|
||||
import { html } from './components.js';
|
||||
import { LocalSprite } from './gameComponents.js';
|
||||
import { DIRS, DIR_LABEL, DEAD_ZONE_TILES, dirFromDelta, dirFromKey, rangeTiles, normDir, boardDir, viewMirrored } from './facing.js';
|
||||
import { facingSwallows } from './gameLogic.js';
|
||||
import { facingSwallows, facingEnter } from './gameLogic.js';
|
||||
import { settingsStore } from './settings.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
|
||||
@@ -236,24 +237,36 @@ export function FacingWheel({ view, row, col, grid, name = '', onPreview, onComm
|
||||
};
|
||||
const onPointerCancel = () => { setDrag(null); setDir(null); };
|
||||
|
||||
// keyboard: arrows preview, Enter commits, Esc cancels (capture: the game's own shortcuts must not see them)
|
||||
// keyboard: arrows preview, Enter commits, Esc cancels (capture: the game's own shortcuts must not see them). Enter
|
||||
// follows the focus (gameLogic facingEnter, GitHub #394): on ✕ it cancels, on any other button (Tab reaches the HUD
|
||||
// behind the wheel) it does nothing, elsewhere it commits the previewed direction. The wheel takes the focus when it
|
||||
// opens, so a button focused before the drop (a click leaves it focused) cannot swallow the confirming Enter; Tab then
|
||||
// reaches ✕ first. Nothing gives the focus back when it closes (a restored 准备 would take the next Enter / Space).
|
||||
const rootRef = useRef(null);
|
||||
useEffect(() => {
|
||||
const onKey = (e) => {
|
||||
const L = live.current;
|
||||
if (e.key === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); L.onCancel(); return; }
|
||||
const k = dirFromKey(e.key);
|
||||
if (k) { e.preventDefault(); e.stopImmediatePropagation(); setDir(k); return; }
|
||||
if (e.key === 'Enter' && L.dir) { e.preventDefault(); e.stopImmediatePropagation(); L.onCommit(L.bdir); return; }
|
||||
const enter = facingEnter(e, !!L.dir);
|
||||
if (enter) {
|
||||
e.preventDefault(); e.stopImmediatePropagation();
|
||||
if (enter === 'cancel') L.onCancel();
|
||||
else if (enter === 'commit') L.onCommit(L.bdir);
|
||||
return;
|
||||
}
|
||||
// no ready / shop while choosing: Space and every key of the player's map (设置 → 快捷键)
|
||||
if (facingSwallows(e, settingsStore.get().keys)) { e.preventDefault(); e.stopImmediatePropagation(); }
|
||||
};
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
try { rootRef.current?.focus({ preventScroll: true }); } catch { /* no focus: Enter still follows whatever has it */ }
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, []);
|
||||
|
||||
const outside = !!drag && !!dir;
|
||||
const box = half * 2;
|
||||
return html`<div class=${cx('fwheel', drag && 'is-pressed', dir && `is-${dir.toLowerCase()}`)} role="dialog" aria-label=${name ? t('选择「{name}」的朝向', { name }) : t('选择朝向')}
|
||||
return html`<div ref=${rootRef} tabIndex="-1" class=${cx('fwheel', drag && 'is-pressed', dir && `is-${dir.toLowerCase()}`)} role="dialog" aria-label=${name ? t('选择「{name}」的朝向', { name }) : t('选择朝向')}
|
||||
onPointerDown=${onDown} onPointerMove=${onMove} onPointerUp=${onUp} onPointerCancel=${onPointerCancel}
|
||||
onContextMenu=${(e) => { e.preventDefault(); onCancel(); }}>
|
||||
${g ? html`<${Stripes} tiles=${tiles} view=${view} row=${row} col=${col} />` : null}
|
||||
|
||||
@@ -332,6 +332,16 @@ export function createFallbackView(host, opts = {}) {
|
||||
const now = performance.now();
|
||||
if (st.mode === 'prep' && st.priv) {
|
||||
const heldPos = (p) => { const t = st.held.get(p.uid); return t ? tilePos(L, t.row, t.col) : null; };
|
||||
for (const u of Array.isArray(st.priv.prepMapChars) ? st.priv.prepMapChars : []) {
|
||||
if (!u || !Number.isInteger(u.x) || !Number.isInteger(u.y) || typeof u.defId !== 'string') continue;
|
||||
const pos = tilePos(L, u.y, u.x);
|
||||
const src = tokenAvatarUrl(m(), u.defId);
|
||||
pieces.push(html`<div key=${`map:${u.uid}`} class="ff-piece ff-piece--token ff-piece--map-char"
|
||||
style=${`transform:translate(${pos.x}px,${pos.y}px);width:${L.tile}px;height:${L.tile}px;pointer-events:none`}
|
||||
title=${u.name || u.defId}>
|
||||
<div class="ff-piece__art">${src ? html`<img src=${src} alt="" draggable=${false} />` : html`<span>${[...(u.name || '?')][0]}</span>`}</div>
|
||||
</div>`);
|
||||
}
|
||||
for (const p of Array.isArray(st.priv.board) ? st.priv.board : []) {
|
||||
if (!p || !Number.isInteger(p.row)) continue;
|
||||
const pos = heldPos(p) || tilePos(L, p.row, p.col);
|
||||
|
||||
+78
-16
@@ -132,8 +132,32 @@ function renderPref() {
|
||||
return globalThis.__SP_RENDER__ === 'fallback' ? 'fallback' : 'auto';
|
||||
}
|
||||
|
||||
function withTimeout(p, ms, what) {
|
||||
return Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(`${what} timed out`)), ms))]);
|
||||
function abortError(signal) {
|
||||
return signal?.reason ?? new DOMException('Field view initialization cancelled', 'AbortError');
|
||||
}
|
||||
|
||||
function checkActive(signal) {
|
||||
if (signal?.aborted) throw abortError(signal);
|
||||
}
|
||||
|
||||
function withTimeout(p, ms, what, signal) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let timer;
|
||||
const finish = (done, value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
done(value);
|
||||
};
|
||||
const onAbort = () => finish(reject, abortError(signal));
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
timer = setTimeout(() => finish(reject, new Error(`${what} timed out`)), ms);
|
||||
// Keep a rejection handler attached even when cancellation wins before this promise settles.
|
||||
Promise.resolve(p).then((value) => finish(resolve, value), (err) => finish(reject, err));
|
||||
if (signal?.aborted) onAbort();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,34 +210,55 @@ export function seedAssets(store) {
|
||||
/**
|
||||
* Create a field view in `host`: the render engine when available, else the DOM fallback.
|
||||
* @param {HTMLElement} host
|
||||
* @param {{ signal?: AbortSignal }} [options] Cancels a pending mount without creating a fallback.
|
||||
* @returns {Promise<ReturnType<typeof guardView>>}
|
||||
*/
|
||||
export async function mountFieldView(host) {
|
||||
export async function mountFieldView(host, { signal } = {}) {
|
||||
checkActive(signal);
|
||||
const pref = renderPref();
|
||||
const opts = { data, assets: data.get('assets'), audio, settings: settingsStore.get(), padding: hudPadding, hud: hudBands };
|
||||
if (pref !== 'fallback') {
|
||||
const controller = new AbortController();
|
||||
const onAbort = () => controller.abort(abortError(signal));
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal?.aborted) onAbort();
|
||||
let engineView = null;
|
||||
const dispose = (view) => { try { view?.destroy?.(); } catch { /* ignore */ } };
|
||||
try {
|
||||
checkActive(controller.signal);
|
||||
// the shared asset store (public/js/assets.js) keeps its Spine cache across remounts (next match, reconnect)
|
||||
const am = await withTimeout(import('../assets.js'), LOAD_TIMEOUT_MS, 'asset store import').catch(() => null);
|
||||
const am = await withTimeout(import('../assets.js'), LOAD_TIMEOUT_MS, 'asset store import', controller.signal).catch(() => {
|
||||
checkActive(controller.signal);
|
||||
return null;
|
||||
});
|
||||
checkActive(controller.signal);
|
||||
if (am?.assets && typeof am.assets.ready === 'function') {
|
||||
opts.assets = am.assets;
|
||||
seedAssets(am.assets);
|
||||
}
|
||||
const mod = await withTimeout(import('../render/app.js'), LOAD_TIMEOUT_MS, 'render engine import');
|
||||
const mod = await withTimeout(import('../render/app.js'), LOAD_TIMEOUT_MS, 'render engine import', controller.signal);
|
||||
checkActive(controller.signal);
|
||||
if (typeof mod?.createFieldView !== 'function') throw new Error('createFieldView missing');
|
||||
const view = await withTimeout(Promise.resolve(mod.createFieldView(host, opts)), LOAD_TIMEOUT_MS, 'createFieldView');
|
||||
// A factory that ignores cancellation still belongs to this attempt when it eventually returns.
|
||||
const pending = Promise.resolve(mod.createFieldView(host, { ...opts, signal: controller.signal })).then((view) => {
|
||||
if (controller.signal.aborted) dispose(view); else engineView = view;
|
||||
return view;
|
||||
});
|
||||
const view = await withTimeout(pending, LOAD_TIMEOUT_MS, 'createFieldView', controller.signal);
|
||||
checkActive(controller.signal);
|
||||
const missing = METHODS.filter((k) => typeof view?.[k] !== 'function');
|
||||
if (missing.length) {
|
||||
try { view?.destroy?.(); } catch { /* ignore */ }
|
||||
throw new Error(`view lacks ${missing.join(', ')}`);
|
||||
}
|
||||
if (missing.length) throw new Error(`view lacks ${missing.join(', ')}`);
|
||||
return guardView(view, 'engine');
|
||||
} catch (err) {
|
||||
controller.abort();
|
||||
dispose(engineView);
|
||||
checkActive(signal);
|
||||
console.warn('[field] render engine unavailable, using the simplified view:', err?.message || err);
|
||||
// anything the engine left behind in the host goes
|
||||
try { while (host.firstChild) host.removeChild(host.firstChild); } catch { /* ignore */ }
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
checkActive(signal);
|
||||
return guardView(createFallbackView(host, { ...opts, assets: data.get('assets') }), 'fallback');
|
||||
}
|
||||
|
||||
@@ -223,29 +268,46 @@ export async function mountFieldView(host) {
|
||||
*/
|
||||
export function useFieldView(hostRef) {
|
||||
const [state, setState] = useState({ view: null, kind: 'loading' });
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const retries = useRef(0);
|
||||
const viewRef = useRef(null);
|
||||
useEffect(() => {
|
||||
let dead = false;
|
||||
let dead = false, retrying = false;
|
||||
const host = hostRef.current;
|
||||
if (!host) return undefined;
|
||||
mountFieldView(host).then((view) => {
|
||||
setState({ view: null, kind: 'loading' });
|
||||
const controller = new AbortController();
|
||||
mountFieldView(host, { signal: controller.signal }).then((view) => {
|
||||
if (dead) { view.destroy(); return; }
|
||||
viewRef.current = view;
|
||||
if (view.kind === 'engine') retries.current = 0;
|
||||
globalThis.__SP_VIEW__ = view; // dev / E2E introspection (view.raw.stats?.())
|
||||
setState({ view, kind: view.kind });
|
||||
}, (err) => console.error('[field] mount failed', err));
|
||||
}, (err) => { if (!dead && !controller.signal.aborted) console.error('[field] mount failed', err); });
|
||||
const unsub = settingsStore.subscribe((s) => viewRef.current?.setSettings?.(s));
|
||||
const onResize = () => viewRef.current?.resize();
|
||||
// A temporary network/vendor failure must not pin this mounted match to fallback forever. Retry on a useful
|
||||
// user event, at most twice in succession; the effect cleanup disposes the old view before creating its successor.
|
||||
const onRetry = () => {
|
||||
if (dead || retrying || viewRef.current?.kind !== 'fallback' || renderPref() === 'fallback'
|
||||
|| document.visibilityState !== 'visible' || globalThis.navigator?.onLine === false || retries.current >= 2) return;
|
||||
retrying = true; retries.current++; setAttempt((n) => n + 1);
|
||||
};
|
||||
window.addEventListener('resize', onResize);
|
||||
window.addEventListener('online', onRetry);
|
||||
document.addEventListener('visibilitychange', onRetry);
|
||||
return () => {
|
||||
dead = true;
|
||||
controller.abort();
|
||||
unsub();
|
||||
window.removeEventListener('resize', onResize);
|
||||
window.removeEventListener('online', onRetry);
|
||||
document.removeEventListener('visibilitychange', onRetry);
|
||||
// the dev hook must not keep the destroyed view — and through its host the whole detached match screen — alive
|
||||
if (viewRef.current && globalThis.__SP_VIEW__ === viewRef.current) globalThis.__SP_VIEW__ = null;
|
||||
viewRef.current?.destroy();
|
||||
viewRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
}, [attempt]);
|
||||
return state;
|
||||
}
|
||||
@@ -48,7 +48,10 @@ export async function act(t, fields = {}, opts = {}) {
|
||||
}
|
||||
|
||||
export const actions = {
|
||||
infoReady: () => act('g.infoReady'),
|
||||
infoReady: (setupRevision = 0) => act('g.infoReady', { setupRevision }),
|
||||
rerollSetup: (setupRevision) => act('room.rerollSetup', { setupRevision }, { sfx: 'confirm' }),
|
||||
rerollVote: (voteId, agree) => act('g.rerollVote', { voteId, agree }, { sfx: agree ? 'confirm' : 'back' }),
|
||||
cancelReroll: (voteId) => act('room.cancelReroll', { voteId }, { sfx: 'back' }),
|
||||
band: (bandId) => act('g.band', { bandId }),
|
||||
bandSkip: () => act('g.bandSkip'),
|
||||
buy: (slot) => act('g.buy', { slot }),
|
||||
@@ -64,7 +67,7 @@ export const actions = {
|
||||
art: (itemUid, row, col, dir) => act('g.art', dir ? { itemUid, row, col, dir } : { itemUid, row, col }),
|
||||
destroy: (uid) => act('g.destroy', { uid }),
|
||||
reward: (idx) => act('g.reward', { idx }),
|
||||
choice: (idx) => act('g.choice', { idx }),
|
||||
choice: (idx, choiceId) => act('g.choice', choiceId === undefined ? { idx } : { idx, choiceId }),
|
||||
ready: (ready) => act('g.ready', { ready }, { sfx: ready ? 'ready' : 'back' }),
|
||||
emote: (id) => act('g.emote', { id }, { quiet: true }),
|
||||
// `playerId`: the player tapped in the team panel (a shared field shows two) — what an eliminated viewer follows
|
||||
@@ -72,4 +75,7 @@ export const actions = {
|
||||
autoplay: (on) => act('g.autoplay', { on }),
|
||||
// solo battles only (ui/matchStatus.js pauseAvailable): m.public.paused follows
|
||||
pause: (on) => act('g.pause', { on: !!on }, { sfx: on ? 'click' : 'confirm' }),
|
||||
// room-level intent (NOT g.*): the host frees a spectator seat while the match runs — the server takes room.removeSpectator at
|
||||
// any time (server/lobby.js removeSpectator), the game screen had no entry for it (ui/hud.js SpectatorPill; GitHub #120)
|
||||
removeSpectator: (playerId) => act('room.removeSpectator', { playerId }, { sfx: 'back' }),
|
||||
};
|
||||
@@ -33,16 +33,16 @@ export { STATUS_META } from './gameLogic/format.js';
|
||||
export { sortedPlayers } from './gameLogic/shared.js';
|
||||
export { ownFieldId, homeFieldId, cycleField, watchTarget, switcherLabel, fieldLabel, activeBubbles } from './gameLogic/watch.js';
|
||||
export { sortBonds, bondTier, nextThreshold, grantedBonds, pieceBondIds, morphPairings, HARMONY_BOND, harmonyMembers, bondMembers, memberHeadCount, bannedPerBond, disabledBondSets, briefingBondTip, modeOffBonds, bandOffBonds, bandOffLine } from './gameLogic/bonds.js';
|
||||
export { priceTone, mergeProgress, mergeTarget, handFull, completesMerge, offerHeader, shopBlockReason, readyFundsPrompt } from './gameLogic/shop.js';
|
||||
export { priceTone, mergeProgress, mergeTarget, handFull, completesMerge, offerHeader, shopBlockReason, readyFundsPrompt, readyShopFold } from './gameLogic/shop.js';
|
||||
export { deploySets, stageOverrides, deployMap, effectiveStage, indexPieces, placementContext, piecePosition, tileAllows, summonRange, summonExcluded, canPlace, equipReplaces, equipMerges, boardTargets, dropIntent, dropFailureReason } from './gameLogic/placement.js';
|
||||
export { terrainInfo } from './gameLogic/terrain.js';
|
||||
export { normalizeDraft, normalizeSp } from './gameLogic/draft.js';
|
||||
export { terrainInfo, deviceInfo, deviceTipAt, noteDeviceUnits, deviceUnitsForEntry } from './gameLogic/terrain.js';
|
||||
export { normalizeDraft, normalizeSp, normalizePersonalChoice } from './gameLogic/draft.js';
|
||||
export { groupEnemies, PEN, penZoneTiles, penPlacement, previewEnemyKey, factionTypes } from './gameLogic/enemies.js';
|
||||
export { snapHud, bossFrac, bossPctText, hasFlag, UF, attackInterval, fmtNum, rangeGridBox } from './gameLogic/format.js';
|
||||
export { shortcutFor, closesOnFieldPress, shortcutBlocked, HOTKEY_ACTIONS, DEFAULT_HOTKEYS, isBindableCode, hotkeyLabel, sanitizeHotkeys, rebindHotkey, isDefaultHotkeys, hotkeyOf, actionForKey, captureHotkey, facingSwallows } from './gameLogic/shortcuts.js';
|
||||
export { DEFAULT_SETTINGS, sanitizeSettings } from './gameLogic/settings.js';
|
||||
export { shortcutFor, closesOnFieldPress, shortcutBlocked, HOTKEY_ACTIONS, DEFAULT_HOTKEYS, isBindableCode, hotkeyLabel, sanitizeHotkeys, rebindHotkey, isDefaultHotkeys, hotkeyOf, actionForKey, captureHotkey, facingSwallows, facingEnter } from './gameLogic/shortcuts.js';
|
||||
export { DEFAULT_SETTINGS, VOICE_LANGS, TEXT_SIZES, sanitizeSettings } from './gameLogic/settings.js';
|
||||
export { normalizeResult } from './gameLogic/result.js';
|
||||
export { chessLoadout, unitLoadout } from './gameLogic/loadout.js';
|
||||
export { chessLoadout, unitLoadout, unitCultivation } from './gameLogic/loadout.js';
|
||||
export { standInIds, fieldsStandIn, standInOf, ownStandIn, cardStandIn, memberStandIn, standInGetter, standInLoadout, deployedRecord, deployedModuleId, standInLabel, standInForText, standInTip } from './gameLogic/standIn.js';
|
||||
export { diyPicks, ownDiyPick, diyRecordFor, ownDiyRecord, cardDiy, diyGetter, pickGetter, isDiyRecord, diyBannedPieces } from './gameLogic/diy.js';
|
||||
export { diyPicks, ownDiyPick, diyRecordFor, ownDiyRecord, cardDiy, unitPick, diyGetter, pickGetter, isDiyRecord, diyBannedPieces } from './gameLogic/diy.js';
|
||||
export { panelSide, panelSlots, PANEL_RIGHT_GAP, PANEL_RIGHT_BOTTOM, PANEL_RIGHT_BOTTOM_SHOP, BPOP, bondPopupPlace } from './gameLogic/panel.js';
|
||||
@@ -8,6 +8,8 @@
|
||||
// player's units say it themselves (UnitInfo `diy`: the sim's, Match.prepFieldMeta's for scouting, m.result lineups). The
|
||||
// composed record is shared/diy.js diyRecordOf over chess.json + backups.json — the one the server and the sim use.
|
||||
// `data` below = `{ chess, backups }` (the client's data.get('chess') / data.get('backups'), localized copies).
|
||||
// 0.2.2: a pick may carry `potential` (the owner's 潜能 of the operator — m.private.ops for the player's own, UnitInfo
|
||||
// `potential` for another player's unit): the record is composed at it (an owned pick; a prototype has none).
|
||||
|
||||
import { diyRecordOf } from '../../../../shared/diy.js';
|
||||
import { isObj } from './shared.js';
|
||||
@@ -26,7 +28,10 @@ export function ownDiyPick(priv, chess) {
|
||||
if (!isObj(chess) || !chess.isDiy) return null;
|
||||
const slot = typeof chess.diyFor === 'string' ? chess.diyFor : chess.baseId || chess.chessId;
|
||||
const p = diyPicks(priv)[slot];
|
||||
return isObj(p) && typeof p.charId === 'string' ? p : null;
|
||||
if (!isObj(p) || typeof p.charId !== 'string') return null;
|
||||
// 0.2.2: at the player's 潜能 of that operator (m.private.ops; none set = 6)
|
||||
const pot = isObj(priv?.ops) && isObj(priv.ops[p.charId]) ? priv.ops[p.charId].potential : null;
|
||||
return Number.isInteger(pot) && pot >= 1 && pot < 6 ? { ...p, potential: pot } : p;
|
||||
}
|
||||
|
||||
/** Per backups object: `chessId|charId|skill|module` → composed record (or null). */
|
||||
@@ -44,10 +49,11 @@ export function diyRecordFor(chess, pick, data) {
|
||||
if (!isObj(pick) || !isObj(data?.backups)) return null;
|
||||
let m = CACHE.get(data.backups);
|
||||
if (!m) { m = new Map(); CACHE.set(data.backups, m); }
|
||||
const key = `${chess.chessId}|${pick.charId}|${pick.skillIndex ?? ''}|${pick.uniEquipId ?? ''}`;
|
||||
const pot = Number.isInteger(pick.potential) ? pick.potential : null;
|
||||
const key = `${chess.chessId}|${pick.charId}|${pick.skillIndex ?? ''}|${pick.uniEquipId ?? ''}|${pot ?? ''}`;
|
||||
if (m.has(key)) return m.get(key);
|
||||
let rec;
|
||||
try { rec = diyRecordOf(chess, pick, data); } catch { rec = null; }
|
||||
try { rec = diyRecordOf(chess, pick, data, { potential: pot }); } catch { rec = null; }
|
||||
m.set(key, rec);
|
||||
return rec;
|
||||
}
|
||||
@@ -65,10 +71,16 @@ export function ownDiyRecord(chess, priv, data) {
|
||||
*/
|
||||
export function cardDiy(chess, { priv = null, unit = null, data = null } = {}) {
|
||||
if (!isObj(chess) || !chess.isDiy) return null;
|
||||
if (unit) return isObj(unit.diy) ? diyRecordFor(chess, unit.diy, data) : null;
|
||||
if (unit) return isObj(unit.diy) ? diyRecordFor(chess, unitPick(unit), data) : null;
|
||||
return ownDiyRecord(chess, priv, data);
|
||||
}
|
||||
|
||||
/** A unit's 自选 pick with its potential (UnitInfo `diy` + `potential`, 0.2.2), or null. */
|
||||
export function unitPick(unit) {
|
||||
if (!isObj(unit) || !isObj(unit.diy)) return null;
|
||||
return Number.isInteger(unit.potential) ? { ...unit.diy, potential: unit.potential } : unit.diy;
|
||||
}
|
||||
|
||||
/**
|
||||
* id → the player's 自选 record of a filled DIY slot (both forms), else the chess record: the lookup the player's own
|
||||
* pieces and cards resolve against (names, art, position, the loadout / range of a 自选 piece — shared/protocol.js
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// ui/gameLogic/draft.js — 机变 and band-draft normalisation. Re-exported from ../gameLogic.js.
|
||||
|
||||
import { isObj } from './shared.js';
|
||||
import { PHASE } from '../../../../shared/constants.js';
|
||||
import { t } from '../../../../shared/i18n.js';
|
||||
|
||||
|
||||
// ---- 机变 / band draft normalisation ----------------------------------------------------------------------
|
||||
@@ -73,3 +75,15 @@ export function normalizeSp(sp, players = []) {
|
||||
cards, order, turnPid, pickOf, takenBy, pickedCount: pickOf.size,
|
||||
};
|
||||
}
|
||||
|
||||
/** Adapt only the recipient's current PREP choice; never write it into the public draft. */
|
||||
export function normalizePersonalChoice(pub, priv, myId) {
|
||||
const choice = priv?.personalChoice;
|
||||
if (pub?.phase !== PHASE.PREP || !priv || priv.playerId !== myId || priv.alive === false
|
||||
|| !choice || choice.round !== pub.round) return null;
|
||||
return {
|
||||
...normalizeSp({ family: 'bounty', name: t('教鞭 · 战术特训'), desc: t('请选择一项战术特训'),
|
||||
cards: choice.cards, turn: myId, order: [myId], picks: {} }),
|
||||
id: choice.id,
|
||||
};
|
||||
}
|
||||
@@ -22,7 +22,9 @@ export const STATUS_META = Object.freeze({
|
||||
// ---- snapshots / battle HUD ---------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* HUD numbers from a b.snap: { killed, total, dp, boss } (boss: { hp, max } when present).
|
||||
* HUD numbers from a b.snap: { killed, resolved, total, dp, boss } (boss: { hp, max } when present).
|
||||
* `resolved` is the capsule's numerator — knocked out + leaked among the round's own enemies (Battle.leakedInTotal);
|
||||
* an older snapshot without it falls back to the kill count.
|
||||
* @param {any} snap
|
||||
*/
|
||||
export function snapHud(snap) {
|
||||
@@ -30,7 +32,8 @@ export function snapHud(snap) {
|
||||
const n = (v) => (Number.isFinite(v) ? v : null);
|
||||
let boss = null;
|
||||
if (isObj(snap.boss) && Number.isFinite(snap.boss.hp)) boss = { hp: snap.boss.hp, max: n(snap.boss.max) ?? n(snap.boss.maxHp) };
|
||||
return { killed: n(snap.killed), total: n(snap.total), dp: n(snap.dp), boss };
|
||||
const killed = n(snap.killed);
|
||||
return { killed, resolved: n(snap.resolved) ?? killed, total: n(snap.total), dp: n(snap.dp), boss };
|
||||
}
|
||||
|
||||
/** Boss HP fraction 0..1 (null when unknown). */
|
||||
|
||||
@@ -2,9 +2,19 @@
|
||||
|
||||
import { MODULE_NONE, loadoutOptions, resolveLoadout } from '../../../../shared/protocol.js';
|
||||
import { loadoutRecord, resolveRecordLoadout } from '../../../../shared/loadoutRecord.js';
|
||||
import { cultivationOf, cultivateMul, cultivatedStats, isPotential, isCultivate } from '../../../../shared/potential.js';
|
||||
import { isObj } from './shared.js';
|
||||
import { t } from '../../../../shared/i18n.js';
|
||||
|
||||
/** The summon owner's variant: exact chess id, normal sibling, then the first available variant. */
|
||||
export function tokenVariantFor(token, ownerId = null) {
|
||||
const vs = token?.variants || {};
|
||||
if (typeof ownerId === 'string') {
|
||||
const v = vs[ownerId] || vs[ownerId.replace(/_b$/, '_a')];
|
||||
if (v) return v;
|
||||
}
|
||||
return Object.values(vs)[0] || null;
|
||||
}
|
||||
|
||||
// ---- operator loadout (DESIGN §16) ----------------------------------------------------------------------------------
|
||||
|
||||
@@ -12,14 +22,21 @@ import { t } from '../../../../shared/i18n.js';
|
||||
* The skill / module a chess fights with under the player's loadout (m.private.loadout, DESIGN §16) — what the shop
|
||||
* card and the detail panel show. Works with data that already lists every selectable skill (`skills[]`, elite
|
||||
* `modules[]`) and with older data (only the default `skill` / `module`).
|
||||
* 0.2.2: the record (stats, talents) is at the operator's 潜能 and its stats carry the 练度 multiplier — the player's
|
||||
* settings (`opts.ops`: m.private.ops / the 干员调配 store; missing = 潜能 6, 精英2 Lv.60), or a unit's own
|
||||
* (`opts.cultivation`: a teammate's UnitInfo — null = none); a 补位 stand-in / prototype 自选 record has neither
|
||||
* (shared/potential.js cultivationOf). The 练度 needs `opts.effects` (data/effects.json). A composed 自选 record is
|
||||
* already at its potential (gameLogic/diy.js: the pick's `potential`).
|
||||
* @param {any} chess the chess record (normal or elite)
|
||||
* @param {any} loadout m.private.loadout `{ [baseChessId]: { skill, module } }` (entries equal to the defaults may be
|
||||
* missing); null → defaults
|
||||
* @param {(id: string) => any} [getChess]
|
||||
* @param {{ ops?: any, cultivation?: { potential?: number|null, cultivate?: number|null } | null, effects?: any }} [opts]
|
||||
* @returns {{ skill: any, skillIndex: number|null, defaultSkill: boolean, module: { id: string, name: string, typeName: string, none: boolean }|null,
|
||||
* defaultModule: boolean, changed: boolean, choices: number } | null}
|
||||
* defaultModule: boolean, changed: boolean, choices: number, record: any,
|
||||
* cultivation: { potential: number, cultivate: number|null } | null } | null}
|
||||
*/
|
||||
export function chessLoadout(chess, loadout, getChess = () => null) {
|
||||
export function chessLoadout(chess, loadout, getChess = () => null, opts = {}) {
|
||||
if (!isObj(chess)) return null;
|
||||
const lo = isObj(loadout) && !Array.isArray(loadout) ? loadout : null;
|
||||
let r = { skillIndex: null, moduleId: null };
|
||||
@@ -43,12 +60,42 @@ export function chessLoadout(chess, loadout, getChess = () => null) {
|
||||
}
|
||||
defaultModule = opt.defaultModule == null || id === opt.defaultModule;
|
||||
}
|
||||
// the record the unit fights with (stats / 特性 / talents of the chosen module or none — the battle's own composition,
|
||||
// shared/loadoutRecord.js): the detail card must show what the sim runs
|
||||
// 0.2.2: the operator's 潜能 / 练度 (the player's settings, or the unit's own)
|
||||
const cv = cultivationFor(chess, opts);
|
||||
// the record the unit fights with (stats / 特性 / talents of the chosen module or none, at its potential — the
|
||||
// battle's own composition, shared/loadoutRecord.js): the detail card must show what the sim runs
|
||||
let record = chess;
|
||||
try { record = loadoutRecord(chess, resolveRecordLoadout(chess, { skillIndex: r.skillIndex, moduleId: r.moduleId })) || chess; } catch { /* the record as is */ }
|
||||
try { record = loadoutRecord(chess, resolveRecordLoadout(chess, { skillIndex: r.skillIndex, moduleId: r.moduleId, potential: cv ? cv.potential : null })) || chess; } catch { /* the record as is */ }
|
||||
const mul = cv && isCultivate(cv.cultivate) ? cultivateMul(opts?.effects, cv.cultivate) : null;
|
||||
if (mul && record && record.stats) record = { ...record, stats: cultivatedStats(record.stats, mul) };
|
||||
return { skill, skillIndex: skill?.index ?? null, defaultSkill, module, defaultModule, changed: !defaultSkill || !defaultModule,
|
||||
choices: Math.max(skills.length, opt.skills?.length || 0), record };
|
||||
choices: Math.max(skills.length, opt.skills?.length || 0), record, cultivation: cv };
|
||||
}
|
||||
|
||||
/**
|
||||
* The 潜能 / 练度 of a card's record (chessLoadout `opts`): the unit's own (`cultivation`, null = none) or the player's
|
||||
* settings (`ops`, shared/potential.js cultivationOf — null for a stand-in / prototype 自选 record).
|
||||
* @returns {{ potential: number, cultivate: number|null } | null}
|
||||
*/
|
||||
function cultivationFor(chess, opts) {
|
||||
if (opts && opts.cultivation !== undefined) {
|
||||
const c = opts.cultivation;
|
||||
if (!isObj(c) || !isObj(chess) || chess.standInFor || chess.diyProto) return null;
|
||||
return { potential: isPotential(c.potential) ? c.potential : 6, cultivate: isCultivate(c.cultivate) ? c.cultivate : null };
|
||||
}
|
||||
return cultivationOf(chess, opts ? opts.ops : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The 潜能 / 练度 a battle / scouting unit fights at (UnitInfo `potential` — below 6 only — and `cultivate`, 0.2.2): for
|
||||
* chessLoadout `opts.cultivation`; null when the unit has neither (a stand-in, a prototype 自选 piece, a raw unit).
|
||||
* @param {any} unit UnitInfo
|
||||
*/
|
||||
export function unitCultivation(unit) {
|
||||
if (!isObj(unit)) return null;
|
||||
const pot = isPotential(unit.potential) ? unit.potential : 6;
|
||||
const cult = isCultivate(unit.cultivate) ? unit.cultivate : null;
|
||||
return cult == null && pot === 6 ? null : { potential: pot, cultivate: cult };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { GEO } from '../../../../shared/constants.js';
|
||||
import { attackRangeGrid } from '../../../../shared/loadoutRecord.js';
|
||||
import { meleeOnHighGround } from '../../../../shared/highGround.js';
|
||||
import { summonPlacementGrid } from '../../../../shared/summonPlacement.js';
|
||||
import { pieceDir, rangeTiles } from '../facing.js';
|
||||
import { isObj, tileKey } from './shared.js';
|
||||
import { boardTileOf, fieldTile } from './camera.js';
|
||||
@@ -250,15 +251,18 @@ export function tileAllows(ctx, piece, row, col) {
|
||||
/**
|
||||
* Board tiles ('r,c') where a summon whose text reads "只能部署在召唤者攻击范围内" may stand (tokens.json `ownerRange`:
|
||||
* 伺夜's 狼群, 缪尔赛思's 流形 — the tactical point; player report #9 after 0.1.0): its owner's attack range (the
|
||||
* loadout's grid, shared/loadoutRecord.js attackRangeGrid, rotated by the owner's facing around its tile). Null when
|
||||
* loadout's grid, shared/loadoutRecord.js attackRangeGrid, rotated by the owner's facing around its tile).
|
||||
* Jessica's shield uses the four-adjacent-tile grid instead, independent of facing/skill/module. Null when
|
||||
* the piece is not range-bound or its owner is not on the board. `owner` ({ row, col, piece }) replaces the owner's
|
||||
* current position (a summon swapped with its own owner). Mirror of server/match/PlayerState.js summonRange.
|
||||
* @param {ReturnType<typeof placementContext>} ctx
|
||||
* @returns {Set<string> | null}
|
||||
*/
|
||||
export function summonRange(ctx, piece, owner = null) {
|
||||
if (!isObj(piece) || piece.kind !== 'token' || ctx?.getToken?.(piece.id)?.ownerRange !== true) return null;
|
||||
return ownerRangeOf(ctx, piece, owner);
|
||||
if (!isObj(piece) || piece.kind !== 'token') return null;
|
||||
const grid = summonPlacementGrid(piece.id);
|
||||
if (!grid && ctx?.getToken?.(piece.id)?.ownerRange !== true) return null;
|
||||
return ownerRangeOf(ctx, piece, owner, grid);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,14 +277,14 @@ export function summonExcluded(ctx, piece, owner = null) {
|
||||
return ownerRangeOf(ctx, piece, owner);
|
||||
}
|
||||
|
||||
/** The attack-range tiles of a summon piece's owner on the board (summonRange / summonExcluded), or null. */
|
||||
function ownerRangeOf(ctx, piece, owner = null) {
|
||||
/** The attack or fixed placement range of a summon piece's owner on the board, or null. */
|
||||
function ownerRangeOf(ctx, piece, owner = null, placementGrid = null) {
|
||||
let at = owner;
|
||||
if (!at) for (const e of ctx.boardAt.values()) if (e.piece.uid === piece.ownerUid && e.piece.kind === 'chess') { at = e; break; }
|
||||
const rec = at && ctx.getChess(at.piece.id);
|
||||
if (!rec) return null;
|
||||
let grid = null;
|
||||
try { grid = attackRangeGrid(deployedRecord(rec, ctx.priv, ctx.getChess, ctx.backups) || rec); } catch { /* the data grid */ }
|
||||
try { grid = placementGrid || attackRangeGrid(deployedRecord(rec, ctx.priv, ctx.getChess, ctx.backups) || rec); } catch { /* the data grid */ }
|
||||
return new Set(rangeTiles(grid || rec.rangeGrid, at.row, at.col, pieceDir(at.piece)).map(([r, c]) => tileKey(r, c)));
|
||||
}
|
||||
|
||||
@@ -301,7 +305,8 @@ function unitAllowed(ctx, piece, row, col, owner = null) {
|
||||
* must be legal on the source tile); from hand/temp the deploy cap applies unless a chess occupant swaps out.
|
||||
* board ← token: legal tile; from the hand the tile must be empty and its summoner deployed; board ↔ board swaps.
|
||||
* hand ← chess from the board: empty slot (withdraw), chess occupant (swap, legal on the source tile), otherwise
|
||||
* it goes to any free slot (HAND_FULL when none). hand ← token from the board: always (back onto its stack).
|
||||
* it uses a free slot or one freed by its own summon stack (HAND_FULL when none). hand ← token from the board:
|
||||
* always (back onto its stack).
|
||||
* hand ← hand/temp piece: move / swap. hand ← EQUIP item onto a chess: equip; onto a non-chess: swap.
|
||||
* board ← EQUIP item: equip the chess on that tile. board ← MAGIC (Arts): used on that tile.
|
||||
* @param {ReturnType<typeof placementContext>} ctx
|
||||
@@ -334,8 +339,11 @@ export function canPlace(ctx, uid, target) {
|
||||
if (!tileAllows(ctx, occ.piece, src.row, src.col)) return no('BAD_TILE', t('交换后的单位无法部署在原位置'));
|
||||
return { ok: true, action: 'swap' };
|
||||
}
|
||||
// the withdrawn operator goes to another free slot
|
||||
const free = [...Array(GEO.HAND_SIZE).keys()].some((i) => !ctx.handAt.has(i));
|
||||
// Withdrawal removes the operator's own summon stacks, freeing their hand slots too.
|
||||
const free = [...Array(GEO.HAND_SIZE).keys()].some((i) => {
|
||||
const p = ctx.handAt.get(i)?.piece;
|
||||
return !p || (p.kind === 'token' && p.ownerUid === piece.uid);
|
||||
});
|
||||
return free ? { ok: true, action: 'move' } : no('HAND_FULL', t('整备区已满'));
|
||||
}
|
||||
return { ok: true, action: 'swap' };
|
||||
@@ -363,7 +371,7 @@ export function canPlace(ctx, uid, target) {
|
||||
// dropped onto its own owner (the two swap); an outside-bound one (战术锚点) outside it
|
||||
const ownerSwap = src.area === 'board' && occ && occ.piece.uid === piece.ownerUid ? { row: src.row, col: src.col, piece: occ.piece } : null;
|
||||
const range = summonRange(ctx, piece, ownerSwap);
|
||||
if (range && !range.has(tileKey(row, col))) return no('BAD_TILE', t('只能部署在召唤者攻击范围内'));
|
||||
if (range && !range.has(tileKey(row, col))) return no('BAD_TILE', summonPlacementGrid(piece.id) ? t('只能部署在召唤者相邻四格') : t('只能部署在召唤者攻击范围内'));
|
||||
const out = summonExcluded(ctx, piece, ownerSwap);
|
||||
if (out && out.has(tileKey(row, col))) return no('BAD_TILE', t('只能部署在召唤者攻击范围外'));
|
||||
if (src.area === 'board') {
|
||||
|
||||
@@ -1,20 +1,37 @@
|
||||
// ui/gameLogic/settings.js — settings defaults and sanitising. Re-exported from ../gameLogic.js.
|
||||
|
||||
import { VOICE_LANGS, sanitizeVoiceOverrides } from '../../voicePrefs.js';
|
||||
export { VOICE_LANGS } from '../../voicePrefs.js';
|
||||
|
||||
import { clamp, isObj } from './shared.js';
|
||||
import { DEFAULT_HOTKEYS, sanitizeHotkeys } from './shortcuts.js';
|
||||
|
||||
|
||||
// ---- settings ------------------------------------------------------------------------------------------------------
|
||||
|
||||
/** keys: the in-match shortcuts' key map (ui/gameLogic/shortcuts.js; settings → 快捷键). */
|
||||
export const DEFAULT_SETTINGS = Object.freeze({ bgm: 0.6, sfx: 0.8, voice: 0.8, muted: false, damageNumbers: true, quality: 'high', keys: DEFAULT_HOTKEYS });
|
||||
/**
|
||||
* The operator voice dubs (settings 语音语言): 'cn' 中文 (`audio.voice`, the default) and 'jp' 日本語 (`audio.voiceJp`,
|
||||
* falling back to the Chinese line it lacks — public/js/audio.js voiceLine). Not tied to the interface language.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* The steps of 设置 →「文字大小」 (textSize): the interface text root `--t` of css/theme.css — 'sm' is the design's own
|
||||
* sizes (`--t: 1rem`), the others lift the phone's 40 px root by a floor and grow the desktop gently. Text only: the
|
||||
* layout root `1rem` (and with it the field camera, the detail card's side and the DOM fallback board) never moves.
|
||||
*/
|
||||
export const TEXT_SIZES = Object.freeze(['sm', 'md', 'lg', 'xl']);
|
||||
|
||||
/** keys: the in-match shortcuts' key map (ui/gameLogic/shortcuts.js; settings → 快捷键). voiceLang: VOICE_LANGS.
|
||||
* textSize: TEXT_SIZES (css/theme.css `--t`, applied by ui/settings.js applyTextSize). */
|
||||
export const DEFAULT_SETTINGS = Object.freeze({ bgm: 0.6, sfx: 0.8, voice: 0.8, voiceLang: 'cn', voiceOverrides: Object.freeze({}), muted: false, damageNumbers: true, quality: 'high', textSize: 'sm', keys: DEFAULT_HOTKEYS });
|
||||
const QUALITIES = ['high', 'medium', 'low'];
|
||||
|
||||
/**
|
||||
* Sanitize persisted settings.
|
||||
* @param {any} raw
|
||||
* @returns {{ bgm: number, sfx: number, voice: number, muted: boolean, damageNumbers: boolean, quality: 'high'|'medium'|'low',
|
||||
* keys: Record<'refresh'|'freeze'|'levelUp'|'retreat'|'sell'|'ready', string> }}
|
||||
* @returns {{ bgm: number, sfx: number, voice: number, voiceLang: 'cn'|'jp', voiceOverrides: Record<string, string>, muted: boolean, damageNumbers: boolean, quality: 'high'|'medium'|'low',
|
||||
* textSize: 'sm'|'md'|'lg'|'xl', keys: Record<'refresh'|'freeze'|'levelUp'|'retreat'|'sell'|'ready', string> }}
|
||||
*/
|
||||
export function sanitizeSettings(raw) {
|
||||
const r = isObj(raw) ? raw : {};
|
||||
@@ -23,9 +40,12 @@ export function sanitizeSettings(raw) {
|
||||
bgm: vol(r.bgm, DEFAULT_SETTINGS.bgm),
|
||||
sfx: vol(r.sfx, DEFAULT_SETTINGS.sfx),
|
||||
voice: vol(r.voice, DEFAULT_SETTINGS.voice),
|
||||
voiceLang: VOICE_LANGS.includes(r.voiceLang) ? r.voiceLang : DEFAULT_SETTINGS.voiceLang,
|
||||
voiceOverrides: sanitizeVoiceOverrides(r.voiceOverrides),
|
||||
muted: typeof r.muted === 'boolean' ? r.muted : DEFAULT_SETTINGS.muted,
|
||||
damageNumbers: typeof r.damageNumbers === 'boolean' ? r.damageNumbers : DEFAULT_SETTINGS.damageNumbers,
|
||||
quality: QUALITIES.includes(r.quality) ? r.quality : DEFAULT_SETTINGS.quality,
|
||||
textSize: TEXT_SIZES.includes(r.textSize) ? r.textSize : DEFAULT_SETTINGS.textSize,
|
||||
keys: sanitizeHotkeys(r.keys),
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
// ui/gameLogic/shop.js — shop prices, merges, offers, the ready-funds prompt. Re-exported from ../gameLogic.js.
|
||||
// ui/gameLogic/shop.js — shop prices, merges, offers, the ready-funds prompt, the shop bar's fold on 准备. Re-exported from
|
||||
// ../gameLogic.js.
|
||||
|
||||
import { GEO } from '../../../../shared/constants.js';
|
||||
import { isObj } from './shared.js';
|
||||
@@ -139,7 +140,10 @@ export function offerHeader(offer) {
|
||||
export function shopBlockReason(kind, { priv, editable, slot } = {}) {
|
||||
if (!priv) return t('尚未就绪');
|
||||
if (priv.alive === false) return t('你已被淘汰');
|
||||
if (kind === 'ready') return priv.canReady === false ? t('临时整备区不为空,请先处理溢出的资源') : null;
|
||||
if (kind === 'ready') {
|
||||
if (priv.personalChoice) return t('请先完成教鞭选择');
|
||||
return priv.canReady === false ? t('临时整备区不为空,请先处理溢出的资源') : null;
|
||||
}
|
||||
if (!editable) {
|
||||
if (kind === 'reward') return t('当前无法选择');
|
||||
return priv.ready ? t('已准备就绪,取消准备后才能操作') : t('当前阶段无法进行该操作');
|
||||
@@ -183,3 +187,18 @@ export function readyFundsPrompt(priv, { ready = true, keptBands = null, autopla
|
||||
text: t('还有 {funds} 资金未使用。休整期结束时,本回合的剩余资金将清零。确定准备就绪吗?', { funds }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The shop bar follows the player's ready state (GitHub #138, the owner's decision of 2026-10-07): pressing 准备就绪 folds
|
||||
* the bar — the board is set, the fight is what to look at —, cancelling it unfolds the bar again. Read from the own CONFIRMED
|
||||
* state (m.private.ready — a refused 准备 folds nothing) and only a change inside one prep counts: the first state seen (a
|
||||
* reconnect in the middle of a prep, the prep's start), the new round's reset to not ready and anything outside a prep are
|
||||
* not a press. The player can still fold / unfold by hand in between.
|
||||
* @param {{ round: any, ready: boolean }|null|undefined} prev the own prep state seen last (null: none — outside a prep)
|
||||
* @param {{ round: any, ready: boolean }|null|undefined} cur the own prep state now (null outside a prep)
|
||||
* @returns {'fold'|'unfold'|null}
|
||||
*/
|
||||
export function readyShopFold(prev, cur) {
|
||||
if (!isObj(prev) || !isObj(cur) || prev.round !== cur.round || !!prev.ready === !!cur.ready) return null;
|
||||
return cur.ready ? 'fold' : 'unfold';
|
||||
}
|
||||
@@ -140,8 +140,8 @@ export function captureHotkey(e) {
|
||||
* Map a keydown to a game shortcut under the player's key map (defaults: R refresh, F freeze, D level-up, Q retreat,
|
||||
* X sell, Space ready) or Esc (close; fixed). A shortcut key means its action even while a HUD button has focus (a
|
||||
* mouse click leaves the shop card / 刷新 focused, and Space must not re-trigger it); the caller prevents the button's
|
||||
* own activation. Enter still activates buttons (it cannot be a shortcut). Nothing while Ctrl / ⌘ / Alt is held or a
|
||||
* text field has the focus.
|
||||
* own activation. Enter still activates buttons (it cannot be a shortcut; behind the facing wheel only its ✕:
|
||||
* facingEnter). Nothing while Ctrl / ⌘ / Alt is held or a text field has the focus.
|
||||
* @param {{ key?: string, code?: string, ctrlKey?: boolean, metaKey?: boolean, altKey?: boolean, repeat?: boolean, target?: any }} e
|
||||
* @param {any} [keys] the player's map (settings `keys`)
|
||||
* @returns {'refresh'|'freeze'|'levelUp'|'retreat'|'sell'|'ready'|'escape'|null}
|
||||
@@ -164,14 +164,36 @@ export function shortcutFor(e, keys = DEFAULT_HOTKEYS) {
|
||||
*/
|
||||
export const facingSwallows = (e, keys = DEFAULT_HOTKEYS) => e?.key === ' ' || actionForKey(e, keys) != null;
|
||||
|
||||
// what a focused element is when Enter would activate it (a button, a link, a form field, an ARIA control)
|
||||
const CONTROL = 'button, a[href], input, select, textarea, summary, [contenteditable=""], [contenteditable="true"], '
|
||||
+ '[role="button"], [role="link"], [role="checkbox"], [role="switch"], [role="tab"], [role="menuitem"], [role="option"]';
|
||||
|
||||
/**
|
||||
* What Enter does while the facing wheel is open (GitHub #394, PR #395): on the wheel's own ✕ button it cancels; on
|
||||
* any other control (准备, 刷新, 设置, 玩法说明, a shop card … — Tab reaches them behind the wheel) nothing happens — the
|
||||
* wheel holds the keyboard as it holds Space and the shortcuts; with the focus anywhere else (the wheel itself, the
|
||||
* page) it confirms the previewed direction, and does nothing while none is previewed. null: not Enter.
|
||||
* @param {{ key?: string, target?: any }} e @param {boolean} chosen a direction is previewed
|
||||
* @returns {'cancel'|'commit'|'swallow'|null}
|
||||
*/
|
||||
export function facingEnter(e, chosen) {
|
||||
if (e?.key !== 'Enter') return null;
|
||||
const t = e.target;
|
||||
const closest = (sel) => (t && typeof t.closest === 'function' ? t.closest(sel) : null);
|
||||
if (closest('.fwheel__cancel')) return 'cancel';
|
||||
if (closest(CONTROL)) return 'swallow';
|
||||
return chosen ? 'commit' : 'swallow';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a press on the field closes the open detail card: a card opened from the field itself (an own piece — tap,
|
||||
* right-click or long press — or a battle / teammate unit). Shop, reward, bond-member and intel (enemy) cards stay.
|
||||
* @param {{ kind?: string }|null|undefined} detail
|
||||
*/
|
||||
// a card opened BY a field press (a piece, a unit, a special terrain tile: issue #184) closes on the next press of
|
||||
// the field; the ones opened from the shop / hand / HUD stay until their own close button (or the flow that opened them)
|
||||
export const closesOnFieldPress = (detail) => detail?.kind === 'piece' || detail?.kind === 'unit' || detail?.kind === 'terrain';
|
||||
// a card opened BY a field press (a piece, a unit, a special terrain tile: issue #184, a stage device: #228) closes on the
|
||||
// next press of the field; the ones opened from the shop / hand / HUD stay until their own close button (or the flow that
|
||||
// opened them)
|
||||
export const closesOnFieldPress = (detail) => detail?.kind === 'piece' || detail?.kind === 'unit' || detail?.kind === 'terrain' || detail?.kind === 'device';
|
||||
|
||||
/**
|
||||
* Whether an open overlay swallows a game shortcut: a modal / the guide own the keyboard (Esc included — they close
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
// ui/gameLogic/terrain.js — special terrain tips (GitHub issue #184: 特殊地形的单击信息提示). Re-exported from
|
||||
// ../gameLogic.js.
|
||||
// ui/gameLogic/terrain.js — the tips of a tap on the ground: special terrain tiles (GitHub issue #184: 特殊地形的单击信息
|
||||
// 提示) and, in the same place, stage devices (阻隔工事 / “双眼皮” / 射击台 / 气流: GitHub #228, PR #229 by @rickylxw —
|
||||
// deviceInfo / deviceTipAt below). Re-exported from ../gameLogic.js.
|
||||
//
|
||||
// The words go through t() (docs/I18N.md: the Chinese text is the msgid, public/i18n/en.json the English): the name /
|
||||
// tag / fact tables are marked N_() and translated where terrainInfo hands them out, the mechanism lines are built
|
||||
// with their numbers as params.
|
||||
// with their numbers as params. A device's NAME is a data text (data/stages.json `devices[].name`, localized by the
|
||||
// data overlay: "Barricade", "'Double Lids'" …), not a msgid.
|
||||
|
||||
import { isObj } from './shared.js';
|
||||
import { t, N_ } from '../../../../shared/i18n.js';
|
||||
@@ -123,3 +125,187 @@ export function terrainInfo(stage, row, col) {
|
||||
else if (tile.groundPassable === true) facts.push(t('地面单位可通过'));
|
||||
return { key, name: t(tip.name), tag: t(tip.tag), row, col, lines: tip.lines(stage.special).filter((s) => typeof s === 'string' && s), facts };
|
||||
}
|
||||
|
||||
// ---- stage device tips (GitHub #228, PR #229 by @rickylxw: the stage DEVICES, not only the tiles) ---------------------
|
||||
|
||||
/** The device roles a tap explains; the rest is invisible (盟约寒风, the 沼泽 / 涨潮 controllers) or not fielded this season. */
|
||||
const DEVICE_TIP_ROLES = Object.freeze(['crate', 'turret', 'platform', 'blower']);
|
||||
/** Roles the battle spawns as device UNITS (Battle._spawnStageDevices, devices.js spawnTurret): in a battle a tap finds them by unit. */
|
||||
const DEVICE_UNIT_ROLES = Object.freeze(['crate', 'turret']);
|
||||
const TIP_TAG = N_('场地装置');
|
||||
const DIR_NAME = Object.freeze({ UP: N_('上'), DOWN: N_('下'), LEFT: N_('左'), RIGHT: N_('右') });
|
||||
|
||||
const round1 = (v) => Math.round(v * 10) / 10;
|
||||
|
||||
/**
|
||||
* What tapping a stage device says — the same contract as TERRAIN_TIPS, but `lines` read the device's own stage entry
|
||||
* (data/stages.json `stage.devices[]`: stats / skill blackboard / dir / rangeTiles), the very numbers the sim runs
|
||||
* (`sim/content/devices.js`, `Battle._spawnStageDevices`), so a tip can never disagree with the battle. The prose is ours
|
||||
* (docs/PLAYING.md wording; PRTS 阻隔工事 / “双眼皮” / 射击台 / 源石流发生装置 and the sim's behaviour). `stats` is the
|
||||
* stat grid under the lines (the turret's), `facts` what the tile allows.
|
||||
*/
|
||||
const DEVICE_TIPS = Object.freeze({
|
||||
crate: {
|
||||
lines: (st, d) => [
|
||||
t('挡在地面上的工事:地面敌人会绕开它走;只有无路可走时才会撞上来,把它摧毁后继续前进'),
|
||||
t('生命 {hp} 点,被摧毁后从场上消失', { hp: param(d.stats?.maxHp, 100) }),
|
||||
],
|
||||
facts: () => [t(BUILDABILITY.NONE)], // board.js buildDeployMap: an active crate takes its tile off the deploy map
|
||||
},
|
||||
turret: {
|
||||
lines: (st, d) => {
|
||||
const bb = isObj(d.skill?.bb) ? d.skill.bb : {};
|
||||
// devices.js spawnTurret: the same blackboard keys and the same `持续N秒` read from the skill text
|
||||
const dur = /持续(\d+(?:\.\d+)?)秒/.exec(String(d.skill?.desc ?? ''));
|
||||
const aspdMax = param(bb.max_attack_speed, Infinity);
|
||||
const fragMax = param(bb.max_damage_scale, Infinity);
|
||||
return [
|
||||
t('自动攻击射程内的一名敌人,造成法术伤害,命中的敌人附加脆弱'),
|
||||
t('按当前层数最高的盟约计算:每 1 层,攻击速度 +{aspd}(至多 +{aspdMax}),附加的脆弱 +{frag}%(至多 +{fragMax}%)', {
|
||||
aspd: param(bb.attack_speed_per_stack, 1),
|
||||
aspdMax: Number.isFinite(aspdMax) ? aspdMax : '∞',
|
||||
frag: round1(param(bb.damage_scale_per_stack, 0.001) * 100),
|
||||
fragMax: Number.isFinite(fragMax) ? round1((fragMax - 1) * 100) : '∞',
|
||||
}),
|
||||
dur ? t('脆弱持续 {sec} 秒', { sec: Number(dur[1]) }) : null,
|
||||
];
|
||||
},
|
||||
stats: (st, d) => {
|
||||
const s = isObj(d.stats) ? d.stats : {};
|
||||
const out = [{ k: t('生命上限'), v: param(s.maxHp, 100) }];
|
||||
if (param(s.atk, 0)) out.push({ k: t('攻击'), v: param(s.atk, 0) });
|
||||
if (param(s.def, 0)) out.push({ k: t('防御'), v: param(s.def, 0) });
|
||||
const sec = param(s.bat, 0) > 0 ? param(s.bat, 0) * 100 / (param(s.aspd, 100) > 0 ? param(s.aspd, 100) : 100) : 0;
|
||||
if (sec) out.push({ k: t('攻击间隔'), v: `${round1(sec)}s` });
|
||||
return out;
|
||||
},
|
||||
facts: () => [t(BUILDABILITY.NONE)],
|
||||
},
|
||||
platform: {
|
||||
lines: () => [
|
||||
t('高台位装置:地面敌人不能走上这一格'),
|
||||
t('远程位干员可以部署在其上;站上去的干员在高位,不阻挡敌人'),
|
||||
],
|
||||
facts: () => [t(BUILDABILITY.RANGED)], // board.js: an active platform makes its tile a 'ranged' deploy tile
|
||||
},
|
||||
blower: {
|
||||
lines: (st, d) => {
|
||||
// devices.js buildTerrain: the device's own skill blackboard, else stage.special.blower.bb; rangeTiles = its own tile + the lane
|
||||
const bb = isObj(d.skill?.bb) ? d.skill.bb : (isObj(st?.blower?.bb) ? st.blower.bb : {});
|
||||
const dir = DIR_NAME[String(d.dir || 'UP').toUpperCase()] || DIR_NAME.UP;
|
||||
const lane = Array.isArray(d.rangeTiles) && d.rangeTiles.length > 1 ? d.rangeTiles.length - 1 : 3;
|
||||
const out = [t('向前方 {n} 格吹出气流(这一台朝{dir})', { n: lane, dir: t(dir) })];
|
||||
const eq = param(bb['blower_s_character[equal].atk'], 0);
|
||||
const op = param(bb['blower_s_character[opposite].atk'], 0);
|
||||
const mods = [];
|
||||
if (eq) mods.push(t('朝向与风向相同的攻击力 {v}', { v: pctText(eq) }));
|
||||
if (op) mods.push(t('相反的 {v}', { v: pctText(op) }));
|
||||
if (mods.length) out.push(t('部署在气流里的干员:{mods}', { mods }));
|
||||
const eqM = param(bb['blower_s_enemy[equal].move_speed'], 0);
|
||||
const opM = param(bb['blower_s_enemy[opposite].move_speed'], 0);
|
||||
const em = [];
|
||||
if (eqM) em.push(t('顺风移动速度 ×{v}', { v: round2(1 + eqM) }));
|
||||
if (opM) em.push(t('逆风 ×{v}', { v: round2(1 + opM) }));
|
||||
if (em.length) out.push(t('在气流里移动的敌人:{mods}', { mods: em }));
|
||||
return out;
|
||||
},
|
||||
facts: () => [t(BUILDABILITY.NONE)],
|
||||
},
|
||||
});
|
||||
const round2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
/** A stage device entry is drawn: `active` when it carries it, else not `hidden` (render/tiles.js _stageDevices, board3d/layout.js stageDevices). */
|
||||
const deviceDrawn = (d) => (typeof d.active === 'boolean' ? d.active : !d.hidden);
|
||||
|
||||
/** The card of stage device `d` standing at (row, col) — `tip` is DEVICE_TIPS[d.role]. */
|
||||
function deviceCard(stage, d, row, col) {
|
||||
const tip = DEVICE_TIPS[d.role];
|
||||
const lines = tip.lines(stage.special, d).filter((s) => typeof s === 'string' && s);
|
||||
const stats = typeof tip.stats === 'function' ? tip.stats(stage.special, d) : null;
|
||||
const name = typeof d.name === 'string' && d.name ? d.name : String(d.role);
|
||||
return {
|
||||
key: d.role, name, tag: t(TIP_TAG), row, col, lines, facts: tip.facts(stage.special, d).filter(Boolean),
|
||||
...(stats && stats.length ? { stats } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The tip a tap on the tile (row, col) opens when a stage DEVICE stands on it (GitHub #228, PR #229), or null: an ordinary
|
||||
* tile — or a device this client does not draw (`active` false: a turret that stays dormant until 机械援助 / a 机变 card
|
||||
* switches it on, a crate such a card removed) — falls through to `terrainInfo`. Visibility mirrors what the renderers draw
|
||||
* (`render/tiles.js _stageDevices`, `board3d/layout.js stageDevices`): `active` when set, else not `hidden`. The stage is
|
||||
* the shown field's (already the player's own `effectiveStage`, so a card-removed crate is not in the way). The device's
|
||||
* name is its data text (localized by the data overlay); the lines are in the current language (t()).
|
||||
* @param {{ devices?: any[], special?: any, rows?: string[], tiles?: Record<string, any> } | null | undefined} stage
|
||||
* @param {number} row board row (row 0 = the bottom row, DESIGN §1)
|
||||
* @param {number} col
|
||||
* @param {{ roles?: readonly string[] }} [opts] `roles`: only these roles answer (default: the four of DEVICE_TIP_ROLES)
|
||||
* @returns {{ key:string, name:string, tag:string, row:number, col:number, lines:string[], facts:string[], stats?:{k:string,v:string|number}[] } | null}
|
||||
*/
|
||||
export function deviceInfo(stage, row, col, { roles = DEVICE_TIP_ROLES } = {}) {
|
||||
const list = Array.isArray(stage?.devices) ? stage.devices : null;
|
||||
if (!list || !Number.isInteger(row) || !Number.isInteger(col)) return null;
|
||||
for (const d of list) {
|
||||
if (!isObj(d) || !Array.isArray(d.pos) || d.pos[0] !== row || d.pos[1] !== col) continue;
|
||||
if (!roles.includes(d.role) || !DEVICE_TIPS[d.role] || !deviceDrawn(d)) continue;
|
||||
return deviceCard(stage, d, row, col);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tip of a tap on (row, col) while a BATTLE shows the field — the live counterpart of `deviceInfo`: crates and “双眼皮”
|
||||
* turrets are device UNITS there (kind 'device', one per drawn stage device, `defId` = the device key), so they are
|
||||
* found by the unit standing on the tile — a turret outside the battle's rect stands on another tile than its stage `pos`
|
||||
* (devices.js deviceTile) — and what the card says comes from the stage entry of that key. The platforms and blowers are no
|
||||
* units: they answer by their stage `pos`, as in the prep.
|
||||
* A destroyed device (HP gone, or no longer in the snapshots once its DIE animation is over) is not there any more: the
|
||||
* tap belongs to the tile under the wreck (null here, so it falls through to `terrainInfo`). Before the first snapshot of the
|
||||
* battle has arrived (`snap` empty) a unit counts as standing.
|
||||
* The result is the same card as `deviceInfo`'s, with `unitId` (the unit, for its live HP: the screen reads `b.snap`
|
||||
* through it, like a unit card's `snapHp`).
|
||||
* @param {object|null|undefined} stage the shown field's stage
|
||||
* @param {number} row @param {number} col
|
||||
* @param {{ units?: any[]|null, snap?: Map<number, any[]>|null }} battle the field's unit infos (m.field.units) and the
|
||||
* latest snapshot tuples by unit id ([id, x, y, hp, maxHp, …])
|
||||
*/
|
||||
export function deviceTipAt(stage, row, col, { units = null, snap = null } = {}) {
|
||||
if (!Number.isInteger(row) || !Number.isInteger(col)) return null;
|
||||
const u = (Array.isArray(units) ? units : []).find((x) => isObj(x) && x.kind === 'device' && Math.round(Number(x.x)) === col && Math.round(Number(x.y)) === row);
|
||||
if (!u) return deviceInfo(stage, row, col, { roles: DEVICE_TIP_ROLES.filter((r) => !DEVICE_UNIT_ROLES.includes(r)) });
|
||||
if (snap && snap.size > 0) {
|
||||
const tuple = snap.get(u.id);
|
||||
if (!Array.isArray(tuple) || !(tuple[3] > 0)) return null;
|
||||
}
|
||||
const list = Array.isArray(stage?.devices) ? stage.devices : [];
|
||||
const same = list.filter((d) => isObj(d) && d.key === u.defId && DEVICE_UNIT_ROLES.includes(d.role));
|
||||
const d = same.find((x) => Array.isArray(x.pos) && x.pos[0] === row && x.pos[1] === col) || same[0];
|
||||
return d ? { ...deviceCard(stage, d, row, col), unitId: u.id } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold the device units a battle shows into `map` (UnitInfo by unit id): the field meta's `units` (what stands when the field
|
||||
* is entered) and the 'spawn' event tuples `['spawn', UnitInfo]` after it — the stage crates and the “双眼皮” turrets come
|
||||
* into being with the battle's first step (`battleStart`), after the meta of a battle shown from its beginning was taken.
|
||||
* Only kind 'device' is kept; `deviceTipAt` reads the map's values.
|
||||
* @param {Map<number, any>} map
|
||||
* @param {{ units?: any[]|null, events?: any[]|null }} [from]
|
||||
*/
|
||||
export function noteDeviceUnits(map, { units = null, events = null } = {}) {
|
||||
for (const u of Array.isArray(units) ? units : []) if (isObj(u) && u.kind === 'device' && u.id != null) map.set(u.id, u);
|
||||
for (const e of Array.isArray(events) ? events : []) if (Array.isArray(e) && e[0] === 'spawn' && isObj(e[1]) && e[1].kind === 'device' && e[1].id != null) map.set(e[1].id, e[1]);
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* The device-unit map after entering a field. A refresh of the same field whose new meta names no device
|
||||
* (the start-of-battle list: crates and turrets arrive as `spawn` and are not repeated) keeps the units
|
||||
* already noted. A meta that names devices replaces the map. A different field does not keep the previous one.
|
||||
* @param {Map<number, any>|null|undefined} previous
|
||||
* @param {Map<number, any>} noted
|
||||
* @param {boolean} sameField
|
||||
*/
|
||||
export function deviceUnitsForEntry(previous, noted, sameField) {
|
||||
if (!(noted instanceof Map) || noted.size > 0 || !sameField) return noted instanceof Map ? noted : new Map();
|
||||
return previous instanceof Map && previous.size > 0 ? previous : noted;
|
||||
}
|
||||
+61
-13
@@ -23,9 +23,9 @@
|
||||
// 准备就绪 is refused while the temp overflow row (临时整备区) holds pieces: the reason shows under the button
|
||||
// (user playtest #3 item 3; the row's own label is ui/underframe.js TempRowNotice).
|
||||
|
||||
import { useRef } from '../../vendor/hooks.module.js';
|
||||
import { useEffect, useRef, useState } from '../../vendor/hooks.module.js';
|
||||
import { PHASE } from '../../../shared/constants.js';
|
||||
import { html, Button, Icon, PingPill, Countdown, Tooltip, MicroLabel, DifficultyTag, useTicker } from './components.js';
|
||||
import { html, Button, Icon, PingPill, Countdown, Tooltip, MicroLabel, DifficultyTag, Modal, useTicker } from './components.js';
|
||||
import { Sprite, LpTower, GIcon, LocalSprite } from './gameComponents.js';
|
||||
import { localAsset } from '../data.js';
|
||||
import { serverNow } from '../store.js';
|
||||
@@ -36,6 +36,45 @@ import { t, tParts, N_ } from '../../../shared/i18n.js';
|
||||
|
||||
const cx = (...p) => p.flat().filter(Boolean).join(' ');
|
||||
|
||||
/**
|
||||
* 观战席 capsule of the in-match top bar (GitHub #120, PR #120 by @salt-fishes; the spectator seats of community report #26):
|
||||
* the room's spectators, which the room screen lists in a strip but the game screen — the route after 开始 — used to hide
|
||||
* completely, so a spectator could only be removed before the match or after it. A small eye + the count beside the latency;
|
||||
* a tap opens the roster, with the host's ✕ on every row (room.removeSpectator: the server takes it at any time; the removed
|
||||
* seat gets room.closed {kicked} and no more frames). Renders nothing while no spectator seat is taken.
|
||||
* @param {{ spectators: any[]|null, myId: any, isHost: boolean, onRemove: ((playerId: any) => any)|null }} props
|
||||
*/
|
||||
export function SpectatorPill({ spectators, myId, isHost, onRemove }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(null);
|
||||
const list = Array.isArray(spectators) ? spectators.filter((s) => s && typeof s === 'object') : [];
|
||||
// the roster closes with its last seat (the pill is gone: it must not pop up again for the next spectator)
|
||||
useEffect(() => { if (!list.length) setOpen(false); }, [list.length]);
|
||||
if (!list.length) return null;
|
||||
const remove = async (playerId) => {
|
||||
if (!onRemove) return;
|
||||
setBusy(playerId);
|
||||
try { await onRemove(playerId); } finally { setBusy(null); }
|
||||
};
|
||||
return html`<${Button} variant="ghost" size="sm" icon="eye" class=${cx('specpill', list.some((s) => s.playerId === myId) && 'is-me')}
|
||||
onClick=${() => setOpen(true)} data-testid="spectators" title=${t('观战席')} aria-label=${t('观战席')}>
|
||||
<span class="specpill__num num">${list.length}</span>
|
||||
<//>
|
||||
${open ? html`<${Modal} open=${true} title=${t('观战席')} micro="SPECTATORS" width="6.4rem" onClose=${() => setOpen(false)}
|
||||
actions=${html`<${Button} variant="secondary" onClick=${() => setOpen(false)}>${t('关闭')}<//>`}>
|
||||
<ul class="spec__roster" data-testid="spectator-roster">
|
||||
${list.map((s) => html`<li key=${s.playerId} class=${cx('spec__row', s.playerId === myId && 'is-me', s.connected === false && 'is-offline')}>
|
||||
<${Icon} name=${s.connected === false ? 'wifiOff' : 'eye'} class="spec__ico" />
|
||||
<span class="spec__name">${s.name || t('博士')}</span>
|
||||
${s.playerId === myId ? html`<span class="seat__you">${t('你')}</span>` : null}
|
||||
${isHost && onRemove ? html`<${Button} variant="ghost" size="sm" square=${true} icon="close" loading=${busy === s.playerId} data-testid="spectator-remove"
|
||||
onClick=${() => remove(s.playerId)} aria-label=${t('移出观战者 {name}', { name: s.name || '' })} title=${t('移出该观战者')} />` : null}
|
||||
</li>`)}
|
||||
</ul>
|
||||
<p class="spec__hint t-lo">${t('观战者不占博士席位,只能观看;创建者可以把观战者移出,被移出的人不再收到战场画面。')}</p>
|
||||
<//>` : null}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase capsule: prep label, kills n/m (combat/unite), kills + boss HP bar (boss rounds).
|
||||
* @param {{ pub:any, hud:any }} props
|
||||
@@ -49,7 +88,7 @@ export function PhaseCapsule({ pub, hud, miss = null }) {
|
||||
const frac = bossFrac(boss);
|
||||
return html`<div class="capsule capsule--boss" role="status">
|
||||
<${Sprite} k="hudPanel/icon_boss" class="capsule__icon" fallback=${html`<${GIcon} name="skull" class="capsule__icon" />`} />
|
||||
${hud?.total != null ? html`<span class="capsule__kills num"><b>${hud.killed ?? 0}</b>/${hud.total}</span>` : null}
|
||||
${hud?.total != null ? html`<span class="capsule__kills num"><b>${hud.resolved ?? hud.killed ?? 0}</b>/${hud.total}</span>` : null}
|
||||
<div class="bossbar" title=${boss ? `${fmtNum(boss.hp)} / ${fmtNum(boss.max)}` : t('敌方领袖')}>
|
||||
<div class="bossbar__fill" style=${`width:${frac == null ? 100 : frac * 100}%`}></div>
|
||||
<span class="bossbar__txt num">${frac == null ? t('敌方领袖') : bossPctText(frac)}</span>
|
||||
@@ -60,7 +99,7 @@ export function PhaseCapsule({ pub, hud, miss = null }) {
|
||||
return html`<div class=${cx('capsule', 'capsule--combat', phase === PHASE.UNITE && 'capsule--unite')} role="status">
|
||||
<${Sprite} k=${phase === PHASE.UNITE ? 'hudPanel/icon_coop' : 'hudPanel/icon_battle'} class="capsule__icon"
|
||||
fallback=${html`<${Icon} name="sword" class="capsule__icon" />`} />
|
||||
<span class="capsule__kills num"><b>${hud?.killed ?? 0}</b>/${hud?.total ?? '--'}</span>
|
||||
<span class="capsule__kills num"><b>${hud?.resolved ?? hud?.killed ?? 0}</b>/${hud?.total ?? '--'}</span>
|
||||
${phase === PHASE.UNITE ? html`<span class="capsule__tag">${t('联防')}</span>` : null}
|
||||
${phase === PHASE.UNITE && Number.isFinite(miss) ? html`<${MissTag} n=${miss} />` : null}
|
||||
</div>`;
|
||||
@@ -207,24 +246,27 @@ export function tempReadyReason(priv) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ready toggle (PREP only). Disabled while the temp row holds pieces — the reason shows under it (not only on hover):
|
||||
* "临时整备区 N 个单位待处理" (user playtest #3 item 3).
|
||||
* Ready toggle (PREP only). Disabled while the temp row holds pieces or a personal choice (教鞭) is open — the reason shows
|
||||
* under it (not only on hover): "临时整备区 N 个单位待处理" (user playtest #3 item 3), "请先完成教鞭选择".
|
||||
* @param {{ priv:any, onToggle:(ready:boolean)=>void, busy?:boolean, readyCount?:number, total?:number }} props
|
||||
*/
|
||||
export function ReadyToggle({ priv, onToggle, busy, readyCount, total }) {
|
||||
const ready = !!priv?.ready;
|
||||
const temp = tempInfo(priv);
|
||||
const reason = !ready ? tempReadyReason(priv) || shopBlockReason('ready', { priv, editable: true }) : null;
|
||||
const choice = !!priv?.personalChoice;
|
||||
const reason = !ready ? (choice ? shopBlockReason('ready', { priv, editable: true }) : tempReadyReason(priv) || shopBlockReason('ready', { priv, editable: true })) : null;
|
||||
const why = !ready && (choice || temp.count > 0);
|
||||
const btn = html`<button type="button" class=${cx('readybtn', 'tapx', ready && 'is-on', busy && 'is-busy')} disabled=${!!reason || busy}
|
||||
aria-pressed=${ready ? 'true' : 'false'} aria-describedby=${!ready && temp.count ? 'readywrap-why' : undefined} onClick=${() => onToggle(!ready)}>
|
||||
aria-pressed=${ready ? 'true' : 'false'} aria-describedby=${why ? 'readywrap-why' : undefined} onClick=${() => onToggle(!ready)}>
|
||||
<span class="readybtn__box">${ready ? html`<${Icon} name="check" />` : null}</span>
|
||||
<span class="readybtn__label">${ready ? t('取消准备') : t('准备就绪')}</span>
|
||||
<kbd class="readybtn__key">${hotkeyLabelOf('ready')}</kbd>
|
||||
</button>`;
|
||||
return html`<div class="readywrap">
|
||||
${reason ? html`<${Tooltip} text=${reason} placement="bottom">${btn}<//>` : btn}
|
||||
${!ready && temp.count ? html`<span class="readywrap__why" id="readywrap-why" role="status" data-testid="ready-why">
|
||||
<${Icon} name="warn" /><span>${tParts('临时整备区 {n} 个单位待处理', { n: html`<b class="num">${temp.count}</b>`, count: temp.count })}</span></span>` : null}
|
||||
${why ? html`<span class="readywrap__why" id="readywrap-why" role="status" data-testid="ready-why">
|
||||
<${Icon} name="warn" />${choice ? html`<span>${reason}</span>`
|
||||
: html`<span>${tParts('临时整备区 {n} 个单位待处理', { n: html`<b class="num">${temp.count}</b>`, count: temp.count })}</span>`}</span>` : null}
|
||||
${Number.isFinite(total) && total > 1 ? html`<span class="readywrap__count">${t('已就绪')} <b class="num">${readyCount}</b>/<span class="num">${total}</span></span>` : null}
|
||||
</div>`;
|
||||
}
|
||||
@@ -306,13 +348,16 @@ export function PauseButton({ paused, busy = false, onToggle }) {
|
||||
* onReady:(r:boolean)=>void, readyBusy?:boolean, readyCount?:number, playerCount?:number,
|
||||
* pen?:boolean, penAvail?:boolean, onPen?:(on:boolean)=>void, config?: any, frozenAt?: number|null,
|
||||
* pause?: { show: boolean, paused: boolean, busy?: boolean, onToggle: () => void } | null,
|
||||
* live?: { pending: number, unite: boolean, left?: number|null } | null }} props
|
||||
* live?: { pending: number, unite: boolean, left?: number|null } | null,
|
||||
* spectators?: any[]|null, myId?: any, isHost?: boolean, onRemoveSpectator?: ((playerId: any) => any)|null }} props
|
||||
* spectators: the room's spectator seats (room.state) — the 观战席 capsule beside the latency (SpectatorPill; the host removes)
|
||||
* frozenAt: the server time every clock shows while the solo match is paused (null = live)
|
||||
* live: the own battle's pending LP loss (liveLp): the tower shows lp − pending in red with a −N tick, 联防中 during 联防;
|
||||
* `left` (a leaker in 联防): its enemies still standing — the capsule's ×N tag
|
||||
*/
|
||||
export function TopBar({ pub, priv, conn, hud, total, drawer, onExit, onDrawer, onReady, readyBusy, readyCount, playerCount, pen = false, penAvail = false, onPen = () => {},
|
||||
config = null, frozenAt = null, pause = null, live = null, spectator = false }) {
|
||||
config = null, frozenAt = null, pause = null, live = null, spectator = false,
|
||||
spectators = null, myId = null, isHost = false, onRemoveSpectator = null }) {
|
||||
const phase = pub?.phase;
|
||||
const boss = isBossPhase(phase);
|
||||
const lp = boss && Number.isFinite(pub?.teamLp) ? pub.teamLp : Number.isFinite(priv?.lp) ? priv.lp : null;
|
||||
@@ -338,7 +383,10 @@ export function TopBar({ pub, priv, conn, hud, total, drawer, onExit, onDrawer,
|
||||
<div class="gtop__left">
|
||||
<${Button} variant="danger" size="lg" square=${true} icon="exit" onClick=${onExit} aria-label=${t('离开')} title=${t('离开 / 暂离')} class="gtop__exit tapx" />
|
||||
<div class="gtop__meta">
|
||||
<${PingPill} ms=${conn?.ping} online=${conn?.status === 'online'} />
|
||||
<div class="gtop__net">
|
||||
<${PingPill} ms=${conn?.ping} online=${conn?.status === 'online'} />
|
||||
<${SpectatorPill} spectators=${spectators} myId=${myId} isHost=${isHost} onRemove=${onRemoveSpectator} />
|
||||
</div>
|
||||
${pub?.difficulty ? html`<${DifficultyTag} difficulty=${pub.difficulty} size="sm" />` : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+21
-5
@@ -23,6 +23,7 @@ import { PACKS_URL, PACK_INDEX_FILE, readPackIndex, langMetaOf } from '../../../
|
||||
import { DEV_BUILD } from '../../../shared/constants.js';
|
||||
import { loadPref, savePref } from '../store.js';
|
||||
import { data } from '../data.js';
|
||||
import { updateRotateHintPwaI18n } from './device.js';
|
||||
import { html } from './components.js';
|
||||
|
||||
/** The switch's own label, in both languages (whoever opens it may not read the current one). */
|
||||
@@ -39,6 +40,8 @@ const uiLoads = new Map();
|
||||
let indexLoad = null;
|
||||
/** Whether the pack index arrived (without it the chain of a pack is taken from its own `_meta` as it loads). */
|
||||
let indexOk = false;
|
||||
/** Only the latest boot or explicit selection may apply its loaded language. */
|
||||
let langRequest = 0;
|
||||
const INDEX_URL = `${PACKS_URL}${PACK_INDEX_FILE}`;
|
||||
|
||||
const defaultFetch = (...a) => globalThis.fetch(...a);
|
||||
@@ -158,6 +161,7 @@ function applyDocument(lang) {
|
||||
doc.documentElement.dataset.lang = lang;
|
||||
doc.documentElement.dataset.script = scriptOf(t('卫戍协议'));
|
||||
doc.title = t('卫戍协议:盟约 · STRONGHOLD PROTOCOL');
|
||||
updateRotateHintPwaI18n(doc);
|
||||
}
|
||||
|
||||
// `{ dn }` params and tName(): Chinese game-data names → the current language (data/i18n/<lang>.json names)
|
||||
@@ -194,20 +198,23 @@ function applyLang(lang) {
|
||||
* @returns {Promise<string>} the language in effect
|
||||
*/
|
||||
export async function initLang() {
|
||||
const request = ++langRequest;
|
||||
wire();
|
||||
applyDocument(getLang());
|
||||
const TIMEOUT = Symbol('timeout');
|
||||
const boot = (async () => {
|
||||
const listed = await loadLangIndex();
|
||||
const { lang, fromUrl } = initialLang(undefined, undefined, { tentative: !listed });
|
||||
if (fromUrl) { savePref(PREF_KEY, lang); stripLangParam(); }
|
||||
if (fromUrl) stripLangParam();
|
||||
if (request !== langRequest) return null;
|
||||
if (fromUrl) savePref(PREF_KEY, lang);
|
||||
if (lang === DEFAULT_LANG) return null;
|
||||
return (await loadLangChain(lang)) ? lang : null;
|
||||
})();
|
||||
const got = await Promise.race([boot, new Promise((r) => setTimeout(() => r(TIMEOUT), BOOT_WAIT_MS))]);
|
||||
if (got === TIMEOUT) {
|
||||
boot.then((lang) => { if (lang && normalizeLang(loadPref(PREF_KEY, null)) === lang) applyLang(lang); });
|
||||
} else if (got) applyLang(got);
|
||||
boot.then((lang) => { if (request === langRequest && lang && normalizeLang(loadPref(PREF_KEY, null)) === lang) applyLang(lang); });
|
||||
} else if (request === langRequest && got) applyLang(got);
|
||||
return getLang();
|
||||
}
|
||||
|
||||
@@ -218,10 +225,12 @@ export async function initLang() {
|
||||
* @returns {Promise<string>} the language in effect
|
||||
*/
|
||||
export async function switchLang(lang) {
|
||||
const request = ++langRequest;
|
||||
wire();
|
||||
const want = normalizeLang(lang) || DEFAULT_LANG;
|
||||
savePref(PREF_KEY, want);
|
||||
if (want !== DEFAULT_LANG && !(await loadLangChain(want))) return getLang();
|
||||
if (request !== langRequest) return getLang();
|
||||
applyLang(want);
|
||||
return getLang();
|
||||
}
|
||||
@@ -290,10 +299,17 @@ export function machineTranslationNote() {
|
||||
export function LangToggle({ class: cls }) {
|
||||
const lang = useLang();
|
||||
const menu = langMenuModel(useLangs(), lang);
|
||||
const pick = (code) => { if (code && code !== getLang()) switchLang(code); };
|
||||
const pick = async (code, select = null) => {
|
||||
if (!code) return;
|
||||
const switched = switchLang(code);
|
||||
const request = langRequest;
|
||||
await switched;
|
||||
// A failed current request keeps the displayed language; stale requests must not reset a newer pending pick.
|
||||
if (select && request === langRequest) select.value = getLang();
|
||||
};
|
||||
if (menu.kind === 'select') {
|
||||
return html`<label class=${`set-seg lang-toggle lang-select${cls ? ` ${cls}` : ''}`} data-testid="lang-toggle">
|
||||
<select aria-label=${SWITCH_LABEL} value=${lang} onChange=${(e) => pick(e.currentTarget.value)}>
|
||||
<select aria-label=${SWITCH_LABEL} value=${lang} onChange=${(e) => pick(e.currentTarget.value, e.currentTarget)}>
|
||||
${menu.items.map((it) => html`<option key=${it.code} value=${it.code} lang=${it.htmlLang} title=${it.title || undefined} selected=${it.on}>${it.label}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
|
||||
+131
-15
@@ -8,8 +8,13 @@
|
||||
// (ModuleRecord: uniEquipId, name, typeName, attr, traitOverride, talentChanges, isDefault) — while the data lacks
|
||||
// them only the default skill / module is offered. The option rules are shared with the server
|
||||
// (shared/protocol.js loadoutOptions / checkLoadout), so a sanitised loadout is always accepted.
|
||||
// 潜能 / 练度 (0.2.2, the owner's decision of 2026-10-08): `ops` = `{ [charId]: { potential?: 1–6, cultivate?: 0–3 } }` —
|
||||
// per operator, so the normal, elite and 自选 forms share them; only values that differ from the defaults (潜能 6,
|
||||
// 精英2 Lv.60) are kept; stored beside the entries (`sp.pref.loadout` = { v: 1, entries, ops }; an older stored loadout
|
||||
// has none = the defaults) and sent with `room.loadout { entries, ops }` (shared/protocol.js checkLoadoutOps).
|
||||
|
||||
import { loadoutOptions, checkLoadout, resolveLoadout, MODULE_NONE, LOADOUT_LIMITS } from '../../../shared/protocol.js';
|
||||
import { loadoutOptions, checkLoadout, checkLoadoutOps, resolveLoadout, MODULE_NONE, LOADOUT_LIMITS } from '../../../shared/protocol.js';
|
||||
import { isPotential, isCultivate, POTENTIAL_DEFAULT, CULTIVATE_DEFAULT } from '../../../shared/potential.js';
|
||||
import { t, N_ } from '../../../shared/i18n.js';
|
||||
|
||||
export { MODULE_NONE };
|
||||
@@ -56,8 +61,95 @@ export function parseStored(raw) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Serialised form for localStorage. */
|
||||
export const toStored = (entries) => ({ v: LOADOUT_VERSION, entries: entries || {} });
|
||||
/**
|
||||
* Parse the stored per-operator 潜能 / 练度 (0.2.2; any junk → {}): structurally valid entries only, defaults dropped.
|
||||
* An older stored loadout (no `ops`) gives {} — every operator at the defaults.
|
||||
* @param {any} raw `{ v, entries, ops }`
|
||||
* @returns {Record<string, { potential?: number, cultivate?: number }>}
|
||||
*/
|
||||
export function parseStoredOps(raw) {
|
||||
const src = isObj(raw) && isObj(raw.ops) ? raw.ops : null;
|
||||
const out = {};
|
||||
if (!src) return out;
|
||||
for (const [id, e] of Object.entries(src)) {
|
||||
if (Object.keys(out).length >= LOADOUT_LIMITS.ops) break;
|
||||
if (UNSAFE_IDS.has(id) || !/^[A-Za-z0-9_\-.:]{1,64}$/.test(id) || !isObj(e)) continue;
|
||||
const x = {};
|
||||
if (isPotential(e.potential) && e.potential !== POTENTIAL_DEFAULT) x.potential = e.potential;
|
||||
if (isCultivate(e.cultivate) && e.cultivate !== CULTIVATE_DEFAULT) x.cultivate = e.cultivate;
|
||||
if (Object.keys(x).length) out[id] = x;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Serialised form for localStorage (`ops`: the per-operator 潜能 / 练度, 0.2.2). */
|
||||
export const toStored = (entries, ops = {}) => ({ v: LOADOUT_VERSION, entries: entries || {}, ops: ops || {} });
|
||||
|
||||
// ---- 潜能 / 练度 (0.2.2) ------------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The effective 潜能 / 练度 of operator `charId` under the stored settings (the defaults for a missing entry or field).
|
||||
* @param {Record<string, any>|null|undefined} ops @param {string|null|undefined} charId
|
||||
* @returns {{ potential: number, cultivate: number, changed: boolean }}
|
||||
*/
|
||||
export function opsOf(ops, charId) {
|
||||
const e = charId && isObj(ops) && Object.hasOwn(ops, charId) && isObj(ops[charId]) ? ops[charId] : null;
|
||||
const potential = e && isPotential(e.potential) ? e.potential : POTENTIAL_DEFAULT;
|
||||
const cultivate = e && isCultivate(e.cultivate) ? e.cultivate : CULTIVATE_DEFAULT;
|
||||
return { potential, cultivate, changed: potential !== POTENTIAL_DEFAULT || cultivate !== CULTIVATE_DEFAULT };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set (part of) one operator's 潜能 / 练度; an entry equal to the defaults is removed. Returns a new map.
|
||||
* @param {Record<string, any>} ops @param {string} charId @param {{ potential?: number, cultivate?: number }} patch
|
||||
*/
|
||||
export function setOps(ops, charId, patch) {
|
||||
if (typeof charId !== 'string' || !charId) return ops;
|
||||
const cur = opsOf(ops, charId);
|
||||
const potential = patch && isPotential(patch.potential) ? patch.potential : cur.potential;
|
||||
const cultivate = patch && isCultivate(patch.cultivate) ? patch.cultivate : cur.cultivate;
|
||||
const out = { ...(ops || {}) };
|
||||
delete out[charId];
|
||||
const e = {};
|
||||
if (potential !== POTENTIAL_DEFAULT) e.potential = potential;
|
||||
if (cultivate !== CULTIVATE_DEFAULT) e.cultivate = cultivate;
|
||||
if (Object.keys(e).length) out[charId] = e;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove one operator's 潜能 / 练度 (恢复默认). */
|
||||
export function resetOps(ops, charId) {
|
||||
if (!ops || !Object.hasOwn(ops, charId)) return ops;
|
||||
const out = { ...ops };
|
||||
delete out[charId];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings to send (`room.loadout.ops`): every stored entry the server would keep for the loaded data (an operator
|
||||
* of the 干员调配 roster or the 自选 owned pool, `isOperator` — shared/protocol.js cultivationCharIds), the rest dropped one
|
||||
* by one; defaults dropped.
|
||||
* @param {Record<string, any>} ops @param {(charId: string) => boolean} isOperator
|
||||
* @returns {Record<string, { potential?: number, cultivate?: number }>}
|
||||
*/
|
||||
export function sanitizeOps(ops, isOperator) {
|
||||
const out = {};
|
||||
for (const [id, e] of Object.entries(ops || {})) {
|
||||
if (Object.keys(out).length >= LOADOUT_LIMITS.ops) break;
|
||||
const one = {};
|
||||
if (isPotential(e?.potential)) one.potential = e.potential;
|
||||
if (isCultivate(e?.cultivate)) one.cultivate = e.cultivate;
|
||||
if (!Object.keys(one).length) continue;
|
||||
const res = checkLoadoutOps({ [id]: one }, isOperator);
|
||||
if (res.ok && res.ops[id]) {
|
||||
const x = {};
|
||||
if (res.ops[id].potential !== POTENTIAL_DEFAULT) x.potential = res.ops[id].potential;
|
||||
if (res.ops[id].cultivate !== CULTIVATE_DEFAULT) x.cultivate = res.ops[id].cultivate;
|
||||
out[id] = x;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- export / import ----------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -71,19 +163,23 @@ export const LOADOUT_EXPORT_KIND = 'stronghold.loadout';
|
||||
export const LOADOUT_IMPORT_MAX_BYTES = 256 * 1024;
|
||||
|
||||
/**
|
||||
* Portable payload of a loadout, as downloaded / copied by 导出.
|
||||
* Portable payload of a loadout, as downloaded / copied by 导出 — with the per-operator 潜能 / 练度 (`ops`, 0.2.2; an
|
||||
* older build reading it ignores the field).
|
||||
* @param {Record<string, any>} entries `room.loadout.entries`
|
||||
* @param {{ now?: number }} [o]
|
||||
* @param {{ now?: number, ops?: Record<string, any> }} [o]
|
||||
*/
|
||||
export function exportPayload(entries, { now = Date.now() } = {}) {
|
||||
export function exportPayload(entries, { now = Date.now(), ops = {} } = {}) {
|
||||
const clean = {};
|
||||
for (const [id, e] of Object.entries(entries || {})) if (isObj(e)) clean[id] = { ...e };
|
||||
const cleanOps = {};
|
||||
for (const [id, e] of Object.entries(ops || {})) if (isObj(e)) cleanOps[id] = { ...e };
|
||||
return {
|
||||
kind: LOADOUT_EXPORT_KIND,
|
||||
v: LOADOUT_VERSION,
|
||||
exportedAt: new Date(Number.isFinite(now) ? now : Date.now()).toISOString(),
|
||||
count: Object.keys(clean).length,
|
||||
entries: clean,
|
||||
ops: cleanOps,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -97,8 +193,10 @@ export function serializeExport(entries, opts) {
|
||||
* `{ [chessId]: { skill, module } }` map all work, as does the serialised text of any of them. Parsing is STRUCTURAL
|
||||
* only — the caller still runs `sanitizeEntries` against the loaded data, because a preset from another season may name
|
||||
* chess / skills / modules this build does not have. `__proto__` / `constructor` keys are skipped (see parseStored).
|
||||
* A payload with `ops` (0.2.2) brings the per-operator 潜能 / 练度 too (`ops` in the result — absent when the payload has
|
||||
* none: an older export leaves the current settings alone); a payload of settings only imports.
|
||||
* @param {any} input payload object or serialised text
|
||||
* @returns {{ ok: true, entries: Record<string, any> } | { ok: false, error: string }}
|
||||
* @returns {{ ok: true, entries: Record<string, any>, ops?: Record<string, any> } | { ok: false, error: string }}
|
||||
*/
|
||||
export function parseImport(input) {
|
||||
let raw = input;
|
||||
@@ -115,8 +213,9 @@ export function parseImport(input) {
|
||||
const kind = typeof raw.kind === 'string' ? raw.kind : null;
|
||||
if (kind && kind !== LOADOUT_EXPORT_KIND) return { ok: false, error: t('这不是干员调配的数据') };
|
||||
const entries = parseStored(raw);
|
||||
if (!Object.keys(entries).length) return { ok: false, error: t('里面没有有效的调配条目') };
|
||||
return { ok: true, entries };
|
||||
const ops = isObj(raw.ops) ? parseStoredOps(raw) : null;
|
||||
if (!Object.keys(entries).length && !(ops && Object.keys(ops).length)) return { ok: false, error: t('里面没有有效的调配条目') };
|
||||
return ops ? { ok: true, entries, ops } : { ok: true, entries };
|
||||
}
|
||||
|
||||
// ---- options & choices ---------------------------------------------------------------------------------------------
|
||||
@@ -281,8 +380,9 @@ export function rosterOf(list) {
|
||||
* @param {Record<string, any>} entries stored loadout (for changedOnly)
|
||||
* @param {(id: string) => any} getChess
|
||||
* @param {(id: string) => any} [getBond] bond lookup (the search also matches bond names)
|
||||
* @param {Record<string, any>|null} [ops] the per-operator 潜能 / 练度 (changedOnly counts them too)
|
||||
*/
|
||||
export function filterRoster(roster, f = {}, entries = {}, getChess = () => null, getBond = () => null) {
|
||||
export function filterRoster(roster, f = {}, entries = {}, getChess = () => null, getBond = () => null, ops = null) {
|
||||
const q = String(f.query || '').trim().toLowerCase();
|
||||
return roster.filter((c) => {
|
||||
if (f.tier && c.tier !== f.tier) return false;
|
||||
@@ -290,7 +390,7 @@ export function filterRoster(roster, f = {}, entries = {}, getChess = () => null
|
||||
if (f.bond && !(Array.isArray(c.bonds) && c.bonds.includes(f.bond))) return false;
|
||||
if (f.changedOnly) {
|
||||
const golden = c.goldenId ? getChess(c.goldenId) : null;
|
||||
if (!effectiveChoice(entries, c, golden).changed) return false;
|
||||
if (!effectiveChoice(entries, c, golden).changed && !opsOf(ops, c.charId).changed) return false;
|
||||
}
|
||||
if (q) {
|
||||
const hay = [c.name, c.appellation, c.subProfessionName, t(PROF_NAME[c.profession]), ...(c.bonds || []).map((b) => getBond(b)?.name)]
|
||||
@@ -302,12 +402,14 @@ export function filterRoster(roster, f = {}, entries = {}, getChess = () => null
|
||||
}
|
||||
|
||||
/** Number of chess whose choice differs from the defaults (only loadout slots of the loaded data count: an entry of a
|
||||
* retired / hidden chess is never sent nor applied). */
|
||||
export function changedCount(entries, getChess) {
|
||||
* retired / hidden chess is never sent nor applied) — with `ops` (0.2.2), also those whose operator's 潜能 / 练度 differ. */
|
||||
export function changedCount(entries, getChess, ops = null, roster = null) {
|
||||
const ids = new Set(Object.keys(entries || {}));
|
||||
if (ops && Object.keys(ops).length && Array.isArray(roster)) for (const c of roster) if (opsOf(ops, c.charId).changed) ids.add(c.chessId);
|
||||
let n = 0;
|
||||
for (const id of Object.keys(entries || {})) {
|
||||
for (const id of ids) {
|
||||
const { base, golden } = recordsOf(id, getChess);
|
||||
if (isLoadoutSlot(base) && base.chessId === id && effectiveChoice(entries, base, golden).changed) n++;
|
||||
if (isLoadoutSlot(base) && base.chessId === id && (effectiveChoice(entries, base, golden).changed || opsOf(ops, base.charId).changed)) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -386,3 +488,17 @@ export function skillTags(rec) {
|
||||
passive,
|
||||
};
|
||||
}
|
||||
|
||||
/** Compact skill preview; SP and duration come from the selected form's generated record. */
|
||||
export function quickSkillTags(rec) {
|
||||
const tags = skillTags(rec);
|
||||
if (!rec) return { ...tags, recovery: '—', duration: '—' };
|
||||
// ON_DEPLOY covers constant passives too. A finite duration distinguishes the deploy-and-expire skills;
|
||||
// some older records carry it only in the blackboard. Never infer it from a localized description.
|
||||
const seconds = Number(rec.duration) > 0 ? Number(rec.duration) : tags.passive ? Number(rec.bb?.duration) : 0;
|
||||
const deployment = tags.passive && seconds > 0;
|
||||
const recovery = deployment ? '—' : tags.passive ? t('被动') : tags.spKind === 'atk' ? t('攻回') : tags.spKind === 'def' ? t('受回') : t('自回');
|
||||
const duration = rec.durationType === 'AMMO' ? t('弹药') : seconds > 0 ? `${seconds}s`
|
||||
: tags.passive ? t('常驻') : Number(rec.duration) < 0 ? '∞' : t('瞬发');
|
||||
return { ...tags, sp: deployment ? t('部署触发') : tags.sp, recovery, duration };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Shared operator stat preview used by roster loadout and DIY selection.
|
||||
import { html, MicroLabel } from './components.js';
|
||||
import { RichText } from './gameComponents.js';
|
||||
import { chessStatsBlock, traitText, chessTalents } from './detailPanel.js';
|
||||
import { chessLoadout } from './gameLogic.js';
|
||||
import { data } from '../data.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
const cx = (...parts) => parts.filter(Boolean).join(' ');
|
||||
const getChessRec = (id) => data.lookup('chess', id);
|
||||
|
||||
/**
|
||||
* What 局内数值 shows (GitHub issue #64): the chess variant — the 精锐 record when asked for and the chess has one, else
|
||||
* the normal one — as the stored loadout makes it. chessLoadout (ui/gameLogic.js) resolves the skill and module the way
|
||||
* the in-match detail card and the sim do (shared/loadoutRecord.js): the elite's chosen module's stats / 特性 / talents
|
||||
* (不装备: the base ones), the chosen skill's passive range; a normal chess has no module, the skill does not change its
|
||||
* stats. Nothing is recomputed here.
|
||||
* @param {any} base normal chess record @param {any} golden its elite record or null
|
||||
* @param {Record<string, any>} entries the stored loadout @param {'normal'|'elite'} level
|
||||
* @param {(id: string) => any} getChess
|
||||
* @param {Record<string, any>|null} [ops] the stored 潜能 / 练度 (0.2.2: the numbers at the operator's settings — the
|
||||
* 练度 multiplier needs effects.json; none set = 潜能 6, 精英2 Lv.60)
|
||||
* @returns {{ elite: boolean, chess: any, lo: any, record: any, trait: string, talents: any[] } | null} null without a record
|
||||
*/
|
||||
export function statsPreview(base, golden, entries, level, getChess, ops = null) {
|
||||
const elite = level === 'elite' && !!golden;
|
||||
const chess = elite ? golden : base;
|
||||
if (!chess) return null;
|
||||
const lo = chessLoadout(chess, entries, getChess, { ops, effects: data.get('effects') });
|
||||
const record = lo?.record || chess;
|
||||
// (the card's own rule: the 特性 line exists when the chess has one; its text follows the chosen module)
|
||||
return { elite, chess, lo, record, trait: chess.trait?.desc ? traitText(chess, !!chess.isGolden, lo) || '' : '', talents: chessTalents(record) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 局内数值: the stats, 攻击范围, 特性 and 天赋 of the selected chess under its chosen skill and module — the detail
|
||||
* card's stats block (ui/detailPanel.js chessStatsBlock) without live numbers, so what a player reads here is what the
|
||||
* shop / board card shows before a battle (not the equipment, bond or skill-cast changes of a running match). The
|
||||
* toggle picks the 普通 or the 精锐 record; 精锐 is the default because the module only exists there.
|
||||
* @param {{ base: any, golden: any, entries: Record<string, any>, level: 'normal'|'elite', onLevel: (l: 'normal'|'elite') => void, getChess?: (id: string) => any }} props
|
||||
*/
|
||||
export function LoadoutStats({ base, golden, entries, level, onLevel, getChess = getChessRec, ops = null }) {
|
||||
const pv = statsPreview(base, golden, entries, level, getChess, ops);
|
||||
if (!pv) return null;
|
||||
// (the caption names 潜能 / 练度 when the numbers carry both — the 练度 multiplier needs effects.json)
|
||||
return html`<section class="lo-sec lo-sec--stats" aria-label=${t('局内数值')} data-variant=${pv.elite ? 'elite' : 'normal'}>
|
||||
<header class="lo-sec__head">
|
||||
<h3>${t('局内数值')}<${MicroLabel}>STATS<//></h3>
|
||||
<div class="lo-seg" role="tablist" aria-label=${t('数值版本')}>
|
||||
<button type="button" role="tab" aria-selected=${pv.elite ? 'false' : 'true'} class=${cx(!pv.elite && 'is-on')} data-variant="normal" onClick=${() => onLevel('normal')}>${t('普通')}</button>
|
||||
<button type="button" role="tab" aria-selected=${pv.elite ? 'true' : 'false'} class=${cx(pv.elite && 'is-on')} data-variant="elite" disabled=${!golden} onClick=${() => onLevel('elite')}>${t('精锐')}</button>
|
||||
</div>
|
||||
</header>
|
||||
${chessStatsBlock({ rec: pv.record, chess: pv.chess })}
|
||||
${pv.trait || pv.talents.length ? html`<div class="lo-minfo lo-minfo--kit">
|
||||
${pv.trait ? html`<div class="lo-minfo__row"><span class="lo-minfo__k">${t('特性')}</span><${RichText} class="lo-minfo__v" text=${pv.trait} /></div>` : null}
|
||||
${pv.talents.map((tal, i) => html`<div key=${i} class="lo-minfo__row"><span class="lo-minfo__k">${t('天赋')}</span>
|
||||
<span class="lo-minfo__v"><b class="lo-minfo__tname">${tal.name}</b><${RichText} text=${tal.descRaw || tal.desc || ''} /></span></div>`)}
|
||||
</div>` : null}
|
||||
<p class="lo-stats__cap">${pv.elite ? t('数值含所选模组;') : golden ? t('普通干员没有模组,所选模组在「精锐」中生效;') : ''}${pv.lo?.cultivation && data.get('effects') ? t('含潜能与练度;') : ''}${t('不含技能发动、装备、盟约等局内加成')}</p>
|
||||
</section>`;
|
||||
}
|
||||
+54
-18
@@ -7,9 +7,9 @@
|
||||
// (called once by main.js) keep the server's copies current — one sync engine (installPrefSync), three settings: after
|
||||
// every `welcome` (new or resumed
|
||||
// session — the server keeps them on the session and on the seat, so joining a room needs no resend) and after every
|
||||
// edit (debounced; a pending edit goes out at once when the overlay closes), they send `room.loadout { entries }`
|
||||
// edit (debounced; a pending edit goes out at once when the overlay closes), they send `room.loadout { entries, ops }`
|
||||
// (sanitised against the loaded data/chess.json: ui/loadoutModel.js sanitizeEntries — a stale entry is dropped, never
|
||||
// the whole loadout), `room.ownership { notOwned }` (sent as stored: the server keeps the droppable chess and drops
|
||||
// the whole loadout; `ops` = the per-operator 潜能 / 练度 of 0.2.2, sanitizeOps against chess.json + backups.json), `room.ownership { notOwned }` (sent as stored: the server keeps the droppable chess and drops
|
||||
// the rest, so no data is needed) and `room.diy { picks }` (sent as stored, structurally clean: the server keeps the
|
||||
// legal picks). Replies: RATE → retried later; WRONG_PHASE / ROOM_STARTED → the running match keeps what it took (the
|
||||
// loadout locks when INFO_CHECK ends; the ownership and the 自选 picks never change during a match) — stored for the
|
||||
@@ -18,7 +18,8 @@
|
||||
|
||||
import { createStore, loadPref, savePref } from '../store.js';
|
||||
import { data } from '../data.js';
|
||||
import { LOADOUT_PREF, parseStored, toStored, sanitizeEntries } from './loadoutModel.js';
|
||||
import { LOADOUT_PREF, parseStored, parseStoredOps, toStored, sanitizeEntries, sanitizeOps } from './loadoutModel.js';
|
||||
import { cultivationCharIds } from '../../../shared/protocol.js';
|
||||
import { OWNERSHIP_PREF, parseStoredOwnership, toStoredOwnership, cleanIds, sanitizeNotOwned } from './ownershipModel.js';
|
||||
import { DIY_PREF, parseStoredDiy, toStoredDiy, cleanPicks, sanitizeDiyPicks } from './diyModel.js';
|
||||
import { toast } from './toasts.js';
|
||||
@@ -30,6 +31,9 @@ export const RETRY_MS = 1500;
|
||||
function readStored() {
|
||||
try { return parseStored(loadPref(LOADOUT_PREF, null)); } catch { return {}; }
|
||||
}
|
||||
function readStoredOps() {
|
||||
try { return parseStoredOps(loadPref(LOADOUT_PREF, null)); } catch { return {}; }
|
||||
}
|
||||
function readStoredOwnership() {
|
||||
try { return parseStoredOwnership(loadPref(OWNERSHIP_PREF, null)); } catch { return []; }
|
||||
}
|
||||
@@ -40,6 +44,7 @@ function readStoredDiy() {
|
||||
/** Loadout + ownership + screen state (separate from the app store: it must survive room / match resets). */
|
||||
export const loadoutStore = createStore({
|
||||
entries: readStored(),
|
||||
ops: readStoredOps(), // 0.2.2 潜能 / 练度: { [charId]: { potential?, cultivate? } } ({} = every operator 潜能 6, 精英2 Lv.60)
|
||||
notOwned: readStoredOwnership(), // 干员持有: base chess ids marked 未持有 (sorted; [] = every operator owned)
|
||||
diy: readStoredDiy(), // 自选编队: { [slotBaseId]: { charId, skillIndex?, uniEquipId? } } ({} = every slot empty)
|
||||
diyKitted: null, // the operators a DIY slot may field (welcome.diyKitted; null before the first welcome)
|
||||
@@ -53,28 +58,46 @@ export const loadoutStore = createStore({
|
||||
diySync: 'idle',
|
||||
});
|
||||
|
||||
/** Replace the stored entries (persisted at once; the sync picks the change up). */
|
||||
/** Replace the stored entries (persisted at once with the settings; the sync picks the change up). */
|
||||
export function setEntries(entries) {
|
||||
const next = entries && typeof entries === 'object' ? entries : {};
|
||||
savePref(LOADOUT_PREF, toStored(next));
|
||||
savePref(LOADOUT_PREF, toStored(next, loadoutStore.get().ops));
|
||||
loadoutStore.set({ entries: next });
|
||||
}
|
||||
|
||||
/** Replace the stored per-operator 潜能 / 练度 (0.2.2; persisted at once with the entries; the sync picks it up). */
|
||||
export function setOpsMap(ops) {
|
||||
const next = ops && typeof ops === 'object' ? ops : {};
|
||||
savePref(LOADOUT_PREF, toStored(loadoutStore.get().entries, next));
|
||||
loadoutStore.set({ ops: next });
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a parsed entry map (an imported preset). Sanitised against the loaded data first, then persisted and synced
|
||||
* like any ordinary edit — so a preset from another build never sends the server an entry it would refuse. An import
|
||||
* that keeps nothing (every chess unknown, or every choice already the default) changes NOTHING: wiping the current
|
||||
* loadout over it would be a loss the player never asked for.
|
||||
* With `ops` (an import that carries the per-operator 潜能 / 练度, 0.2.2: `isOperator` from the loaded data) those are
|
||||
* sanitised and replace the current ones as well; without, the current ones stay.
|
||||
* @param {Record<string, any>} entries `parseImport(...).entries`
|
||||
* @param {(id: string) => any} lookup chess lookup
|
||||
* @returns {{ applied: number, dropped: number }} entries kept / entries that were not imported
|
||||
* @param {{ ops?: Record<string, any>|null, isOperator?: (charId: string) => boolean }} [o]
|
||||
* @returns {{ applied: number, dropped: number, ops?: number }} entries kept / entries (and settings) not imported / settings
|
||||
* kept (only with `ops`)
|
||||
*/
|
||||
export function applyLoadoutEntries(entries, lookup) {
|
||||
export function applyLoadoutEntries(entries, lookup, { ops = null, isOperator = null } = {}) {
|
||||
const asked = Object.keys(entries || {}).length;
|
||||
const clean = sanitizeEntries(entries, lookup);
|
||||
const applied = Object.keys(clean).length;
|
||||
if (applied) setEntries(clean);
|
||||
return { applied, dropped: Math.max(0, asked - applied) };
|
||||
const cleanOps = ops && isOperator ? sanitizeOps(ops, isOperator) : null;
|
||||
const nOps = cleanOps ? Object.keys(cleanOps).length : 0;
|
||||
const askedOps = ops ? Object.keys(ops).length : 0;
|
||||
if (applied || nOps) {
|
||||
if (cleanOps) loadoutStore.set({ ops: cleanOps });
|
||||
setEntries(applied ? clean : loadoutStore.get().entries);
|
||||
}
|
||||
const dropped = Math.max(0, asked - applied) + Math.max(0, askedOps - nOps);
|
||||
return cleanOps ? { applied, dropped, ops: nOps } : { applied, dropped };
|
||||
}
|
||||
|
||||
/** Replace the stored not-owned list (干员持有; persisted at once, the sync picks the change up). */
|
||||
@@ -128,14 +151,17 @@ export function openLoadout(from = 'lobby', sel = null, tab = null) {
|
||||
data.load('assets');
|
||||
data.load('local');
|
||||
data.load('backups');
|
||||
data.load('effects'); // 0.2.2: the 练度 multipliers of the 局内数值 (effects.json CHAR_MAP)
|
||||
data.load('garrisons'); // the 特质 at the top of the detail (PR #301)
|
||||
loadoutStore.set({ open: true, from, ...(sel ? { sel } : {}), ...(tab === 'loadout' || tab === 'ownership' || tab === 'diy' ? { tab } : {}) });
|
||||
}
|
||||
export const closeLoadout = () => loadoutStore.set({ open: false });
|
||||
|
||||
/**
|
||||
* One setting kept in sync with the server (see the header): `key` = the store field, `stateKey` = its sync state field,
|
||||
* `msgType` / `field` = the C2S message, `prepare()` → the payload to send (may await data; null = the data is missing:
|
||||
* nothing is sent, state 'error'), `lockedText` = what a refused edit tells the player.
|
||||
* One setting kept in sync with the server (see the header): `key` = the store field (or a list of them: the loadout's
|
||||
* `entries` and `ops`), `stateKey` = its sync state field, `msgType` / `field` = the C2S message (`field` null: the payload
|
||||
* is the message body), `prepare()` → the payload to send (may await data; null = the data is missing: nothing is sent,
|
||||
* state 'error'), `lockedText` = what a refused edit tells the player.
|
||||
*/
|
||||
function installPrefSync({ net, timers, target, notify, key, stateKey, msgType, field, prepare, lockedText, tag }) {
|
||||
const T = timers || { setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms), clearTimeout: (id) => globalThis.clearTimeout(id) };
|
||||
@@ -177,7 +203,7 @@ function installPrefSync({ net, timers, target, notify, key, stateKey, msgType,
|
||||
pendingJson = json;
|
||||
setState('sending');
|
||||
try {
|
||||
await net.request(msgType, { [field]: payload });
|
||||
await net.request(msgType, field ? { [field]: payload } : payload);
|
||||
if (my !== seq) return;
|
||||
pendingJson = null;
|
||||
lastSent = json;
|
||||
@@ -201,8 +227,9 @@ function installPrefSync({ net, timers, target, notify, key, stateKey, msgType,
|
||||
}
|
||||
|
||||
const offWelcome = net.on('welcome', () => { lastSent = null; pendingJson = null; seq++; schedule(50); });
|
||||
const keys = Array.isArray(key) ? key : [key];
|
||||
const offStore = target.subscribe((s, prev) => {
|
||||
if (s[key] !== prev[key]) { edited = true; schedule(); }
|
||||
if (keys.some((k) => s[k] !== prev[k])) { edited = true; schedule(); }
|
||||
// closing the overlay sends a pending edit at once (review fix): the player's next click — 准备就绪 in the solo
|
||||
// briefing, 开始模拟 in the room — must not overtake the debounced message (the match locks its loadout when
|
||||
// INFO_CHECK ends, so a late edit would silently only apply to the next match). Same socket ⇒ ordered.
|
||||
@@ -229,20 +256,29 @@ function installPrefSync({ net, timers, target, notify, key, stateKey, msgType,
|
||||
* timers?: { setTimeout: Function, clearTimeout: Function }, target?: ReturnType<typeof createStore> }} deps
|
||||
* @returns {{ flush: () => Promise<void>, dispose: () => void }}
|
||||
*/
|
||||
export function installLoadoutSync({ net, getChessReady, lookupChess, timers, target = loadoutStore, notify } = {}) {
|
||||
export function installLoadoutSync({ net, getChessReady, getBackupsReady, lookupChess, operatorIds, timers, target = loadoutStore, notify } = {}) {
|
||||
const ready = getChessReady || (() => data.load('chess'));
|
||||
const readyBackups = getBackupsReady || (() => data.load('backups'));
|
||||
const lookup = lookupChess || ((id) => data.lookup('chess', id));
|
||||
// the operators a 潜能 / 练度 may name (shared/protocol.js cultivationCharIds: the roster + the 自选 owned pool)
|
||||
const opIds = operatorIds || (() => cultivationCharIds(data.get('chess'), data.get('backups')));
|
||||
return installPrefSync({
|
||||
net, timers, target, notify, key: 'entries', stateKey: 'sync', msgType: 'room.loadout', field: 'entries', tag: 'loadout',
|
||||
net, timers, target, notify, key: ['entries', 'ops'], stateKey: 'sync', msgType: 'room.loadout', field: null, tag: 'loadout',
|
||||
lockedText: N_('本局的干员调配已锁定,修改将在下一局生效'),
|
||||
async prepare() {
|
||||
const current = target.get().entries;
|
||||
const ops = target.get().ops;
|
||||
const hasOps = !!ops && Object.keys(ops).length > 0;
|
||||
// an empty loadout needs no data (nothing to sanitise): a player who never opened 干员调配 does not download
|
||||
// chess.json in the lobby just for this
|
||||
if (!current || Object.keys(current).length === 0) return {};
|
||||
if ((!current || Object.keys(current).length === 0) && !hasOps) return { entries: {}, ops: {} };
|
||||
const loaded = await ready();
|
||||
if (loaded == null) return null;
|
||||
return sanitizeEntries(target.get().entries, lookup);
|
||||
const entries = sanitizeEntries(target.get().entries, lookup);
|
||||
if (!hasOps) return { entries, ops: {} };
|
||||
if ((await readyBackups()) == null) return null;
|
||||
const ids = opIds();
|
||||
return { entries, ops: sanitizeOps(target.get().ops, (id) => ids.has(id)) };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { net } from '../net.js';
|
||||
import { store, useStore, shallowEqual, emptyMatch, createStore, isSpectating } from '../store.js';
|
||||
import { GIcon } from './gameComponents.js';
|
||||
import { GuideButton } from './guide.js';
|
||||
import { recordQuit } from './stats.js';
|
||||
import { t, tParts, N_ } from '../../../shared/i18n.js';
|
||||
|
||||
/**
|
||||
@@ -37,18 +38,27 @@ export const awayEnds = (s, prev) => (!!prev?.match?.public && !s?.match?.public
|
||||
store.subscribe((s, prev) => { if (awayStore.get().away && awayEnds(s, prev)) awayStore.set({ away: false }); });
|
||||
|
||||
/**
|
||||
* Leave the match for good (g.leave → room.leave), then drop local room/match state.
|
||||
* Leave the match for good (g.leave → room.leave), then drop local room/match state. The server sends a leaver no
|
||||
* settlement, so the page records the match itself before it is cleared (本机统计, ui/stats.js recordQuit: a 中途退出
|
||||
* entry of the history; it counts only when a round had been cleared) — once the leave went through.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function quitMatch() {
|
||||
const before = store.get();
|
||||
let left = false;
|
||||
try {
|
||||
try { await net.request('g.leave', {}); } catch (err) {
|
||||
if (err?.code !== 'NOT_IN_ROOM' && err?.code !== 'WRONG_PHASE' && err?.code !== 'OFFLINE') throw err;
|
||||
}
|
||||
try { await net.request('room.leave', {}); } catch (err) { if (err?.code !== 'NOT_IN_ROOM' && err?.code !== 'OFFLINE') throw err; }
|
||||
left = true;
|
||||
} catch (err) {
|
||||
toastError(err);
|
||||
} finally {
|
||||
// (a settlement that arrived while the leave was in flight is the match's record already)
|
||||
if (left && !store.get().match.result) {
|
||||
try { recordQuit(before); } catch (err) { console.warn('[stats] quit record failed', err); }
|
||||
}
|
||||
store.set({ room: null, match: emptyMatch() });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Local listening preference, shared by roster and DIY details; deliberately absent from room.loadout.
|
||||
import { html } from './components.js';
|
||||
import { useSettings, updateSettings } from './settings.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
|
||||
const VOICE_LANG_NAMES = { cn: '中文', jp: '日本語' }; // i18n-ignore
|
||||
|
||||
export function OperatorVoice({ charId }) {
|
||||
const settings = useSettings();
|
||||
if (!charId) return null;
|
||||
const value = settings.voiceOverrides[charId] || '';
|
||||
const change = (lang) => {
|
||||
const voiceOverrides = { ...settings.voiceOverrides };
|
||||
if (lang) voiceOverrides[charId] = lang;
|
||||
else delete voiceOverrides[charId];
|
||||
updateSettings({ voiceOverrides });
|
||||
};
|
||||
return html`<label class="lo-voice" data-voice-char=${charId}>
|
||||
<span>${t('此干员语音')}</span>
|
||||
<span class="lo-select"><select aria-label=${t('此干员语音')} value=${value} onChange=${(e) => change(e.currentTarget.value)}>
|
||||
<option value="">${t('跟随全局')}</option><option value="cn">${VOICE_LANG_NAMES.cn}</option><option value="jp">${VOICE_LANG_NAMES.jp}</option>
|
||||
</select></span>
|
||||
<small>${t('仅保存在此浏览器,缺失的日语语音会回退到中文。')}</small>
|
||||
</label>`;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Recover an explicitly selected local seat; nickname and IP never identify a player.
|
||||
import { useEffect, useState } from '../../vendor/hooks.module.js';
|
||||
import { html, Button, Modal } from './components.js';
|
||||
import { identity, net } from '../net.js';
|
||||
import { store } from '../store.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
import { toast } from './toasts.js';
|
||||
|
||||
export function ResumeMatchButton() {
|
||||
const [items, setItems] = useState(() => identity.recoverable());
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
const refresh = () => setItems(identity.recoverable());
|
||||
window.addEventListener('storage', refresh);
|
||||
window.addEventListener('focus', refresh);
|
||||
refresh();
|
||||
return () => { window.removeEventListener('storage', refresh); window.removeEventListener('focus', refresh); };
|
||||
}, []);
|
||||
if (!items.length) return null;
|
||||
const resume = async (item) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
if (await identity.resume(item.id)) {
|
||||
identity.setEntered(true);
|
||||
store.patch('session', { entered: true });
|
||||
// Keep the tentative token in this document until welcome persists it. Reloading here
|
||||
// would either lose the selection or falsely turn it into an established session claim.
|
||||
net.close();
|
||||
net.setName(item.name);
|
||||
net.connect();
|
||||
setOpen(false);
|
||||
setBusy(false);
|
||||
} else {
|
||||
setBusy(false);
|
||||
toast(t('此对局仍在其他窗口中,或当前浏览器无法安全恢复。请关闭原窗口后重试。'), 'warn');
|
||||
}
|
||||
};
|
||||
return html`<${Button} variant="secondary" size="sm" data-testid="resume-local-match" onClick=${() => setOpen(true)}>${t('恢复本机对局')}<//>
|
||||
<${Modal} open=${open} onClose=${() => !busy && setOpen(false)} title=${t('恢复本机对局')}>
|
||||
<p>${t('选择已关闭窗口的对局。服务器重启或对局过期后无法恢复。')}</p>
|
||||
${items.map((item) => html`<${Button} key=${item.id} variant="secondary" block=${true} disabled=${busy} onClick=${() => resume(item)}>
|
||||
${t('{name} · 同盟 {code}', { name: item.name || t('博士'), code: item.code || '—' })}<//>`)}
|
||||
<//>`;
|
||||
}
|
||||
+131
-13
@@ -1,30 +1,59 @@
|
||||
// Player settings (BGM/SFX/voice volume, mute, damage numbers, render quality, the shortcut keys): a tiny observable
|
||||
// store persisted in localStorage (`sp.pref.settings`), applied to the audio manager on every change, plus
|
||||
// the settings modal — which also holds the language switch (ui/lang.js; kept apart in `sp.pref.lang`; under it a note
|
||||
// while the current language's pack is a machine translation, `_meta.machineTranslated`) and the 快捷键
|
||||
// section that rebinds the in-match shortcuts (the key map: ui/gameLogic/shortcuts.js; the community request
|
||||
// 「快捷键可不可以自己设置」, the owner's decision of 2026-10-07).
|
||||
// Player settings (BGM/SFX/voice volume, the voice dub 语音语言, mute, damage numbers, render quality, 文字大小, the
|
||||
// shortcut keys): a tiny observable store persisted in localStorage (`sp.pref.settings`), applied to the audio manager
|
||||
// and to the document on every change, plus the settings modal — which also holds the language switch (ui/lang.js; kept
|
||||
// apart in `sp.pref.lang`; under it a note while the current language's pack is a machine translation,
|
||||
// `_meta.machineTranslated`) and the 快捷键 section that rebinds the in-match shortcuts (the key map:
|
||||
// ui/gameLogic/shortcuts.js; the community request 「快捷键可不可以自己设置」, the owner's decision of 2026-10-07) and
|
||||
// 问题反馈, which copies the diagnostics of this page for a bug report (diag.js: the error log, this browser, optionally
|
||||
// the battle on screen; nothing is uploaded). The lobby and the room open it from a 设置 button next to 玩法说明
|
||||
// (SettingsButton, GitHub #238); the title screen and the match have their own gear.
|
||||
//
|
||||
// 文字大小 (textSize, applied by applyTextSize): the interface text root `--t` of css/theme.css — a phone clamps the
|
||||
// layout root `1rem` at 40 px (theme.css), which left the .18rem body text at 7.2 CSS px while the browser's own font
|
||||
// settings only inflate the glyphs inside fixed boxes (and page zoom is off: index.html's viewport, ui/device.js).
|
||||
// Only font-size declarations read `--t`, so the board, the HUD bands the prep camera keeps clear and the detail
|
||||
// card's side do not move — the field is sized from the host element's clientWidth (render/app.js).
|
||||
|
||||
import { useLayoutEffect, useState } from '../../vendor/hooks.module.js';
|
||||
import { useLayoutEffect, useRef, useState } from '../../vendor/hooks.module.js';
|
||||
import { html, Modal, Button, Icon, MicroLabel } from './components.js';
|
||||
import { createStore, useStore, loadPref, savePref } from '../store.js';
|
||||
import { sanitizeSettings, HOTKEY_ACTIONS, DEFAULT_HOTKEYS, hotkeyLabel, rebindHotkey, isDefaultHotkeys, captureHotkey } from './gameLogic.js';
|
||||
import { GIcon } from './gameComponents.js';
|
||||
import { createStore, useStore, loadPref, savePref, store } from '../store.js';
|
||||
import { sanitizeSettings, HOTKEY_ACTIONS, DEFAULT_HOTKEYS, hotkeyLabel, rebindHotkey, isDefaultHotkeys, captureHotkey, VOICE_LANGS, TEXT_SIZES } from './gameLogic.js';
|
||||
import { audio } from '../audio.js';
|
||||
import { openGuide } from './guide.js';
|
||||
import { detectFeatures } from './device.js';
|
||||
import { LangToggle, machineTranslationNote } from './lang.js';
|
||||
import { t, tc, N_ } from '../../../shared/i18n.js';
|
||||
import { errorCount, currentBattle, diagnosticsText } from '../diag.js';
|
||||
import { copyText } from './clipboard.js';
|
||||
|
||||
const cx = (...p) => p.flat().filter(Boolean).join(' ');
|
||||
|
||||
/** Settings store: { bgm, sfx, voice, muted, damageNumbers, quality, keys }. */
|
||||
/** Settings store: { bgm, sfx, voice, voiceLang, voiceOverrides, muted, damageNumbers, quality, textSize, keys }. */
|
||||
export const settingsStore = createStore(sanitizeSettings(loadPref('settings', null)));
|
||||
|
||||
/**
|
||||
* 设置 →「文字大小」: put the step on <html data-text> — css/theme.css turns it into the text root `--t`
|
||||
* (`:root[data-text="md"] { --t: … }`), which every readable font-size reads; no layout value does. The attribute
|
||||
* (not an inline style) keeps the default in the stylesheet: without it — no JavaScript, an old saved profile, a
|
||||
* value a future version dropped — the page is the design's own sizes. Values outside TEXT_SIZES fall back to 小.
|
||||
* @param {'sm'|'md'|'lg'|'xl'} v
|
||||
*/
|
||||
export function applyTextSize(v) {
|
||||
const el = globalThis.document?.documentElement;
|
||||
if (el) el.dataset.text = TEXT_SIZES.includes(v) ? v : 'sm';
|
||||
}
|
||||
|
||||
settingsStore.subscribe((s) => {
|
||||
savePref('settings', sanitizeSettings(s));
|
||||
audio.setVolumes(s);
|
||||
audio.setVoiceLang(s.voiceLang, s.voiceOverrides);
|
||||
applyTextSize(s.textSize);
|
||||
});
|
||||
audio.setVolumes(settingsStore.get());
|
||||
audio.setVoiceLang(settingsStore.get().voiceLang, settingsStore.get().voiceOverrides);
|
||||
// before the first render (main.js boot renders after its imports ran): the stored step is on screen without a flash
|
||||
applyTextSize(settingsStore.get().textSize);
|
||||
|
||||
/** @param {Partial<ReturnType<typeof sanitizeSettings>>} patch */
|
||||
export function updateSettings(patch) {
|
||||
@@ -60,6 +89,16 @@ function Toggle({ label, micro, value, onChange }) {
|
||||
}
|
||||
|
||||
const QUALITY = [['high', N_('高')], ['medium', N_('中')], ['low', N_('低')]];
|
||||
/**
|
||||
* 文字大小: one step of TEXT_SIZES (ui/gameLogic/settings.js) with its label — 小 is the design's own sizes, the others
|
||||
* raise the text root `--t` (css/theme.css) and with it every readable font-size; the board and the HUD's boxes stay.
|
||||
*/
|
||||
const TEXT_SCALES = [['sm', N_('小')], ['md', N_('中')], ['lg', N_('大')], ['xl', N_('特大')]];
|
||||
/**
|
||||
* 语音语言: each dub named in its own language, like the interface language switch (ui/lang.js) — the owner's
|
||||
* 「中文 / 日本語」 (2026-10-08); VOICE_LANGS order.
|
||||
*/
|
||||
const VOICE_LANG_NAMES = { cn: '中文', jp: '日本語' }; // i18n-ignore
|
||||
/** The rebindable shortcuts' names (msgids), by action. */
|
||||
const HOTKEY_NAMES = { refresh: N_('刷新商店'), freeze: N_('冻结 / 解冻商店'), levelUp: N_('升级调度中心'), retreat: N_('撤退选中干员'),
|
||||
sell: N_('出售选中干员'), ready: N_('准备就绪 / 暂停(独立模拟)') };
|
||||
@@ -144,6 +183,55 @@ function HotkeySection({ keys, touchUi }) {
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** Where a report goes: the upstream issue tracker (shown as text the player can select; a link may open nothing). */
|
||||
export const ISSUES_URL = 'https://github.com/sganggs/Stronghold-Protocol/issues';
|
||||
|
||||
/**
|
||||
* 问题反馈: copy the diagnostics of this page (diag.js) for a GitHub issue — the errors recorded since the page opened,
|
||||
* this browser and device, where the player is, and, switched on by default while a battle is on screen, that battle's
|
||||
* spec (the dev tools replay it). Player names, the room code and the token are replaced; nothing is uploaded. Laid out
|
||||
* like 快捷键 above it (a head with its button, a hint, the result line); the battle switch is the settings' Toggle, and
|
||||
* when the clipboard refuses (some in-app browsers), the report is shown selected in a box styled like 干员调配's 导出.
|
||||
*/
|
||||
/** The result line of 复制诊断信息, by outcome (msgids: translated when shown, so a language switch reaches it). */
|
||||
const DIAG_NOTES = { copied: N_('已复制诊断信息,可以粘贴到 GitHub issue 中'), refused: N_('无法写入剪贴板,请手动复制下面的内容') };
|
||||
|
||||
function DiagSection() {
|
||||
const [attach, setAttach] = useState(true);
|
||||
const [note, setNote] = useState(null); // 'copied' | 'refused' | null: the result line
|
||||
const [manual, setManual] = useState(null); // the report, when the clipboard refused it
|
||||
const boxRef = useRef(null);
|
||||
// the box opens selected for a manual copy, scrolled to its first line (select() leaves it at the end)
|
||||
useLayoutEffect(() => {
|
||||
const el = boxRef.current;
|
||||
if (manual && el) { el.focus(); el.select(); el.scrollTop = 0; }
|
||||
}, [manual]);
|
||||
const n = errorCount();
|
||||
const battle = currentBattle();
|
||||
const copy = async () => {
|
||||
const text = diagnosticsText({ state: store.get(), settings: settingsStore.get(), attachBattle: attach && !!battle });
|
||||
const ok = await copyText(text);
|
||||
setManual(ok ? null : text);
|
||||
setNote(ok ? 'copied' : 'refused');
|
||||
};
|
||||
return html`<section class="set-diag" aria-labelledby="set-diag-title">
|
||||
<div class="set-keys__head">
|
||||
<span class="set-row__label" id="set-diag-title">${t('问题反馈')}<${MicroLabel}>DIAGNOSTICS<//></span>
|
||||
<${Button} variant="ghost" size="sm" icon="copy" class="set-diag__copy" data-testid="diag-copy" onClick=${copy}>${t('复制诊断信息')}<//>
|
||||
</div>
|
||||
<p class="set-hint">${t('遇到问题时,复制诊断信息并粘贴到 GitHub issue 中,开发者就能看到出错时的情况。诊断信息只在本机生成,不会自动上传;玩家名和房间号会被替换。')}</p>
|
||||
<div class="set-diag__meta">
|
||||
<span class="set-diag__stat">${t('已记录的错误')}<b class=${cx('set-diag__count num', n > 0 && 'is-warn')} data-testid="diag-count">${n}</b></span>
|
||||
<span class="set-diag__url">${ISSUES_URL.replace(/^https:\/\//, '')}</span>
|
||||
</div>
|
||||
${battle ? html`<${Toggle} label=${t('附上本场战斗')} micro="BATTLE DATA" value=${attach} onChange=${setAttach} />
|
||||
<p class="set-hint set-diag__battle-hint">${t('开发者可以用附上的战斗数据重现这场战斗。')}</p>` : null}
|
||||
${note ? html`<p class=${cx('set-keys__note', note === 'refused' && 'is-warn')} role="status" aria-live="polite">${t(DIAG_NOTES[note])}</p>` : null}
|
||||
${manual ? html`<textarea ref=${boxRef} class="set-diag__text" data-testid="diag-text" spellcheck=${false} readOnly
|
||||
aria-label=${t('诊断信息')} value=${manual}></textarea>` : null}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings modal.
|
||||
* @param {{ open: boolean, onClose: Function }} props
|
||||
@@ -154,8 +242,8 @@ export function SettingsModal({ open, onClose }) {
|
||||
const [touchUi] = useState(() => detectFeatures().coarse && !detectFeatures().fine);
|
||||
const mtNote = machineTranslationNote(); // a pack marked as machine translation says so under the switch
|
||||
return html`<${Modal} open=${open} onClose=${onClose} title=${t('设置')} micro="SETTINGS" width="7.4rem"
|
||||
actions=${html`<${Button} variant="secondary" icon="book" class="set-guide" onClick=${() => openGuide(0)}>${t('玩法说明')}<//>
|
||||
<${Button} variant="primary" icon="check" onClick=${onClose}>${t('完成')}<//>`}>
|
||||
actions=${html`<${Button} variant="secondary" icon="book" class="set-guide" onClick=${() => openGuide(0)}>${t('玩法说明')}<//>
|
||||
<${Button} variant="primary" icon="check" onClick=${onClose}>${t('完成')}<//>`}>
|
||||
<div class="set-list">
|
||||
<div class="set-row">
|
||||
<span class="set-row__label">${t('语言')}<${MicroLabel}>LANGUAGE<//></span>
|
||||
@@ -164,8 +252,15 @@ export function SettingsModal({ open, onClose }) {
|
||||
${mtNote ? html`<p class="set-hint set-lang-note" data-testid="lang-mt-note">${mtNote}</p>` : null}
|
||||
<${Slider} label=${t('背景音乐')} micro="BGM" icon="play" value=${s.bgm} onInput=${(v) => updateSettings({ bgm: v })} />
|
||||
<${Slider} label=${t('干员语音')} micro="VOICE" icon="mic" value=${s.voice} onInput=${(v) => updateSettings({ voice: v })} />
|
||||
<div class="set-row">
|
||||
<span class="set-row__label">${t('语音语言')}<${MicroLabel}>VOICE LANGUAGE<//></span>
|
||||
<div class="set-seg" role="radiogroup" aria-label=${t('语音语言')} data-testid="voice-lang">
|
||||
${VOICE_LANGS.map((id) => html`<button key=${id} type="button" role="radio" aria-checked=${s.voiceLang === id ? 'true' : 'false'}
|
||||
lang=${id === 'jp' ? 'ja' : 'zh'} class=${s.voiceLang === id ? 'is-on' : ''} onClick=${() => updateSettings({ voiceLang: id })}>${VOICE_LANG_NAMES[id]}</button>`)}
|
||||
</div>
|
||||
</div>
|
||||
<${Slider} label=${t('音效')} micro="SFX" icon="signal" value=${s.sfx}
|
||||
onInput=${(v) => { updateSettings({ sfx: v }); if (!tested) { setTested(true); setTimeout(() => setTested(false), 400); audio.sfx('click'); } }} />
|
||||
onInput=${(v) => { updateSettings({ sfx: v }); if (!tested) { setTested(true); setTimeout(() => setTested(false), 400); audio.sfx('click'); } }} />
|
||||
<${Toggle} label=${t('静音')} micro="MUTE" value=${s.muted} onChange=${(v) => updateSettings({ muted: v })} />
|
||||
<${Toggle} label=${t('显示伤害数字')} micro="DAMAGE NUMBERS" value=${s.damageNumbers} onChange=${(v) => updateSettings({ damageNumbers: v })} />
|
||||
<div class="set-row">
|
||||
@@ -175,8 +270,31 @@ export function SettingsModal({ open, onClose }) {
|
||||
class=${s.quality === id ? 'is-on' : ''} onClick=${() => updateSettings({ quality: id })}>${t(label)}</button>`)}
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<span class="set-row__label">${t('文字大小')}<${MicroLabel}>TEXT SIZE<//></span>
|
||||
<div class="set-seg set-textsize" role="radiogroup" aria-label=${t('文字大小')} data-testid="text-size">
|
||||
${TEXT_SCALES.map(([id, label]) => html`<button key=${id} type="button" role="radio" aria-checked=${s.textSize === id ? 'true' : 'false'}
|
||||
class=${s.textSize === id ? 'is-on' : ''} onClick=${() => updateSettings({ textSize: id })}>${t(label)}</button>`)}
|
||||
</div>
|
||||
</div>
|
||||
<p class="set-hint set-textsize-note">${t('调整界面文字大小,棋盘保持原比例。')}</p>
|
||||
<${HotkeySection} keys=${s.keys} touchUi=${touchUi} />
|
||||
<${DiagSection} />
|
||||
<p class="set-hint">${touchUi ? t('触屏操作:点击单位选中(撤退 / 出售)· 长按单位或卡牌查看详情 · 拖动部署后滑动选择朝向') : t('右键查看详情')}</p>
|
||||
</div>
|
||||
<//>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 设置 button of the lobby and the room (GitHub #238 — before it the settings were reachable only from the title
|
||||
* screen and a running match): the twin of the 玩法说明 button (ui/guide.js GuideButton), with the settings modal behind it
|
||||
* (mounted only while open). The same modal as the title screen's and the match's: nothing in it is match-only.
|
||||
* `square`: the gear alone (the lobby's top bar), the name stays title / aria-label — like GuideButton's.
|
||||
* @param {{ class?: string, size?: 'sm'|'md'|'lg'|'xl', variant?: string, label?: string, square?: boolean }} props
|
||||
*/
|
||||
export function SettingsButton({ class: cls, size = 'sm', variant = 'ghost', label = t('设置'), square = false }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return html`<${Button} variant=${variant} size=${size} square=${square} class=${cx('settings-btn', cls)} onClick=${() => setOpen(true)}
|
||||
title=${t('设置')} aria-label=${t('设置')} data-testid="settings-btn"><${GIcon} name="gear" class="btn__icon" />${square ? null : label}<//>
|
||||
${open ? html`<${SettingsModal} open=${true} onClose=${() => setOpen(false)} />` : null}`;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// A server-owned unanimous vote. Reconnects render the current vote from m.public.
|
||||
import { useRef, useState } from '../../vendor/hooks.module.js';
|
||||
import { html, Button } from './components.js';
|
||||
import { actions } from './gameActions.js';
|
||||
import { useStore } from '../store.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
|
||||
export function SetupReroll({ pub }) {
|
||||
const myId = useStore((s) => s.me.playerId);
|
||||
const hostId = useStore((s) => s.room?.hostId);
|
||||
const online = useStore((s) => s.connection.status === 'online');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const pending = useRef(false);
|
||||
const vote = pub.rerollVote;
|
||||
const host = myId === hostId;
|
||||
const players = pub.players || [];
|
||||
const me = players.find((p) => p.playerId === myId && p.status !== 'left');
|
||||
const allConnected = players.every((p) => p.isBot || p.status === 'left' || p.connected);
|
||||
const voter = !!vote?.voters.includes(myId);
|
||||
const agreed = !!vote?.agreed.includes(myId);
|
||||
const send = async (fn) => {
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setBusy(true);
|
||||
try { await fn(); } finally { pending.current = false; setBusy(false); }
|
||||
};
|
||||
if (!vote && (!host || !me)) return null;
|
||||
return html`<section class="brief-reroll" aria-label=${t('重刷本局')} aria-live="polite">
|
||||
<div class="brief-reroll__text">
|
||||
<strong>${vote ? t('重刷本局投票:{agreed}/{total}', { agreed: vote.agreed.length, total: vote.voters.length }) : t('重刷本局')}</strong>
|
||||
<span>${vote ? t('全员同意后重新随机战场、领袖、特训敌人和禁用;确认倒计时已暂停。') : t('保留房间和个人配置,重新随机全部开局信息。')}</span>
|
||||
${vote ? html`<div class="brief-reroll__players">${vote.voters.map((id) => {
|
||||
const p = players.find((p) => p.playerId === id);
|
||||
return html`<span key=${id} class=${vote.agreed.includes(id) ? 'is-agreed' : ''}>${p?.name || id} · ${vote.agreed.includes(id) ? t('已同意') : t('待同意')}</span>`;
|
||||
})}</div>` : null}
|
||||
</div>
|
||||
<div class="brief-reroll__actions">
|
||||
${!vote ? html`<${Button} icon="refresh" size="lg" loading=${busy} disabled=${!online || !allConnected}
|
||||
title=${allConnected ? t('全体真人玩家一致同意后刷新,随机结果可能重复。') : t('请等待所有玩家连接后再发起投票')}
|
||||
onClick=${() => send(() => actions.rerollSetup(pub.setupRevision ?? 0))}>${t('重刷本局')}<//>` : null}
|
||||
${vote && voter ? html`<${Button} variant="primary" loading=${busy} disabled=${!online || agreed}
|
||||
onClick=${() => send(() => actions.rerollVote(vote.id, true))}>${agreed ? t('已同意') : t('同意重刷')}<//>
|
||||
<${Button} variant="danger" disabled=${busy || !online}
|
||||
onClick=${() => send(() => actions.rerollVote(vote.id, false))}>${t('拒绝重刷')}<//>` : null}
|
||||
${vote && host && me ? html`<${Button} disabled=${busy || !online}
|
||||
onClick=${() => send(() => actions.cancelReroll(vote.id))}>${t('取消投票')}<//>` : null}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
+30
-8
@@ -57,6 +57,14 @@ export function mergeHint(priv, chessId) {
|
||||
return mergeTarget(priv, chessId, LOOKUPS.getChess) ? t('精锐干员将出现在作战区原位置') : t('精锐干员将进入整备区');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a shop card shows its frost: its own slot's `frozen` (m.private shop.slots[i].frozen) — the 冻结 toggle copies onto
|
||||
* every unsold slot, and 梓兰's 猎头顾问 freezes ONE copied card with every active refresh while the toggle stays off
|
||||
* (GitHub #354: the bar drew only the toggle, so the frozen card showed no frost) — or the toggle itself (a frame without
|
||||
* per-slot flags). The 冻结 button and the bar's frame keep following the toggle alone.
|
||||
*/
|
||||
export const slotFrozen = (slot, toggle = false) => !!slot?.frozen || !!toggle;
|
||||
|
||||
/** The armed (first-tapped) card's confirm strip: 确认购买 / 确认选择, or 无法购买 + why. */
|
||||
function ArmedTag({ reason, free }) {
|
||||
if (reason) return html`<span class="scard__confirm is-no" role="status"><b>${t('无法购买')}</b><small>${reason}</small></span>`;
|
||||
@@ -84,7 +92,7 @@ export function ChessCard({ slot, idx, priv, frozen = false, reason = null, free
|
||||
const willMerge = !!hint;
|
||||
const bonds = Array.isArray(c?.bonds) ? c.bonds : [];
|
||||
const disabled = !!reason;
|
||||
const lo = si ? standInLoadout(si, LOOKUPS.getChess, data.get('backups')) : c ? chessLoadout(c, priv?.loadout, dr ? diyGetter(LOOKUPS.getChess, priv, diyData) : LOOKUPS.getChess) : null;
|
||||
const lo = si ? standInLoadout(si, LOOKUPS.getChess, data.get('backups')) : c ? chessLoadout(c, priv?.loadout, dr ? diyGetter(LOOKUPS.getChess, priv, diyData) : LOOKUPS.getChess, { ops: priv?.ops ?? null, effects: data.get('effects') }) : null;
|
||||
const tap = () => { if (onTap) onTap(idx); else if (!disabled) onBuy(idx); else onDetail(slot.id, 'chess', hint); };
|
||||
const name = `${c?.name || t('干员')}${si ? t('({note})', { note: standInForText(c0.name) }) : ''}`;
|
||||
const card = html`<button type="button" class=${cx('scard', `scard--t${tier}`, frozen && 'is-frozen', disabled && 'is-disabled', willMerge && 'is-merge', armed && 'is-armed', si && 'is-standin')}
|
||||
@@ -175,6 +183,17 @@ function SoldCard({ item = false }) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slot with no card in it: the one a 调度中心 upgrade has just opened (a `null` slot — server/match/player/economy.js
|
||||
* _openLevelSlots; GitHub #332 / PR #333: the official shop shows the new slot, empty, until the next refresh or round
|
||||
* start fills it). Never 已招募 / SOLD OUT: nothing was bought there.
|
||||
*/
|
||||
function EmptyCard({ item = false }) {
|
||||
// `scard--sold` too: the same inert frame (no hover lift, not a buyable card for every `:not(.scard--sold)` rule); `scard--empty` only restyles it
|
||||
return html`<div class=${cx('scard', 'scard--sold', 'scard--empty', item && 'scard--item')} role="img" aria-label=${t('空栏位:刷新或下回合开始时补满')}
|
||||
title=${t('空栏位:刷新或下回合开始时补满')}></div>`;
|
||||
}
|
||||
|
||||
function LevelCard({ shop, reason, armed = false, onTap }) {
|
||||
const lv = shop?.level ?? 1;
|
||||
const max = lv >= (shop?.maxLevel ?? 6);
|
||||
@@ -196,7 +215,7 @@ function LevelCard({ shop, reason, armed = false, onTap }) {
|
||||
export const armKey = (kind, idx, slot) => `${kind}:${idx}:${slot?.id ?? ''}`;
|
||||
|
||||
/**
|
||||
* The slot an armed key names (`c` / `i` shop slots, `r` reward slots), or null ('lv', nothing armed, a stale key).
|
||||
* The slot an armed key names (`c` / `i` shop slots, `r` reward slots), or null (a level card, nothing armed, a stale key).
|
||||
* @param {string|null} key
|
||||
* @param {any[]} slots the shop's slots
|
||||
* @param {any[]|null} rewardSlots the shown reward offer's slots
|
||||
@@ -288,10 +307,12 @@ export function ShopBar({ priv, editable, collapsed, onCollapse, onBuy, onLevel,
|
||||
const free = Number(shop.freeRefreshes) || 0;
|
||||
const showReward = !!(reward && Array.isArray(reward.slots) && reward.slots.length);
|
||||
|
||||
// A completed upgrade changes the level, so its confirmation cannot carry into the next upgrade.
|
||||
const levelKey = `lv:${shop.level ?? 1}`;
|
||||
// two-tap: the keys that may stay armed right now
|
||||
const keys = new Set();
|
||||
if (!collapsed) {
|
||||
if (!lvReason) keys.add('lv');
|
||||
if (!lvReason) keys.add(levelKey);
|
||||
slots.forEach((s, i) => { if (s && !s.sold) keys.add(armKey(s.kind === 'item' ? 'i' : 'c', i, s)); });
|
||||
if (showReward) reward.slots.forEach((s, i) => { if (s && !s.sold) keys.add(armKey('r', i, s)); });
|
||||
}
|
||||
@@ -312,7 +333,7 @@ export function ShopBar({ priv, editable, collapsed, onCollapse, onBuy, onLevel,
|
||||
buy(idx);
|
||||
};
|
||||
const tapLevel = () => {
|
||||
if (armed !== 'lv') { setArmed('lv'); return; }
|
||||
if (armed !== levelKey) { setArmed(levelKey); return; }
|
||||
setArmed(null);
|
||||
onLevel();
|
||||
};
|
||||
@@ -341,14 +362,15 @@ export function ShopBar({ priv, editable, collapsed, onCollapse, onBuy, onLevel,
|
||||
</button>
|
||||
</div>
|
||||
<div class="shopbar__row">
|
||||
<${LevelCard} shop=${shop} reason=${lvReason} armed=${armed === 'lv'} onTap=${tapLevel} />
|
||||
<${LevelCard} shop=${shop} reason=${lvReason} armed=${armed === levelKey} onTap=${tapLevel} />
|
||||
${showReward ? html`<${RewardCards} offer=${reward} priv=${priv} editable=${editable} onPick=${onReward} onDetail=${onDetail} onLater=${onRewardLater}
|
||||
armed=${armed} onTap=${tapCard} offBonds=${offBonds} />`
|
||||
: html`<div class="shopbar__cards">
|
||||
${chessSlots.map(({ s, i }) => {
|
||||
if (!s || s.sold) return html`<${SoldCard} key=${`s${i}`} />`;
|
||||
if (!s) return html`<${EmptyCard} key=${`e${i}`} />`;
|
||||
if (s.sold) return html`<${SoldCard} key=${`s${i}`} />`;
|
||||
const reason = shopBlockReason('buy', { priv, editable, slot: s, ...LOOKUPS });
|
||||
return html`<${ChessCard} key=${`c${i}:${s.id}`} slot=${s} idx=${i} priv=${priv} frozen=${frozen} onBuy=${onBuy} onDetail=${onDetail} offBonds=${offBonds}
|
||||
return html`<${ChessCard} key=${`c${i}:${s.id}`} slot=${s} idx=${i} priv=${priv} frozen=${slotFrozen(s, frozen)} onBuy=${onBuy} onDetail=${onDetail} offBonds=${offBonds}
|
||||
reason=${reason} armed=${armed === armKey('c', i, s)} onTap=${editable ? (idx) => tapCard('c', idx, s, 'chess', reason, onBuy) : null} />`;
|
||||
})}
|
||||
</div>`}
|
||||
@@ -357,7 +379,7 @@ export function ShopBar({ priv, editable, collapsed, onCollapse, onBuy, onLevel,
|
||||
? itemSlots.map(({ s, i }) => {
|
||||
if (s.sold) return html`<${SoldCard} key=${`is${i}`} item=${true} />`;
|
||||
const reason = shopBlockReason('buy', { priv, editable, slot: s, ...LOOKUPS });
|
||||
return html`<${ItemCard} key=${`i${i}:${s.id}`} slot=${s} idx=${i} frozen=${frozen} onBuy=${onBuy} onDetail=${onDetail} reason=${reason}
|
||||
return html`<${ItemCard} key=${`i${i}:${s.id}`} slot=${s} idx=${i} frozen=${slotFrozen(s, frozen)} onBuy=${onBuy} onDetail=${onDetail} reason=${reason}
|
||||
armed=${armed === armKey('i', i, s)} onTap=${editable ? (idx) => tapCard('i', idx, s, 'item', reason, onBuy) : null} />`;
|
||||
})
|
||||
: html`<${SoldCard} item=${true} />`}
|
||||
|
||||
@@ -0,0 +1,744 @@
|
||||
// Local match statistics: every match the local player took part in is appended as one record to localStorage
|
||||
// (`sp.pref.stats`). Per-browser only — the server keeps matches in memory and has no identity, so there is nowhere
|
||||
// else for cross-match numbers to live; nothing here is ever sent anywhere. The stats page labels itself 本机数据 and
|
||||
// offers JSON export / import for moving between devices. (Ported from PR #323 by @2321Robin, reworked for 0.2.2.)
|
||||
//
|
||||
// Two kinds of record (`end`):
|
||||
// 'settled' the match reached its settlement: m.result arrived (server/match/results.js buildResult). The record
|
||||
// keeps what the settlement offers — the match frame (difficulty, mode, boss, seed, duration, hidden-core
|
||||
// outcome, reason) and one row per player (band, title, lineup, bonds, the stat block) — so the page can
|
||||
// re-view the settlement screen (recordToResult).
|
||||
// 'quit' the player gave up (放弃模拟) before the settlement; the server sends a leaver nothing, so the record is
|
||||
// built from what the client knew at that moment (buildQuitRecord): the frame, the player's own row, the
|
||||
// rounds cleared. It is listed in the history, marked 中途退出, and cannot be re-viewed.
|
||||
//
|
||||
// What counts (countsTowardStats, the owner's decision of 2026-10-08: a match entered and left right away must not
|
||||
// count): every aggregate — games, wins, win rate, hidden core, best round, time played, the strategy table, titles
|
||||
// and the combat totals — is taken over the records that count. A settled record always counts. A quit record counts
|
||||
// once at least one of the player's own battles had finished — a round cleared (the server's rule: leaving while
|
||||
// round k runs has passed k − 1 rounds, leaving in its settlement k) or already eliminated. A match left earlier is
|
||||
// history only.
|
||||
//
|
||||
// Bounded storage: at most MAX_RECORDS matches and MAX_CHARS characters of JSON. Only the newest FULL_KEEP records
|
||||
// keep their full rows (lineups, bonds, teammates' names — what the settlement replay needs); older ones are compacted
|
||||
// to the player's own summary row, which is all the aggregates read. The oldest records go first when a budget is hit,
|
||||
// and a write the browser refuses shrinks the list further instead of failing. Teammates' display names are part of
|
||||
// the newest records and of an export file: they stay on this device unless the player exports them.
|
||||
//
|
||||
// Format evolution: the envelope carries a version (`STATS_VERSION`); `migrateStats` walks records through a chain of
|
||||
// per-version steps and every loaded / imported record passes `normalizeRecord`, a strict schema: missing fields get
|
||||
// defaults, unknown fields and oversized values are dropped, a row it cannot salvage is dropped. An envelope from a
|
||||
// NEWER version than this build is refused (never downgraded and written back); an unreadable one is set aside
|
||||
// (`sp.pref.stats.damaged`) and the history starts again.
|
||||
//
|
||||
// Pure logic, no Preact / DOM: Node-testable (test/ui/stats.test.js); localStorage is touched only by loadStats /
|
||||
// saveStats / their helpers.
|
||||
|
||||
import { PHASE } from '../../../shared/constants.js';
|
||||
|
||||
/** Current record-envelope version (bump + add a MIGRATIONS step when the record shape changes). */
|
||||
export const STATS_VERSION = 1;
|
||||
/** localStorage key under the app's `sp.pref.` prefix (store.js loadPref). */
|
||||
export const STATS_PREF_KEY = 'stats';
|
||||
/** Oldest records are dropped beyond this many matches. */
|
||||
export const MAX_RECORDS = 1000;
|
||||
/** The newest records that keep their full rows (lineups, bonds, teammates) — what the settlement replay reads. */
|
||||
export const FULL_KEEP = 30;
|
||||
/** Budget of the stored JSON in characters (a character costs up to 2 bytes of the browser's ~5 MB quota): the oldest records go first. */
|
||||
export const MAX_CHARS = 800_000;
|
||||
/** Largest export file the page reads. */
|
||||
export const IMPORT_MAX_CHARS = 8_000_000;
|
||||
|
||||
const FULL_KEY = `sp.pref.${STATS_PREF_KEY}`;
|
||||
const DAMAGED_KEY = `${FULL_KEY}.damaged`;
|
||||
|
||||
/** @returns {{ v: number, records: Array }} a fresh empty envelope */
|
||||
export const emptyStats = () => ({ v: STATS_VERSION, records: [] });
|
||||
|
||||
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const int = (v, d) => (Number.isFinite(v) ? Math.round(v) : d);
|
||||
const num = (v) => (Number.isFinite(v) ? v : null);
|
||||
const bool = (v, d = false) => (typeof v === 'boolean' ? v : d);
|
||||
/** A non-empty string, cut to `max` characters. */
|
||||
const str = (v, max = 64) => (typeof v === 'string' && v.length ? v.slice(0, max) : null);
|
||||
|
||||
// per-record bounds (an imported file is foreign data: nothing a row holds may grow without limit)
|
||||
const MAX_PLAYERS = 6; // the game seats 4
|
||||
const MAX_LINEUP = 12;
|
||||
const MAX_ITEMS = 4;
|
||||
const MAX_BONDS = 24;
|
||||
const MAX_STAT_KEYS = 24;
|
||||
const MAX_NAME = 24;
|
||||
|
||||
/**
|
||||
* Copy only the finite numeric keys of a stats block (the settlement's numbers; a numeric field this build does not
|
||||
* know is kept too, up to MAX_STAT_KEYS — display can lag, data should not).
|
||||
* @param {any} raw
|
||||
* @returns {Record<string, number>}
|
||||
*/
|
||||
function normalizeStatBlock(raw) {
|
||||
const out = {};
|
||||
if (!isObj(raw)) return out;
|
||||
let n = 0;
|
||||
for (const [k, v] of Object.entries(raw)) {
|
||||
if (!Number.isFinite(v) || k.length > 32) continue;
|
||||
out[k] = v;
|
||||
if (++n >= MAX_STAT_KEYS) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* FNV-1a 32-bit, hex — a content hash needs no crypto, only stability across sessions.
|
||||
* @param {string} s
|
||||
* @returns {string}
|
||||
*/
|
||||
function fnv1a(s) {
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
h ^= s.charCodeAt(i);
|
||||
h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
|
||||
}
|
||||
return h.toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* The record's dedupe id, from match facts the server replays byte-identically on reconnect / reload
|
||||
* (server/lobby.js result replay): seed + duration + mode + rounds + outcome + who I was. Two distinct
|
||||
* matches colliding on all of these is not a real scenario; a replayed m.result hits the same id and is
|
||||
* dropped, which is the point (recording happens on every m.result arrival, replays included).
|
||||
* @param {any} res raw m.result payload
|
||||
* @param {string|null|undefined} myId the local player's id at that moment
|
||||
* @returns {string}
|
||||
*/
|
||||
export function recordId(res, myId) {
|
||||
const r = isObj(res) ? res : {};
|
||||
return `r1.${fnv1a([r.seed ?? '-', r.durationMs ?? '-', r.modeId ?? '-', r.roundsPassed ?? '-', r.victory ? 1 : 0, myId ?? '-'].join('|'))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize ONE player row: known fields defaulted and bounded, unknown fields dropped. `quit`: the record is a quit
|
||||
* record, whose row may not know its rounds (`roundsPassed: null`).
|
||||
* @param {any} raw
|
||||
* @param {boolean} [quit]
|
||||
* @returns {any}
|
||||
*/
|
||||
function normalizePlayerRow(raw, quit = false) {
|
||||
const p = isObj(raw) ? raw : {};
|
||||
// the page and the replay read the title record from the game data by id: the sent texts are not kept
|
||||
const title = isObj(p.title) && str(p.title.id) ? { id: str(p.title.id) } : null;
|
||||
const lineup = (Array.isArray(p.lineup) ? p.lineup : []).filter(isObj).slice(0, MAX_LINEUP).map((u) => {
|
||||
// ids only — the tile position (row/col) is replay detail, not a statistic; items kept (配发装备统计); a 自选
|
||||
// pick and a 补位 stand-in kept too, or the replayed card would draw the plain operator
|
||||
const e = {
|
||||
id: str(u.id) || '', golden: bool(u.golden), tier: int(u.tier, 0),
|
||||
items: (Array.isArray(u.items) ? u.items : []).filter((i) => typeof i === 'string' && i.length).slice(0, MAX_ITEMS).map((i) => i.slice(0, 64)),
|
||||
};
|
||||
if (u.kind === 'token') e.kind = 'token';
|
||||
if (isObj(u.diy) && str(u.diy.charId)) {
|
||||
e.diy = { charId: str(u.diy.charId), skillIndex: Number.isInteger(u.diy.skillIndex) ? u.diy.skillIndex : 0, uniEquipId: str(u.diy.uniEquipId) };
|
||||
}
|
||||
if (str(u.standInFor)) e.standInFor = str(u.standInFor);
|
||||
return e;
|
||||
}).filter((u) => u.id);
|
||||
const bonds = (Array.isArray(p.bonds) ? p.bonds : []).filter(isObj).slice(0, MAX_BONDS).map((b) => ({
|
||||
bondId: str(b.bondId) || str(b.id) || '', layers: int(b.layers, 0), active: bool(b.active),
|
||||
})).filter((b) => b.bondId);
|
||||
return {
|
||||
playerId: str(p.playerId) || '',
|
||||
seat: int(p.seat, 0),
|
||||
name: str(p.name, MAX_NAME) || '',
|
||||
isBot: bool(p.isBot),
|
||||
left: bool(p.left),
|
||||
alive: bool(p.alive, true),
|
||||
victory: bool(p.victory), // server semantics: team won AND this player was still in at the end
|
||||
roundsPassed: quit ? num(p.roundsPassed) : int(p.roundsPassed, 0),
|
||||
eliminatedRound: num(p.eliminatedRound),
|
||||
lp: num(p.lp),
|
||||
bandId: str(p.bandId),
|
||||
title,
|
||||
trophies: int(p.trophies, 0),
|
||||
reward: int(p.reward, 0),
|
||||
lineup,
|
||||
bonds,
|
||||
stats: normalizeStatBlock(p.stats),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize ONE match record to the current shape (a strict schema: missing fields get defaults, unknown ones are
|
||||
* dropped, every string / list is bounded). A record without an `end` is a settled one — the PR #323 build, which
|
||||
* never recorded anything else, wrote none.
|
||||
* @param {any} raw
|
||||
* @returns {any|null} null when the row is not salvageable (no usable player row at all)
|
||||
*/
|
||||
export function normalizeRecord(raw) {
|
||||
const r = isObj(raw) ? raw : {};
|
||||
// a record IS a played match — no usable players array, no record
|
||||
if (!Array.isArray(r.players)) return null;
|
||||
const quit = r.end === 'quit';
|
||||
const players = r.players.filter(isObj).slice(0, MAX_PLAYERS).map((p) => normalizePlayerRow(p, quit));
|
||||
if (!players.length) return null;
|
||||
const rec = {
|
||||
id: str(r.id),
|
||||
v: STATS_VERSION,
|
||||
t: int(r.t, 0),
|
||||
end: quit ? 'quit' : 'settled',
|
||||
victory: bool(r.victory),
|
||||
roundsPassed: quit ? num(r.roundsPassed) : int(r.roundsPassed, 0),
|
||||
lastRound: num(r.lastRound),
|
||||
hiddenReached: bool(r.hiddenReached),
|
||||
hiddenCleared: bool(r.hiddenCleared),
|
||||
reason: str(r.reason, 32),
|
||||
modeId: str(r.modeId),
|
||||
difficulty: str(r.difficulty, 24),
|
||||
stageId: str(r.stageId),
|
||||
bossId: str(r.bossId),
|
||||
hiddenBossId: str(r.hiddenBossId),
|
||||
seed: num(r.seed),
|
||||
durationMs: num(r.durationMs),
|
||||
teamLp: num(r.teamLp),
|
||||
roomMode: r.roomMode === 'solo' || r.roomMode === 'coop' ? r.roomMode : null,
|
||||
selfId: str(r.selfId),
|
||||
players,
|
||||
};
|
||||
if (r.compact === true) rec.compact = true;
|
||||
// an id-less (hand-made) record gets a content id, so both copies of it land on the same key
|
||||
if (!rec.id) rec.id = `c.${fnv1a(JSON.stringify(rec))}`;
|
||||
return rec;
|
||||
}
|
||||
|
||||
/**
|
||||
* The MIGRATIONS chain: `MIGRATIONS[v]` upgrades a v-envelope to v+1, for v = STATS_VERSION and down.
|
||||
* Empty at v1 — the steps exist so the next format change lands as one function here and every stored /
|
||||
* imported envelope walks the whole chain.
|
||||
* @type {Record<number, (stats: any) => any>}
|
||||
*/
|
||||
export const MIGRATIONS = {};
|
||||
|
||||
/** Newest first (the stored order): by time, then id. */
|
||||
const newestFirst = (a, b) => (b.t - a.t) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
||||
|
||||
/**
|
||||
* Bring any stored / imported envelope to the current version.
|
||||
* @param {any} raw
|
||||
* @returns {{ stats: { v: number, records: any[] }, changed: boolean, newer: boolean, dropped: number }}
|
||||
* `newer` = the data was written by a NEWER build: returned untouched, callers must not save over it.
|
||||
* `dropped` = rows that were not salvageable, repeated a record or went beyond MAX_RECORDS: gone from `stats`.
|
||||
*/
|
||||
export function migrateStats(raw) {
|
||||
if (!isObj(raw) || !Array.isArray(raw.records)) return { stats: emptyStats(), changed: false, newer: false, dropped: 0 };
|
||||
if ((raw.v ?? 0) > STATS_VERSION) {
|
||||
return { stats: { v: raw.v, records: raw.records }, changed: false, newer: true, dropped: 0 };
|
||||
}
|
||||
let v = Number.isFinite(raw.v) ? raw.v : 0;
|
||||
let records = raw.records;
|
||||
let changed = v !== STATS_VERSION;
|
||||
while (v < STATS_VERSION) {
|
||||
const step = MIGRATIONS[v];
|
||||
if (typeof step === 'function') records = step({ v, records }).records;
|
||||
v++;
|
||||
}
|
||||
// a hand-edited / merged list can be oversized, unsorted or repeat a record: only the newest MAX_RECORDS survive, newest first
|
||||
const normalized = [];
|
||||
const seen = new Set(); // a record listed twice (hand-merged data) counts once: the first copy
|
||||
for (const r of records) {
|
||||
const rec = normalizeRecord(r);
|
||||
if (rec && !seen.has(rec.id)) { seen.add(rec.id); normalized.push(rec); }
|
||||
}
|
||||
normalized.sort(newestFirst);
|
||||
const kept = normalized.slice(0, MAX_RECORDS);
|
||||
const dropped = records.length - kept.length;
|
||||
// storage is rewritten (self-healed) when a row went, the order changed or an id-less row got its content id
|
||||
changed ||= dropped > 0 || kept.some((rec, i) => !isObj(records[i]) || rec.id !== records[i].id);
|
||||
return { stats: { v: STATS_VERSION, records: kept }, changed, newer: false, dropped };
|
||||
}
|
||||
|
||||
/** Read the raw stored string (null when absent or unreadable). */
|
||||
function readRaw() {
|
||||
try { return globalThis.localStorage?.getItem(FULL_KEY) ?? null; } catch { return null; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read + migrate the persisted envelope; self-heals older shapes back to storage. An unreadable value (not JSON, or
|
||||
* not an envelope) is moved to `sp.pref.stats.damaged` — kept for a manual recovery — and the history starts again.
|
||||
* @returns {{ v: number, records: any[], newer: boolean, dropped: number, damaged: boolean }}
|
||||
*/
|
||||
export function loadStats() {
|
||||
const raw = readRaw();
|
||||
if (raw == null) return { ...emptyStats(), newer: false, dropped: 0, damaged: false };
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(raw); } catch { parsed = undefined; }
|
||||
if (!isObj(parsed) || !Array.isArray(parsed.records)) {
|
||||
// keep the bad value where a person can find it; if even that write fails the next save simply replaces it
|
||||
try { globalThis.localStorage?.setItem(DAMAGED_KEY, raw); globalThis.localStorage?.removeItem(FULL_KEY); } catch { /* keep it in place */ }
|
||||
return { ...emptyStats(), newer: false, dropped: 0, damaged: true };
|
||||
}
|
||||
const { stats, changed, newer, dropped } = migrateStats(parsed);
|
||||
if (!newer && changed) saveStats(stats);
|
||||
return { ...stats, newer, dropped, damaged: false };
|
||||
}
|
||||
|
||||
// ---- compaction + the storage budget ---------------------------------------------------------------------------
|
||||
|
||||
const COMPACT_FRAME = ['id', 'v', 't', 'end', 'victory', 'roundsPassed', 'lastRound', 'hiddenReached', 'hiddenCleared', 'reason', 'modeId',
|
||||
'difficulty', 'roomMode', 'durationMs', 'selfId'];
|
||||
|
||||
/**
|
||||
* The compact form of a record: the frame and the player's OWN row without lineup, bonds and name — everything the
|
||||
* aggregates and the history list read, nothing a replay needs. Teammates are gone. Idempotent.
|
||||
* @param {any} rec a normalized record
|
||||
* @returns {any}
|
||||
*/
|
||||
export function compactRecord(rec) {
|
||||
const self = selfRowOf(rec);
|
||||
const out = {};
|
||||
for (const k of COMPACT_FRAME) if (rec[k] != null) out[k] = rec[k];
|
||||
out.compact = true;
|
||||
out.players = self ? [{
|
||||
playerId: self.playerId, seat: self.seat, alive: self.alive, victory: self.victory, roundsPassed: self.roundsPassed,
|
||||
eliminatedRound: self.eliminatedRound, bandId: self.bandId, title: self.title, left: self.left, stats: self.stats,
|
||||
}] : [];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What goes to storage: the newest FULL_KEEP records as they are, older ones compacted, then the oldest dropped until
|
||||
* the JSON fits `maxChars` (the newest record is always kept).
|
||||
* @param {any[]} records newest first
|
||||
* @param {number} [maxChars]
|
||||
* @returns {any[]}
|
||||
*/
|
||||
export function fitToBudget(records, maxChars = MAX_CHARS) {
|
||||
const kept = [];
|
||||
let used = 40; // the envelope itself
|
||||
records.slice(0, MAX_RECORDS).forEach((r, i) => {
|
||||
const rec = i < FULL_KEEP ? r : compactRecord(r);
|
||||
const n = JSON.stringify(rec).length + 1;
|
||||
if (kept.length && used + n > maxChars) return;
|
||||
used += n;
|
||||
kept.push(rec);
|
||||
});
|
||||
return kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the envelope. Never overwrites an envelope of a newer build. Compacts and trims to the budget first; a write
|
||||
* the browser refuses (quota — other keys share it) is retried with half the history, down to a handful of records.
|
||||
* @param {{ v: number, records: any[], newer?: boolean }} stats
|
||||
* @returns {boolean} whether a write stuck
|
||||
*/
|
||||
export function saveStats(stats) {
|
||||
if (stats.newer) return false;
|
||||
let recs = fitToBudget(stats.records);
|
||||
for (;;) {
|
||||
try {
|
||||
const ls = globalThis.localStorage;
|
||||
if (!ls) return false; // no storage at all (disabled by the browser)
|
||||
ls.setItem(FULL_KEY, JSON.stringify({ v: STATS_VERSION, records: recs }));
|
||||
return true;
|
||||
} catch { /* quota or storage disabled — fall through to shrinking */ }
|
||||
if (recs.length <= 8) return false; // a small history that still does not fit is foreign quota pressure
|
||||
recs = recs.slice(0, Math.max(8, Math.ceil(recs.length / 2)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the room shape ('solo' | 'coop') the way constants.js modeIdFor builds modeIds.
|
||||
* @param {string|null|undefined} modeId
|
||||
* @param {string|null|undefined} roomMode room.state `mode` when known
|
||||
* @returns {'solo'|'coop'|null}
|
||||
*/
|
||||
export function roomModeOf(modeId, roomMode) {
|
||||
if (roomMode === 'solo' || roomMode === 'coop') return roomMode;
|
||||
if (typeof modeId !== 'string') return null;
|
||||
if (modeId.includes('_single_')) return 'solo';
|
||||
if (modeId.includes('_multi_')) return 'coop';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one settled record from a raw m.result payload (+ context). Null when there is nothing to store: payloads
|
||||
* without players (the error-path settlement) or matches the local player did not take part in (spectator
|
||||
* seats get every result pushed too — eliminated players, who ARE in players[], keep recording).
|
||||
* @param {any} res raw m.result payload
|
||||
* @param {{ myId?: string|null, roomMode?: string|null, now?: number }} ctx
|
||||
* @returns {any|null}
|
||||
*/
|
||||
export function buildRecord(res, ctx = {}) {
|
||||
const r = isObj(res) ? res : {};
|
||||
if (!Array.isArray(r.players) || !r.players.length) return null;
|
||||
const myId = str(ctx.myId);
|
||||
const selfRow = r.players.find((p) => isObj(p) && p.playerId === myId);
|
||||
if (!selfRow) return null; // spectator / observer: not my match
|
||||
return normalizeRecord({
|
||||
v: STATS_VERSION,
|
||||
t: int(ctx.now, 0),
|
||||
id: recordId(r, myId),
|
||||
end: 'settled',
|
||||
victory: bool(r.victory),
|
||||
roundsPassed: int(r.roundsPassed, 0),
|
||||
lastRound: num(r.lastRound),
|
||||
hiddenReached: bool(r.hiddenReached),
|
||||
hiddenCleared: bool(r.hiddenCleared),
|
||||
reason: str(r.reason),
|
||||
modeId: str(r.modeId),
|
||||
difficulty: str(r.difficulty),
|
||||
stageId: str(r.stageId),
|
||||
bossId: str(r.bossId),
|
||||
hiddenBossId: str(r.hiddenBossId),
|
||||
seed: num(r.seed),
|
||||
durationMs: num(r.durationMs),
|
||||
teamLp: num(r.teamLp),
|
||||
roomMode: roomModeOf(str(r.modeId), ctx.roomMode),
|
||||
selfId: myId,
|
||||
players: r.players,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- the match left early ----------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* What the page remembers of the match on screen, so that giving it up can still be recorded: when the page first saw
|
||||
* it, whether that was at the start (a duration is only kept then), and the last round the player was seen alive in
|
||||
* (the server tells the others at the settlement, a leaver nothing).
|
||||
* @returns {{ active: boolean, startedAt: number, sawStart: boolean, aliveRound: number|null }}
|
||||
*/
|
||||
export const createLiveMatch = () => ({ active: false, startedAt: 0, sawStart: false, aliveRound: null });
|
||||
|
||||
/** The module's own tracker (fed by installStatsRecorder, read by recordQuit). */
|
||||
export const liveMatch = createLiveMatch();
|
||||
|
||||
/**
|
||||
* Feed the tracker one app state (cheap: called on every store change).
|
||||
* @param {ReturnType<typeof createLiveMatch>} live
|
||||
* @param {any} state the app store state
|
||||
* @param {number} [now]
|
||||
*/
|
||||
export function observeMatch(live, state, now = Date.now()) {
|
||||
const pub = state?.match?.public;
|
||||
const inMatch = !!pub && !!pub.phase && pub.phase !== PHASE.LOBBY && pub.phase !== PHASE.RESULT && !state.match.result;
|
||||
if (!inMatch) { live.active = false; return live; }
|
||||
const round = Number(pub.round) || 0;
|
||||
if (!live.active) {
|
||||
live.active = true;
|
||||
live.startedAt = now;
|
||||
live.sawStart = round <= 1;
|
||||
live.aliveRound = null;
|
||||
}
|
||||
const me = Array.isArray(pub.players) ? pub.players.find((p) => isObj(p) && p.playerId === state.me?.playerId) : null;
|
||||
if (me && me.alive !== false) live.aliveRound = Math.max(live.aliveRound ?? 0, round);
|
||||
return live;
|
||||
}
|
||||
|
||||
/** Start following the store (main.js). Returns the unsubscribe function. */
|
||||
export function installStatsRecorder(store) {
|
||||
observeMatch(liveMatch, store.get());
|
||||
return store.subscribe((s) => observeMatch(liveMatch, s));
|
||||
}
|
||||
|
||||
/**
|
||||
* The rounds a player who leaves in `phase` of `round` has cleared — the server's rule for a quit (platform.js _quit:
|
||||
* eliminated in round k ⇒ k − 1 passed; leaving in the settlement of round k counts k).
|
||||
* @param {string} phase @param {number} round
|
||||
*/
|
||||
export function clearedRounds(phase, round) {
|
||||
const r = Number.isFinite(round) ? round : 0;
|
||||
return Math.max(0, phase === PHASE.SETTLE ? r : r - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the quit record of a match the local player is leaving (放弃模拟), from the app state and the tracker. Null when
|
||||
* there is nothing of mine to record: no match on screen, its settlement already here (that one is recorded by
|
||||
* recordResult), a spectator seat, or a match the page never saw.
|
||||
* @param {any} state the app store state BEFORE the match is cleared
|
||||
* @param {{ live?: ReturnType<typeof createLiveMatch>, now?: number }} [ctx]
|
||||
* @returns {any|null}
|
||||
*/
|
||||
export function buildQuitRecord(state, ctx = {}) {
|
||||
const live = ctx.live ?? liveMatch;
|
||||
const now = int(ctx.now, Date.now());
|
||||
const pub = state?.match?.public;
|
||||
const myId = str(state?.me?.playerId);
|
||||
if (!pub || !myId || state.match.result || !live.active) return null;
|
||||
const row = Array.isArray(pub.players) ? pub.players.find((p) => isObj(p) && p.playerId === myId) : null;
|
||||
if (!row) return null; // a spectator seat is no player of the match
|
||||
const alive = row.alive !== false;
|
||||
const round = Number(pub.round) || 0;
|
||||
// alive: the rounds cleared so far; already eliminated: the round it was seen alive in, less one (unknown when the
|
||||
// page never saw it alive — a reload after the elimination)
|
||||
const roundsPassed = alive ? clearedRounds(pub.phase, round) : (live.aliveRound != null ? Math.max(0, live.aliveRound - 1) : null);
|
||||
return normalizeRecord({
|
||||
v: STATS_VERSION,
|
||||
t: now,
|
||||
id: `q.${fnv1a([myId, live.startedAt, pub.modeId ?? '-', state.room?.code ?? '-'].join('|'))}`,
|
||||
end: 'quit',
|
||||
victory: false,
|
||||
roundsPassed,
|
||||
lastRound: num(pub.lastRound),
|
||||
hiddenReached: pub.phase === PHASE.HIDDEN_CORE,
|
||||
hiddenCleared: false,
|
||||
reason: 'quit',
|
||||
modeId: str(pub.modeId),
|
||||
difficulty: str(pub.difficulty),
|
||||
stageId: str(pub.stageId),
|
||||
bossId: str(pub.bossId),
|
||||
hiddenBossId: str(pub.hiddenBossId),
|
||||
seed: null,
|
||||
durationMs: live.sawStart ? Math.max(0, now - live.startedAt) : null,
|
||||
teamLp: num(pub.teamLp),
|
||||
roomMode: roomModeOf(str(pub.modeId), state.room?.mode),
|
||||
selfId: myId,
|
||||
players: [{
|
||||
playerId: myId, seat: row.seat, name: row.name, isBot: false, left: true, alive, victory: false, roundsPassed,
|
||||
eliminatedRound: alive ? null : live.aliveRound, lp: row.lp, bandId: row.bandId,
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The m.result-shaped payload behind a settled record — the inverse of buildRecord. The stats page's history
|
||||
* rows hand this to the settlement view (screens/result.js reads it through normalizeResult): a finished match can be
|
||||
* RE-VIEWED because the record kept every field the payload had. Whatever a record never stored is simply absent and
|
||||
* normalizeResult defaults it, exactly like a tolerant live payload. A quit record (nothing was settled) and a
|
||||
* compacted one (its rows are gone) have no settlement to show.
|
||||
* @param {any} rec
|
||||
* @returns {any|null} null when the row is not a usable, full, settled record
|
||||
*/
|
||||
export function recordToResult(rec) {
|
||||
const r = normalizeRecord(rec);
|
||||
if (!r || r.end === 'quit' || r.compact) return null;
|
||||
const res = {
|
||||
victory: r.victory,
|
||||
roundsPassed: r.roundsPassed,
|
||||
hiddenReached: r.hiddenReached,
|
||||
hiddenCleared: r.hiddenCleared,
|
||||
reason: r.reason,
|
||||
modeId: r.modeId,
|
||||
difficulty: r.difficulty,
|
||||
bossId: r.bossId,
|
||||
hiddenBossId: r.hiddenBossId,
|
||||
seed: r.seed,
|
||||
durationMs: r.durationMs,
|
||||
teamLp: r.teamLp,
|
||||
players: r.players,
|
||||
};
|
||||
if (Number.isFinite(r.lastRound)) res.lastRound = r.lastRound;
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one record: replays (same content id) are dropped, newest first, capped at MAX_RECORDS.
|
||||
* @param {{ v: number, records: any[] }} stats
|
||||
* @param {any} record
|
||||
* @returns {{ stats: { v: number, records: any[] }, added: boolean }}
|
||||
*/
|
||||
export function appendRecord(stats, record) {
|
||||
if (!record || !record.id) return { stats, added: false };
|
||||
if (stats.records.some((r) => r.id === record.id)) return { stats, added: false };
|
||||
const records = [record, ...stats.records].slice(0, MAX_RECORDS);
|
||||
return { stats: { v: STATS_VERSION, records }, added: true };
|
||||
}
|
||||
|
||||
/** load → append → save of one built record (never over an envelope of a newer build). @returns {any|null} the record when stored */
|
||||
function storeRecord(rec) {
|
||||
if (!rec) return null;
|
||||
const stats = loadStats();
|
||||
if (stats.newer) return null;
|
||||
const { stats: next, added } = appendRecord(stats, rec);
|
||||
if (added && !saveStats(next)) console.warn('[stats] localStorage write failed (quota?), record not persisted');
|
||||
return added ? rec : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a finished match end-to-end (load → append → save). Returns the built record, or null when
|
||||
* nothing was stored (no players / not my match / replay).
|
||||
* @param {any} res raw m.result payload
|
||||
* @param {{ myId?: string|null, roomMode?: string|null, now?: number }} [ctx]
|
||||
* @returns {any|null}
|
||||
*/
|
||||
export function recordResult(res, ctx = {}) {
|
||||
return storeRecord(buildRecord(res, ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the match the player is giving up (放弃模拟), before the app clears its state. Returns the record, or null.
|
||||
* @param {any} state the app store state before the match is cleared
|
||||
* @param {{ live?: ReturnType<typeof createLiveMatch>, now?: number }} [ctx]
|
||||
* @returns {any|null}
|
||||
*/
|
||||
export function recordQuit(state, ctx = {}) {
|
||||
const live = ctx.live ?? liveMatch;
|
||||
const rec = storeRecord(buildQuitRecord(state, ctx));
|
||||
live.active = false; // one record per match
|
||||
return rec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge two envelopes (import into existing): union by record id, newest first, capped.
|
||||
* @param {{ records: any[] }} a current (wins ties)
|
||||
* @param {{ records: any[] }} b incoming
|
||||
* @returns {{ v: number, records: any[] }}
|
||||
*/
|
||||
export function mergeStats(a, b) {
|
||||
const byId = new Map();
|
||||
for (const r of [...(Array.isArray(b?.records) ? b.records : []), ...(Array.isArray(a?.records) ? a.records : [])]) {
|
||||
const rec = normalizeRecord(r);
|
||||
if (rec) byId.set(rec.id, rec);
|
||||
}
|
||||
const records = [...byId.values()].sort(newestFirst).slice(0, MAX_RECORDS);
|
||||
return { v: STATS_VERSION, records };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse + migrate + merge an exported / pasted payload into the current data.
|
||||
* @param {any} raw parsed JSON of the imported file
|
||||
* @param {{ records: any[] }} current current envelope
|
||||
* @returns {{ stats: { v: number, records: any[] }, added: number, skipped: number, dropped: number }}
|
||||
* added = records new to this device; skipped = duplicates of records it has; dropped = rows of the file that could
|
||||
* not be read
|
||||
*/
|
||||
export function importStats(raw, current) {
|
||||
if (isObj(raw) && raw.kind != null && raw.kind !== 'local-stats') {
|
||||
const err = new Error('not a stats export'); // the page shows its own text
|
||||
err.code = 'stats-bad-file';
|
||||
throw err;
|
||||
}
|
||||
if (!isObj(raw) || !Array.isArray(raw.records)) {
|
||||
const err = new Error('not a stats export');
|
||||
err.code = 'stats-bad-file';
|
||||
throw err;
|
||||
}
|
||||
const { stats: incoming, newer, dropped } = migrateStats(raw);
|
||||
if (newer) {
|
||||
const err = new Error('exported by a newer client'); // the page shows its own text
|
||||
err.code = 'stats-newer-version';
|
||||
throw err;
|
||||
}
|
||||
const have = new Set((Array.isArray(current?.records) ? current.records : []).map((r) => r.id));
|
||||
const merged = mergeStats(current, incoming);
|
||||
const added = incoming.records.filter((r) => !have.has(r.id)).length;
|
||||
return { stats: merged, added, skipped: incoming.records.length - added, dropped };
|
||||
}
|
||||
|
||||
/**
|
||||
* The payload the export button downloads (envelope + a little provenance).
|
||||
* @param {{ records: any[] }} stats
|
||||
* @returns {{ app: string, kind: string, v: number, exportedAt: string, records: any[] }}
|
||||
*/
|
||||
export function exportStats(stats) {
|
||||
return {
|
||||
app: 'stronghold-protocol',
|
||||
kind: 'local-stats',
|
||||
v: STATS_VERSION,
|
||||
exportedAt: new Date().toISOString(),
|
||||
records: fitToBudget(Array.isArray(stats?.records) ? stats.records : []),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- aggregation (what the page shows; records may hold more than any view uses) ------------------------------------
|
||||
|
||||
const SELF_STATS = ['dmgDealt', 'kills', 'bossDamage', 'activatedLayers', 'merges', 'itemsEquipped', 'gold', 'perfectRounds', 'refreshes', 'leaks', 'lpLost'];
|
||||
|
||||
/**
|
||||
* The row that "is me" in a record: selfId, else the only human, else seat 0 — records written by
|
||||
* recordResult always have selfId; the fallbacks only serve imported / hand-made data.
|
||||
* @param {any} rec
|
||||
* @returns {any|null}
|
||||
*/
|
||||
export function selfRowOf(rec) {
|
||||
const ps = Array.isArray(rec?.players) ? rec.players : [];
|
||||
return ps.find((p) => p.playerId && p.playerId === rec.selfId)
|
||||
|| ps.find((p) => !p.isBot)
|
||||
|| ps[0]
|
||||
|| null;
|
||||
}
|
||||
|
||||
/** Whether this record counts as a win for its self player (per-row victory = team won AND still in). */
|
||||
const selfWon = (rec, self) => (self ? !!self.victory : !!rec.victory);
|
||||
|
||||
/**
|
||||
* The rounds the player passed in a record: its own row's (the table the settlement prints per player), else the
|
||||
* team's; 0 when the record does not know.
|
||||
* @param {any} rec
|
||||
*/
|
||||
export function roundsOf(rec) {
|
||||
const self = selfRowOf(rec);
|
||||
const v = self && Number.isFinite(self.roundsPassed) ? self.roundsPassed : rec?.roundsPassed;
|
||||
return Number.isFinite(v) ? v : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a record enters the aggregates (see the header). A settled record always does. A quit record does once the
|
||||
* player had finished at least one battle: cleared a round, or was already eliminated; a match given up before that —
|
||||
* entered and left right away — is history only.
|
||||
* @param {any} rec a normalized record
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function countsTowardStats(rec) {
|
||||
if (!isObj(rec)) return false;
|
||||
if (rec.end !== 'quit') return true;
|
||||
const self = selfRowOf(rec);
|
||||
if (!self) return false;
|
||||
return self.alive === false || (Number.isFinite(self.roundsPassed) && self.roundsPassed >= 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate records for the stats page — over the records that count; `total` / `excluded` say how many did not.
|
||||
* Everything is keyed by ids (bandId / titleId / difficulty); the page maps them to names and icons through the game
|
||||
* data. The combat totals read the settled records' stat blocks (a quit record has none).
|
||||
* @param {any[]} records
|
||||
* @returns {any}
|
||||
*/
|
||||
export function aggregateStats(records) {
|
||||
const all = Array.isArray(records) ? records : [];
|
||||
const rs = all.filter(countsTowardStats);
|
||||
const out = {
|
||||
total: all.length, count: rs.length, excluded: all.length - rs.length, wins: 0,
|
||||
rounds: { total: 0, max: 0 },
|
||||
duration: { totalMs: 0 },
|
||||
hidden: { reached: 0, cleared: 0 },
|
||||
byDifficulty: {}, byMode: { solo: 0, coop: 0 },
|
||||
titles: {}, bands: {}, sums: {},
|
||||
};
|
||||
for (const rec of rs) {
|
||||
const self = selfRowOf(rec);
|
||||
const won = selfWon(rec, self);
|
||||
if (won) out.wins++;
|
||||
const rounds = roundsOf(rec);
|
||||
out.rounds.total += rounds;
|
||||
out.rounds.max = Math.max(out.rounds.max, rounds);
|
||||
out.duration.totalMs += num(rec.durationMs) || 0;
|
||||
if (rec.hiddenReached) out.hidden.reached++;
|
||||
if (rec.hiddenCleared) out.hidden.cleared++;
|
||||
|
||||
const d = rec.difficulty || 'UNKNOWN';
|
||||
const bd = (out.byDifficulty[d] ||= { games: 0, wins: 0, hiddenCleared: 0 });
|
||||
bd.games++;
|
||||
if (won) bd.wins++;
|
||||
if (rec.hiddenCleared) bd.hiddenCleared++;
|
||||
|
||||
if (rec.roomMode === 'solo' || rec.roomMode === 'coop') out.byMode[rec.roomMode]++;
|
||||
|
||||
const titleId = self?.title?.id;
|
||||
if (titleId) {
|
||||
const t = (out.titles[titleId] ||= { count: 0 });
|
||||
t.count++;
|
||||
}
|
||||
|
||||
const bandId = self?.bandId;
|
||||
if (bandId) {
|
||||
const b = (out.bands[bandId] ||= { games: 0, wins: 0 });
|
||||
b.games++;
|
||||
if (won) b.wins++;
|
||||
}
|
||||
|
||||
if (rec.end !== 'quit' && self && isObj(self.stats)) {
|
||||
for (const k of SELF_STATS) {
|
||||
const v = self.stats[k];
|
||||
if (Number.isFinite(v)) out.sums[k] = (out.sums[k] || 0) + v;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -5,7 +5,10 @@
|
||||
// Observing (client-side combat, `observe` prop — the official flow): tapping a teammate's avatar expands a mint
|
||||
// "前往查看" button under the row (when that teammate can be observed now; otherwise the reason is toasted through
|
||||
// onWatch); while observing, the own row shows a "返回战场" button. Without `observe` (server-run combat) a click
|
||||
// watches that player's field at once.
|
||||
// watches that player's field at once, and a click while that field is already on screen does not ask again.
|
||||
// In PHASE.PREP a double-click on a teammate's avatar opens their field (GitHub #131, the 「前往查看」 shortcut).
|
||||
// It does not open a field the teammate does not have, and it does not open one the click already opened.
|
||||
// Boss-prep phases (最终攻势 / 隐秘核心) are not PHASE.PREP, so they still use 「前往查看」.
|
||||
// Live LP (user playtest #3 item 2): during a normal round's battle each row's tower shows lp − the loss that player's
|
||||
// leaks so far will cost (red, −N): the own row the top bar's live value (`self`, ui/hud.js liveLp), a teammate's row
|
||||
// m.public players[].pendingLp (server/match/match/views.js, ~1 Hz). 联防 (user playtest #6 item 7): a leaker's row adds the
|
||||
@@ -15,7 +18,7 @@
|
||||
// the player watches, so the number moves with the kills on screen), else m.public players[].uniteLeft (the authority's
|
||||
// report, ~1 Hz).
|
||||
|
||||
import { useEffect, useState } from '../../vendor/hooks.module.js';
|
||||
import { useEffect, useRef, useState } from '../../vendor/hooks.module.js';
|
||||
import { PHASE } from '../../../shared/constants.js';
|
||||
import { html, Icon, Tooltip } from './components.js';
|
||||
import { PlayerAvatar, LpTower, GIcon, LocalSprite } from './gameComponents.js';
|
||||
@@ -55,6 +58,45 @@ export function rowLp(p, pub, self = null, { uniteLocal = null, cap = 10 } = {})
|
||||
return { lp, pending, unite: (pending > 0 || left != null) && (self ? !!self.unite : pub.phase === PHASE.UNITE), left };
|
||||
}
|
||||
|
||||
/** True when `watching` is already this teammate's field (their live field, or the prep scout `n:<id>`). */
|
||||
export function teammateFieldShown(watching, player) {
|
||||
if (!watching || !player) return false;
|
||||
return watching === player.fieldId || watching === `n:${player.playerId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single click on a teammate avatar calls onWatch only in server-run combat (no `observe`), and only when
|
||||
* that field is not already on screen. A double-click fires click first; the second click, and any later click
|
||||
* while the view is already theirs, must not open it again. Client combat never watches from the avatar click.
|
||||
* `askedRecently`: this avatar's click already called onWatch in the last moment (the other click of a double-click,
|
||||
* before `watching` has re-rendered).
|
||||
* @param {{ observe?: unknown, watching?: string|null, player?: { playerId?: string, fieldId?: string }|null, askedRecently?: boolean }} [o]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function teammateClickWatches(o = {}) {
|
||||
if (o.observe || o.askedRecently) return false;
|
||||
if (teammateFieldShown(o.watching, o.player)) return false;
|
||||
return !!o.player;
|
||||
}
|
||||
|
||||
/**
|
||||
* Double-click in PHASE.PREP opens a teammate's field, skipping 「前往查看」. False — do not call onWatch — when
|
||||
* the phase is not PREP, the row is your own, there is no client-combat `observe` (the click already watched),
|
||||
* `canObserve` has no field (do not force a view; the click toasts), or that field is already open.
|
||||
* @param {{ phase?: string, self?: boolean, observe?: { canObserve?: (p: any) => { fieldId?: string }|null }|null,
|
||||
* watching?: string|null, player?: any, askedRecently?: boolean }} [o]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function prepDblClickWatches(o = {}) {
|
||||
if (o.phase !== PHASE.PREP || o.self || !o.player || !o.observe) return false;
|
||||
if (o.askedRecently || teammateFieldShown(o.watching, o.player)) return false;
|
||||
const view = (typeof o.observe.canObserve === 'function' ? o.observe.canObserve(o.player) : null) || {};
|
||||
return !!view.fieldId;
|
||||
}
|
||||
|
||||
/** How long the second click of a double-click counts as "already asked" before `watching` re-renders. */
|
||||
const AVATAR_CLICK_GAP_MS = 500;
|
||||
|
||||
/**
|
||||
* Tooltip of a row's LP tower with a pending loss (null without one).
|
||||
* @param {{ lp: number|null, pending: number, unite: boolean, left: number|null } | null} lp rowLp(...)
|
||||
@@ -76,6 +118,8 @@ export function rowLpTip(lp, cap = 10) {
|
||||
*/
|
||||
export function TeamPanel({ pub, myId, watching, bubbles, onWatch, compact = false, observe = null, self: selfLive = null, cap = 10, uniteLocal = null }) {
|
||||
const [openPid, setOpenPid] = useState(null);
|
||||
// the playerId whose avatar just called onWatch, so the other click of a double-click does not open the view again
|
||||
const askedAt = useRef(/** @type {{ id: string|null, at: number }} */ ({ id: null, at: 0 }));
|
||||
const phaseKey = `${pub?.phase}:${pub?.round}`;
|
||||
useEffect(() => { setOpenPid(null); }, [phaseKey, watching, observe?.observing]);
|
||||
const players = sortedPlayers(pub);
|
||||
@@ -84,19 +128,39 @@ export function TeamPanel({ pub, myId, watching, bubbles, onWatch, compact = fal
|
||||
// tinted like the official green; a plain green ring without the local art)
|
||||
const team = teamFrameIds(pub, myId);
|
||||
const frameArt = team.size ? localAsset('ui/battle', 'bg_team_border') : null;
|
||||
const askedRecently = (p) => askedAt.current.id === p?.playerId && Date.now() - askedAt.current.at < AVATAR_CLICK_GAP_MS;
|
||||
const noteAsked = (p) => { askedAt.current = { id: p.playerId, at: Date.now() }; };
|
||||
const click = (p, self) => {
|
||||
if (!observe) { onWatch(p); return; }
|
||||
if (!observe) {
|
||||
// your own row still goes home; a teammate already on screen (or just opened by this double-click) does not
|
||||
if (self || teammateClickWatches({ watching, player: p, askedRecently: askedRecently(p) })) {
|
||||
if (!self) noteAsked(p);
|
||||
onWatch(p);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (self) { if (observe.observing) observe.onBack(); setOpenPid(null); return; }
|
||||
const t = observe.canObserve(p) || {};
|
||||
if (!t.fieldId) { setOpenPid(null); onWatch(p); return; } // the game screen toasts the reason
|
||||
const view = observe.canObserve(p) || {};
|
||||
if (!view.fieldId) {
|
||||
setOpenPid(null);
|
||||
if (!askedRecently(p)) { noteAsked(p); onWatch(p); } // the game screen toasts the reason; a double-click toasts once
|
||||
return;
|
||||
}
|
||||
setOpenPid((cur) => (cur === p.playerId ? null : p.playerId));
|
||||
};
|
||||
const dblClick = (e, p, self) => {
|
||||
if (!prepDblClickWatches({ phase: pub?.phase, self, observe, watching, player: p, askedRecently: askedRecently(p) })) return;
|
||||
e.preventDefault();
|
||||
setOpenPid(null);
|
||||
noteAsked(p);
|
||||
onWatch(p);
|
||||
};
|
||||
return html`<aside class=${cx('team', compact && 'team--compact')} aria-label=${t('同盟成员')}>
|
||||
${players.map((p) => {
|
||||
const self = p.playerId === myId;
|
||||
const status = p.alive === false ? 'dead' : p.status;
|
||||
const meta = STATUS_META[status] || STATUS_META.acting;
|
||||
const watched = watching && (watching === p.fieldId || watching === `n:${p.playerId}`);
|
||||
const watched = teammateFieldShown(watching, p);
|
||||
const bubble = bubbles?.get(p.playerId);
|
||||
const offline = p.connected === false && !p.isBot;
|
||||
const open = !!observe && openPid === p.playerId && !self;
|
||||
@@ -105,7 +169,7 @@ export function TeamPanel({ pub, myId, watching, bubbles, onWatch, compact = fal
|
||||
const lp = rowLp(p, pub, self ? selfLive : null, { uniteLocal, cap });
|
||||
const inTeam = team.has(p.playerId);
|
||||
return html`<div key=${p.playerId} class=${cx('team__row', self && 'is-self', inTeam && 'is-team', watched && 'is-watched', p.alive === false && 'is-dead', open && 'is-open')}>
|
||||
<button type="button" class="team__btn" onClick=${() => click(p, self)} title=${inTeam && !self ? `${title} · ${t('与你在同一战场')}` : title} aria-expanded=${observe && !self ? String(open) : undefined}>
|
||||
<button type="button" class="team__btn" onClick=${() => click(p, self)} onDblClick=${(e) => dblClick(e, p, self)} title=${inTeam && !self ? `${title} · ${t('与你在同一战场')}` : title} aria-expanded=${observe && !self ? String(open) : undefined}>
|
||||
<${PlayerAvatar} player=${p} self=${self} />
|
||||
${inTeam ? html`<span class=${cx('team__frame', !frameArt && 'team__frame--plain')} style=${frameArt ? `--frame:url("${frameArt}")` : undefined} aria-hidden="true"></span>` : null}
|
||||
<span class="team__seat num">P${(p.seat ?? 0) + 1}</span>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useEffect, useReducer } from '../../vendor/hooks.module.js';
|
||||
import htm from '../../vendor/htm.module.js';
|
||||
import { ERR_TEXT } from '../../../shared/constants.js';
|
||||
import { t } from '../../../shared/i18n.js';
|
||||
import { recordError } from '../diag.js';
|
||||
|
||||
// no shared static vnodes (see components.js hFresh: htm's static cache would retain unmounted DOM)
|
||||
function hFresh(type, props, ...children) {
|
||||
@@ -108,6 +109,7 @@ export function describeError(err) {
|
||||
* @returns {number}
|
||||
*/
|
||||
export function toastError(err) {
|
||||
recordError('request', err);
|
||||
return toast(describeError(err), 'error');
|
||||
}
|
||||
|
||||
|
||||
+19
-16
@@ -151,27 +151,30 @@ export function withLiveLayers(bonds, live) {
|
||||
* A teammate's board as far as the screen shows it, in the m.private shape the bond popup's member list reads
|
||||
* (gameLogic bondMembers): their operators on the field meta on screen (the prep scouting board, a server-run battle
|
||||
* field's units) and, under client-side combat, the battle on screen's (`extra` = battle/runner.js ownerOps: the meta
|
||||
* the runner publishes is taken before the operators deploy). Their hand is never sent — members count as owned only
|
||||
* when they are on the field. Their operators keep the items the unit info carries (UnitInfo `items`), so a 变形同构体
|
||||
* wearer is listed as a member of the bond it grants (gameLogic grantedBonds), and a 补位 unit its `standInFor` (the
|
||||
* popup draws the stand-in). null without a field or battle.
|
||||
* @param {any} field @param {string} ownerId @param {any[]|null} [extra] UnitInfo-like { kind, ownerId, defId, items?, standInFor? }
|
||||
* the runner publishes is taken before the operators deploy). A prep scout also carries their bench, each unit tagged
|
||||
* with its `area` (server prepFieldMeta): a 'hand' operator goes to the hand list, a 'temp' one to the temp list, so the
|
||||
* popup counts them as the player's own popup does (GitHub #385, PR #387) — owned, not 在场; a hand operator counts for
|
||||
* the bonds that count the 整备区 (投资人 远见 奇迹: memberHeadCount), the 5 temporary slots for none. A unit without
|
||||
* an area (a battle's, an older server's) is on the board; a battle sends no bench. Their operators keep the items the
|
||||
* unit info carries (UnitInfo `items`), so a 变形同构体 wearer is listed as a member of the bond it grants (gameLogic
|
||||
* grantedBonds), and a 补位 unit its `standInFor` (the popup draws the stand-in). null without a field or battle.
|
||||
* @param {any} field @param {string} ownerId @param {any[]|null} [extra] UnitInfo-like { kind, ownerId, defId, area?, items?, standInFor? }
|
||||
*/
|
||||
export function ownerBoard(field, ownerId, extra = null) {
|
||||
const fromField = isObj(field) && Array.isArray(field.units) ? field.units : null;
|
||||
const fromBattle = Array.isArray(extra) ? extra : null;
|
||||
if (!fromField && !fromBattle) return null;
|
||||
const board = [...(fromField || []), ...(fromBattle || [])]
|
||||
.filter((u) => isObj(u) && u.ownerId === ownerId && u.kind === 'op' && typeof u.defId === 'string')
|
||||
.map((u) => {
|
||||
const p = Array.isArray(u.items) && u.items.length ? { kind: 'chess', id: u.defId, items: u.items.filter((x) => typeof x === 'string') } : { kind: 'chess', id: u.defId };
|
||||
// 0.2.0 自选编队: a DIY slot's unit names its operator (UnitInfo diy) — the popup counts it for that operator's bonds
|
||||
if (isObj(u.diy) && typeof u.diy.charId === 'string') p.diy = u.diy;
|
||||
// 0.2.0 补位: a unit fighting as its stand-in says so (UnitInfo standInFor) — the popup draws that member as the stand-in
|
||||
if (typeof u.standInFor === 'string' && u.standInFor) p.standInFor = u.standInFor;
|
||||
return p;
|
||||
});
|
||||
return { board, hand: [], temp: [] };
|
||||
const out = { board: /** @type {any[]} */ ([]), hand: /** @type {any[]} */ ([]), temp: /** @type {any[]} */ ([]) };
|
||||
for (const u of [...(fromField || []), ...(fromBattle || [])]) {
|
||||
if (!isObj(u) || u.ownerId !== ownerId || u.kind !== 'op' || typeof u.defId !== 'string') continue;
|
||||
const p = Array.isArray(u.items) && u.items.length ? { kind: 'chess', id: u.defId, items: u.items.filter((x) => typeof x === 'string') } : { kind: 'chess', id: u.defId };
|
||||
// 0.2.0 自选编队: a DIY slot's unit names its operator (UnitInfo diy) — the popup counts it for that operator's bonds
|
||||
if (isObj(u.diy) && typeof u.diy.charId === 'string') p.diy = u.diy;
|
||||
// 0.2.0 补位: a unit fighting as its stand-in says so (UnitInfo standInFor) — the popup draws that member as the stand-in
|
||||
if (typeof u.standInFor === 'string' && u.standInFor) p.standInFor = u.standInFor;
|
||||
out[u.area === 'hand' ? 'hand' : u.area === 'temp' ? 'temp' : 'board'].push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user