96 lines
8.0 KiB
JavaScript
96 lines
8.0 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import ts from 'typescript';
|
|
import React from 'react';
|
|
|
|
const tick = () => new Promise(resolve => setImmediate(resolve));
|
|
const deferred = () => { let resolve, reject; const promise = new Promise((r,j) => { resolve=r; reject=j; }); return {promise,resolve,reject}; };
|
|
const text = tree => typeof tree === 'string' ? tree : !tree || typeof tree !== 'object' ? '' : React.Children.toArray(tree.props?.children).map(text).join('');
|
|
const find = (tree, predicate) => {
|
|
if (!tree || typeof tree !== 'object') return;
|
|
if (tree.type === 'Modal' && !tree.props.open) return;
|
|
if (predicate(tree)) return tree;
|
|
for (const child of React.Children.toArray(tree.props?.children)) { const hit=find(child,predicate); if(hit)return hit; }
|
|
};
|
|
const visual = () => ({ id:'same-id',title:'正式趋势',subtitle:'已核实数据',chartable:true,type:'line',metric:'composite_rate',
|
|
period:{year:2026,monthStart:8,monthEnd:9},scope:{product:'原规格'},categories:[{key:'2026-08'},{key:'2026-09'}],
|
|
series:[{key:'composite_rate',label:'合格率',values:[.82,.84]}],evidenceRefs:['QFIXTURE'],coverage:{totalRows:2,returnedRows:2,truncated:false} });
|
|
|
|
// Run the actual component, attaching host refs before its actual effect callbacks.
|
|
function fixture({ authorize=async()=>{}, load }={}) {
|
|
const states=new Map(),refs=new Map(),effects=new Map(),nodes=new Map();let cursor=0,dirty=false,queued=[],tree,attached=new Set();
|
|
const calls={loads:0,authorization:0,disposed:0,options:[]};
|
|
const runtime={init:()=>({setOption(option){calls.options.push(option);},resize(){},dispose(){calls.disposed++;}})};
|
|
const hooks={
|
|
useState(initial){const i=cursor++;if(!states.has(i))states.set(i,typeof initial==='function'?initial():initial);return [states.get(i),value=>{const next=typeof value==='function'?value(states.get(i)):value;if(!Object.is(next,states.get(i))){states.set(i,next);dirty=true;}}];},
|
|
useRef(initial){const i=cursor++;if(!refs.has(i))refs.set(i,{current:initial});return refs.get(i);},
|
|
useCallback(fn){cursor++;return fn;},
|
|
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});},
|
|
};
|
|
hooks.useDelayedIndicator=(active,delayMs=150)=>{
|
|
const [visible,setVisible]=hooks.useState(false);
|
|
hooks.useEffect(()=>{
|
|
if(!active){setVisible(false);return;}
|
|
setVisible(false);const timer=setTimeout(()=>setVisible(true),delayMs);return()=>clearTimeout(timer);
|
|
},[active,delayMs]);
|
|
return active&&visible;
|
|
};
|
|
const source=fs.readFileSync(new URL('../src/AnalysisVisuals.tsx',import.meta.url),'utf8');
|
|
const componentSource=source.slice(source.indexOf('export function AnalysisVisualCard('),source.indexOf('export function AnalysisVisuals(')).replace('export function','function');
|
|
const body=ts.transpileModule(componentSource,{fileName:'component.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
|
const Component=new Function('React','hooks','runtime',`
|
|
const {useState,useRef,useEffect,useCallback,useDelayedIndicator}=hooks;
|
|
const Button='Button',Dropdown='Dropdown',Tag='Tag',Modal='Modal',TableOutlined='TableOutlined',DownloadOutlined='DownloadOutlined',MoreOutlined='MoreOutlined',ChartDataTable='ChartDataTable';
|
|
const document={visibilityState:'visible',documentElement:{},addEventListener(){},removeEventListener(){}};
|
|
const documentIsHidden=()=>false,visualTheme=()=>({}),visualPeriodSummary=()=>'',visualScopeSummary=()=>'',chartSummary=v=>v.title,analysisVisualTypeLabel=()=>'',visualUnitLabel=()=>'';
|
|
const buildAnalysisVisualOption=v=>structuredClone({scope:v.scope,series:v.series}),renderVisualPng=()=>{throw Error('unexpected export');},safeFilename=()=>'';
|
|
const loadAnalysisVisualECharts=async()=>runtime,requestAnimationFrame=fn=>fn();
|
|
class IntersectionObserver {constructor(fn){this.fn=fn;}observe(){this.fn([{isIntersecting:true}]);}disconnect(){}}
|
|
class ResizeObserver {observe(){}disconnect(){}}
|
|
class MutationObserver {observe(){}disconnect(){}}
|
|
${body}
|
|
return AnalysisVisualCard;
|
|
`)(React,hooks,runtime);
|
|
const props={visual:visual(),beforeExport:async()=>{calls.authorization++;return authorize();},loadRuntime:async()=>{
|
|
calls.loads++;if(load)return load(calls.loads,runtime);if(calls.loads===1)throw Error('render failed');return runtime;
|
|
}};
|
|
function render(){let n=0;do{
|
|
dirty=false;cursor=0;queued=[];tree=Component(props);
|
|
const next=new Set();const attach=node=>{if(!node||typeof node!=='object')return;const ref=node.props?.ref;if(ref){next.add(ref);if(!nodes.has(ref))nodes.set(ref,{getBoundingClientRect:()=>({width:800,height:320})});ref.current=nodes.get(ref);}React.Children.toArray(node.props?.children).forEach(attach);};attach(tree);
|
|
attached.forEach(ref=>{if(!next.has(ref))ref.current=null;});attached=next;queued.forEach(fn=>fn());
|
|
if(++n>20)throw Error('render loop');
|
|
}while(dirty);return tree;}
|
|
return {props,calls,render,async settle(){await tick();return render();},retry(){const button=find(tree,node=>node.type==='Button'&&text(node)==='重试图表');assert.ok(button,'retry button');button.props.onClick({stopPropagation(){}});},unmount(){effects.forEach(effect=>effect.cleanup?.());attached.forEach(ref=>ref.current=null);}};
|
|
}
|
|
|
|
test('a chart-only retry reauthorizes once, keeps the data table, and remounts the same verified values',async()=>{
|
|
const auth=deferred(),ui=fixture({authorize:()=>auth.promise});ui.render();let tree=await ui.settle();
|
|
assert.ok(find(tree,node=>node.type==='ChartDataTable'));assert.equal(ui.calls.loads,1);
|
|
ui.retry();ui.retry();tree=ui.render();assert.equal(ui.calls.authorization,1);assert.equal(ui.calls.loads,1);
|
|
assert.ok(find(tree,node=>node.type==='ChartDataTable'));
|
|
auth.resolve();await ui.settle();tree=await ui.settle();assert.equal(ui.calls.loads,2);
|
|
assert.equal(find(tree,node=>node.type==='ChartDataTable'),undefined);assert.deepEqual(ui.calls.options.at(-1).series[0].values,[.82,.84]);ui.unmount();
|
|
});
|
|
|
|
test('failed authorization hides cached data and never retries the renderer until access is restored',async()=>{
|
|
let denied=true;const ui=fixture({authorize:async()=>{if(denied)throw Error('无权读取');}});ui.render();await ui.settle();ui.retry();let tree=await ui.settle();
|
|
assert.match(text(tree),/无权读取/);assert.equal(find(tree,node=>node.type==='ChartDataTable'),undefined);assert.equal(ui.calls.loads,1);
|
|
denied=false;ui.retry();await ui.settle();tree=await ui.settle();assert.equal(ui.calls.loads,2);assert.doesNotMatch(text(tree),/无权读取/);ui.unmount();
|
|
});
|
|
|
|
test('late authorization for an older snapshot cannot remount or overwrite a changed scope with the same visual id',async()=>{
|
|
const auth=deferred(),ui=fixture({authorize:()=>auth.promise});ui.render();await ui.settle();ui.retry();
|
|
ui.props.visual={...visual(),scope:{product:'新规格'},series:[{key:'composite_rate',values:[.91,.93]}]};ui.render();await ui.settle();const loads=ui.calls.loads;
|
|
auth.resolve();await ui.settle();assert.equal(ui.calls.loads,loads);assert.equal(ui.calls.options.at(-1).scope.product,'新规格');assert.deepEqual(ui.calls.options.at(-1).series[0].values,[.91,.93]);ui.unmount();
|
|
});
|
|
|
|
test('unmounting while authorization is pending prevents a late renderer start',async()=>{
|
|
const auth=deferred(),ui=fixture({authorize:()=>auth.promise});ui.render();await ui.settle();ui.retry();ui.unmount();auth.resolve();await tick();assert.equal(ui.calls.loads,1);
|
|
});
|
|
|
|
test('switching snapshots clears the previous permission error and closes its data dialog',async()=>{
|
|
const ui=fixture({authorize:async()=>{throw Error('旧结果无权读取');}});ui.render();await ui.settle();ui.retry();let tree=await ui.settle();assert.match(text(tree),/旧结果无权读取/);
|
|
ui.props.visual={...visual(),scope:{product:'新结果'}};ui.render();tree=await ui.settle();assert.doesNotMatch(text(tree),/旧结果无权读取/);assert.equal(ui.calls.options.at(-1).scope.product,'新结果');ui.unmount();
|
|
});
|