Author SHA1 Message Date
github-actions[bot] 40df5b7ac7 Prepare manifest for v2.0.2.3-rc.11 2026-11-24 06:10:45 +00:00
9 changed files with 120 additions and 417 deletions
+6 -6
View File
@@ -1,11 +1,11 @@
{ {
"version": "2.0.2.3-rc.12", "version": "2.0.2.3-rc.11",
"generated_at": "2026-11-24T09:48:22.826349+00:00", "generated_at": "2026-11-24T06:10:42.618424+00:00",
"algorithm": "sha256", "algorithm": "sha256",
"update_channels": true, "update_channels": true,
"file_count": 288, "file_count": 288,
"size_bytes": 48059903, "size_bytes": 48059903,
"folder_sha256": "9e1cc4963c9a7196cac7a4859085e64d20c023c8e5b633511576a52f3f4f90c4", "folder_sha256": "d9c01ad655f662ee47b2c946e5d5d03e2531059eac1e5d69bace975366ab9a8d",
"core": [ "core": [
"extension.js", "extension.js",
"menu.js", "menu.js",
@@ -439,7 +439,7 @@
}, },
"extension.js": { "extension.js": {
"size": 15732, "size": 15732,
"sha256": "10e65b526a40e307dcac38c3b7819b3122755676bab26722f5c8ec762c4ea044" "sha256": "01bedc58c3acb22f3628ce8cad93795dd6e51488f5bbe93121934f48e4a9a384"
}, },
"function.js": { "function.js": {
"size": 38588, "size": 38588,
@@ -1696,7 +1696,7 @@
"extension.js": { "extension.js": {
"type": "file", "type": "file",
"size": 15732, "size": 15732,
"sha256": "10e65b526a40e307dcac38c3b7819b3122755676bab26722f5c8ec762c4ea044" "sha256": "01bedc58c3acb22f3628ce8cad93795dd6e51488f5bbe93121934f48e4a9a384"
}, },
"function.js": { "function.js": {
"type": "file", "type": "file",
@@ -3116,7 +3116,7 @@
"entry": "mengsan/register.js", "entry": "mengsan/register.js",
"manifest": "dist/modules/mengsan.json", "manifest": "dist/modules/mengsan.json",
"file_count": 846, "file_count": 846,
"size_bytes": 150445067, "size_bytes": 150439572,
"legacy_manifest": "dist/modules/mengsan.legacy.json" "legacy_manifest": "dist/modules/mengsan.legacy.json"
} }
} }
+20 -20
View File
@@ -1,11 +1,11 @@
{ {
"version": "2.0.2.3-rc.12", "version": "2.0.2.3-rc.11",
"generated_at": "2026-11-24T09:48:22.828556+00:00", "generated_at": "2026-11-24T06:10:42.620435+00:00",
"algorithm": "sha256", "algorithm": "sha256",
"update_channels": true, "update_channels": true,
"file_count": 846, "file_count": 846,
"size_bytes": 150445067, "size_bytes": 150439572,
"folder_sha256": "217415a2ab324c7b08b010a3269422933db6671093c655340a97cc9e92f488b5", "folder_sha256": "cc14fd5cb299151caf8e9f2527e49a11a5e49690ba17207d23127d84d0ab3627",
"core": [ "core": [
"mengsan/register.js" "mengsan/register.js"
], ],
@@ -3724,8 +3724,8 @@
"sha256": "6397fcbcd50dba1dc1901b1ea5a3a720d4156c6a761290f904a2135e7a84d373" "sha256": "6397fcbcd50dba1dc1901b1ea5a3a720d4156c6a761290f904a2135e7a84d373"
}, },
"mengsan/cards/personal-piles.js": { "mengsan/cards/personal-piles.js": {
"size": 25275, "size": 24068,
"sha256": "3b8b7311f527b7b0ac1b0dee89f6b77caa751c9562f4b0a70ec2094a973e403a" "sha256": "49c8fc467c159efac1087da5c41ee4eb27707867128135b59042e9bbfde65846"
}, },
"mengsan/cards/rampage.js": { "mengsan/cards/rampage.js": {
"size": 5265, "size": 5265,
@@ -3876,8 +3876,8 @@
"sha256": "580282573457b4fcc27fe976e81aea415148310f0ce543b18dbc18e719dff909" "sha256": "580282573457b4fcc27fe976e81aea415148310f0ce543b18dbc18e719dff909"
}, },
"mengsan/mode.js": { "mengsan/mode.js": {
"size": 126443, "size": 126390,
"sha256": "d46a0e698ff3b1ce9a7f738cbf5c3c3bce847e349cf69a6601484db4ef7f3138" "sha256": "b6715380f36bee8a52d404a8f307ddd967a407c6c3d6bf573c94b3315b4c1f1a"
}, },
"mengsan/monsters/actions.js": { "mengsan/monsters/actions.js": {
"size": 33807, "size": 33807,
@@ -4104,8 +4104,8 @@
"sha256": "784641ea207432c3fe9e55b83d95a7976490521bbfb736d01973f7adaee749d1" "sha256": "784641ea207432c3fe9e55b83d95a7976490521bbfb736d01973f7adaee749d1"
}, },
"mengsan/ui/card-library.js": { "mengsan/ui/card-library.js": {
"size": 25506, "size": 22146,
"sha256": "0b75ac71ef4a9a8ace598aeb03fe59fe866371369d2db035380b0ea169d6f528" "sha256": "029789405e732ff01d537fd7826980c9a9f2c07c95bde087c0e49478de0bd7b9"
}, },
"mengsan/ui/character-select.css": { "mengsan/ui/character-select.css": {
"size": 6060, "size": 6060,
@@ -4240,8 +4240,8 @@
"sha256": "82a31f514ee896cb1c94fd4a2998a2c9e53b49d13a7155028dc72deded7c6c26" "sha256": "82a31f514ee896cb1c94fd4a2998a2c9e53b49d13a7155028dc72deded7c6c26"
}, },
"mengsan/ui/virtual-card-grid.js": { "mengsan/ui/virtual-card-grid.js": {
"size": 5695, "size": 4820,
"sha256": "c63c929576ac341ce0fd1090b4957cb42f1b86c442330f66f841b4ea71f869dd" "sha256": "0933ec3eea0169b34a6e7b4c20e9f75b0645fa787ea70b7ec7d4469213f94ae2"
} }
}, },
"tree": { "tree": {
@@ -7921,8 +7921,8 @@
}, },
"personal-piles.js": { "personal-piles.js": {
"type": "file", "type": "file",
"size": 25275, "size": 24068,
"sha256": "3b8b7311f527b7b0ac1b0dee89f6b77caa751c9562f4b0a70ec2094a973e403a" "sha256": "49c8fc467c159efac1087da5c41ee4eb27707867128135b59042e9bbfde65846"
}, },
"rampage.js": { "rampage.js": {
"type": "file", "type": "file",
@@ -8148,8 +8148,8 @@
}, },
"mode.js": { "mode.js": {
"type": "file", "type": "file",
"size": 126443, "size": 126390,
"sha256": "d46a0e698ff3b1ce9a7f738cbf5c3c3bce847e349cf69a6601484db4ef7f3138" "sha256": "b6715380f36bee8a52d404a8f307ddd967a407c6c3d6bf573c94b3315b4c1f1a"
}, },
"monsters": { "monsters": {
"type": "directory", "type": "directory",
@@ -8456,8 +8456,8 @@
}, },
"card-library.js": { "card-library.js": {
"type": "file", "type": "file",
"size": 25506, "size": 22146,
"sha256": "0b75ac71ef4a9a8ace598aeb03fe59fe866371369d2db035380b0ea169d6f528" "sha256": "029789405e732ff01d537fd7826980c9a9f2c07c95bde087c0e49478de0bd7b9"
}, },
"character-select.css": { "character-select.css": {
"type": "file", "type": "file",
@@ -8641,8 +8641,8 @@
}, },
"virtual-card-grid.js": { "virtual-card-grid.js": {
"type": "file", "type": "file",
"size": 5695, "size": 4820,
"sha256": "c63c929576ac341ce0fd1090b4957cb42f1b86c442330f66f841b4ea71f869dd" "sha256": "0933ec3eea0169b34a6e7b4c20e9f75b0645fa787ea70b7ec7d4469213f94ae2"
} }
} }
} }
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"version": "2.0.2.3-rc.12", "version": "2.0.2.3-rc.11",
"module_id": "mengsan", "module_id": "mengsan",
"snapshot": "legacy", "snapshot": "legacy",
"files": [ "files": [
+1 -1
View File
@@ -6,7 +6,7 @@ import { configureDiagnostics } from "./diagnostics/index.js";
export const type = "extension"; export const type = "extension";
export let shuYing = new Object(); export let shuYing = new Object();
const shuYingLocalVersion = "2.0.2.3-rc.12"; const shuYingLocalVersion = "2.0.2.3-rc.11";
shuYing.name = "术樱包"; shuYing.name = "术樱包";
shuYing.editable = false; shuYing.editable = false;
+23 -56
View File
@@ -20,15 +20,13 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
// Detached nodes: engine get.position recognises these IDs; no duplicate document IDs. // Detached nodes: engine get.position recognises these IDs; no duplicate document IDs.
draw.id = "cardPile"; discard.id = "discardPile"; draw.id = "cardPile"; discard.id = "discardPile";
const owned = new Set(), topPlaying = new Set(), restores = []; 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; const strict = env.strict !== false;
let released = false, forcedOwner = false, forcedPublic = false, exhaustTotal = 0; let released = false, forcedOwner = false, forcedPublic = false, exhaustTotal = 0;
function recordExhaust(card) { function recordExhaust(card) {
if (card.storage?.mengsanExhausted_shuying) return false; if (card.storage?.mengsanExhausted_shuying) return false;
card.storage.mengsanExhausted_shuying = true; card.storage.mengsanExhausted_shuying = true;
battle.exhaustPile.push(snapshotExhausted(card)); exhaustTotal++; battle.exhaustPile.push(snapshot(card)); exhaustTotal++;
queueIroncladExhaust(owner, card); queueRelicExhaust(owner, card); refresh("exhaustPile"); return true; queueIroncladExhaust(owner, card); queueRelicExhaust(owner, card); refresh(); return true;
} }
const personal = () => { const personal = () => {
if (released || forcedPublic) return false; if (released || forcedPublic) return false;
@@ -44,7 +42,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
} }
return false; // Never infer ownership from whose turn it is. return false; // Never infer ownership from whose turn it is.
}; };
const refresh = (...piles) => { if (!released) env.refresh(...piles); }; const refresh = () => { if (!released) env.refresh(); };
const canReceiveTransfer = (card, sourceSession) => !released && session.active && sourceSession===session && const canReceiveTransfer = (card, sourceSession) => !released && session.active && sourceSession===session &&
owner.isAlive() && !owned.has(card) && typeof card?.storage?.mengsanCard_shuying?.id==="string" && 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); ![...owned].some(c=>c.storage?.mengsanCard_shuying?.id===card.storage.mengsanCard_shuying.id);
@@ -97,19 +95,6 @@ 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, 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 }; 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) { for (const data of battle.drawPile) {
if (data.name === "muniu") continue; if (data.name === "muniu") continue;
const card = game.createCard(data.name, data.suit, data.number, data.nature); const card = game.createCard(data.name, data.suit, data.number, data.nature);
@@ -126,28 +111,16 @@ 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 }); if (Object.getOwnPropertyDescriptor(ui, key)?.get === read) Object.defineProperty(ui, key, descriptor.get ? descriptor : { ...descriptor, value: publicNode });
}); });
} }
for (const [key, node] of Object.entries(pileNodes)) { for (const [key, node] of [["drawPile", draw], ["discardPile", discard]]) {
Object.defineProperty(battle, key, { configurable: true, enumerable: true, Object.defineProperty(battle, key, { configurable: true, enumerable: true,
get: () => Array.from(node.childNodes, snapshot) }); get: () => Array.from(node.childNodes, snapshot) });
} }
const observer = new MutationObserver(records => { const observer = new MutationObserver(() => {
if (released) return; 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. // A card from our deck can be discarded during an enemy-owned event.
if (changed.has(publicDiscard)) { for (const card of Array.from(publicDiscard.childNodes)) if (owned.has(card)) discard.appendChild(card);
for (const card of Array.from(publicDiscard.childNodes)) { for (const node of [draw, discard]) for (const card of node.childNodes) adopt(card);
if (!owned.has(card)) continue; refresh();
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 }); for (const node of [draw, discard, publicDiscard]) observer.observe(node, { childList: true });
function wash() { function wash() {
@@ -156,7 +129,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
shuffle(run, cards); shuffle(run, cards);
queueRelicShuffle(owner); queueRelicShuffle(owner);
for (const card of cards) { card.fix?.(); draw.appendChild(card); } for (const card of cards) { card.fix?.(); draw.appendChild(card); }
refresh("drawPile", "discardPile"); refresh();
return true; return true;
} }
function take(number = 1, putBack = false, bottom = false) { function take(number = 1, putBack = false, bottom = false) {
@@ -174,7 +147,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
if (putBack) for (let i = cards.length - 1; i >= 0; i--) { if (putBack) for (let i = cards.length - 1; i >= 0; i--) {
if (bottom) draw.appendChild(cards[i]); else draw.insertBefore(cards[i], draw.firstChild); if (bottom) draw.appendChild(cards[i]); else draw.insertBefore(cards[i], draw.firstChild);
} }
refresh("drawPile"); return cards; refresh(); return cards;
} }
function wrap(object, key, replacement, shouldReplace = personal) { function wrap(object, key, replacement, shouldReplace = personal) {
const descriptor = Object.getOwnPropertyDescriptor(object, key), original = object[key]; const descriptor = Object.getOwnPropertyDescriptor(object, key), original = object[key];
@@ -204,17 +177,6 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
owned.clear(); topPlaying.clear(); draw.remove(); discard.remove(); exhausted.remove(); owned.clear(); topPlaying.clear(); draw.remove(); discard.remove(); exhausted.remove();
}); });
return { 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, take,
canReceiveTransfer, canReceiveTransfer,
receiveTransfer(card,sourceSession) { receiveTransfer(card,sourceSession) {
@@ -297,12 +259,13 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
exhaustTotal() { return exhaustTotal; }, exhaustTotal() { return exhaustTotal; },
exhaustedCards() { return [...owned].filter(card => card.storage?.mengsanExhausted_shuying); }, exhaustedCards() { return [...owned].filter(card => card.storage?.mengsanExhausted_shuying); },
syncExhaustSnapshots() { syncExhaustSnapshots() {
if (released || !session.active) return; if(released || !session.active)return;
for (let index = 0; index < battle.exhaustPile.length; index++) { const current=new Map([...owned].filter(card=>card.storage?.mengsanExhausted_shuying)
const card = exhaustSources.get(battle.exhaustPile[index]); .map(card=>[card.storage.mengsanCard_shuying?.id,card]));
if (card?.storage?.mengsanExhausted_shuying) battle.exhaustPile[index] = snapshotExhausted(card); for(let index=0;index<battle.exhaustPile.length;index++){
const card=current.get(battle.exhaustPile[index].id);
if(card)battle.exhaustPile[index]=snapshot(card);
} }
// Whole-deck upgrades also mutate draw and discard cards in place.
refresh(); refresh();
}, },
// 自动打出不会触发抽牌、洗牌或堆顶牌不足的失败规则。 // 自动打出不会触发抽牌、洗牌或堆顶牌不足的失败规则。
@@ -310,7 +273,9 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
if (released || !session.active || !owned.has(card)) return false; if (released || !session.active || !owned.has(card)) return false;
if (fromExhaust) { if (fromExhaust) {
if (!card.storage?.mengsanExhausted_shuying) return false; if (!card.storage?.mengsanExhausted_shuying) return false;
removeExhaustSnapshot(card); const id = card.storage?.mengsanCard_shuying?.id;
const index = battle.exhaustPile.findIndex(data => data.id === id);
if (index >= 0) battle.exhaustPile.splice(index,1);
delete card.storage.mengsanExhausted_shuying; delete card.storage.mengsanExhausted_shuying;
delete card._selfDestroyed; delete card._selfDestroyed;
} else if (card.parentNode !== draw && card.parentNode !== discard) return false; } else if (card.parentNode !== draw && card.parentNode !== discard) return false;
@@ -350,7 +315,9 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
if(released || !session.active || !owner.isAlive() || !owned.has(card))return false; if(released || !session.active || !owner.isAlive() || !owned.has(card))return false;
if(owner.getCards("h").includes(card))return true; if(owner.getCards("h").includes(card))return true;
if(card.storage?.mengsanExhausted_shuying){ if(card.storage?.mengsanExhausted_shuying){
removeExhaustSnapshot(card); const id=card.storage.mengsanCard_shuying?.id;
const index=battle.exhaustPile.findIndex(data=>data.id===id);
if(index>=0)battle.exhaustPile.splice(index,1);
delete card.storage.mengsanExhausted_shuying;delete card._selfDestroyed; delete card.storage.mengsanExhausted_shuying;delete card._selfDestroyed;
} }
delete card.storage.mengsanConsumed_shuying; delete card.storage.mengsanConsumed_shuying;
@@ -389,7 +356,7 @@ export function installPersonalPiles(session, owner, battle, run, resources, env
const card = game.createCard(data.name, data.suit, data.number, data.nature); const card = game.createCard(data.name, data.suit, data.number, data.nature);
adopt(card, data); adopt(card, data);
discard.appendChild(card); discard.appendChild(card);
refresh("discardPile"); refresh();
return card; return card;
}, },
async addToHand(data) { async addToHand(data) {
+2 -2
View File
@@ -703,7 +703,7 @@ const prepareBattle = async (run, node, encounter, session, resources) => {
activeBattle.personalPiles = installPersonalPiles(session, me, _status.mengsanBattle_shuying, run, resources, { activeBattle.personalPiles = installPersonalPiles(session, me, _status.mengsanBattle_shuying, run, resources, {
game, ui, get, lib, _status, document, MutationObserver, shuffle: shuffleBattlePile, game, ui, get, lib, _status, document, MutationObserver, shuffle: shuffleBattlePile,
refresh: (...piles) => activeBattle?.session === session && activeBattle.pilesUI?.refresh(...piles), refresh: () => activeBattle?.session === session && activeBattle.pilesUI?.refresh(),
}); });
activeBattle.personalPiles.withOwner(() => me.init(run.player.character)); activeBattle.personalPiles.withOwner(() => me.init(run.player.character));
me.storage.mengsanUnitId_shuying = "player"; me.storage.mengsanUnitId_shuying = "player";
@@ -799,7 +799,7 @@ const prepareBattle = async (run, node, encounter, session, resources) => {
session.ownResource({}, () => game.removeGlobalSkill(skill)); session.ownResource({}, () => game.removeGlobalSkill(skill));
} }
} }
activeBattle.pilesUI = mountBattlePiles(session, _status.mengsanBattle_shuying, activeBattle.personalPiles.pileView); activeBattle.pilesUI = mountBattlePiles(session, _status.mengsanBattle_shuying);
currentBattle.owner = me; currentBattle.owner = me;
currentBattle.run = run; currentBattle.run = run;
potionSkillIds.forEach(skill => me.addSkill(skill)); potionSkillIds.forEach(skill => me.addSkill(skill));
+1 -171
View File
@@ -94,11 +94,7 @@ async function mountSurface(page, origin, prefix, settings, surface) {
openCardLibrary(run); openCardLibrary(run);
} else if (surface==='牌堆') { } else if (surface==='牌堆') {
const {mountBattlePiles} = await modules('card-library'); const {mountBattlePiles} = await modules('card-library');
const battle = {drawPile:run.player.deck,discardPile:[],exhaustPile:[]}; mountBattlePiles({active:true,ownResource(){}},{drawPile:run.player.deck,discardPile:[],exhaustPile:[]});
window.pileReview = {
battle,
control: mountBattlePiles({active:true,ownResource(){}},battle),
};
} else if (surface==='遗物') { } else if (surface==='遗物') {
const {mountRelics} = await modules('relics'); const {mountRelics} = await modules('relics');
mountRelics({active:true,ownResource(){}},run,{status(){},counter:()=>({value:null,label:null})},{stripRoot:ui.arena}); mountRelics({active:true,ownResource(){}},run,{status(){},counter:()=>({value:null,label:null})},{stripRoot:ui.arena});
@@ -182,173 +178,7 @@ async function checkSurface(page, surface, settings, origin, prefix) {
if (result!==null) assert.equal(await page.evaluate(()=>zoomReviewResult),result,'the original action returns the choice'); 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) { 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 = []; const failures = [];
let checks = 0; let checks = 0;
const scenarios = [{zoom:.5},{zoom:.65},{zoom:1},{zoom:1.5},{zoom:2},{zoom:3},{zoom:1.5,transform:true}, const scenarios = [{zoom:.5},{zoom:.65},{zoom:1},{zoom:1.5},{zoom:2},{zoom:3},{zoom:1.5,transform:true},
+45 -117
View File
@@ -115,7 +115,6 @@ export function openCardLibrary(run, options = {}) {
if (existing) { existing.focus(); return () => {}; } if (existing) { existing.focus(); return () => {}; }
const previousFocus = document.activeElement; const previousFocus = document.activeElement;
const selection = options.selection; const selection = options.selection;
const sections = options.sections;
const dialog = element("dialog", "mengsan-deck-dialog-shuying", null); const dialog = element("dialog", "mengsan-deck-dialog-shuying", null);
dialog.setAttribute("aria-label", options.title || "卡牌库"); dialog.setAttribute("aria-label", options.title || "卡牌库");
const header = element("header", "ms-deck-header", null, dialog); const header = element("header", "ms-deck-header", null, dialog);
@@ -123,13 +122,10 @@ export function openCardLibrary(run, options = {}) {
element("span", "ms-deck-eyebrow", options.eyebrow || "梦三 · 行囊", title); element("span", "ms-deck-eyebrow", options.eyebrow || "梦三 · 行囊", title);
element("h2", "ms-deck-title", options.title || "卡牌库", title); element("h2", "ms-deck-title", options.title || "卡牌库", title);
let closed = false, sizeObserver = null, virtualGrid = null, searchTimer = 0; let closed = false, sizeObserver = null, virtualGrid = null, searchTimer = 0;
let refreshFrame = 0;
const pendingPiles = new Set();
const close = () => { const close = () => {
if (closed) return; if (closed) return;
closed = true; closed = true;
clearTimeout(searchTimer); clearTimeout(searchTimer);
cancelPileRefresh();
virtualGrid?.dispose(); virtualGrid?.dispose();
sizeObserver?.disconnect(); sizeObserver?.disconnect();
if (typeof window !== "undefined") window.removeEventListener?.("resize", fitCards); if (typeof window !== "undefined") window.removeEventListener?.("resize", fitCards);
@@ -138,7 +134,7 @@ export function openCardLibrary(run, options = {}) {
list.replaceChildren(); detailPanel.replaceChildren(); body.replaceChildren(); list.replaceChildren(); detailPanel.replaceChildren(); body.replaceChildren();
dialog.replaceChildren(); dialog.replaceChildren();
catalogRecords = null; descriptionCache = new WeakMap(); catalogRecords = null; descriptionCache = new WeakMap();
selectedButton = null; current = []; sectionRecords = []; detailListPosition = null; selectedButton = null; current = [];
virtualGrid = null; sizeObserver = null; virtualGrid = null; sizeObserver = null;
if (previousFocus?.isConnected) previousFocus.focus(); if (previousFocus?.isConnected) previousFocus.focus();
const onClose = options.onClose; const onClose = options.onClose;
@@ -146,16 +142,16 @@ export function openCardLibrary(run, options = {}) {
onClose?.(close); onClose?.(close);
}; };
button("关闭", header, close); button("关闭", header, close);
let view = selection || (!sections && options.view === "catalog") let view = selection || (!options.sections && options.view === "catalog")
? "catalog" : "deck"; ? "catalog" : "deck";
const navigation = element("nav", "ms-deck-tabs", null, dialog); const navigation = element("nav", "ms-deck-tabs", null, dialog);
navigation.setAttribute("aria-label", "卡牌列表视图"); navigation.setAttribute("aria-label", "卡牌列表视图");
const deckTab = button("持有牌", navigation, () => { view = "deck"; render(); }); const deckTab = button("持有牌", navigation, () => { view = "deck"; render(); });
const catalogTab = button("图鉴", navigation, () => { view = "catalog"; render(); }); const catalogTab = button("图鉴", navigation, () => { view = "catalog"; render(); });
deckTab.hidden = catalogTab.hidden = Boolean(sections || selection); deckTab.hidden = catalogTab.hidden = Boolean(options.sections || selection);
let sectionIndex = 0; let sectionIndex = 0;
const sectionTabs = sections?.map((section, index) => const sectionTabs = options.sections ? options.sections().map((section, index) =>
button(section.title, navigation, () => { sectionIndex = index; render(); })); button(section.title, navigation, () => { sectionIndex = index; render(); })) : [];
const filters = element("div", "ms-catalog-filters", null, dialog); const filters = element("div", "ms-catalog-filters", null, dialog);
function field(label) { function field(label) {
const wrapper = element("label", "ms-catalog-field", null, filters); const wrapper = element("label", "ms-catalog-field", null, filters);
@@ -196,7 +192,6 @@ export function openCardLibrary(run, options = {}) {
const footer = element("p", "ms-deck-footer", "点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序", dialog); const footer = element("p", "ms-deck-footer", "点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序", dialog);
let current = Array.isArray(run?.player?.deck) ? run.player.deck : []; let current = Array.isArray(run?.player?.deck) ? run.player.deck : [];
let detail = false, selectedButton = null, scrollTop = 0, orderedView = false; 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 list = element("div", "ms-deck-grid ms-library-grid", null, body);
const detailPanel = element("section", "ms-deck-detail", null, body); const detailPanel = element("section", "ms-deck-detail", null, body);
detailPanel.hidden = true; detailPanel.hidden = true;
@@ -204,15 +199,7 @@ export function openCardLibrary(run, options = {}) {
virtualGrid = createVirtualCardGrid(body, list, createTile); virtualGrid = createVirtualCardGrid(body, list, createTile);
function back() { function back() {
detail = false; detailPanel.hidden = true; list.hidden = false; detail = false; detailPanel.hidden = true; list.hidden = false;
detailPanel.replaceChildren(); detailPanel.replaceChildren(); body.scrollTop = scrollTop; fitCards();
if (sections) {
cancelPileRefresh();
updateSectionTabs();
renderSection({ position: detailListPosition });
detailListPosition = null; selectedButton = null;
return;
}
body.scrollTop = scrollTop; fitCards();
virtualGrid?.resume(); virtualGrid?.resume();
if (selectedButton?.isConnected) selectedButton.focus({ preventScroll: true }); if (selectedButton?.isConnected) selectedButton.focus({ preventScroll: true });
else if (virtualGrid && selectedButton) virtualGrid.focus(Number(selectedButton.dataset.cardIndex)); else if (virtualGrid && selectedButton) virtualGrid.focus(Number(selectedButton.dataset.cardIndex));
@@ -220,7 +207,6 @@ export function openCardLibrary(run, options = {}) {
function showDetail(card, details, owner, catalog = false) { function showDetail(card, details, owner, catalog = false) {
clearTimeout(searchTimer); clearTimeout(searchTimer);
selectedButton = owner; scrollTop = body.scrollTop; selectedButton = owner; scrollTop = body.scrollTop;
if (sections) detailListPosition = captureListPosition(owner);
detail = true; list.hidden = true; detailPanel.hidden = false; detail = true; list.hidden = true; detailPanel.hidden = false;
detailPanel.replaceChildren(); detailPanel.replaceChildren();
const backButton = button(catalog ? "返回图鉴" : "返回牌库", detailPanel, back); const backButton = button(catalog ? "返回图鉴" : "返回牌库", detailPanel, back);
@@ -256,8 +242,7 @@ export function openCardLibrary(run, options = {}) {
} }
body.scrollTop = 0; backButton.focus(); body.scrollTop = 0; backButton.focus();
} }
function fitCards() { layoutCards(); } function fitCards() {
function layoutCards(position = null) {
if (closed || !body.clientHeight) return; if (closed || !body.clientHeight) return;
const padding = getComputedStyle(body); const padding = getComputedStyle(body);
const available = body.clientHeight - parseFloat(padding.paddingTop) - parseFloat(padding.paddingBottom); const available = body.clientHeight - parseFloat(padding.paddingTop) - parseFloat(padding.paddingBottom);
@@ -265,7 +250,7 @@ export function openCardLibrary(run, options = {}) {
const height = Math.max(128, Math.min(218, Math.floor((available - (rows - 1) * 8) / rows))); 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-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"); 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, position); virtualGrid?.layout(height);
} }
function createTile(record, index) { function createTile(record, index) {
const { card, catalog = false, ordered = false } = record; const { card, catalog = false, ordered = false } = record;
@@ -281,95 +266,33 @@ export function openCardLibrary(run, options = {}) {
element("span", "ms-deck-excerpt", details.description, tile); element("span", "ms-deck-excerpt", details.description, tile);
return 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() { function render() {
clearTimeout(searchTimer); clearTimeout(searchTimer);
detail = false; list.hidden = false; detailPanel.hidden = true; detail = false; list.hidden = false; detailPanel.hidden = true;
detailPanel.replaceChildren(); detailPanel.replaceChildren();
body.scrollTop = 0; body.scrollTop = 0;
selectedButton = null; selectedButton = null;
const catalog = !sections && view === "catalog"; const catalog = !options.sections && view === "catalog";
filters.hidden = !catalog; filters.hidden = !catalog;
deckTab.setAttribute("aria-pressed", String(!catalog)); deckTab.setAttribute("aria-pressed", String(!catalog));
catalogTab.setAttribute("aria-pressed", String(catalog)); catalogTab.setAttribute("aria-pressed", String(catalog));
list.classList.toggle("ms-catalog-grid", catalog); list.classList.toggle("ms-catalog-grid", catalog);
if (sections) { let records = [], emptyMessage = "此处暂无卡牌。";
cancelPileRefresh(); orderedView = false;
detailListPosition = null; if (options.sections) {
updateSectionTabs(); const sections = options.sections();
renderSection(); const section = sections[sectionIndex];
return; orderedView = Boolean(section?.ordered);
} if (section?.ordered) emptyMessage = "剩余牌堆为空;下一次摸牌需按规则洗切弃牌堆,洗切后的顺序尚未确定。";
let records = []; sectionTabs.forEach((tab, index) => {
if (catalog) { 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) {
const query = search.value.trim().toLocaleLowerCase(); const query = search.value.trim().toLocaleLowerCase();
catalogRecords ||= getCardCatalog().map(card => { catalogRecords ||= getCardCatalog().map(card => {
const details = describeCatalogCard(card); const details = describeCatalogCard(card);
@@ -388,14 +311,15 @@ export function openCardLibrary(run, options = {}) {
details.cost !== null && details.cost === Number(costFilter.value)))); details.cost !== null && details.cost === Number(costFilter.value))));
summary.textContent = `卡牌图鉴 · 共 ${total} 种 · 当前显示 ${records.length} 种`; summary.textContent = `卡牌图鉴 · 共 ${total} 种 · 当前显示 ${records.length} 种`;
} else { } else {
summary.textContent = `本次征程实际携带 · 共 ${current.length} 张 · 同名不同花色、点数分别展示`; summary.textContent = options.sections ? "剩余牌堆按从左到右、从上到下的顺序摸取;第 1 张为下一张。" :
`本次征程实际携带 · 共 ${current.length} 张 · 同名不同花色、点数分别展示`;
} }
if (catalog && selection) footer.textContent = selection.description; if (catalog && selection) footer.textContent = selection.description;
else footer.textContent = catalog ? "图鉴仅供查阅,不会获得卡牌或改变征程牌组 · 点击卡牌查看完整介绍" : else footer.textContent = catalog ? "图鉴仅供查阅,不会获得卡牌或改变征程牌组 · 点击卡牌查看完整介绍" :
"点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序"; "点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序";
virtualGrid.setRecords(catalog ? records : current.map(card => ({ card }))); virtualGrid.setRecords(catalog || options.sections ? records : current.map(card => ({ card })));
if (!(catalog ? records : current).length) { if (!(catalog || options.sections ? records : current).length) {
element("p", "ms-deck-empty", catalog ? "没有符合筛选的卡牌,可清空筛选后查看全部图鉴。" : "此处暂无卡牌。", list); element("p", "ms-deck-empty", catalog ? "没有符合筛选的卡牌,可清空筛选后查看全部图鉴。" : emptyMessage, list);
} }
fitCards(); fitCards();
} }
@@ -414,12 +338,20 @@ export function openCardLibrary(run, options = {}) {
window.addEventListener?.("resize", fitCards); window.addEventListener?.("resize", fitCards);
} }
header.querySelector("button").focus(); header.querySelector("button").focus();
if (sections) close.refresh = schedulePileRefresh; 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();
};
return close; return close;
} }
// The battle view exposes only this player's own piles, including consumed cards. // The battle view exposes only this player's own piles, including consumed cards.
export function mountBattlePiles(session, battle, pileView) { export function mountBattlePiles(session, battle) {
let closeDialog = null, disposed = false; let closeDialog = null, disposed = false;
const control = button("牌堆", ui.window, () => { const control = button("牌堆", ui.window, () => {
if (disposed || !session.active || battle.resolving) return; if (disposed || !session.active || battle.resolving) return;
@@ -427,14 +359,10 @@ export function mountBattlePiles(session, battle, pileView) {
closeDialog = openCardLibrary(null, { closeDialog = openCardLibrary(null, {
title: "战斗牌堆", eyebrow: "梦三 · 个人牌堆", title: "战斗牌堆", eyebrow: "梦三 · 个人牌堆",
onClose(handle) { if (closeDialog === handle) closeDialog = null; }, onClose(handle) { if (closeDialog === handle) closeDialog = null; },
pileView: pileView ?? { sections: () => [
count: key => battle[key].length, { title: "剩余牌堆", cards: battle.drawPile, ordered: true },
records: key => battle[key].map(card => ({ card, key: card.id ?? card })), { title: "弃牌堆", cards: battle.discardPile, ordered: false },
}, { title: "消耗牌堆", cards: battle.exhaustPile, ordered: false },
sections: [
{ title: "剩余牌堆", key: "drawPile", ordered: true },
{ title: "弃牌堆", key: "discardPile", ordered: false },
{ title: "消耗牌堆", key: "exhaustPile", ordered: false },
], ],
}); });
}, "mengsan-battle-piles-button-shuying"); }, "mengsan-battle-piles-button-shuying");
@@ -444,5 +372,5 @@ export function mountBattlePiles(session, battle, pileView) {
disposed = true; closeDialog?.(); closeDialog = null; control.remove(); disposed = true; closeDialog?.(); closeDialog = null; control.remove();
}; };
session.ownResource(control, dispose); session.ownResource(control, dispose);
return { dispose, refresh(...piles) { if (!disposed && session.active) closeDialog?.refresh?.(...piles); } }; return { dispose, refresh() { if (!disposed) closeDialog?.refresh?.(); } };
} }
+21 -43
View File
@@ -5,21 +5,6 @@ export function createVirtualCardGrid(viewport, grid, createCard) {
const maxCached = 24; const maxCached = 24;
let records = [], columns = 1, height = 218, gap = 8, padding = 5, viewportHeight = 0; let records = [], columns = 1, height = 218, gap = 8, padding = 5, viewportHeight = 0;
let frame = 0, disposed = false; 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() { function draw() {
if (disposed || grid.hidden || !viewportHeight) return; if (disposed || grid.hidden || !viewportHeight) return;
const stride = height + gap; const stride = height + gap;
@@ -35,26 +20,25 @@ export function createVirtualCardGrid(viewport, grid, createCard) {
while (cached.size > maxCached) cached.delete(cached.keys().next().value); while (cached.size > maxCached) cached.delete(cached.keys().next().value);
} }
} }
for (let index = first; index < end; index++) mount(index); 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);
}
} }
function schedule() { function schedule() {
if (!frame && !disposed) frame = requestAnimationFrame(() => { frame = 0; draw(); }); if (!frame && !disposed) frame = requestAnimationFrame(() => { frame = 0; draw(); });
} }
function rowTop(index) { function layout(cardHeight = height) {
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; height = cardHeight;
if (disposed || grid.hidden || !grid.clientWidth) return; if (disposed || grid.hidden || !grid.clientWidth) return;
const style = getComputedStyle(grid); const style = getComputedStyle(grid);
@@ -69,21 +53,16 @@ export function createVirtualCardGrid(viewport, grid, createCard) {
node.style.gridRow = String(Math.floor(index / columns) + 1); node.style.gridRow = String(Math.floor(index / columns) + 1);
node.style.gridColumn = String(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(); draw();
} }
function focus(index, { scroll = true } = {}) { function focus(index) {
if (!Number.isInteger(index) || index < 0 || index >= records.length || disposed) return; if (!Number.isInteger(index) || index < 0 || index >= records.length || disposed) return;
if (scroll) { const top = padding + Math.floor(index / columns) * (height + gap);
const top = rowTop(index); if (top < viewport.scrollTop) viewport.scrollTop = top;
if (top < viewport.scrollTop) viewport.scrollTop = top; else if (top + height > viewport.scrollTop + viewportHeight) {
else if (top + height > viewport.scrollTop + viewportHeight) { viewport.scrollTop = top + height - viewportHeight;
viewport.scrollTop = top + height - viewportHeight;
}
draw();
} }
mount(index).focus({ preventScroll: true }); draw(); mounted.get(index)?.focus({ preventScroll: true });
} }
function keydown(event) { function keydown(event) {
const card = event.target.closest("[data-card-index]"); const card = event.target.closest("[data-card-index]");
@@ -104,7 +83,6 @@ export function createVirtualCardGrid(viewport, grid, createCard) {
records = value; mounted.clear(); cached.clear(); grid.replaceChildren(); records = value; mounted.clear(); cached.clear(); grid.replaceChildren();
}, },
layout, layout,
visiblePositions,
focus, focus,
resume() { draw(); }, resume() { draw(); },
dispose() { dispose() {