// Real browser DOM/CSS with engine services isolated; this is not a full-game test. const assert = require('node:assert/strict'); const http = require('node:http'); const fs = require('node:fs'); const path = require('node:path'); const app = path.resolve(__dirname, '../../../..'); const packages = process.env.CODEX_NODE_MODULES; const { chromium } = require(packages ? path.join(packages, 'playwright') : 'playwright'); const prefix = '/extension/' + encodeURIComponent('术樱包') + '/mengsan'; const decadePrefix = '/extension/' + encodeURIComponent('十周年UI'); const reviewOnly = process.env.HUD_REVIEW === '1'; const journeyReview = process.env.UI_ZOOM_REVIEW === '1'; const holdStatus = async (page, locator, pointerType = 'mouse') => { const box = await locator.boundingBox(); const point = {x:box.x + box.width / 2,y:box.y + box.height / 2}; if (pointerType === 'touch') { await locator.dispatchEvent('pointerdown', {button:0,pointerId:44, pointerType,clientX:point.x,clientY:point.y}); await page.waitForTimeout(550); await page.evaluate(() => window.dispatchEvent( new PointerEvent('pointerup', {pointerId:44,pointerType:'touch'}))); } else { await page.mouse.move(point.x,point.y); await page.mouse.down(); await page.waitForTimeout(550); await page.mouse.up(); } }; // Native themes use different button sizes. Drag onto an exposed point on the // original player, rather than assuming its center is clear in the dense fixture. const exposedTarget = (page,index) => page.evaluate(index => { const player=game.players[index],rect=player.getBoundingClientRect(); for(const y of [.5,.15,.85,.05,.95])for(const x of [.5,.15,.85]) { const px=rect.left+rect.width*x,py=rect.top+rect.height*y; if(document.elementFromPoint(px,py)?.closest('.player')===player)return {x:px,y:py,width:0,height:0}; } throw new Error('Native target has no exposed drag point: '+index); },index); async function checkMobileTargetLine(page, artifact) { const touch = await page.context().newCDPSession(page); const handCard = page.locator('.handcards>.card').first(); const target = await exposedTarget(page, 1); const end = {x:target.x, y:target.y}; const aim = page.locator('.mengsan-hand-aim-shuying'); async function drag() { const start = await handCard.boundingBox(); const source = {x:start.x + start.width / 2,y:start.y + start.height / 2}; await touch.send('Input.dispatchTouchEvent', {type:'touchStart',touchPoints:[source]}); await touch.send('Input.dispatchTouchEvent', {type:'touchMove',touchPoints:[end]}); await aim.waitFor({state:'visible',timeout:2500}); } // Exercise a WebView-style mismatch between the SVG matrix and its painted bounds. await page.evaluate(() => { const create = document.createElementNS.bind(document); document.createElementNS = (namespace,tag) => { const node = create(namespace,tag); if (tag === 'svg') { const screenMatrix = node.getScreenCTM.bind(node); node.getScreenCTM = () => screenMatrix()?.translate(-120,45); } return node; }; }); await drag(); const geometry = await aim.evaluate((overlay, pointer) => { const card = window.card.getBoundingClientRect(); const origin = {x:card.left + card.width / 2, y:card.top}; const line = overlay.querySelector('line'); if (line) { const matrix = line.getScreenCTM(); return {origin,pointer,from:new DOMPoint(line.x1.baseVal.value,line.y1.baseVal.value).matrixTransform(matrix).toJSON(), to:new DOMPoint(line.x2.baseVal.value,line.y2.baseVal.value).matrixTransform(matrix).toJSON(),bounds:line.getBoundingClientRect().toJSON()}; } const bounds = overlay.getBoundingClientRect(); const left = origin.x <= pointer.x, up = origin.y <= pointer.y; return {origin,pointer,from:{x:left?bounds.left:bounds.right,y:up?bounds.top:bounds.bottom}, to:{x:left?bounds.right:bounds.left,y:up?bounds.bottom:bounds.top}}; },end); await page.evaluate(() => { delete document.createElementNS; }); if (artifact) await page.screenshot({path:artifact}); await touch.send('Input.dispatchTouchEvent', {type:'touchCancel',touchPoints:[]}); assert.equal(await aim.count(),0,'the target line disappears on touch cancellation'); assert.ok(Math.hypot(geometry.from.x-geometry.origin.x,geometry.from.y-geometry.origin.y)<=2, 'A012 target line starts at the selected card’s top center: '+JSON.stringify(geometry)); assert.ok(Math.hypot(geometry.to.x-end.x,geometry.to.y-end.y)<=2, 'A012 target line ends at the current touch: '+JSON.stringify(geometry)); assert.ok(geometry.bounds && Math.abs(geometry.bounds.bottom-geometry.origin.y)<=2 && Math.abs(geometry.bounds.top-end.y)<=2,'A012 the rendered line reaches both endpoint heights'); await page.waitForTimeout(180); await drag(); const before = await page.evaluate(()=>game.isSubmitted()); await touch.send('Input.dispatchTouchEvent', {type:'touchEnd',touchPoints:[]}); assert.equal(await aim.count(),0,'the target line disappears on touch release'); assert.equal(await page.evaluate(()=>game.isSubmitted()),before+1,'touch release still submits the valid target once'); } async function checkOrdinaryPlayCenter(page, skin, artifact) { const geometry = await page.evaluate(async skin => { const {arena,control,me} = ui; const prompt = document.createElement('div'); prompt.className = skin === 'native' ? 'dialog' : 'hand-tip'; prompt.textContent = '请选择要使用的牌'; arena.append(prompt); ui.dialog = prompt; hudEventState.event.dialog = prompt; hud.refresh(); await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))); const bounds = node => node.getBoundingClientRect().toJSON(); const result = {arena:bounds(arena),hand:bounds(me),card:bounds(card),prompt:bounds(prompt), buttons:[...control.firstElementChild.children].map(bounds)}; if (!window.card.isConnected) throw new Error('The original hand card must remain connected'); return result; },skin); if (artifact) await page.screenshot({path:artifact}); await page.evaluate(()=>{ui.dialog.remove();delete ui.dialog;delete hudEventState.event.dialog;hud.refresh();}); const {arena,hand,card,prompt,buttons} = geometry; const center = box => (box.left+box.right)/2; const actions = {left:Math.min(...buttons.map(box=>box.left)),right:Math.max(...buttons.map(box=>box.right))}; assert.ok([hand,card,prompt,actions].every(box=>Math.abs(center(box)-center(arena))<=2), 'ordinary play fan, prompt and action buttons share the arena center: '+JSON.stringify(geometry)); } async function setBattleZoom(page, zoom) { await page.evaluate(zoom => { const {style} = document.body; style.zoom = zoom; style.width = style.height = '100%'; },zoom); // Let the native hand transform and the resize observers settle after a zoom change. await page.waitForFunction(() => { const arena = ui.arena.getBoundingClientRect(), hand = card.getBoundingClientRect(); return Math.abs(arena.width-innerWidth)<=2 && Math.abs((arena.left+arena.right-hand.left-hand.right)/2)<=2; },null,{timeout:2500}); } async function checkCommittedLine(page, skin) { const geometry = await page.evaluate(async ({skin,decadePrefix}) => { const engine = await import('/noname.js'); const {Player} = await import('/noname/library/element/player.js'); const {arena,me:hand} = window.ui; const [actor,target] = window.game.players; // Use the shipped line producers and renderer, with only the game lifecycle isolated. engine.lib.config ??= {}; engine.setUI({arena,create:{div:selector => { const node = document.createElement('div'); if (selector) node.className = 'linexy hidden'; node.show = () => node.classList.remove('hidden'); node.listenTransition = () => {}; node.setBackgroundImage = path => {node.style.backgroundImage = `url(${path})`;}; return node; }},refresh:node=>node.getBoundingClientRect()}); const get = engine.get; engine.setGet({itemtype:()=> 'player',objtype:get.objtype.bind(get),xyDistance:get.xyDistance.bind(get)}); engine.setGame({me:actor,broadcast(){},addVideo(){},linexy:engine.Game.prototype.linexy}); actor.getLeft = target.getLeft = function() { return this.offsetLeft; }; actor.getTop = target.getTop = function() { return this.offsetTop; }; let line = Player.prototype.line; if (skin !== 'native') { const {playerLine} = await import(decadePrefix+'/src/overrides/player/animations.js'); const {BoundsCache} = await import(decadePrefix+'/src/utils/bounds.js'); window.decadeUI ??= {boundsCaches:{hand:new BoundsCache(hand)}}; actor.checkBoundsCache = target.checkBoundsCache = function() { this.cacheLeft = this.offsetLeft; this.cacheTop = this.offsetTop; this.cacheWidth = this.offsetWidth; this.cacheHeight = this.offsetHeight; }; line = playerLine; } line.call(actor,target,{duration:120}); const effect = arena.querySelector('.linexy'); if (!effect) return null; await new Promise(resolve=>setTimeout(resolve,150)); const matrix = new DOMMatrix(getComputedStyle(effect).transform); const x1 = parseFloat(effect.style.left), y1 = parseFloat(effect.style.top); const length = parseFloat(effect.style.height); const expectedStart = skin === 'native' ? {x:actor.offsetLeft+actor.offsetWidth/2,y:actor.offsetTop+actor.offsetHeight/2} : {x:arena.offsetWidth/2,y:hand.offsetTop}; const result = {x1,y1,x2:x1+matrix.c*length,y2:y1+matrix.d*length,expectedStart, expectedEnd:{x:target.offsetLeft+target.offsetWidth/2,y:target.offsetTop+target.offsetHeight/2}}; effect.remove(); // Run the configured renderer as well as the default one. Its art may be provided by the Android package. Object.assign(engine.game,{ linexy:engine.Game.prototype.zsJinlongLineXy, zsPlayLineAnimationByName:engine.Game.prototype.zsPlayLineAnimationByName, zsPlayLineAnimation:engine.Game.prototype.zsPlayLineAnimation, jianqiLineAnim:new engine.Game().jianqiLineAnim, }); line.call(actor,target,{duration:120}); const dragon = arena.lastElementChild; const {left,top,width,transform,backgroundImage} = dragon.style; const degrees = Number(transform.match(/rotate\(([-.\d]+)deg\)/)?.[1]); const radians = degrees*Math.PI/180; const distance = parseFloat(width)-2; const start = {x:parseFloat(left),y:parseFloat(top)+10}; result.dragon = {start,end:{x:start.x+distance*Math.cos(radians),y:start.y+distance*Math.sin(radians)},backgroundImage}; return result; },{skin,decadePrefix}); assert.ok(geometry && Math.hypot(geometry.x1-geometry.expectedStart.x,geometry.y1-geometry.expectedStart.y)<=2 && Math.hypot(geometry.x2-geometry.expectedEnd.x,geometry.y2-geometry.expectedEnd.y)<=2, 'A012 the committed card effect retains its native origin and reaches the target: '+JSON.stringify(geometry)); assert.ok(geometry.dragon.backgroundImage.includes('jinlonglinexy') && Math.hypot(geometry.dragon.start.x-geometry.expectedStart.x,geometry.dragon.start.y-geometry.expectedStart.y)<=2 && Math.hypot(geometry.dragon.end.x-geometry.expectedEnd.x,geometry.dragon.end.y-geometry.expectedEnd.y)<=2, 'the configured Jinlong effect retains its origin and reaches the target: '+JSON.stringify(geometry)); } async function checkBattlePotionSlots(page, skin, artifact) { await page.evaluate(async ({prefix,skin}) => { const {mountPotionSlots} = await import(prefix+'/ui/potions.js'); const {ui,battle,hud} = window; const counter = document.createElement('div'); counter.className = 'cardRoundNumber'; counter.innerHTML = '
23
第3轮
03:00
'; if (skin === 'native') counter.style.cssText = 'left:18px;top:4px;width:140px;height:40px'; (skin === 'shousha' ? document.body : ui.arena).append(counter); ui.cardRoundTime = counter; window.reviewCounter = counter; window.potionActionCalls = 0; battle.potionUI = mountPotionSlots(ui.arena,{potions:['ENERGY_POTION',null,'FIRE_POTION']},{ canUse:()=>true,use:()=>{ window.potionActionCalls++; }, }); hud.refresh(); },{prefix,skin}); const geometry = await page.evaluate(() => { const box = node => node.getBoundingClientRect().toJSON(); return {arena:box(ui.arena),strip:box(document.querySelector('.mengsan-battle-potions')), counters:[reviewCounter,...reviewCounter.querySelectorAll('div,span')].map(box)}; }); const {arena,strip,counters} = geometry; assert.ok(strip.left>=arena.left && strip.right<=arena.left+arena.width/2 && strip.top>=arena.top && strip.bottom<=arena.top+140,'battle potions stay at the upper left: '+JSON.stringify(geometry)); assert.ok(counters.every(box=>!box.width||!box.height||strip.right<=box.left||strip.left>=box.right|| strip.bottom<=box.top||strip.top>=box.bottom),'battle potion slots clear the round, time and pile counters'); if (artifact) await page.screenshot({path:artifact}); await page.getByRole('button',{name:'能量药水',exact:true}).tap(); await page.getByRole('button',{name:'使用',exact:true}).tap(); assert.equal(await page.evaluate(()=>potionActionCalls),1,'the relocated potion button opens details and submits once'); const fallback = await page.evaluate(() => { reviewCounter.className = ''; reviewCounter.replaceChildren(); reviewCounter.style.cssText = 'position:absolute;left:0;top:0;width:46%;height:46px;transition:none'; hud.refresh(); const panel = reviewCounter.getBoundingClientRect(), arena = ui.arena.getBoundingClientRect(); const slots = ui.arena.querySelector('.mengsan-battle-potions').getBoundingClientRect(); return slots.top>panel.bottom && slots.left>=arena.left && slots.right<=arena.left+arena.width/2; }); assert.ok(fallback,'the potion strip drops below a counter that leaves no room beside it'); await page.evaluate(()=>{battle.potionUI.dispose();delete battle.potionUI;reviewCounter.remove();delete ui.cardRoundTime;}); } async function checkPotionSkillsDuringDiscard(page, skin, artifact) { const [factory,filename] = {shousha:['createShoushaSkillPlugin','shousha'], shizhounian:['createShizhounianSkillPlugin','shizhounian'],xinsha:['createXinshaSkillPlugin','xinsha']}[skin]; await page.evaluate(async ({prefix,decadePrefix,filename,factory}) => { const [engine,{Click},{Check},skinModule,{createBaseLbtnPlugin},potions] = await Promise.all([ import('/noname.js'),import('/noname/ui/click/index.js'),import('/noname/game/check.js'), import(decadePrefix+`/ui/skill/skins/${filename}.js`),import(decadePrefix+'/ui/lbtn/skins/base.js'),import(prefix+'/potions/battle.js'), ]); const {ui,game,card,hud,hudEventState:status} = window; const me = game.me; const passive = 'mengsan_taoyuan_bond_shuying'; const names = {...potions.potionSkillTranslations,[passive]:'桃园羁绊'}; const skill = {...potions.createPotionSkills(()=>null,game),[passive]:{locked:true,mark:true}}; const config = {touchscreen:true,phonelayout:true,extension_十周年UI_rightLayout:'on'}; const lib = {config,skill}; const get = {info:id=>skill[id],translation:id=>names[id]||id, is:{locked:id=>id===passive,zhuanhuanji:()=>false,phoneLayout:()=>true}}; const app = {listen(){},reWriteFunction(){},get:{skillInfo(id) { return {id,name:id,info:skill[id],translation:names[id],type:skill[id].enable?'enable':'trigger'}; }}}; Array.prototype.addArray ??= function(items){for(const item of items)if(!this.includes(item))this.push(item);return this;}; Array.prototype.add ??= function(item){if(!this.includes(item))this.push(item);return this;}; Array.prototype.remove ??= function(item){const i=this.indexOf(item);if(i!==-1)this.splice(i,1);return this;}; ui.controls = [ui.control.firstElementChild]; ui.updatec = ()=>{}; ui.create = {div(selector,parent,label) { const node = document.createElement('div'); if(selector) node.className = selector.split('.').filter(Boolean).join(' '); if(label) node.textContent=label; parent?.appendChild(node); return node; },control:()=>ui.control.firstElementChild}; engine.lib.config = config; engine.lib.device = 'android'; engine.setUI(ui);engine.setGame(game);engine.setGet(get);engine.setStatus(status); Object.assign(status.event,{name:'chooseToDiscard',selectCard:[2,2],position:'h'}); delete status.event.respondTo; window.reviewResponse.card.remove(); ui.thrown = []; const prompt = window.reviewResponse.prompt; const count = document.createElement('span'); count.textContent = '0/2'; prompt.replaceChildren('请弃置两张手牌',document.createElement('br'),count); status.event.custom = {add:{card() {count.textContent = `${ui.selected.cards.length}/2`;}}}; Object.assign(me,{getSkills:type=>type==='e'?[]:Object.keys(skill),invisibleSkills:[],awakenedSkills:[], getStorage:(key,fallback=[])=>me.storage[key]??fallback,isTempBanned:()=>false}); Object.assign(game,{expandSkills:skills=>skills,addVideo(){},countChoose(){},check:()=>Check.prototype.confirm(status.event,'')}); const plugin = skinModule[factory](lib,game,ui,get,{},status,app); if (filename === 'xinsha') { plugin.initCreateFunctions(); plugin.initUpdateFunctions(); } else { plugin._extendUICreate(); plugin._extendUI(); } plugin.updateSkillMarks=()=>{}; createBaseLbtnPlugin(lib,game,ui,get,{},status,app).initConfirmRewrite(); ui.confirm = null; ui.create.confirm(''); card.classList.remove('selected'); card.updateTransform=()=>{}; card.addEventListener('touchend',()=>{ status.clicked=false; Click.prototype.card.call(card); }); hud.refresh(); const visiblePotionButtons = () => [...ui.skillControl.querySelectorAll('[data-id]')].filter(node=> node.getClientRects().length && potions.potionSkillIds.includes(node.dataset.id)).map(node=>node.dataset.id); window.discardSkillCheck = {frames:[],visiblePotionButtons,passive, initialPotionButton:ui.skillControl.querySelector(`[data-id="${potions.potionSkillIds[0]}"]`)}; const capture = event => { if (event.target.closest('.card')!==card) return; // Listen after the real card handler, before any scheduled HUD refresh. discardSkillCheck.frames.push(visiblePotionButtons()); requestAnimationFrame(()=>discardSkillCheck.frames.push(visiblePotionButtons())); }; window.addEventListener('touchend',capture,{once:true}); },{prefix,decadePrefix,factory,filename}); await page.locator('.handcards>.card').first().tap(); const result = await page.evaluate(async () => { await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))); const {frames,passive,initialPotionButton,visiblePotionButtons} = discardSkillCheck; return {frames,visible:visiblePotionButtons(),rebuilt:initialPotionButton && !initialPotionButton.isConnected, selected:ui.selected.cards.length,count:ui.dialog.textContent,passiveVisible:Boolean(ui.skillControl.querySelector(`[data-id="${passive}"]`)?.getClientRects().length)}; }); if (artifact) await page.screenshot({path:artifact}); assert.equal(result.rebuilt,true,'ten-year UI rebuilt the skill row on tap'); assert.ok(result.selected===1 && result.count.endsWith('1/2'),'the original touch selects one discard card and updates the count'); assert.ok(result.passiveVisible,'normal skills remain visible'); assert.equal(result.frames.length,2,'both touch and first animation frame were sampled'); assert.deepEqual([...result.frames.flat(),...result.visible],[],'potion skill duplicates are hidden from the first frame'); } async function checkMobileResponseLayout(page, skin, artifact) { await page.evaluate(({skin,decadePrefix}) => { const {arena,control} = ui; const card = document.createElement('div'); const scale = Math.min(arena.clientHeight * .18 / 156,1); card.className = 'card thrown'; card.style.cssText = `left:calc(50% - 56px);top:calc(50% - 78px);width:112px;height:156px;transform:scale(${scale});`; card.style.background = `center/100% 100% url("${decadePrefix}/image/card-skins/decade/sha.png")`; arena.appendChild(card); ui.thrown = [card]; const prompt = document.createElement('div'); prompt.className = skin === 'native' ? 'dialog' : 'hand-tip'; prompt.innerHTML = skin === 'native' ? '
请使用一张闪响应杀
' : '请使用一张闪响应杀'; arena.appendChild(prompt); ui.dialog = prompt; const event = hudEventState.event; event.name = 'chooseToUse'; event.respondTo = [game.players[1],{name:'sha'}]; event.dialog = prompt; window.reviewResponses = []; const confirm = control.firstElementChild; confirm.classList.remove('stayleft'); ui.confirm = confirm; if (skin !== 'native') confirm.classList.add('combo-control','lbtn-confirm'); const [ok,cancel] = confirm.children; confirm.node = {ok,cancel}; [ok,cancel].forEach((node,index) => { node.dataset.response = index ? 'cancel' : 'ok'; if (skin !== 'native') node.classList.add('control'); if (skin === 'shousha') { (node.firstElementChild || node).textContent = ''; if (index) node.innerHTML = '取消'; } else (node.firstElementChild || node).textContent = index ? '取消' : '确定'; node.addEventListener('click',()=>reviewResponses.push(node.dataset.response)); }); window.reviewResponse = {card,prompt}; window.card.classList.add('selected'); window.card.style.backgroundImage = `url("${decadePrefix}/image/card-skins/decade/shan.png")`; window.card.textContent = ''; hud.refresh(); },{skin,decadePrefix}); await page.waitForTimeout(550); const geometry = await page.evaluate(() => { const box = node => node.getBoundingClientRect().toJSON(); return {arena:box(ui.arena), card:box(reviewResponse.card), prompt:box(reviewResponse.prompt), ok:box(document.querySelector('[data-response="ok"]')),cancel:box(document.querySelector('[data-response="cancel"]')), hand:box(card)}; }); if (artifact) await page.screenshot({path:artifact}); const {arena, card, prompt, ok, cancel, hand} = geometry; const center = ({left,right}) => (left + right) / 2; assert.ok([card,prompt,{left:ok.left,right:cancel.right}].every(box=>Math.abs(center(box)-center(arena))<=2), 'A013 played card, response prompt and action group share the arena center: '+JSON.stringify(geometry)); const gap = 4; assert.ok(card.top >= arena.top+2 && card.bottom+gap <= prompt.top && prompt.bottom+gap <= Math.min(ok.top,cancel.top) && Math.max(ok.bottom,cancel.bottom)+gap <= hand.top && ok.right <= cancel.left, 'A013 played card, prompt, actions and selected hand card do not overlap: '+JSON.stringify(geometry)); await page.locator('[data-response="ok"]').tap(); await page.locator('[data-response="cancel"]').tap(); assert.deepEqual(await page.evaluate(()=>reviewResponses),['ok','cancel'],'both original response callbacks are reachable'); const restored = await page.evaluate(() => { delete hudEventState.event.respondTo; hud.refresh(); const verticalShift = Number.parseFloat(ui.control.style.translate.split(/\s+/)[1]) || 0; return verticalShift === 0 && reviewResponse.card.style.translate === ''; }); assert.ok(restored,'response spacing is released when the original event ends'); } const fixture = `
测试技能
结束出牌
`; const importMap = reviewOnly || journeyReview ? fs.readFileSync(path.join(app,'index.html'),'utf8').match(/