diff --git a/headless/README.md b/headless/README.md index 95a19c1..c39f06f 100644 --- a/headless/README.md +++ b/headless/README.md @@ -999,3 +999,19 @@ normal ordered durability; unsaved work is private preparation with no created elements or requests. The low-level helper defaults to its prior per-slice checkpoint policy unless a cadence is requested. Checkpoint/source formats and resume IDs stay unchanged; a crash/pause can redo only unsaved private planning. + +Native culling now checks active interaction owners instead of disabling itself +for every focused input or editing mode. Visible native nodes (including nodes +React Flow itself retains while dragging/initially measuring) keep culling on. +An offscreen owner, connection/custom owner without a native node, or focused +portal input without a native node still uses the conservative full-graph +fallback so viewport changes cannot discard IME, drafts or gesture leases. +Focus tracking stores the current input element and keeps the deferred blur +fence, including direct transfers between inputs. This is not selective pinning: +offscreen/custom interaction fallbacks can still mount the complete graph. + +The actual-page performance probe double-clicks a visible text card with native +Chrome input, checks mounted-node growth, inserts text and checks DOM identity, +focus and content before measuring deep copy. It then clears selection with a +native empty-pane click. Reports include `inputCheck.beforeEditing` and +`inputCheck.duringEditing`; this preflight is outside the copy timing window. diff --git a/src/components/canvas/headless-graph-canvas.tsx b/src/components/canvas/headless-graph-canvas.tsx index 3eeb204..1f09779 100644 --- a/src/components/canvas/headless-graph-canvas.tsx +++ b/src/components/canvas/headless-graph-canvas.tsx @@ -71,8 +71,8 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi needsLoadingFit.current=false;void flow.fitView({nodes,padding:.2,maxZoom:1}); },[engine,flow,root.document,view.canvasId]); const preparingCopy = [...(root.runtime.imports?.values() ?? [])].some(job => job.status === 'preparing' && job.source?.targetCanvasId === view.canvasId); - const [editorFocused, setEditorFocused] = useState(false), focusEpoch = useRef(0); - useEffect(() => { focusEpoch.current++; setEditorFocused(false); return () => { focusEpoch.current++; }; }, [engine,viewId]); + const [focusedEditor, setFocusedEditor] = useState(null), focusEpoch = useRef(0); + useEffect(() => { focusEpoch.current++; setFocusedEditor(null); return () => { focusEpoch.current++; }; }, [engine,viewId]); const [copying, setCopying] = useState(false); const [resourcePicker,setResourcePicker]=useState<{canvasId:Id;position:{x:number;y:number}}|null>(null); const copyAvailability=useMemo(()=>engine.imports.canDuplicate([...view.selection].map(id=>root.document.elements.get(id)).filter((element):element is ElementRecord=>!!element).map(({id,incarnation})=>({id,incarnation})),{viewCanvasId:view.canvasId}),[engine,root,view.selection,view.canvasId]); @@ -202,9 +202,15 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi return () => { window.removeEventListener('blur', cancel); window.removeEventListener('keydown', escape); }; }, [engine, viewId]); const modes = view.modes; - // Native culling keeps the full graph in React Flow. Retain every mounted editor/lease - // while an interaction is active so viewport changes cannot discard IME or capture. - const cullVisible = !overlayVisible && !connectionPaintVisible && !paintVisible && !editorFocused && modes.size === 0 && sessions.gesture?.viewId !== viewId && sessions.connectionGesture?.viewId !== viewId; + // Visible native owners already survive React Flow culling. Fall back only if + // culling could discard an active editor/lease (including unknown custom owners). + const interactionOwners = new Set(modes.keys()); + if (sessions.gesture?.viewId === viewId) for (const target of sessions.gesture.targets) interactionOwners.add(target.id); + if (sessions.connectionGesture?.viewId === viewId) interactionOwners.add(sessions.connectionGesture.target.id); + const focusedNode = focusedEditor?.closest('.react-flow__node')?.getAttribute('data-id'); + if (focusedNode) interactionOwners.add(focusedNode); + const retainInteraction = !!focusedEditor && !focusedNode || [...interactionOwners].some(id => !flow.getInternalNode(id) || !nativeVisible(id)); + const cullVisible = !overlayVisible && !connectionPaintVisible && !paintVisible && !retainInteraction; const selected = view.selection.size === 1 ? root.document.elements.get([...view.selection][0]) : undefined; const selectedResource=selected?.structure==='node'&&engine.editor.registry.resolve(selected)==='known'&&engine.editor.registry.supports(selected,'geometry.resize')&&typeof selected.data.assetId==='string'&&engine.editor.registry.components.get(selected.componentId)?.resourceFields?.includes('assetId')?root.runtime.resources.get(selected.data.assetId):undefined; const canFitImage=!!selectedResource&&(selectedResource.image?.version===1&&selectedResource.image.status==='ready'||!!selectedResource.stored)&&!sessions.gesture; @@ -252,8 +258,8 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi const rendererCommands=useMemo(()=>({dispatch(command,options){const result=engine.editor.dispatch(command,{label:options?.label,groupId:options?.groupId});report(result);return result;},transaction(callback,options){const result=engine.editor.transaction(callback,{label:options?.label,groupId:options?.groupId});report(result);return result;}}),[engine,report]); if (!liveView) return

