techtools
Головна / proto / flow-old / src / components / WorkflowCanvas.vue

WorkflowCanvas.vue

Vue · 156 рядків

1<script setup>
2import { computed, ref, onMounted, onBeforeUnmount, watch } from 'vue'
3import { addedSchema, inputSchema, outputSchema } from '../dataFlow.js'
4import { duplicateCanvasSelection, rectanglesIntersect } from '../canvasGraph.js'
5import { boardStages, stageOf, stageHandoffs } from '../../shared/stages.ts'
6const props = defineProps({ workflow:Object, models:{type:Array,default:()=>[]}, selectedId:String, selectedIds:{type:Array,default:()=>[]}, selectedEdgeId:String, selectedPort:Object, selectedStageId:String, execution:Object, nodeErrors:{type:Object,default:()=>({})}, edgeErrors:{type:Object,default:()=>({})} })
7const emit = defineEmits(['select','select-edge','select-port','select-stage','add-node','update','connect','reconnect','remove-edge','selection-change'])
8// Етапи борду (R-30.12): області з назвою; блок у етапі — якщо його центр в області. Здалеку (масштаб < MAP_ZOOM) —
9// карта: етапи карткою, передачі TASK → етап стрілками з сутністю задачі (тара), блоки етапів сховано.
10const STAGE_HEAD=44,MAP_ZOOM=.45,RESIZE=22,stagePalette=['#38bdf8','#22c55e','#f59e0b','#a855f7','#f43f5e','#14b8a6','#eab308']
11const mapActive=ref(false)
12function stages(){return boardStages(props.workflow)}
13function stageColor(stage){const index=stages().indexOf(stage);return stage.color||stagePalette[Math.max(0,index)%stagePalette.length]}
14function mapMode(){return zoom<MAP_ZOOM&&stages().length>0}
15// у карті підписи — сталого екранного розміру, але не дрібніше за масштаб 25% (інакше вилазять за картки)
16function px(size){return mapMode()?size/Math.max(zoom,.25):size}
17function stageInfo(stage){const nodes=props.workflow.nodes.filter(n=>stageOf(props.workflow,n)?.id===stage.id),events=[...new Set(nodes.filter(n=>n.type==='EVENT'&&n.config?.activation==='TASK').map(n=>n.config?.event).filter(Boolean))],model=props.models.find(m=>m.id===stage.taskContextModelId);return{nodes,events,screens:nodes.filter(n=>n.type==='SCREEN').length,rules:nodes.filter(n=>n.type==='DECISION').length,model:model?.name||''}}
18function drawArrow(p1,p2,color,label,width){const dx=Math.max(60,Math.abs(p2.x-p1.x)/2);ctx.strokeStyle=color;ctx.lineWidth=width;ctx.setLineDash([px(10),px(6)]);ctx.beginPath();ctx.moveTo(p1.x,p1.y);ctx.bezierCurveTo(p1.x+dx,p1.y,p2.x-dx,p2.y,p2.x,p2.y);ctx.stroke();ctx.setLineDash([]);const a=px(12);ctx.fillStyle=color;ctx.beginPath();ctx.moveTo(p2.x,p2.y);ctx.lineTo(p2.x-a,p2.y-a*.6);ctx.lineTo(p2.x-a,p2.y+a*.6);ctx.closePath();ctx.fill();if(label){const mx=(p1.x+p2.x)/2,my=(p1.y+p2.y)/2;ctx.font=`700 ${px(12)}px Inter, sans-serif`;const w=ctx.measureText(label).width+px(16);ctx.fillStyle='#0b1220';rounded(mx-w/2,my-px(11),w,px(22),px(11));ctx.fill();ctx.strokeStyle=color;ctx.lineWidth=px(1.5);ctx.stroke();ctx.fillStyle=color;ctx.textAlign='center';ctx.fillText(label,mx,my+px(4));ctx.textAlign='left'}}
19function drawStages(){const map=mapMode();for(const s of stages()){const c=stageColor(s),sel=props.selectedStageId===s.id;ctx.fillStyle=c+(map?'2a':'10');rounded(s.x,s.y,s.width,s.height,18);ctx.fill();ctx.strokeStyle=sel?c:c+'99';ctx.lineWidth=px(sel?3:1.5);ctx.setLineDash(map?[]:[12,8]);ctx.stroke();ctx.setLineDash([]);ctx.fillStyle=c+(map?'40':'2e');ctx.beginPath();ctx.roundRect(s.x,s.y,s.width,map?Math.min(s.height,px(56)):STAGE_HEAD,[18,18,0,0]);ctx.fill();const info=stageInfo(s)
20    if(map){ctx.save();ctx.beginPath();ctx.rect(s.x,s.y,s.width,s.height);ctx.clip();ctx.fillStyle='#f8fafc';ctx.font=`800 ${px(20)}px Inter, sans-serif`;ctx.fillText(s.name.slice(0,40),s.x+px(16),s.y+px(36));ctx.fillStyle='#cbd5e1';ctx.font=`600 ${px(13)}px Inter, sans-serif`;const lines=[info.events.length?'Чекає: '+info.events.join(', '):'Немає TASK-подій',`${info.nodes.length} блоків · ${info.screens} екранів · ${info.rules} правил`];if(info.model)lines.push('Контекст: '+info.model);lines.forEach((line,i)=>ctx.fillText(line.slice(0,60),s.x+px(16),s.y+px(86)+i*px(22)));ctx.restore()}
21    else{ctx.fillStyle='#f8fafc';ctx.font='800 17px Inter, sans-serif';ctx.fillText(s.name.slice(0,60),s.x+16,s.y+28);ctx.fillStyle=c;ctx.font='700 10px Inter, sans-serif';ctx.textAlign='right';ctx.fillText(('ЕТАП'+(info.model?' · '+info.model:'')+(info.events.length?' · '+info.events.join(', '):'')).slice(0,80),s.x+s.width-16,s.y+27);ctx.textAlign='left'}
22    ctx.fillStyle=c+'cc';ctx.beginPath();ctx.moveTo(s.x+s.width-4,s.y+s.height-px(RESIZE));ctx.lineTo(s.x+s.width-4,s.y+s.height-4);ctx.lineTo(s.x+s.width-px(RESIZE),s.y+s.height-4);ctx.closePath();ctx.fill()}}
23function drawHandoffs(){const map=mapMode(),list=stages();for(const h of stageHandoffs(props.workflow)){const to=list.find(s=>s.id===h.to),node=props.workflow.nodes.find(n=>n.id===h.nodeId);if(!to||!node)continue;const from=h.from?list.find(s=>s.id===h.from):null,c='#f59e0b';let p1,p2;if(map){p1=from?{x:from.x+from.width,y:from.y+from.height/2}:{x:node.x+W,y:node.y+nodeHeight(node)/2};p2={x:to.x,y:to.y+to.height/2}}else{p1={x:node.x+W/2,y:node.y+nodeHeight(node)};p2={x:to.x,y:to.y+STAGE_HEAD/2}}drawArrow(p1,p2,c,'⇢ '+h.label,px(map?3:2))}}
24function drawMapOutsideNodes(){for(const n of props.workflow.nodes){if(stageOf(props.workflow,n))continue;const base=colors[n.type]||'#64748b',sel=selectedIds.value.has(n.id)||props.selectedId===n.id;ctx.fillStyle=base+'33';rounded(n.x,n.y,W,nodeHeight(n),14);ctx.fill();ctx.strokeStyle=sel?'#fff':base;ctx.lineWidth=px(2);ctx.stroke();ctx.save();ctx.beginPath();ctx.rect(n.x,n.y,W,nodeHeight(n));ctx.clip();ctx.fillStyle='#f8fafc';const size=Math.min(px(13),26);ctx.font=`700 ${size}px Inter, sans-serif`;let label=n.type==='EVENT'?n.config?.event||n.name:n.name;while(label.length>4&&ctx.measureText(label).width>W-20)label=label.slice(0,-2);if(label!==(n.type==='EVENT'?n.config?.event||n.name:n.name))label+='…';ctx.fillText(label,n.x+10,n.y+nodeHeight(n)/2+size/3);ctx.restore()}}
25function stageAt(p){let found=null;for(const s of stages())if(p.x>=s.x&&p.x<=s.x+s.width&&p.y>=s.y&&p.y<=s.y+s.height&&(!found||s.width*s.height<found.width*found.height))found=s;return found}
26function stageHeadHit(p){const s=stageAt(p);return s&&p.y<=s.y+(mapMode()?s.height:STAGE_HEAD)?s:null}
27function stageResizeHit(p){const r=px(RESIZE);return stages().find(s=>p.x>=s.x+s.width-r&&p.x<=s.x+s.width+4&&p.y>=s.y+s.height-r&&p.y<=s.y+s.height+4)}
28function stageDrag(stage,p){const members=props.workflow.nodes.filter(n=>stageOf(props.workflow,n)?.id===stage.id);return{kind:'stage',stage,start:p,origin:{x:stage.x,y:stage.y},members:new Map(members.map(n=>[n.id,{x:n.x,y:n.y}]))}}
29function selectStage(id){selectedIds.value=new Set();emit('selection-change',[]);emit('select','');emit('select-edge','');emit('select-stage',id)}
30const canvas=ref(); const host=ref(); const hovered=ref(null); const selectedIds=ref(new Set());let ctx, ratio=1, pan={x:0,y:0}, zoom=.82, drag=null, connecting=null, pendingPort=null, pointer={x:0,y:0}
31const colors={ EVENT:'#8b5cf6', FIRE_EVENT:'#14b8a6', API_REQUEST:'#38bdf8', MAPPING:'#f97316', DELAY:'#64748b', TASK:'#f59e0b', TASK_UPDATE:'#fb923c', ACTION:'#22c55e', CLIENT_RESPONSE:'#ec4899', CONDITION:'#eab308', WORKFLOW:'#a855f7', DECISION:'#d946ef', SCREEN:'#f43f5e' }
32const hoverData=computed(()=>{if(!hovered.value)return null;if(hovered.value.direction==='input')return{result:inputSchema(props.workflow,hovered.value.node.id,props.models,hovered.value.port.id),added:{}};return{result:outputSchema(props.workflow,hovered.value.node.id,hovered.value.port.id,props.models),added:addedSchema(hovered.value.node,hovered.value.port.id,props.models)}})
33const W=190,BASE_H=92,PORT_GAP=28
34function pos(e){ const r=canvas.value.getBoundingClientRect(); return {x:(e.clientX-r.left-pan.x)/zoom,y:(e.clientY-r.top-pan.y)/zoom,sx:e.clientX-r.left,sy:e.clientY-r.top} }
35function nodeHeight(node){return BASE_H+Math.max(0,Math.max(node.inputs?.length||0,node.outputs?.length||0)-2)*PORT_GAP}
36function port(node,out,index){const ports=out?node.outputs:node.inputs,count=ports?.length||1,height=nodeHeight(node);return{x:out?node.x+W:node.x,y:node.y+(count===1?height/2:count===2?54+index*28:42+index*PORT_GAP)}}
37function rounded(x,y,w,h,r=12){ctx.beginPath();ctx.roundRect(x,y,w,h,r)}
38function draw(){ if(!ctx||!props.workflow)return; const rect=canvas.value.getBoundingClientRect(); ctx.setTransform(ratio,0,0,ratio,0,0);ctx.clearRect(0,0,rect.width,rect.height);ctx.save();ctx.translate(pan.x,pan.y);ctx.scale(zoom,zoom)
39  const grid=32;ctx.strokeStyle='#1f293733';ctx.lineWidth=1/zoom;for(let x=(-pan.x/zoom)%grid;x<rect.width/zoom;x+=grid){ctx.beginPath();ctx.moveTo(x,-pan.y/zoom);ctx.lineTo(x,(rect.height-pan.y)/zoom);ctx.stroke()}for(let y=(-pan.y/zoom)%grid;y<rect.height/zoom;y+=grid){ctx.beginPath();ctx.moveTo(-pan.x/zoom,y);ctx.lineTo((rect.width-pan.x)/zoom,y);ctx.stroke()}
40  mapActive.value=mapMode();drawStages()
41  if(mapMode()){drawHandoffs();drawMapOutsideNodes();if(drag?.kind==='selection'){const left=Math.min(drag.start.x,drag.end.x),top=Math.min(drag.start.y,drag.end.y);ctx.strokeStyle='#38bdf8';ctx.lineWidth=px(1.5);ctx.strokeRect(left,top,Math.abs(drag.end.x-drag.start.x),Math.abs(drag.end.y-drag.start.y))}ctx.restore();return}
42  for(const edge of props.workflow.edges){if(connecting?.edge?.id===edge.id)continue;const a=props.workflow.nodes.find(n=>n.id===edge.source),b=props.workflow.nodes.find(n=>n.id===edge.target);if(!a||!b)continue;const ai=Math.max(0,a.outputs.findIndex(p=>p.id===edge.sourcePort)),bi=Math.max(0,b.inputs.findIndex(p=>p.id===edge.targetPort)),p1=port(a,true,ai),p2=port(b,false,bi),selected=props.selectedEdgeId===edge.id,invalid=!!props.edgeErrors[edge.id];ctx.shadowColor=invalid?'#ef4444':selected?'#38bdf8':'transparent';ctx.shadowBlur=invalid||selected?12:0;ctx.strokeStyle=invalid?'#ef4444':selected?'#38bdf8':'#64748b';ctx.lineWidth=invalid||selected?4:2;ctx.beginPath();ctx.moveTo(p1.x,p1.y);ctx.bezierCurveTo(p1.x+80,p1.y,p2.x-80,p2.y,p2.x,p2.y);ctx.stroke();ctx.shadowBlur=0}
43  if(connecting){const moving=connecting.snap||pointer,p1=connecting.moving==='source'?moving:connecting.fixed,p2=connecting.moving==='target'?moving:connecting.fixed;ctx.strokeStyle=connecting.snap?'#22c55e':'#38bdf8';ctx.lineWidth=3;ctx.setLineDash(connecting.snap?[]:[7,5]);ctx.beginPath();ctx.moveTo(p1.x,p1.y);ctx.bezierCurveTo(p1.x+80,p1.y,p2.x-80,p2.y,p2.x,p2.y);ctx.stroke();ctx.setLineDash([]);if(connecting.snap){ctx.strokeStyle='#22c55e';ctx.lineWidth=3;ctx.beginPath();ctx.arc(moving.x,moving.y,11/zoom,0,Math.PI*2);ctx.stroke()}}
44  drawHandoffs()
45  const status=new Map((props.execution?.history||[]).map(h=>[h.nodeId,h.status]));
46  for(const n of props.workflow.nodes){const active=props.execution?.currentNodeId===n.id,selected=selectedIds.value.has(n.id)||props.selectedId===n.id,invalid=!!props.nodeErrors[n.id],base=colors[n.type]||'#64748b',height=nodeHeight(n);ctx.shadowColor=invalid?'#ef4444':active?'#38bdf8':selected?base:'#0009';ctx.shadowBlur=invalid||active?20:selected?15:8;ctx.fillStyle=invalid?'#ef444424':base+'24';rounded(n.x,n.y,W,height);ctx.fill();ctx.strokeStyle=invalid?'#ef4444':active?'#38bdf8':selected?base:base+'b8';ctx.lineWidth=invalid||selected?3:active?2:1.5;ctx.stroke();if(invalid){ctx.fillStyle='#ef4444';ctx.beginPath();ctx.arc(n.x+W-17,n.y+20,10,0,Math.PI*2);ctx.fill();ctx.fillStyle='#fff';ctx.font='700 12px Inter';ctx.textAlign='center';ctx.fillText('!',n.x+W-17,n.y+24);ctx.textAlign='left'}ctx.shadowBlur=0;ctx.fillStyle=selected?'#ffffff':'#dbe4f0';ctx.font='600 13px Inter, sans-serif';ctx.fillText(n.name.slice(0,28),n.x+2,n.y-10);ctx.fillStyle=base;ctx.font='600 10px Inter, sans-serif';ctx.fillText(n.type.replace('_',' '),n.x+16,n.y+24);if(n.type==='EVENT'){ctx.fillStyle='#e2e8f0';ctx.font='600 11px JetBrains Mono, monospace';ctx.fillText((n.config?.event||'EVENT NOT SET').slice(0,24),n.x+16,n.y+48)}if(n.type==='API_REQUEST'){ctx.fillStyle=base;ctx.font='700 11px JetBrains Mono, monospace';ctx.fillText((n.config?.method||'GET').toUpperCase(),n.x+16,n.y+47);ctx.fillStyle='#e2e8f0';ctx.font='500 10px JetBrains Mono, monospace';ctx.fillText((n.config?.url||'URL NOT SET').slice(0,27),n.x+16,n.y+66)}if(n.type==='DECISION'){ctx.fillStyle='#e2e8f0';ctx.font='600 11px JetBrains Mono, monospace';ctx.fillText((n.config?.rows?.length||0)+' rules → '+String(n.config?.resultPath||'decision').slice(0,14),n.x+16,n.y+48)}if(n.type==='SCREEN'){ctx.fillStyle=base;ctx.font='700 11px JetBrains Mono, monospace';ctx.fillText(String(n.config?.expect||'none').toUpperCase(),n.x+16,n.y+47);ctx.fillStyle='#e2e8f0';ctx.font='500 10px JetBrains Mono, monospace';ctx.fillText(String(n.config?.text||'TEXT NOT SET').slice(0,27),n.x+16,n.y+66)}const s=status.get(n.id);if(s){ctx.fillStyle=s==='completed'?'#22c55e':s==='waiting'?'#38bdf8':'#ef4444';ctx.beginPath();ctx.arc(n.x+W-17,n.y+20,6,0,Math.PI*2);ctx.fill()}
47    n.inputs.forEach((p,i)=>{const q=port(n,false,i),active=hovered.value?.direction==='input'&&hovered.value.node.id===n.id&&hovered.value.port.id===p.id;ctx.fillStyle=active?'#f8fafc':'#94a3b8';ctx.beginPath();ctx.arc(q.x,q.y,active?7:5,0,Math.PI*2);ctx.fill()});n.outputs.forEach((p,i)=>{const q=port(n,true,i),active=hovered.value?.direction==='output'&&hovered.value.node.id===n.id&&hovered.value.port.id===p.id;ctx.fillStyle=active?'#f8fafc':colors[n.type]||'#64748b';ctx.beginPath();ctx.arc(q.x,q.y,active?7:5,0,Math.PI*2);ctx.fill();ctx.fillStyle='#94a3b8';ctx.textAlign='right';ctx.font='9px Inter';ctx.fillText(p.name,q.x-10,q.y+3);ctx.textAlign='left'})
48  }if(drag?.kind==='selection'){const left=Math.min(drag.start.x,drag.end.x),top=Math.min(drag.start.y,drag.end.y),width=Math.abs(drag.end.x-drag.start.x),height=Math.abs(drag.end.y-drag.start.y);ctx.fillStyle='#38bdf822';ctx.strokeStyle='#38bdf8';ctx.lineWidth=1.5/zoom;ctx.setLineDash([7/zoom,5/zoom]);ctx.fillRect(left,top,width,height);ctx.strokeRect(left,top,width,height);ctx.setLineDash([])}ctx.restore() }
49function hit(p){return [...props.workflow.nodes].reverse().find(n=>p.x>=n.x&&p.x<=n.x+W&&p.y>=n.y&&p.y<=n.y+nodeHeight(n))}
50function edgeHit(p){let closest=null,best=12/zoom;for(const edge of props.workflow.edges){const a=props.workflow.nodes.find(n=>n.id===edge.source),b=props.workflow.nodes.find(n=>n.id===edge.target);if(!a||!b)continue;const p0=port(a,true,Math.max(0,a.outputs.findIndex(v=>v.id===edge.sourcePort))),p3=port(b,false,Math.max(0,b.inputs.findIndex(v=>v.id===edge.targetPort))),p1={x:p0.x+80,y:p0.y},p2={x:p3.x-80,y:p3.y};for(let i=0;i<=40;i++){const t=i/40,u=1-t,x=u*u*u*p0.x+3*u*u*t*p1.x+3*u*t*t*p2.x+t*t*t*p3.x,y=u*u*u*p0.y+3*u*u*t*p1.y+3*u*t*t*p2.y+t*t*t*p3.y,d=Math.hypot(p.x-x,p.y-y);if(d<best){best=d;closest=edge}}}return closest}
51function outputHit(p){for(const n of props.workflow.nodes)for(let i=0;i<n.outputs.length;i++){const q=port(n,true,i);if(Math.hypot(p.x-q.x,p.y-q.y)<Math.max(12,16/zoom))return{node:n,port:n.outputs[i],...q}}}
52function inputHit(p){for(const n of props.workflow.nodes)for(let i=0;i<n.inputs.length;i++){const q=port(n,false,i);if(Math.hypot(p.x-q.x,p.y-q.y)<Math.max(14,18/zoom))return{node:n,port:n.inputs[i],...q}}}
53function hoverPortHit(p){let found=null,best=18/zoom;for(const n of props.workflow.nodes){for(const [direction,ports,out] of [['input',n.inputs,false],['output',n.outputs,true]])for(let i=0;i<ports.length;i++){const q=port(n,out,i),distance=Math.hypot(p.x-q.x,p.y-q.y);if(distance<best){best=distance;found={node:n,port:ports[i],direction,...q}}}}return found}
54function edgeEndpointHit(p){const edge=props.workflow.edges.find(e=>e.id===props.selectedEdgeId);if(!edge)return null;const a=props.workflow.nodes.find(n=>n.id===edge.source),b=props.workflow.nodes.find(n=>n.id===edge.target);if(!a||!b)return null;const source=port(a,true,Math.max(0,a.outputs.findIndex(v=>v.id===edge.sourcePort))),target=port(b,false,Math.max(0,b.inputs.findIndex(v=>v.id===edge.targetPort)));let found=null,best=7/zoom;for(const [side,q] of [['source',source],['target',target]]){const d=Math.hypot(p.x-q.x,p.y-q.y);if(d<best){best=d;found={edge,side,source,target}}}return found}
55function nearestPort(p,out,excludeNode){let found=null,best=30/zoom;for(const n of props.workflow.nodes){if(n.id===excludeNode)continue;const ports=out?n.outputs:n.inputs;for(let i=0;i<ports.length;i++){const q=port(n,out,i),d=Math.hypot(p.x-q.x,p.y-q.y);if(d<best){best=d;found={node:n,port:ports[i],...q}}}}return found}
56function beginPortPress(hit,direction,endpoint=null){const descriptor={nodeId:hit.node.id,portId:hit.port.id,direction};pendingPort={descriptor,activated:false,timer:setTimeout(()=>{if(!pendingPort)return;pendingPort.activated=true;hovered.value=null;if(endpoint){emit('select','');emit('select-edge',endpoint.edge.id);connecting={edge:endpoint.edge,moving:endpoint.side,fixed:endpoint.side==='source'?endpoint.target:endpoint.source,oppositeNode:endpoint.side==='source'?endpoint.edge.target:endpoint.edge.source,snap:null}}else if(direction==='output'){emit('select','');emit('select-edge','');connecting={moving:'target',fixed:{x:hit.x,y:hit.y},source:hit,snap:null}}draw()},500)}}
57function clearPortPress(){if(pendingPort?.timer)clearTimeout(pendingPort.timer)}
58function selectNodes(ids,primary=ids.at(-1)||''){selectedIds.value=new Set(ids);emit('select-edge','');emit('select',primary);emit('selection-change',ids)}
59function nodeDrag(ids,start){return{kind:'nodes',ids,start,origins:new Map(ids.map(id=>{const node=props.workflow.nodes.find(item=>item.id===id);return[id,{x:node.x,y:node.y}]}))}}
60function copyNodes(ids,options){const result=duplicateCanvasSelection(props.workflow,ids,options);const copies=result.nodes.map(node=>node.id);selectNodes(copies,copies.at(-1));emit('update');return copies}
61function down(e){
62  hovered.value=null
63  const p=pos(e);pointer=p
64  if(e.button===1||(e.button===0&&spaceHeld.value)){e.preventDefault();drag={kind:'pan',x:e.clientX-pan.x,y:e.clientY-pan.y};panning.value=true;canvas.value.setPointerCapture(e.pointerId);return}
65  // Ctrl+клік на Mac — це правий клік: меню не потрібне, копію він не робить
66  if(e.button===0&&e.ctrlKey&&isMac)return
67  if(e.button!==0)return
68  if(mapMode()){
69    const resize=stageResizeHit(p),outside=hit(p)
70    if(resize){selectStage(resize.id);drag={kind:'stage-resize',stage:resize,start:p,origin:{w:resize.width,h:resize.height}}}
71    else if(outside&&!stageOf(props.workflow,outside)){selectNodes([outside.id],outside.id);drag=nodeDrag([outside.id],p)}
72    else{const stage=stageAt(p);if(stage){selectStage(stage.id);drag=stageDrag(stage,p)}else{selectStage('');drag={kind:'pan',x:e.clientX-pan.x,y:e.clientY-pan.y};panning.value=true}}
73    canvas.value.setPointerCapture(e.pointerId);draw();return
74  }
75  const endpoint=edgeEndpointHit(p)
76  if(endpoint){const edge=endpoint.edge,nodeId=endpoint.side==='source'?edge.source:edge.target,node=props.workflow.nodes.find(item=>item.id===nodeId),ports=endpoint.side==='source'?node.outputs:node.inputs,portId=endpoint.side==='source'?edge.sourcePort:edge.targetPort,hit={node,port:ports.find(item=>item.id===portId),...(endpoint.side==='source'?endpoint.source:endpoint.target)};beginPortPress(hit,endpoint.side==='source'?'output':'input',endpoint);canvas.value.setPointerCapture(e.pointerId);return}
77  const out=outputHit(p);if(out){beginPortPress(out,'output');canvas.value.setPointerCapture(e.pointerId);return}
78  const input=inputHit(p);if(input){beginPortPress(input,'input');canvas.value.setPointerCapture(e.pointerId);return}
79  const node=hit(p)
80  if(node){
81    if(e.altKey||(e.ctrlKey&&!isMac)){copyNodes([node.id],{offset:{x:32,y:32},copyInternalEdges:false});draw();return}
82    const ids=selectedIds.value.has(node.id)?[...selectedIds.value]:[node.id]
83    if(!selectedIds.value.has(node.id))selectNodes(ids,node.id)
84    drag=e.shiftKey?{kind:'duplicate-pending',ids,start:p}:nodeDrag(ids,p)
85  }else{
86    const edge=edgeHit(p),resize=stageResizeHit(p),head=stageHeadHit(p)
87    if(edge){selectedIds.value=new Set();emit('selection-change',[]);emit('select','');emit('select-edge',edge.id)}
88    else if(resize){selectStage(resize.id);drag={kind:'stage-resize',stage:resize,start:p,origin:{w:resize.width,h:resize.height}}}
89    else if(head){selectStage(head.id);drag=stageDrag(head,p)}
90    else{selectNodes([]);drag={kind:'selection',start:p,end:p}}
91  }
92  canvas.value.setPointerCapture(e.pointerId)
93}
94function move(e){
95  const p=pos(e);pointer=p
96  if(pendingPort&&!pendingPort.activated)return
97  if(connecting){connecting.snap=nearestPort(p,connecting.moving==='source',connecting.oppositeNode||connecting.source?.node.id);draw();return}
98  if(!drag&&mapMode()){if(hovered.value){hovered.value=null;draw()}return}
99  if(!drag){const previous=hovered.value,target=hoverPortHit(p);hovered.value=target?{...target,sx:p.sx,sy:p.sy}:null;if(previous?.node.id!==hovered.value?.node.id||previous?.port.id!==hovered.value?.port.id||previous?.direction!==hovered.value?.direction)draw();return}
100  hovered.value=null
101  if(drag.kind==='pan')pan={x:e.clientX-drag.x,y:e.clientY-drag.y}
102  else if(drag.kind==='selection')drag.end=p
103  else if(drag.kind==='stage'){const dx=Math.round((p.x-drag.start.x)/8)*8,dy=Math.round((p.y-drag.start.y)/8)*8;drag.stage.x=drag.origin.x+dx;drag.stage.y=drag.origin.y+dy;for(const [id,origin] of drag.members){const node=props.workflow.nodes.find(item=>item.id===id);if(node){node.x=origin.x+dx;node.y=origin.y+dy}}emit('update')}
104  else if(drag.kind==='stage-resize'){drag.stage.width=Math.max(240,Math.round((drag.origin.w+p.x-drag.start.x)/8)*8);drag.stage.height=Math.max(160,Math.round((drag.origin.h+p.y-drag.start.y)/8)*8);emit('update')}
105  else{
106    if(drag.kind==='duplicate-pending'){
107      if(Math.hypot(p.x-drag.start.x,p.y-drag.start.y)<4/zoom)return
108      const copies=copyNodes(drag.ids,{offset:{x:0,y:0},copyInternalEdges:true})
109      drag=nodeDrag(copies,drag.start)
110    }
111    const dx=p.x-drag.start.x,dy=p.y-drag.start.y
112    for(const id of drag.ids){const node=props.workflow.nodes.find(item=>item.id===id),origin=drag.origins.get(id);node.x=Math.round((origin.x+dx)/8)*8;node.y=Math.round((origin.y+dy)/8)*8}
113    emit('update')
114  }
115  draw()
116}
117function up(){
118  if(pendingPort&&!pendingPort.activated){clearPortPress();selectedIds.value=new Set();emit('selection-change',[]);emit('select-port',pendingPort.descriptor);pendingPort=null;draw();return}
119  clearPortPress();pendingPort=null
120  if(connecting){const snap=connecting.snap;if(connecting.edge){if(snap)emit('reconnect',{edgeId:connecting.edge.id,side:connecting.moving,nodeId:snap.node.id,portId:snap.port.id});else emit('remove-edge',connecting.edge.id)}else if(snap)emit('connect',{source:connecting.source.node.id,sourcePort:connecting.source.port.id,target:snap.node.id,targetPort:snap.port.id});connecting=null}
121  if(drag?.kind==='selection'){const area={x1:drag.start.x,y1:drag.start.y,x2:drag.end.x,y2:drag.end.y};const ids=props.workflow.nodes.filter(node=>rectanglesIntersect(area,{x:node.x,y:node.y,width:W,height:nodeHeight(node)})).map(node=>node.id);selectNodes(ids)}
122  drag=null;panning.value=false;draw()
123}
124function leave(){hovered.value=null;if(pendingPort&&!pendingPort.activated){clearPortPress();pendingPort=null}draw()}
125// Навігація як у Figma / Miro — працює і з мишею, і з трекпадом MacBook:
126//   прокрутка двома пальцями / колесо — пан (Shift+колесо — по горизонталі), pinch або Ctrl/⌘+колесо — масштаб,
127//   Space+перетягування або середня кнопка — пан; масштаб плавний за величиною deltaY, а не крок на кожну подію.
128const MIN_ZOOM=.1,MAX_ZOOM=2
129const isMac=/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent)
130const spaceHeld=ref(false),panning=ref(false),zoomLabel=ref(Math.round(zoom*100)+'%')
131function zoomAt(next,sx,sy){const x=(sx-pan.x)/zoom,y=(sy-pan.y)/zoom;zoom=Math.min(MAX_ZOOM,Math.max(MIN_ZOOM,next));pan.x=sx-x*zoom;pan.y=sy-y*zoom;zoomLabel.value=Math.round(zoom*100)+'%';draw()}
132function wheel(e){e.preventDefault();const r=canvas.value.getBoundingClientRect(),unit=e.deltaMode===1?16:e.deltaMode===2?r.height:1,dx=e.deltaX*unit,dy=e.deltaY*unit
133  if(e.ctrlKey||e.metaKey){zoomAt(zoom*Math.exp(-dy*.01),e.clientX-r.left,e.clientY-r.top);return}
134  if(e.shiftKey&&!dx){pan.x-=dy}else{pan.x-=dx;pan.y-=dy}draw()}
135// Safari на macOS віддає pinch не колесом, а gesture-подіями
136let gestureStart=1
137function gestureStartHandler(e){e.preventDefault();gestureStart=zoom}
138function gestureChange(e){e.preventDefault();const r=canvas.value.getBoundingClientRect();zoomAt(gestureStart*e.scale,e.clientX-r.left,e.clientY-r.top)}
139function zoomStep(factor){const r=canvas.value.getBoundingClientRect();zoomAt(zoom*factor,r.width/2,r.height/2)}
140function bounds(){const boxes=[...(props.workflow?.nodes||[]).map(n=>({x:n.x,y:n.y,w:W,h:nodeHeight(n)})),...stages().map(s=>({x:s.x,y:s.y,w:s.width,h:s.height}))];if(!boxes.length)return null;return{minX:Math.min(...boxes.map(b=>b.x)),minY:Math.min(...boxes.map(b=>b.y)),maxX:Math.max(...boxes.map(b=>b.x+b.w)),maxY:Math.max(...boxes.map(b=>b.y+b.h))}}
141function toggleMap(){const r=canvas.value.getBoundingClientRect();if(mapMode()){fitView();if(zoom<MAP_ZOOM)zoomAt(MAP_ZOOM+.1,r.width/2,r.height/2)}else{fitView();if(zoom>=MAP_ZOOM)zoomAt(MAP_ZOOM*.8,r.width/2,r.height/2)}}
142function fitView(){const b=bounds();if(!b)return;const r=canvas.value.getBoundingClientRect(),pad=48,{minX,minY,maxX,maxY}=b;zoom=Math.min(1,Math.max(MIN_ZOOM,Math.min((r.width-pad*2)/(maxX-minX),(r.height-pad*2)/(maxY-minY))));pan={x:(r.width-(maxX-minX)*zoom)/2-minX*zoom,y:(r.height-(maxY-minY)*zoom)/2-minY*zoom};zoomLabel.value=Math.round(zoom*100)+'%';draw()}
143function editingField(){const t=document.activeElement;return['INPUT','TEXTAREA','SELECT'].includes(t?.tagName)||t?.isContentEditable}
144function keyDown(e){if(e.code==='Space'&&!editingField()&&!e.repeat){spaceHeld.value=true;e.preventDefault()}else if(e.code==='Space'&&spaceHeld.value)e.preventDefault()
145  if(!editingField()&&e.shiftKey&&e.code==='Digit1'){e.preventDefault();fitView()}}
146function keyUp(e){if(e.code==='Space')spaceHeld.value=false}
147const helpText=isMac?'Drag: select · Two-finger scroll or Space+drag: pan · Pinch or ⌘+scroll: zoom · ⇧1: fit · ⌘C / ⌘V · ⌥-click or ⇧-drag: copy':'Drag: select · Wheel or Space+drag: pan · Ctrl+wheel: zoom · Shift+1: fit · Ctrl+C / Ctrl+V · Alt-click or Shift-drag: copy'
148function resize(){if(!host.value||!canvas.value)return;const r=host.value.getBoundingClientRect();ratio=devicePixelRatio||1;canvas.value.width=r.width*ratio;canvas.value.height=r.height*ratio;canvas.value.style.width=r.width+'px';canvas.value.style.height=r.height+'px';ctx=canvas.value.getContext('2d');draw()}
149function dropNode(e){e.preventDefault();const type=e.dataTransfer?.getData('application/x-wms-flow-node')||e.dataTransfer?.getData('text/plain');if(!type)return;const p=pos(e);emit('add-node',{type,x:Math.round((p.x-W/2)/8)*8,y:Math.round((p.y-BASE_H/2)/8)*8})}
150watch(()=>props.selectedIds,ids=>{selectedIds.value=new Set(ids||[]);draw()},{deep:true})
151watch(()=>props.selectedId,id=>{if(id&&!selectedIds.value.has(id))selectedIds.value=new Set([id]);if(!id&&selectedIds.value.size===1)selectedIds.value=new Set();draw()})
152onMounted(()=>{resize();new ResizeObserver(resize).observe(host.value);canvas.value.addEventListener('wheel',wheel,{passive:false});canvas.value.addEventListener('gesturestart',gestureStartHandler);canvas.value.addEventListener('gesturechange',gestureChange);window.addEventListener('keydown',keyDown);window.addEventListener('keyup',keyUp);window.addEventListener('blur',keyUp)});onBeforeUnmount(()=>{clearPortPress();canvas.value?.removeEventListener('wheel',wheel);canvas.value?.removeEventListener('gesturestart',gestureStartHandler);canvas.value?.removeEventListener('gesturechange',gestureChange);window.removeEventListener('keydown',keyDown);window.removeEventListener('keyup',keyUp);window.removeEventListener('blur',keyUp)});watch(()=>[props.workflow,props.selectedId,props.selectedEdgeId,props.selectedPort,props.selectedStageId,props.execution,props.nodeErrors,props.edgeErrors],draw,{deep:true})
153</script>
154<template><div ref="host" class="canvas-host" @dragover.prevent @drop="dropNode"><canvas ref="canvas" :class="{grab:spaceHeld,grabbing:panning}" @contextmenu.prevent @pointerdown="down" @pointermove="move" @pointerleave="leave" @pointerup="up" @pointercancel="up"/><div v-if="hovered&&hoverData" class="port-preview" :style="{left:(hovered.sx+16)+'px',top:(hovered.sy+16)+'px'}"><div class="port-preview-head"><b>{{hovered.node.name}} · {{hovered.port.name}}</b><span>{{hovered.direction==='input'?'INPUT DATA':'OUTPUT DATA'}}</span></div><small>{{hovered.direction==='input'?'Data received by this port':'Result passed forward'}}</small><pre>{{JSON.stringify(hoverData.result,null,2)}}</pre><div v-if="hovered.node.type==='EVENT'&&Object.keys(hoverData.added).length" class="port-runtime-preview"><b>RUNTIME SCOPES · ENTITY TASK LOOKUP</b><pre>{{JSON.stringify(hoverData.added,null,2)}}</pre></div><details v-else-if="Object.keys(hoverData.added).length"><summary>Added by this block</summary><pre>{{JSON.stringify(hoverData.added,null,2)}}</pre></details></div><div class="canvas-zoom" @pointerdown.stop><button title="Zoom out" @click="zoomStep(1/1.2)">−</button><button class="zoom-value" title="Reset to 100%" @click="zoomStep(1/zoom)">{{zoomLabel}}</button><button title="Zoom in" @click="zoomStep(1.2)">+</button><button title="Fit the whole workflow (Shift+1)" @click="fitView">Fit</button><button v-if="workflow?.settings?.stages?.length" :class="{active:mapActive}" title="Карта етапів: етапи й передачі між ними (або віддаліть масштаб)" @click="toggleMap">{{mapActive?'Блоки':'Карта'}}</button></div><div class="canvas-help">{{helpText}}</div></div></template>
155
156