{"version":3,"file":"useGraphController.js","names":[],"sources":["jsx/react-flow/useGraphController.js"],"sourcesContent":["import { startTransition, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { applyCommand, createHistory, validateConnection, validateDrop } from \"../model/index\";\nimport { layout, reconcilePositions } from \"../layout/layout\";\nimport { FINE_PORT_PITCH, portSpacing } from \"../nodes/nodeMeasure\";\nimport { preserveFlowState, toFlowEdges, toFlowNodes } from \"./flowAdapter\";\nimport { applyEdgeChanges, applyNodeChanges } from \"./xy\";\nconst warned = /* @__PURE__ */ new Set();\nfunction warnOnce(message) {\n  if (process.env.NODE_ENV === \"production\") return;\n  if (warned.has(message)) return;\n  warned.add(message);\n  console.warn(`[@multiplatform.one/node-graph] ${message}`);\n}\nfunction resetControllerWarnings() {\n  warned.clear();\n}\nconst defaultGraphNodeType = \"mpGraphNode\";\nconst emptyDocument = { version: 1, nodes: [], edges: [] };\nfunction positionsOf(nodes) {\n  const out = {};\n  for (const node of nodes) out[node.id] = node.position;\n  return out;\n}\nfunction dragDeltas(document, nodes) {\n  const live = positionsOf(nodes);\n  const deltas = {};\n  for (const node of document.nodes) {\n    const to = live[node.id];\n    if (!to) continue;\n    const dx = to.x - node.position.x;\n    const dy = to.y - node.position.y;\n    if (dx === 0 && dy === 0) continue;\n    deltas[node.id] = { x: dx, y: dy };\n  }\n  return deltas;\n}\nfunction useGraphController(options) {\n  const {\n    schema,\n    document: controlledDocument,\n    defaultDocument,\n    onDocumentChange,\n    onConnectionRefused,\n    readOnly = false,\n    size = \"medium\",\n    coarsePointer = false,\n    nodeType = defaultGraphNodeType,\n    readMeasuredSizes\n  } = options;\n  const controlled = controlledDocument !== void 0;\n  if (controlled && defaultDocument !== void 0) {\n    warnOnce(\n      \"useGraphController received both `document` and `defaultDocument`. `document` wins; drop `defaultDocument` to silence this.\"\n    );\n  }\n  const [ownDocument, setOwnDocument] = useState(\n    () => defaultDocument ?? controlledDocument ?? emptyDocument\n  );\n  const document = controlled ? controlledDocument : ownDocument;\n  const history = useMemo(\n    () => createHistory(options.history),\n    // The journal is per-controller, not per-render. Rebuilding it on an\n    // inline `{ limit: 100 }` literal would silently erase the undo stack on\n    // every render of the parent.\n    // oxlint-disable-next-line exhaustive-deps\n    []\n  );\n  const [historyVersion, setHistoryVersion] = useState(0);\n  const portSpacingPx = coarsePointer ? portSpacing({ coarsePointer }) : FINE_PORT_PITCH;\n  const mapping = useMemo(\n    () => ({ size, portSpacingPx, nodeType }),\n    [size, portSpacingPx, nodeType]\n  );\n  const [nodes, setNodes] = useState(\n    () => toFlowNodes(document, schema, mapping)\n  );\n  const [edges, setEdges] = useState(() => toFlowEdges(document, schema));\n  const nodesRef = useRef(nodes);\n  nodesRef.current = nodes;\n  const documentRef = useRef(document);\n  documentRef.current = document;\n  const schemaRef = useRef(schema);\n  schemaRef.current = schema;\n  useEffect(() => {\n    const current = schemaRef.current;\n    setNodes((previous) => preserveFlowState(toFlowNodes(document, current, mapping), previous));\n    setEdges(toFlowEdges(document, current));\n  }, [document, schema.id, mapping]);\n  const commit = useCallback(\n    (command) => {\n      const current = documentRef.current;\n      const next = history.commit(current, command);\n      setHistoryVersion((version) => version + 1);\n      if (!controlled) setOwnDocument(next);\n      documentRef.current = next;\n      onDocumentChange?.(next, command);\n    },\n    [controlled, history, onDocumentChange]\n  );\n  const onNodesChange = useCallback(\n    (changes) => {\n      const next = applyNodeChanges(changes, nodesRef.current);\n      nodesRef.current = next;\n      setNodes(next);\n      if (layoutTouchedRef.current) {\n        for (const change of changes) {\n          if (change.type === \"position\") layoutTouchedRef.current.add(change.id);\n        }\n      }\n      if (readOnly) return;\n      const dragEnded = changes.some(\n        (change) => change.type === \"position\" && change.dragging === false\n      );\n      if (!dragEnded) return;\n      const deltas = dragDeltas(documentRef.current, next);\n      if (Object.keys(deltas).length === 0) return;\n      commit({ t: \"moveNodes\", deltas });\n    },\n    [commit, readOnly]\n  );\n  const onEdgesChange = useCallback(\n    (changes) => {\n      const next = applyEdgeChanges(changes, edges);\n      setEdges(next);\n      if (readOnly) return;\n      const removed = changes.filter(\n        (change) => change.type === \"remove\"\n      ).map((change) => change.id);\n      if (removed.length === 0) return;\n      commit({ t: \"removeEdges\", ids: removed });\n    },\n    [commit, edges, readOnly]\n  );\n  const connectionContext = useCallback(\n    (connection) => {\n      if (!connection.source || !connection.target) return void 0;\n      if (!connection.sourceHandle || !connection.targetHandle) return void 0;\n      return {\n        document: documentRef.current,\n        schema,\n        source: { node: connection.source, port: connection.sourceHandle },\n        target: { node: connection.target, port: connection.targetHandle }\n      };\n    },\n    [schema]\n  );\n  const isValidConnection = useCallback(\n    (connection) => {\n      if (readOnly) return false;\n      const ctx = connectionContext(connection);\n      if (!ctx) return false;\n      return validateConnection(ctx).ok;\n    },\n    [connectionContext, readOnly]\n  );\n  const onConnect = useCallback(\n    (connection) => {\n      if (readOnly) return;\n      const ctx = connectionContext(connection);\n      if (!ctx) return;\n      const verdict = validateDrop(ctx);\n      if (!verdict.ok) {\n        onConnectionRefused?.(verdict);\n        return;\n      }\n      const kind = defaultEdgeKind(schema);\n      if (!kind) return;\n      const spec = schema.edges[kind];\n      const edge = {\n        id: `${ctx.source.node}:${ctx.source.port}->${ctx.target.node}:${ctx.target.port}`,\n        kind,\n        source: ctx.source,\n        target: ctx.target,\n        // The kind's own `defaultData`. `E[kind]` cannot be proven from a\n        // runtime string, so the cast is at the ONE place the kind is chosen,\n        // not spread through the command type.\n        data: spec?.defaultData ?? {}\n      };\n      commit({ t: \"addEdges\", edges: [edge] });\n    },\n    [commit, connectionContext, onConnectionRefused, readOnly, schema]\n  );\n  const measuredRef = useRef(readMeasuredSizes);\n  measuredRef.current = readMeasuredSizes;\n  const layoutGenerationRef = useRef(0);\n  const layoutTouchedRef = useRef(null);\n  const [layoutRunner, setLayoutRunner] = useState(\"none\");\n  const [lastLayoutMs, setLastLayoutMs] = useState(null);\n  const [layoutPending, setLayoutPending] = useState(false);\n  const relayout = useCallback(\n    async (layoutOptions = {}) => {\n      const source = documentRef.current;\n      if (source.nodes.length === 0) return null;\n      const generation = layoutGenerationRef.current += 1;\n      layoutTouchedRef.current = /* @__PURE__ */ new Set();\n      setLayoutPending(true);\n      let result;\n      try {\n        result = await layout(source, schemaRef.current, {\n          ...layoutOptions,\n          size,\n          coarsePointer,\n          measured: layoutOptions.measured ?? measuredRef.current?.()\n        });\n      } finally {\n        if (layoutGenerationRef.current === generation) setLayoutPending(false);\n      }\n      if (layoutGenerationRef.current !== generation) return result;\n      const touched = layoutTouchedRef.current ?? /* @__PURE__ */ new Set();\n      layoutTouchedRef.current = null;\n      setLayoutRunner(result.runner ?? \"inline\");\n      setLastLayoutMs(result.ms);\n      if (readOnly) return result;\n      const positions = reconcilePositions(result, touched);\n      if (Object.keys(positions).length === 0) return result;\n      startTransition(() => {\n        commit({ t: \"setPositions\", positions });\n      });\n      return result;\n    },\n    [coarsePointer, commit, readOnly, size]\n  );\n  const publishHistoryChange = useCallback(\n    (next, command) => {\n      if (next === documentRef.current) return;\n      if (!controlled) setOwnDocument(next);\n      documentRef.current = next;\n      onDocumentChange?.(next, command);\n    },\n    [controlled, onDocumentChange]\n  );\n  const undo = useCallback(() => {\n    history.undo(documentRef.current, publishHistoryChange);\n    setHistoryVersion((version) => version + 1);\n  }, [history, publishHistoryChange]);\n  const redo = useCallback(() => {\n    history.redo(documentRef.current, publishHistoryChange);\n    setHistoryVersion((version) => version + 1);\n  }, [history, publishHistoryChange]);\n  return {\n    document,\n    nodes,\n    edges,\n    onNodesChange,\n    onEdgesChange,\n    onConnect,\n    isValidConnection,\n    commit,\n    undo,\n    redo,\n    // `historyVersion` is what makes these re-read after a commit; the journal\n    // itself is a stable object, so nothing else would tell React to look.\n    canUndo: useMemo(() => history.canUndo(), [history, historyVersion]),\n    canRedo: useMemo(() => history.canRedo(), [history, historyVersion]),\n    relayout,\n    layoutRunner,\n    lastLayoutMs,\n    layoutPending\n  };\n}\nfunction defaultEdgeKind(schema) {\n  const names = Object.keys(schema.edges);\n  return names.includes(\"flow\") ? \"flow\" : names[0];\n}\nfunction applyGraphCommand(document, command) {\n  return applyCommand(document, command);\n}\nexport {\n  applyGraphCommand,\n  defaultGraphNodeType,\n  resetControllerWarnings,\n  useGraphController\n};\n//# sourceMappingURL=useGraphController.js.map\n"],"mappings":";;;;;;;;AAMA,MAAM,yBAAyB,IAAI,IAAI;AACvC,SAAS,SAAS,SAAS;CACzB,IAAI,QAAQ,IAAI,aAAa,cAAc;CAC3C,IAAI,OAAO,IAAI,OAAO,GAAG;CACzB,OAAO,IAAI,OAAO;CAClB,QAAQ,KAAK,mCAAmC,SAAS;AAC3D;AACA,SAAS,0BAA0B;CACjC,OAAO,MAAM;AACf;AACA,MAAM,uBAAuB;AAC7B,MAAM,gBAAgB;CAAE,SAAS;CAAG,OAAO,CAAC;CAAG,OAAO,CAAC;AAAE;AACzD,SAAS,YAAY,OAAO;CAC1B,MAAM,MAAM,CAAC;CACb,KAAK,MAAM,QAAQ,OAAO,IAAI,KAAK,MAAM,KAAK;CAC9C,OAAO;AACT;AACA,SAAS,WAAW,UAAU,OAAO;CACnC,MAAM,OAAO,YAAY,KAAK;CAC9B,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,QAAQ,SAAS,OAAO;EACjC,MAAM,KAAK,KAAK,KAAK;EACrB,IAAI,CAAC,IAAI;EACT,MAAM,KAAK,GAAG,IAAI,KAAK,SAAS;EAChC,MAAM,KAAK,GAAG,IAAI,KAAK,SAAS;EAChC,IAAI,OAAO,KAAK,OAAO,GAAG;EAC1B,OAAO,KAAK,MAAM;GAAE,GAAG;GAAI,GAAG;EAAG;CACnC;CACA,OAAO;AACT;AACA,SAAS,mBAAmB,SAAS;CACnC,MAAM,EACJ,QACA,UAAU,oBACV,iBACA,kBACA,qBACA,WAAW,OACX,OAAO,UACP,gBAAgB,OAChB,WAAW,sBACX,sBACE;CACJ,MAAM,aAAa,uBAAuB,KAAK;CAC/C,IAAI,cAAc,oBAAoB,KAAK,GAAG;EAC5C,SACE,6HACF;CACF;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