画布已关闭

; return
{ if ((event.target as HTMLElement).closest('input,textarea,[contenteditable="true"],[role="textbox"]')) { focusEpoch.current++; setEditorFocused(true); } }} - onBlurCapture={() => { const epoch = ++focusEpoch.current; queueMicrotask(() => { if (focusEpoch.current === epoch) setEditorFocused(false); }); }} + onFocusCapture={event => { if ((event.target as HTMLElement).closest('input,textarea,[contenteditable="true"],[role="textbox"]')) { focusEpoch.current++; setFocusedEditor(event.target as HTMLElement); } }} + onBlurCapture={() => { const epoch = ++focusEpoch.current; queueMicrotask(() => { if (focusEpoch.current === epoch) setFocusedEditor(null); }); }} onMouseDownCapture={event => { if (event.button === 0 && (event.target as HTMLElement).closest('.react-flow__node')) pointerStart.current = {...flow.screenToFlowPosition({ x: event.clientX, y: event.clientY }),pointerId:pointerStart.current?.pointerId}; }} onTouchStartCapture={event => { if (event.touches.length > 1) { const state=engine.sessions.getSnapshot();if(state.gesture?.viewId===viewId||state.connectionGesture?.viewId===viewId)engine.sessions.cancel('multi_touch');drag.current = null;pointerStart.current=null;return; } const touch = event.touches[0]; if (touch && (event.target as HTMLElement).closest('.react-flow__node')) pointerStart.current = {...flow.screenToFlowPosition({ x: touch.clientX, y: touch.clientY }),pointerId:pointerStart.current?.pointerId}; }} onPointerDownCapture={event => { if (event.button === 0 && (event.target as HTMLElement).closest('.react-flow__node')) pointerStart.current = {...flow.screenToFlowPosition({ x: event.clientX, y: event.clientY }),pointerId:event.pointerId}; }} diff --git a/tests/headless/renderer-performance.mjs b/tests/headless/renderer-performance.mjs index e4bb7b1..d561880 100644 --- a/tests/headless/renderer-performance.mjs +++ b/tests/headless/renderer-performance.mjs @@ -12,6 +12,27 @@ export async function measureRenderer({call,evaluate,documents,root,partition,co await wait(`!!document.querySelector('.react-flow__node[data-id="perf-frame"]')&&document.querySelectorAll('.react-flow__node').length>=2`,'initial large canvas did not render'); assert.equal(await evaluate('document.querySelectorAll(".react-flow__node-toolbar").length'),0,'unselected nodes retained empty toolbar subscriptions'); const initialReadyMs=await evaluate('performance.now()');console.log('PERF initial scene ready '+Math.round(initialReadyMs)+' ms'); + // Use native input: synthetic focus alone misses the editing-mode transition. + await wait(`!!document.querySelector('.react-flow__node[data-id="perf-0"] [aria-label^="单击选中"]')`,'first visible text card missing'); + const beforeEditing=await evaluate('document.querySelectorAll(".react-flow__node").length'); + const editPoint=await evaluate(`(()=>{const rect=document.querySelector('.react-flow__node[data-id="perf-0"] [aria-label^="单击选中"]').getBoundingClientRect();return{x:rect.x+60,y:rect.y+30};})()`); + await call('Input.dispatchMouseEvent',{type:'mousePressed',...editPoint,button:'left',buttons:1,clickCount:2}); + await call('Input.dispatchMouseEvent',{type:'mouseReleased',...editPoint,button:'left',buttons:0,clickCount:2}); + await wait(`document.activeElement===document.querySelector('.react-flow__node[data-id="perf-0"] textarea')&&!document.activeElement.readOnly`,'native text editing did not start'); + await evaluate('window.__performanceEditor=document.activeElement;new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))'); + const duringEditing=await evaluate('document.querySelectorAll(".react-flow__node").length'); + if(count>=100)assert.ok(duringEditing<=beforeEditing+10,'editing one visible card mounted the offscreen canvas'); + await call('Input.insertText',{text:'Native editing remains responsive'}); + assert.equal(await evaluate('window.__performanceEditor.isConnected&&document.activeElement===window.__performanceEditor&&window.__performanceEditor.value.includes("Native editing remains responsive")'),true,'native input lost its DOM, focus or value'); + await evaluate('document.activeElement.blur();delete window.__performanceEditor;new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))'); + await wait(`[...document.querySelectorAll('[role=status]')].some(item=>item.textContent.trim()==='已同步')`,'native input did not synchronize before copy measurement'); + const inputCheck={beforeEditing,duringEditing}; + console.log('PERF native editing '+JSON.stringify(inputCheck)); + const panePoint=await evaluate(`(()=>{const pane=document.querySelector('.react-flow__pane'),rect=pane.getBoundingClientRect();for(let y=rect.y+5;yrequestAnimationFrame(()=>requestAnimationFrame(resolve)))`); @@ -39,7 +60,7 @@ export async function measureRenderer({call,evaluate,documents,root,partition,co await evaluate(`(()=>{const pane=document.querySelector('.react-flow__pane'),rect=pane.getBoundingClientRect(),matrix=new DOMMatrix(getComputedStyle(document.querySelector('.react-flow__viewport')).transform);pane.dispatchEvent(new WheelEvent('wheel',{deltaX:(${world.x}*matrix.a+matrix.e-rect.width/2)/.5,deltaY:(${world.y}*matrix.a+matrix.f-rect.height/2)/.5,bubbles:true,cancelable:true}));})()`); await wait(`!!document.querySelector('.react-flow__node[data-id="${copiedLast.id}"] textarea')`,'offscreen copied card did not mount after viewport pan'); const viewportCheck={visibleEdgesBeforePan:visibleEdges,copiedId:copiedLast.id,mountedAfterPan:await evaluate('document.querySelectorAll(".react-flow__node").length')}; - report={baseline,heapSamples,browserLogs:browserLogs(),scenario:'actual GraphPage deep copy of expanded partition',mode:`Next ${buildMode} webpack; isolated fixture HTTP; real Chrome/IndexedDB/Web Locks`,count,initialReadyMs,buildMs,internals:{batches:internalsBatches.length,maxBatch:Math.max(0,...internalsBatches),totalRequests:internalsBatches.reduce((sum,size)=>sum+size,0)},measurements,viewportCheck,browser:await call('Browser.getVersion'),serverElements:document.elements.size,serverCanvases:document.canvases.size,wallMs:Date.now()-started}; + report={inputCheck,baseline,heapSamples,browserLogs:browserLogs(),scenario:'actual GraphPage deep copy of expanded partition',mode:`Next ${buildMode} webpack; isolated fixture HTTP; real Chrome/IndexedDB/Web Locks`,count,initialReadyMs,buildMs,internals:{batches:internalsBatches.length,maxBatch:Math.max(0,...internalsBatches),totalRequests:internalsBatches.reduce((sum,size)=>sum+size,0)},measurements,viewportCheck,browser:await call('Browser.getVersion'),serverElements:document.elements.size,serverCanvases:document.canvases.size,wallMs:Date.now()-started}; const screenshot=await call('Page.captureScreenshot',{format:'png'});await writeFile(reportPath.endsWith('.json')?reportPath.slice(0,-5)+'.png':reportPath+'.png',Buffer.from(screenshot.data,'base64')); }catch(error){let measurements;try{measurements=await evaluate('window.__canvasPerformance?.stop()');}catch{}report={baseline,heapSamples,browserLogs:browserLogs(),scenario:'actual GraphPage deep copy of expanded partition',count,buildMode,buildMs,error:error.message,measurements,serverElements:documents.get(root)?.elements.size,serverCanvases:documents.get(root)?.canvases.size,wallMs:Date.now()-started};await writeFile(reportPath,JSON.stringify(report,null,2));throw error;} await writeFile(reportPath,JSON.stringify(report,null,2));console.log('MEASURE '+JSON.stringify({...report,measurements:{...report.measurements,longTasks:undefined}}));console.log('REPORT '+reportPath);