diff --git a/extension.js b/extension.js index 2244b16..3d25855 100644 --- a/extension.js +++ b/extension.js @@ -6,7 +6,7 @@ import { configureDiagnostics } from "./diagnostics/index.js"; export const type = "extension"; export let shuYing = new Object(); -const shuYingLocalVersion = "2.0.2.3-rc.11"; +const shuYingLocalVersion = "2.0.2.3-rc.12"; shuYing.name = "术樱包"; shuYing.editable = false; diff --git a/mengsan/cards/personal-piles.js b/mengsan/cards/personal-piles.js index 797a246..fca5242 100644 --- a/mengsan/cards/personal-piles.js +++ b/mengsan/cards/personal-piles.js @@ -20,13 +20,15 @@ export function installPersonalPiles(session, owner, battle, run, resources, env // Detached nodes: engine get.position recognises these IDs; no duplicate document IDs. draw.id = "cardPile"; discard.id = "discardPile"; const owned = new Set(), topPlaying = new Set(), restores = []; + const pileNodes = { drawPile: draw, discardPile: discard }; + const viewKeys = new WeakMap(), exhaustSources = new WeakMap(); const strict = env.strict !== false; let released = false, forcedOwner = false, forcedPublic = false, exhaustTotal = 0; function recordExhaust(card) { if (card.storage?.mengsanExhausted_shuying) return false; card.storage.mengsanExhausted_shuying = true; - battle.exhaustPile.push(snapshot(card)); exhaustTotal++; - queueIroncladExhaust(owner, card); queueRelicExhaust(owner, card); refresh(); return true; + battle.exhaustPile.push(snapshotExhausted(card)); exhaustTotal++; + queueIroncladExhaust(owner, card); queueRelicExhaust(owner, card); refresh("exhaustPile"); return true; } const personal = () => { if (released || forcedPublic) return false; @@ -42,7 +44,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env } return false; // Never infer ownership from whose turn it is. }; - const refresh = () => { if (!released) env.refresh(); }; + const refresh = (...piles) => { if (!released) env.refresh(...piles); }; const canReceiveTransfer = (card, sourceSession) => !released && session.active && sourceSession===session && owner.isAlive() && !owned.has(card) && typeof card?.storage?.mengsanCard_shuying?.id==="string" && ![...owned].some(c=>c.storage?.mengsanCard_shuying?.id===card.storage.mengsanCard_shuying.id); @@ -95,6 +97,19 @@ export function installPersonalPiles(session, owner, battle, run, resources, env return { ...data, ...snapshotRampage(card), ...ironcladHooks(owner)?.snapshotCard(card), ...sharedHooks(owner)?.snapshotCard?.(card), name: card.name, suit: card.suit, number: card.number, nature: card.nature || null, affixes: data.affixes?.slice() || [], upgrade: data.upgrade || 0 }; } + function viewKey(card) { + if (!viewKeys.has(card)) viewKeys.set(card, Symbol()); + return viewKeys.get(card); + } + function snapshotExhausted(card) { + const data = snapshot(card); + exhaustSources.set(data, card); + return data; + } + function removeExhaustSnapshot(card) { + const index = battle.exhaustPile.findIndex(data => exhaustSources.get(data) === card); + if (index >= 0) battle.exhaustPile.splice(index, 1); + } for (const data of battle.drawPile) { if (data.name === "muniu") continue; const card = game.createCard(data.name, data.suit, data.number, data.nature); @@ -111,16 +126,28 @@ export function installPersonalPiles(session, owner, battle, run, resources, env if (Object.getOwnPropertyDescriptor(ui, key)?.get === read) Object.defineProperty(ui, key, descriptor.get ? descriptor : { ...descriptor, value: publicNode }); }); } - for (const [key, node] of [["drawPile", draw], ["discardPile", discard]]) { + for (const [key, node] of Object.entries(pileNodes)) { Object.defineProperty(battle, key, { configurable: true, enumerable: true, get: () => Array.from(node.childNodes, snapshot) }); } - const observer = new MutationObserver(() => { + const observer = new MutationObserver(records => { if (released) return; + const changed = new Set(records.map(record => record.target)); // A card from our deck can be discarded during an enemy-owned event. - for (const card of Array.from(publicDiscard.childNodes)) if (owned.has(card)) discard.appendChild(card); - for (const node of [draw, discard]) for (const card of node.childNodes) adopt(card); - refresh(); + if (changed.has(publicDiscard)) { + for (const card of Array.from(publicDiscard.childNodes)) { + if (!owned.has(card)) continue; + discard.appendChild(card); + changed.add(discard); + } + } + const piles = []; + for (const [key, node] of Object.entries(pileNodes)) { + if (!changed.has(node)) continue; + for (const card of node.childNodes) adopt(card); + piles.push(key); + } + if (piles.length) refresh(...piles); }); for (const node of [draw, discard, publicDiscard]) observer.observe(node, { childList: true }); function wash() { @@ -129,7 +156,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env shuffle(run, cards); queueRelicShuffle(owner); for (const card of cards) { card.fix?.(); draw.appendChild(card); } - refresh(); + refresh("drawPile", "discardPile"); return true; } function take(number = 1, putBack = false, bottom = false) { @@ -147,7 +174,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env if (putBack) for (let i = cards.length - 1; i >= 0; i--) { if (bottom) draw.appendChild(cards[i]); else draw.insertBefore(cards[i], draw.firstChild); } - refresh(); return cards; + refresh("drawPile"); return cards; } function wrap(object, key, replacement, shouldReplace = personal) { const descriptor = Object.getOwnPropertyDescriptor(object, key), original = object[key]; @@ -177,6 +204,17 @@ export function installPersonalPiles(session, owner, battle, run, resources, env owned.clear(); topPlaying.clear(); draw.remove(); discard.remove(); exhausted.remove(); }); return { + pileView: { + count(key) { + return pileNodes[key]?.childNodes.length ?? battle.exhaustPile.length; + }, + records(key) { + const node = pileNodes[key]; + return node + ? Array.from(node.childNodes, card => ({ card: snapshot(card), key: viewKey(card) })) + : battle.exhaustPile.map(card => ({ card, key: viewKey(exhaustSources.get(card) ?? card) })); + }, + }, take, canReceiveTransfer, receiveTransfer(card,sourceSession) { @@ -259,13 +297,12 @@ export function installPersonalPiles(session, owner, battle, run, resources, env exhaustTotal() { return exhaustTotal; }, exhaustedCards() { return [...owned].filter(card => card.storage?.mengsanExhausted_shuying); }, syncExhaustSnapshots() { - if(released || !session.active)return; - const current=new Map([...owned].filter(card=>card.storage?.mengsanExhausted_shuying) - .map(card=>[card.storage.mengsanCard_shuying?.id,card])); - for(let index=0;index data.id === id); - if (index >= 0) battle.exhaustPile.splice(index,1); + removeExhaustSnapshot(card); delete card.storage.mengsanExhausted_shuying; delete card._selfDestroyed; } else if (card.parentNode !== draw && card.parentNode !== discard) return false; @@ -315,9 +350,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env if(released || !session.active || !owner.isAlive() || !owned.has(card))return false; if(owner.getCards("h").includes(card))return true; if(card.storage?.mengsanExhausted_shuying){ - const id=card.storage.mengsanCard_shuying?.id; - const index=battle.exhaustPile.findIndex(data=>data.id===id); - if(index>=0)battle.exhaustPile.splice(index,1); + removeExhaustSnapshot(card); delete card.storage.mengsanExhausted_shuying;delete card._selfDestroyed; } delete card.storage.mengsanConsumed_shuying; @@ -356,7 +389,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env const card = game.createCard(data.name, data.suit, data.number, data.nature); adopt(card, data); discard.appendChild(card); - refresh(); + refresh("discardPile"); return card; }, async addToHand(data) { diff --git a/mengsan/mode.js b/mengsan/mode.js index a223865..7128628 100644 --- a/mengsan/mode.js +++ b/mengsan/mode.js @@ -703,7 +703,7 @@ const prepareBattle = async (run, node, encounter, session, resources) => { activeBattle.personalPiles = installPersonalPiles(session, me, _status.mengsanBattle_shuying, run, resources, { game, ui, get, lib, _status, document, MutationObserver, shuffle: shuffleBattlePile, - refresh: () => activeBattle?.session === session && activeBattle.pilesUI?.refresh(), + refresh: (...piles) => activeBattle?.session === session && activeBattle.pilesUI?.refresh(...piles), }); activeBattle.personalPiles.withOwner(() => me.init(run.player.character)); me.storage.mengsanUnitId_shuying = "player"; @@ -799,7 +799,7 @@ const prepareBattle = async (run, node, encounter, session, resources) => { session.ownResource({}, () => game.removeGlobalSkill(skill)); } } - activeBattle.pilesUI = mountBattlePiles(session, _status.mengsanBattle_shuying); + activeBattle.pilesUI = mountBattlePiles(session, _status.mengsanBattle_shuying, activeBattle.personalPiles.pileView); currentBattle.owner = me; currentBattle.run = run; potionSkillIds.forEach(skill => me.addSkill(skill)); diff --git a/mengsan/tools/test-journey-ui-zoom.cjs b/mengsan/tools/test-journey-ui-zoom.cjs index e6728a8..e82bc8a 100644 --- a/mengsan/tools/test-journey-ui-zoom.cjs +++ b/mengsan/tools/test-journey-ui-zoom.cjs @@ -94,7 +94,11 @@ async function mountSurface(page, origin, prefix, settings, surface) { openCardLibrary(run); } else if (surface==='牌堆') { const {mountBattlePiles} = await modules('card-library'); - mountBattlePiles({active:true,ownResource(){}},{drawPile:run.player.deck,discardPile:[],exhaustPile:[]}); + const battle = {drawPile:run.player.deck,discardPile:[],exhaustPile:[]}; + window.pileReview = { + battle, + control: mountBattlePiles({active:true,ownResource(){}},battle), + }; } else if (surface==='遗物') { const {mountRelics} = await modules('relics'); mountRelics({active:true,ownResource(){}},run,{status(){},counter:()=>({value:null,label:null})},{stripRoot:ui.arena}); @@ -178,7 +182,173 @@ async function checkSurface(page, surface, settings, origin, prefix) { if (result!==null) assert.equal(await page.evaluate(()=>zoomReviewResult),result,'the original action returns the choice'); } +async function checkLivePiles(page, origin, prefix) { + await mountSurface(page,origin,prefix,{zoom:1},'牌堆'); + await page.evaluate(async prefix => { + const {battle,control} = window.pileReview; + control.dispose(); + const engine = await import('/noname.js'); + const {mountBattlePiles} = await import(prefix+'/ui/card-library.js'); + const {installPersonalPiles} = await import(prefix+'/cards/personal-piles.js'); + const {DAZED_NAME,dazedDefinition,createDazedData} = await import(prefix+'/cards/status-cards.js'); + battle.drawPile = Array.from({length:48},(_,index) => ({id:`card-${index}`,name:'sha',suit:'heart',number:index%13+1})); + engine.lib.card[DAZED_NAME] = dazedDefinition; + engine.lib.translate[DAZED_NAME] = '晕眩'; + const hand = document.createElement('div'); + const owner = {playerid:'pile-review',isAlive:()=>true,getCards:()=>Array.from(hand.childNodes), + lose(card,pile) { pile.appendChild(card); return {}; }}; + const session = {active:true,ownResource(){}}; + const publicDiscard = document.createElement('div'); + const ui = {cardPile:document.createElement('div'),discardPile:publicDiscard}; + const game = {createCard(name,suit,number,nature) { + return Object.assign(document.createElement('div'),{name,suit,number,nature,gaintag:new Set(), + addGaintag(tag) { this.gaintag.add(tag); }}); + }}; + let dialogControl; + const piles = installPersonalPiles(session,owner,battle,{}, {card(){}}, { + game,ui,get:{},lib:engine.lib,_status:{},document,MutationObserver,shuffle:(_,cards)=>cards.reverse(), + refresh: (...keys) => dialogControl?.refresh(...keys), + }); + const reads = {count:0,records:0}; + dialogControl = mountBattlePiles(session,battle,{ + count(key) { reads.count++; return piles.pileView.count(key); }, + records(key) { reads.records++; return piles.pileView.records(key); }, + }); + window.pileReview = {piles,control:dialogControl,draw:piles.withOwner(()=>ui.cardPile),publicDiscard,createDazedData,reads, + makeNative(suit,number) { return hand.appendChild(game.createCard('sha',suit,number)); }}; + },prefix); + await page.locator('.mengsan-battle-piles-button-shuying').tap(); + const result = await page.evaluate(async () => { + const {piles,draw,publicDiscard,createDazedData,reads,makeNative} = window.pileReview; + const dialog = document.querySelector('.mengsan-deck-dialog-shuying'); + const [drawTab,discardTab,exhaustTab] = dialog.querySelectorAll('.ms-deck-tabs button:not([hidden])'); + const grid = dialog.querySelector('.ms-library-grid'); + const body = dialog.querySelector('.ms-deck-body'); + const frame = async () => { + // Let native pile mutations notify the dialog before waiting for its next paint. + await Promise.resolve(); + await new Promise(resolve => requestAnimationFrame(resolve)); + }; + const cardAt = index => grid.querySelector(`[data-card-index="${index}"]`); + const first = cardAt(0); + reads.count = reads.records = 0; + publicDiscard.appendChild(document.createElement('div')); + await frame(); + const unrelatedReads = {...reads}; + let countUpdates = 0; + const observer = new MutationObserver(records => { countUpdates += records.length; }); + observer.observe(discardTab,{childList:true}); + for (let index=0;index<3;index++) { + piles.addToDiscard(createDazedData(`status-${index}`)); + } + const beforeFrame = discardTab.textContent; + await frame(); + observer.disconnect(); + const afterBatch = {beforeFrame,countUpdates,discard:discardTab.textContent,sameCard:first===cardAt(0),reads:{...reads}}; + + first.click(); + const heading = dialog.querySelector('.ms-deck-detail h3'); + const back = dialog.querySelector('.ms-deck-detail button'); + const [seen] = piles.take(1); + await frame(); + const detail = {stillOpen:heading.isConnected && !heading.closest('section').hidden,focused:document.activeElement===back,draw:drawTab.textContent}; + if (!detail.stillOpen) return {afterBatch,detail}; + back.click(); + const afterBack = {top:body.scrollTop,number:cardAt(0).querySelector('.ms-deck-corner').textContent, + focused:document.activeElement===drawTab}; + + const start = 12; + const original = cardAt(start); + body.scrollTop = original.getBoundingClientRect().top - body.getBoundingClientRect().top - 5; + await frame(); + const topBefore = cardAt(start).getBoundingClientRect().top - body.getBoundingClientRect().top; + cardAt(start).focus({preventScroll:true}); + draw.prepend(seen,...Array.from(draw.childNodes).slice(25,33)); + await frame(); + const moved = cardAt(start+9); + const reorder = {topBefore,topAfter:moved?.getBoundingClientRect().top-body.getBoundingClientRect().top, + focused:document.activeElement===moved,order:moved?.querySelector('.ms-deck-order').textContent}; + + const upgraded = draw.childNodes[start+9]; + upgraded.storage.mengsanCard_shuying.upgrade = 1; + piles.syncExhaustSnapshots(); + await frame(); + const upgrade = {tag:cardAt(start+9).querySelector('.ms-deck-tags')?.textContent,focused:document.activeElement===cardAt(start+9)}; + + body.style.maxHeight = '32px'; + draw.replaceChildren(); + await frame(); + const empty = {visible:!!grid.querySelector('.ms-deck-empty'),top:body.scrollTop,focused:document.activeElement===drawTab}; + body.scrollTop = body.scrollHeight; + piles.take(1); + await frame(); + const wash = {draw:drawTab.textContent,discard:discardTab.textContent,top:body.scrollTop, + first:cardAt(0).querySelector('.ms-deck-name').textContent}; + body.style.maxHeight = ''; + + publicDiscard.appendChild(seen); + await frame(); + const reclaimed = {stillPublic:publicDiscard.contains(seen),discard:discardTab.textContent}; + piles.addToDiscard(createDazedData('status-4')); + discardTab.click(); + const switched = {discard:discardTab.textContent,visible:cardAt(1).querySelector('.ms-deck-name').textContent}; + cardAt(1).click(); + piles.addToDiscard(createDazedData('status-5')); + await frame(); + const discardDetail = {visible:!dialog.querySelector('.ms-deck-detail').hidden, + summary:dialog.querySelector('.ms-deck-summary').textContent}; + + const nativeFirst = makeNative('club',7), nativeSecond = makeNative('diamond',8); + await piles.exhaustFromHand(nativeFirst); + await piles.exhaustFromHand(nativeSecond); + exhaustTab.click(); + cardAt(0).focus({preventScroll:true}); + piles.syncExhaustSnapshots(); + await frame(); + const corners = () => Array.from(grid.querySelectorAll('.ms-deck-corner'),card => card.textContent); + const exhaust = {cards:corners(),focused:document.activeElement===cardAt(0)}; + piles.beginAutoPlay(nativeSecond,true); + await frame(); + exhaust.remaining = corners(); + discardTab.click(); + return {unrelatedReads,afterBatch,detail,afterBack,reorder,upgrade,empty,wash,reclaimed,switched,discardDetail,exhaust}; + }); + assert.deepEqual(result.unrelatedReads,{count:0,records:0}); + assert.deepEqual(result.afterBatch,{beforeFrame:'弃牌堆 · 0',countUpdates:1,discard:'弃牌堆 · 3',sameCard:true, + reads:{count:1,records:0}}); + assert.deepEqual(result.detail,{stillOpen:true,focused:true,draw:'剩余牌堆 · 47'}); + assert.deepEqual(result.afterBack,{top:0,number:'♥ 红桃 2',focused:true}); + assert.ok(Math.abs(result.reorder.topAfter-result.reorder.topBefore)<=2,JSON.stringify(result.reorder)); + assert.equal(result.reorder.focused,true); + assert.equal(result.reorder.order,'22'); + assert.deepEqual(result.upgrade,{tag:'+1',focused:true}); + assert.deepEqual(result.empty,{visible:true,top:0,focused:true}); + assert.deepEqual(result.wash,{draw:'剩余牌堆 · 2',discard:'弃牌堆 · 0',top:0,first:'晕眩'}); + assert.deepEqual(result.reclaimed,{stillPublic:false,discard:'弃牌堆 · 1'}); + assert.deepEqual(result.switched,{discard:'弃牌堆 · 2',visible:'晕眩'}); + assert.deepEqual(result.discardDetail,{visible:true,summary:'弃牌堆 · 共 3 张'}); + assert.deepEqual(result.exhaust,{cards:['♣ 梅花 7','♦ 方块 8'],focused:true,remaining:['♣ 梅花 7']}); + if (process.env.HUD_ARTIFACTS) { + await page.screenshot({path:path.join(process.env.HUD_ARTIFACTS,'battle-piles-live.png')}); + } + const readsAfterClose = await page.evaluate(async () => { + const {control,reads} = window.pileReview; + reads.count = reads.records = 0; + control.refresh(); + document.querySelector('.ms-deck-header button').click(); + await new Promise(resolve => requestAnimationFrame(resolve)); + return {...reads}; + }); + assert.deepEqual(readsAfterClose,{count:0,records:0}); + assert.equal(await page.locator('.mengsan-deck-dialog-shuying').count(),0); +} + exports.testJourneyZoom = async function testJourneyZoom(browser,origin,prefix) { + const pilePage = await browser.newPage({viewport:{width:812,height:375},hasTouch:true}); + try { await checkLivePiles(pilePage,origin,prefix); } + finally { await pilePage.close(); } + console.log('Live battle piles: passed'); + if (process.env.PILE_REFRESH_REVIEW === '1') return; const failures = []; let checks = 0; const scenarios = [{zoom:.5},{zoom:.65},{zoom:1},{zoom:1.5},{zoom:2},{zoom:3},{zoom:1.5,transform:true}, diff --git a/mengsan/ui/card-library.js b/mengsan/ui/card-library.js index d2c2a68..46c6dd7 100644 --- a/mengsan/ui/card-library.js +++ b/mengsan/ui/card-library.js @@ -115,6 +115,7 @@ export function openCardLibrary(run, options = {}) { if (existing) { existing.focus(); return () => {}; } const previousFocus = document.activeElement; const selection = options.selection; + const sections = options.sections; const dialog = element("dialog", "mengsan-deck-dialog-shuying", null); dialog.setAttribute("aria-label", options.title || "卡牌库"); const header = element("header", "ms-deck-header", null, dialog); @@ -122,10 +123,13 @@ export function openCardLibrary(run, options = {}) { element("span", "ms-deck-eyebrow", options.eyebrow || "梦三 · 行囊", title); element("h2", "ms-deck-title", options.title || "卡牌库", title); let closed = false, sizeObserver = null, virtualGrid = null, searchTimer = 0; + let refreshFrame = 0; + const pendingPiles = new Set(); const close = () => { if (closed) return; closed = true; clearTimeout(searchTimer); + cancelPileRefresh(); virtualGrid?.dispose(); sizeObserver?.disconnect(); if (typeof window !== "undefined") window.removeEventListener?.("resize", fitCards); @@ -134,7 +138,7 @@ export function openCardLibrary(run, options = {}) { list.replaceChildren(); detailPanel.replaceChildren(); body.replaceChildren(); dialog.replaceChildren(); catalogRecords = null; descriptionCache = new WeakMap(); - selectedButton = null; current = []; + selectedButton = null; current = []; sectionRecords = []; detailListPosition = null; virtualGrid = null; sizeObserver = null; if (previousFocus?.isConnected) previousFocus.focus(); const onClose = options.onClose; @@ -142,16 +146,16 @@ export function openCardLibrary(run, options = {}) { onClose?.(close); }; button("关闭", header, close); - let view = selection || (!options.sections && options.view === "catalog") + let view = selection || (!sections && options.view === "catalog") ? "catalog" : "deck"; const navigation = element("nav", "ms-deck-tabs", null, dialog); navigation.setAttribute("aria-label", "卡牌列表视图"); const deckTab = button("持有牌", navigation, () => { view = "deck"; render(); }); const catalogTab = button("图鉴", navigation, () => { view = "catalog"; render(); }); - deckTab.hidden = catalogTab.hidden = Boolean(options.sections || selection); + deckTab.hidden = catalogTab.hidden = Boolean(sections || selection); let sectionIndex = 0; - const sectionTabs = options.sections ? options.sections().map((section, index) => - button(section.title, navigation, () => { sectionIndex = index; render(); })) : []; + const sectionTabs = sections?.map((section, index) => + button(section.title, navigation, () => { sectionIndex = index; render(); })); const filters = element("div", "ms-catalog-filters", null, dialog); function field(label) { const wrapper = element("label", "ms-catalog-field", null, filters); @@ -192,6 +196,7 @@ export function openCardLibrary(run, options = {}) { const footer = element("p", "ms-deck-footer", "点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序", dialog); let current = Array.isArray(run?.player?.deck) ? run.player.deck : []; let detail = false, selectedButton = null, scrollTop = 0, orderedView = false; + let sectionRecords = [], displayedSection = -1, detailListPosition = null; const list = element("div", "ms-deck-grid ms-library-grid", null, body); const detailPanel = element("section", "ms-deck-detail", null, body); detailPanel.hidden = true; @@ -199,7 +204,15 @@ export function openCardLibrary(run, options = {}) { virtualGrid = createVirtualCardGrid(body, list, createTile); function back() { detail = false; detailPanel.hidden = true; list.hidden = false; - detailPanel.replaceChildren(); body.scrollTop = scrollTop; fitCards(); + detailPanel.replaceChildren(); + if (sections) { + cancelPileRefresh(); + updateSectionTabs(); + renderSection({ position: detailListPosition }); + detailListPosition = null; selectedButton = null; + return; + } + body.scrollTop = scrollTop; fitCards(); virtualGrid?.resume(); if (selectedButton?.isConnected) selectedButton.focus({ preventScroll: true }); else if (virtualGrid && selectedButton) virtualGrid.focus(Number(selectedButton.dataset.cardIndex)); @@ -207,6 +220,7 @@ export function openCardLibrary(run, options = {}) { function showDetail(card, details, owner, catalog = false) { clearTimeout(searchTimer); selectedButton = owner; scrollTop = body.scrollTop; + if (sections) detailListPosition = captureListPosition(owner); detail = true; list.hidden = true; detailPanel.hidden = false; detailPanel.replaceChildren(); const backButton = button(catalog ? "返回图鉴" : "返回牌库", detailPanel, back); @@ -242,7 +256,8 @@ export function openCardLibrary(run, options = {}) { } body.scrollTop = 0; backButton.focus(); } - function fitCards() { + function fitCards() { layoutCards(); } + function layoutCards(position = null) { if (closed || !body.clientHeight) return; const padding = getComputedStyle(body); const available = body.clientHeight - parseFloat(padding.paddingTop) - parseFloat(padding.paddingBottom); @@ -250,7 +265,7 @@ export function openCardLibrary(run, options = {}) { const height = Math.max(128, Math.min(218, Math.floor((available - (rows - 1) * 8) / rows))); dialog.style.setProperty("--ms-card-height", String(height) + "px"); dialog.style.setProperty("--ms-card-art-width", String(Math.max(8, Math.min(98, Math.floor((height - (orderedView ? 104 : 80)) * 5 / 7)))) + "px"); - virtualGrid?.layout(height); + virtualGrid?.layout(height, position); } function createTile(record, index) { const { card, catalog = false, ordered = false } = record; @@ -266,33 +281,95 @@ export function openCardLibrary(run, options = {}) { element("span", "ms-deck-excerpt", details.description, tile); return tile; } + function captureListPosition(focused = document.activeElement) { + const scrollTop = sectionRecords.length ? body.scrollTop : 0; + const anchors = scrollTop > 0 ? virtualGrid.visiblePositions().map(({ index, offset }) => + ({ key: sectionRecords[index].key, offset })) : []; + const focusKey = list.contains(focused) ? sectionRecords[Number(focused.dataset.cardIndex)]?.key : undefined; + return { scrollTop, anchors, focusKey }; + } + function restoreListPosition(position) { + if (!position) { fitCards(); return; } + const indices = new Map(sectionRecords.map(({ key }, index) => [key, index])); + const anchor = position.anchors.find(({ key }) => indices.has(key)); + layoutCards({ index: anchor ? indices.get(anchor.key) : -1, offset: anchor?.offset, + scrollTop: sectionRecords.length ? position.scrollTop : 0 }); + if (position.focusKey === undefined) return; + const index = indices.get(position.focusKey); + if (index === undefined) sectionTabs[sectionIndex].focus({ preventScroll: true }); + else virtualGrid.focus(index, { scroll: false }); + } + function updateSectionTabs(piles = null) { + sections.forEach(({ title, key, ordered }, index) => { + if (piles && !piles.has(key)) return; + const tab = sectionTabs[index]; + const count = options.pileView.count(key); + const label = `${title} · ${count}`; + if (tab.textContent !== label) tab.textContent = label; + if (!piles) tab.setAttribute("aria-pressed", String(index === sectionIndex)); + if (index !== sectionIndex) return; + const summaryLabel = ordered ? "剩余牌堆按从左到右、从上到下的顺序摸取;第 1 张为下一张。" : + `${title} · 共 ${count} 张`; + if (summary.textContent !== summaryLabel) summary.textContent = summaryLabel; + }); + } + function renderSection({ position = null, preserve = false } = {}) { + const { key, ordered } = sections[sectionIndex]; + const records = options.pileView.records(key).map(({ card, key }) => + ({ card, key, ordered, signature: JSON.stringify(card) })); + if (displayedSection === sectionIndex && records.length === sectionRecords.length && + records.every(({ key, signature }, index) => key === sectionRecords[index].key && signature === sectionRecords[index].signature)) { + if (position) restoreListPosition(position); + else if (!preserve) virtualGrid.resume(); + return; + } + if (preserve) position = captureListPosition(); + displayedSection = sectionIndex; sectionRecords = records; orderedView = ordered; + descriptionCache = new WeakMap(); + virtualGrid.setRecords(records); + if (!records.length) { + const emptyMessage = ordered ? "剩余牌堆为空;下一次摸牌需按规则洗切弃牌堆,洗切后的顺序尚未确定。" : "此处暂无卡牌。"; + element("p", "ms-deck-empty", emptyMessage, list); + } + restoreListPosition(position); + } + function cancelPileRefresh() { + if (refreshFrame) cancelAnimationFrame(refreshFrame); + refreshFrame = 0; + pendingPiles.clear(); + } + function schedulePileRefresh(...piles) { + if (closed) return; + for (const key of piles.length ? piles : sections.map(section => section.key)) pendingPiles.add(key); + if (refreshFrame) return; + refreshFrame = requestAnimationFrame(() => { + refreshFrame = 0; + updateSectionTabs(pendingPiles); + const updateList = !detail && pendingPiles.has(sections[sectionIndex].key); + pendingPiles.clear(); + if (updateList) renderSection({ preserve: true }); + }); + } function render() { clearTimeout(searchTimer); detail = false; list.hidden = false; detailPanel.hidden = true; detailPanel.replaceChildren(); body.scrollTop = 0; selectedButton = null; - const catalog = !options.sections && view === "catalog"; + const catalog = !sections && view === "catalog"; filters.hidden = !catalog; deckTab.setAttribute("aria-pressed", String(!catalog)); catalogTab.setAttribute("aria-pressed", String(catalog)); list.classList.toggle("ms-catalog-grid", catalog); - let records = [], emptyMessage = "此处暂无卡牌。"; - orderedView = false; - if (options.sections) { - const sections = options.sections(); - const section = sections[sectionIndex]; - orderedView = Boolean(section?.ordered); - if (section?.ordered) emptyMessage = "剩余牌堆为空;下一次摸牌需按规则洗切弃牌堆,洗切后的顺序尚未确定。"; - sectionTabs.forEach((tab, index) => { - tab.textContent = `${sections[index].title} · ${sections[index].cards.length}`; - tab.setAttribute("aria-pressed", String(index === sectionIndex)); - }); - records = (section?.cards || []).map(card => ({ card, ordered: section.ordered })); - summary.textContent = section?.ordered - ? "剩余牌堆按从左到右、从上到下的顺序摸取;第 1 张为下一张。" - : `${section?.title || "牌堆"} · 共 ${records.length} 张`; - } else if (catalog) { + if (sections) { + cancelPileRefresh(); + detailListPosition = null; + updateSectionTabs(); + renderSection(); + return; + } + let records = []; + if (catalog) { const query = search.value.trim().toLocaleLowerCase(); catalogRecords ||= getCardCatalog().map(card => { const details = describeCatalogCard(card); @@ -311,15 +388,14 @@ export function openCardLibrary(run, options = {}) { details.cost !== null && details.cost === Number(costFilter.value)))); summary.textContent = `卡牌图鉴 · 共 ${total} 种 · 当前显示 ${records.length} 种`; } else { - summary.textContent = options.sections ? "剩余牌堆按从左到右、从上到下的顺序摸取;第 1 张为下一张。" : - `本次征程实际携带 · 共 ${current.length} 张 · 同名不同花色、点数分别展示`; + summary.textContent = `本次征程实际携带 · 共 ${current.length} 张 · 同名不同花色、点数分别展示`; } if (catalog && selection) footer.textContent = selection.description; else footer.textContent = catalog ? "图鉴仅供查阅,不会获得卡牌或改变征程牌组 · 点击卡牌查看完整介绍" : "点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序"; - virtualGrid.setRecords(catalog || options.sections ? records : current.map(card => ({ card }))); - if (!(catalog || options.sections ? records : current).length) { - element("p", "ms-deck-empty", catalog ? "没有符合筛选的卡牌,可清空筛选后查看全部图鉴。" : emptyMessage, list); + virtualGrid.setRecords(catalog ? records : current.map(card => ({ card }))); + if (!(catalog ? records : current).length) { + element("p", "ms-deck-empty", catalog ? "没有符合筛选的卡牌,可清空筛选后查看全部图鉴。" : "此处暂无卡牌。", list); } fitCards(); } @@ -338,20 +414,12 @@ export function openCardLibrary(run, options = {}) { window.addEventListener?.("resize", fitCards); } header.querySelector("button").focus(); - close.refresh = () => { - if (closed) return; - // Rebuild from live arrays after a pile mutation, including while viewing details. - const wasDetail = detail, offset = body.scrollTop; - catalogRecords = null; descriptionCache = new WeakMap(); - render(); body.scrollTop = offset; - virtualGrid?.resume(); - if (wasDetail) header.querySelector("button").focus(); - }; + if (sections) close.refresh = schedulePileRefresh; return close; } // The battle view exposes only this player's own piles, including consumed cards. -export function mountBattlePiles(session, battle) { +export function mountBattlePiles(session, battle, pileView) { let closeDialog = null, disposed = false; const control = button("牌堆", ui.window, () => { if (disposed || !session.active || battle.resolving) return; @@ -359,10 +427,14 @@ export function mountBattlePiles(session, battle) { closeDialog = openCardLibrary(null, { title: "战斗牌堆", eyebrow: "梦三 · 个人牌堆", onClose(handle) { if (closeDialog === handle) closeDialog = null; }, - sections: () => [ - { title: "剩余牌堆", cards: battle.drawPile, ordered: true }, - { title: "弃牌堆", cards: battle.discardPile, ordered: false }, - { title: "消耗牌堆", cards: battle.exhaustPile, ordered: false }, + pileView: pileView ?? { + count: key => battle[key].length, + records: key => battle[key].map(card => ({ card, key: card.id ?? card })), + }, + sections: [ + { title: "剩余牌堆", key: "drawPile", ordered: true }, + { title: "弃牌堆", key: "discardPile", ordered: false }, + { title: "消耗牌堆", key: "exhaustPile", ordered: false }, ], }); }, "mengsan-battle-piles-button-shuying"); @@ -372,5 +444,5 @@ export function mountBattlePiles(session, battle) { disposed = true; closeDialog?.(); closeDialog = null; control.remove(); }; session.ownResource(control, dispose); - return { dispose, refresh() { if (!disposed) closeDialog?.refresh?.(); } }; + return { dispose, refresh(...piles) { if (!disposed && session.active) closeDialog?.refresh?.(...piles); } }; } diff --git a/mengsan/ui/virtual-card-grid.js b/mengsan/ui/virtual-card-grid.js index 268e95c..e678b6a 100644 --- a/mengsan/ui/virtual-card-grid.js +++ b/mengsan/ui/virtual-card-grid.js @@ -5,6 +5,21 @@ export function createVirtualCardGrid(viewport, grid, createCard) { const maxCached = 24; let records = [], columns = 1, height = 218, gap = 8, padding = 5, viewportHeight = 0; let frame = 0, disposed = false; + function mount(index) { + if (mounted.has(index)) return mounted.get(index); + const node = cached.get(index) || createCard(records[index], index); + cached.delete(index); + node.dataset.cardIndex = String(index); + node.style.gridRow = String(Math.floor(index / columns) + 1); + node.style.gridColumn = String(index % columns + 1); + // 保持 DOM 顺序与屏幕顺序一致,方便键盘与读屏浏览。 + let next = null; + for (const [otherIndex, other] of mounted) { + if (otherIndex > index && (!next || otherIndex < Number(next.dataset.cardIndex))) next = other; + } + grid.insertBefore(node, next); mounted.set(index, node); + return node; + } function draw() { if (disposed || grid.hidden || !viewportHeight) return; const stride = height + gap; @@ -20,25 +35,26 @@ export function createVirtualCardGrid(viewport, grid, createCard) { while (cached.size > maxCached) cached.delete(cached.keys().next().value); } } - for (let index = first; index < end; index++) { - if (mounted.has(index)) continue; - const node = cached.get(index) || createCard(records[index], index); - cached.delete(index); - node.dataset.cardIndex = String(index); - node.style.gridRow = String(Math.floor(index / columns) + 1); - node.style.gridColumn = String(index % columns + 1); - // 保持 DOM 顺序与屏幕顺序一致,方便键盘与读屏浏览。 - let next = null; - for (const [otherIndex, other] of mounted) { - if (otherIndex > index && (!next || otherIndex < Number(next.dataset.cardIndex))) next = other; - } - grid.insertBefore(node, next); mounted.set(index, node); - } + for (let index = first; index < end; index++) mount(index); } function schedule() { if (!frame && !disposed) frame = requestAnimationFrame(() => { frame = 0; draw(); }); } - function layout(cardHeight = height) { + function rowTop(index) { + return padding + Math.floor(index / columns) * (height + gap); + } + function visiblePositions() { + const top = viewport.scrollTop, bottom = top + viewportHeight; + const firstRow = Math.max(0, Math.floor((top - padding) / (height + gap))); + const positions = []; + for (let index = firstRow * columns; index < records.length; index++) { + const position = rowTop(index); + if (position >= bottom) break; + if (position + height > top) positions.push({ index, offset: position - top }); + } + return positions; + } + function layout(cardHeight = height, position = null) { height = cardHeight; if (disposed || grid.hidden || !grid.clientWidth) return; const style = getComputedStyle(grid); @@ -53,16 +69,21 @@ export function createVirtualCardGrid(viewport, grid, createCard) { node.style.gridRow = String(Math.floor(index / columns) + 1); node.style.gridColumn = String(index % columns + 1); } + if (position) viewport.scrollTop = position.index >= 0 + ? rowTop(position.index) - position.offset : position.scrollTop; draw(); } - function focus(index) { + function focus(index, { scroll = true } = {}) { if (!Number.isInteger(index) || index < 0 || index >= records.length || disposed) return; - const top = padding + Math.floor(index / columns) * (height + gap); - if (top < viewport.scrollTop) viewport.scrollTop = top; - else if (top + height > viewport.scrollTop + viewportHeight) { - viewport.scrollTop = top + height - viewportHeight; + if (scroll) { + const top = rowTop(index); + if (top < viewport.scrollTop) viewport.scrollTop = top; + else if (top + height > viewport.scrollTop + viewportHeight) { + viewport.scrollTop = top + height - viewportHeight; + } + draw(); } - draw(); mounted.get(index)?.focus({ preventScroll: true }); + mount(index).focus({ preventScroll: true }); } function keydown(event) { const card = event.target.closest("[data-card-index]"); @@ -83,6 +104,7 @@ export function createVirtualCardGrid(viewport, grid, createCard) { records = value; mounted.clear(); cached.clear(); grid.replaceChildren(); }, layout, + visiblePositions, focus, resume() { draw(); }, dispose() {