libpetri 2.3.0 → 2.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/doclet/resources/petrinet-diagrams.js +28 -28
- package/dist/{chunk-RNWTYK5B.js → render-UY4OKXXQ.js} +65 -6
- package/dist/render-UY4OKXXQ.js.map +1 -0
- package/dist/viewer/index.d.ts +2 -13
- package/dist/viewer/index.js +6 -20
- package/dist/viewer/index.js.map +1 -1
- package/dist/viewer/viewer.iife.js +28 -28
- package/package.json +1 -7
- package/dist/chunk-RNWTYK5B.js.map +0 -1
- package/dist/render-QK57X4TP.js +0 -73
- package/dist/render-QK57X4TP.js.map +0 -1
- package/dist/viewer/layout/index.d.ts +0 -200
- package/dist/viewer/layout/index.js +0 -15
- package/dist/viewer/layout/index.js.map +0 -1
- package/dist/viewer/viewer-static.iife.js +0 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "libpetri",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.1",
|
|
4
4
|
"description": "Coloured Time Petri Net engine — TypeScript port",
|
|
5
5
|
"homepage": "https://libpetri.org",
|
|
6
6
|
"repository": {
|
|
@@ -51,12 +51,6 @@
|
|
|
51
51
|
"import": "./dist/viewer/index.js",
|
|
52
52
|
"types": "./dist/viewer/index.d.ts"
|
|
53
53
|
},
|
|
54
|
-
"./viewer/layout": {
|
|
55
|
-
"node": {
|
|
56
|
-
"import": "./dist/viewer/layout/index.js",
|
|
57
|
-
"types": "./dist/viewer/layout/index.d.ts"
|
|
58
|
-
}
|
|
59
|
-
},
|
|
60
54
|
"./viewer/iife": "./dist/viewer/viewer.iife.js",
|
|
61
55
|
"./viewer/css": "./dist/viewer/viewer.css"
|
|
62
56
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/viewer/layout/preprocess.ts","../src/viewer/layout/elk-place.ts"],"sourcesContent":["/**\n * Graph pre-processing for the C0-replicate-default layout pipeline.\n *\n * Three pure-ish transforms operate on a {@link GraphModel} parsed from a\n * libpetri-exported DOT string:\n *\n * parseLibpetriDot(dot) → GraphModel\n * foldOrphans(graph, threshold) → GraphModel (REASSIGN_ORPHANS)\n * replicateShared(graph, opts) → GraphModel (REPLICATE_SHARED)\n *\n * The pipeline turns a flat cluster soup into a cluster-internal one by\n * (a) folding orphan nodes whose edges concentrate in one cluster into that\n * cluster, and (b) cloning shared places into every foreign cluster they\n * touch so cross-cluster spaghetti disappears. The resulting GraphModel is\n * what ELK lays out (Stage 2) and Graphviz then renders in pin-mode.\n *\n * Algorithm lineage: ported from\n * `/home/db/otto-repos/nucleus_marvin/.scratch/javadoc-layout-exp/CHECKPOINTS/run16_GOOD_v3_skip-junctions.mjs`\n * lines 14–220. The arc-type detection, replica naming\n * (`${placeId}__rep__${clusterShortName}`), and the `__replica` /\n * `replicaOf` markers are load-bearing — downstream stages key off them.\n *\n * @module viewer/layout/preprocess\n */\n\nexport type ArcType = 'normal' | 'reset' | 'inhibitor' | 'read';\nexport type NodeKind = 'place' | 'transition' | 'junction';\n\nexport interface ParsedNode {\n readonly id: string;\n readonly kind: NodeKind;\n readonly attrs: Record<string, string>;\n /** True iff this node was emitted by replicateShared. */\n readonly replica?: boolean;\n /** For a replica, the id of the original logical place. */\n readonly replicaOf?: string;\n}\n\nexport interface ParsedEdge {\n readonly src: string;\n readonly dst: string;\n readonly arc: ArcType;\n /**\n * Raw attribute body from the libpetri DOT (between the `[…]` brackets,\n * brackets stripped). Carries style/penwidth/label that we want to\n * round-trip verbatim so the rendered output matches `DotExporter`'s\n * native look.\n */\n readonly rawAttrs: string;\n}\n\nexport interface ParsedCluster {\n readonly id: string; // \"cluster_productSearch\"\n readonly shortName: string; // \"productSearch\"\n readonly nodes: readonly string[];\n}\n\nexport interface GraphModel {\n readonly nodes: ReadonlyMap<string, ParsedNode>;\n readonly clusters: ReadonlyMap<string, ParsedCluster>;\n readonly nodeToCluster: ReadonlyMap<string, string>;\n /** Node ids not in any cluster (rendered at the orchestrator root). */\n readonly orphans: readonly string[];\n readonly edges: readonly ParsedEdge[];\n}\n\nfunction classifyKind(id: string): NodeKind {\n if (id.startsWith('p_')) return 'place';\n if (id.startsWith('t_')) return 'transition';\n return 'junction';\n}\n\n/**\n * Recover key=value attributes from inside a DOT `[...]` block.\n *\n * Mirrors v3 line 29. The regex is intentionally permissive about quoted\n * values containing escaped quotes; it does not validate DOT syntax.\n */\nfunction parseAttrs(body: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const m of body.matchAll(/(\\w+)=(\"(?:[^\"]|\\\\.)*\"|\\S+?)(?=[\\s,]|$)/g)) {\n const [, key, raw] = m as unknown as [string, string, string];\n const v = raw.startsWith('\"') && raw.endsWith('\"') ? raw.slice(1, -1) : raw;\n attrs[key] = v;\n }\n return attrs;\n}\n\n/**\n * Parse a libpetri-exported DOT string into a {@link GraphModel}.\n *\n * Tolerates the current exporter shape (see\n * `java/src/main/java/org/libpetri/export/StyleConstants.java`):\n * - inhibitor arcs use `arrowhead=\"odot\"` + color `#dc3545`\n * - reset arcs use `label=\"reset\"` + color `#fd7e14`\n * - read arcs use `label=\"read\"` + color `#6c757d`\n *\n * Mirrors v3 lines 24–103.\n */\nexport function parseLibpetriDot(dot: string): GraphModel {\n const nodes = new Map<string, ParsedNode>();\n // Greedy `.*` (no /s flag) consumes the full attrs body up to the line's\n // trailing `];`. The v3 reference used `[^\\]]*` which silently dropped\n // transitions whose label contained `[…]` text (e.g., `\"[0, ∞]ms\"`); we\n // can't tolerate that here because the typed model wants every cluster\n // member to have a Node entry.\n for (const m of dot.matchAll(/^\\s*([pjt]_[A-Za-z0-9_]+)\\s*\\[(.*)\\];\\s*$/gm)) {\n const [, id, body] = m as unknown as [string, string, string];\n nodes.set(id, { id, kind: classifyKind(id), attrs: parseAttrs(body) });\n }\n\n const clusters = new Map<string, ParsedCluster>();\n const nodeToCluster = new Map<string, string>();\n for (const cm of dot.matchAll(/subgraph (cluster_\\w+)\\s*\\{([^]*?)^\\s*\\}/gm)) {\n const [, clusterId, body] = cm as unknown as [string, string, string];\n const memberIds = [...body.matchAll(/^\\s*([pjt]_[A-Za-z0-9_]+)\\s*\\[/gm)]\n .map(m => (m as unknown as [string, string])[1]);\n clusters.set(clusterId, {\n id: clusterId,\n shortName: clusterId.replace(/^cluster_/, ''),\n nodes: memberIds,\n });\n for (const n of memberIds) nodeToCluster.set(n, clusterId);\n }\n\n // Catch nodes declared at root (orphans) — strip cluster bodies, then scan\n const stripped = dot.replace(/subgraph cluster_\\w+\\s*\\{[^]*?^\\s*\\}/gm, '');\n for (const m of stripped.matchAll(/^\\s*([pjt]_[A-Za-z0-9_]+)\\s*\\[/gm)) {\n const id = (m as unknown as [string, string])[1];\n if (!nodes.has(id)) {\n // Root-declared node without full attrs (rare); seed with empty attrs.\n nodes.set(id, { id, kind: classifyKind(id), attrs: {} });\n }\n }\n\n const orphans = [...nodes.keys()].filter(n => !nodeToCluster.has(n));\n\n const edges: ParsedEdge[] = [];\n for (const m of dot.matchAll(/([pjt]_[A-Za-z0-9_]+)\\s*->\\s*([pjt]_[A-Za-z0-9_]+)\\s*(\\[[^\\]]*\\])?/g)) {\n const [, src, dst, rawAttrs] = m as unknown as [string, string, string, string | undefined];\n const attrs = rawAttrs ?? '';\n // Cluster-anchor edges (lhead/ltail) are exporter-internal routing hints,\n // not real arcs in the Petri net — skip per v3 line 97.\n if (attrs.includes('lhead=') || attrs.includes('ltail=')) continue;\n let arc: ArcType = 'normal';\n if (attrs.includes('label=\"reset\"') || attrs.includes('#fd7e14')) arc = 'reset';\n else if (attrs.includes('arrowhead=\"odot\"') || attrs.includes('#dc3545')) arc = 'inhibitor';\n else if (attrs.includes('label=\"read\"')) arc = 'read';\n // Strip the `[…]` brackets so writeBack can splice the body into a new\n // attr list. Empty if libpetri emitted a bare `src -> dst;`.\n const stripped = attrs.startsWith('[') && attrs.endsWith(']')\n ? attrs.slice(1, -1)\n : '';\n edges.push({ src, dst, arc, rawAttrs: stripped });\n }\n\n return { nodes, clusters, nodeToCluster, orphans, edges };\n}\n\n/**\n * Adopt orphan nodes into the cluster their edges most prefer.\n *\n * For each orphan, tally how many of its edges touch each cluster. If the\n * dominant cluster gets at least `threshold` of the orphan's cluster-touching\n * edges, the orphan is reassigned to that cluster.\n *\n * Mirrors v3 lines 105–136. Default threshold 0.7 matches REASSIGN_ORPHANS.\n */\nexport function foldOrphans(graph: GraphModel, threshold = 0.7): GraphModel {\n if (threshold <= 0) return graph;\n\n const nodeToCluster = new Map(graph.nodeToCluster);\n const clusterMembers = new Map<string, string[]>();\n for (const [id, c] of graph.clusters) clusterMembers.set(id, [...c.nodes]);\n\n const tally = new Map<string, Map<string, number>>();\n const bump = (orphan: string, other: string): void => {\n const oc = nodeToCluster.get(other);\n if (!oc) return;\n let t = tally.get(orphan);\n if (!t) { t = new Map(); tally.set(orphan, t); }\n t.set(oc, (t.get(oc) ?? 0) + 1);\n };\n\n for (const e of graph.edges) {\n const sIsOrphan = !nodeToCluster.has(e.src);\n const dIsOrphan = !nodeToCluster.has(e.dst);\n if (sIsOrphan && !dIsOrphan) bump(e.src, e.dst);\n if (dIsOrphan && !sIsOrphan) bump(e.dst, e.src);\n }\n\n for (const id of graph.orphans) {\n const t = tally.get(id);\n if (!t) continue;\n let total = 0;\n let bestCluster: string | null = null;\n let bestCount = 0;\n for (const [c, n] of t) {\n total += n;\n if (n > bestCount) { bestCount = n; bestCluster = c; }\n }\n if (bestCluster && total > 0 && bestCount / total >= threshold) {\n clusterMembers.get(bestCluster)!.push(id);\n nodeToCluster.set(id, bestCluster);\n }\n }\n\n const clusters = new Map<string, ParsedCluster>();\n for (const [id, c] of graph.clusters) {\n clusters.set(id, { ...c, nodes: clusterMembers.get(id)! });\n }\n const orphans = [...graph.nodes.keys()].filter(n => !nodeToCluster.has(n));\n return { ...graph, clusters, nodeToCluster, orphans };\n}\n\nexport interface ReplicateOptions {\n /**\n * Skip places that touch more than this many foreign clusters. Per the\n * plan's \"no cap\" decision, default is `Infinity`. Set to a finite value\n * to suppress replication of hub places that would otherwise produce many\n * copies.\n */\n readonly max?: number;\n /** If true, replicate transitions as well as places. Default false. */\n readonly replicateTransitions?: boolean;\n}\n\nexport interface ReplicateStats {\n readonly replicatedPlaces: number;\n readonly totalCopies: number;\n}\n\n/**\n * For each place P, replicate it into every foreign cluster touched by its\n * edges, and redirect those cross-cluster edges to the local copy.\n *\n * Replica id convention is load-bearing: `${placeId}__rep__${shortClusterName}`.\n * Downstream stages (mount-time tagging, overlay highlight, click-all-copies)\n * key off this naming and the `replica: true` / `replicaOf` markers.\n *\n * If P has a home cluster (folded earlier), the original stays as the primary\n * copy and is also marked as a replica so the ⇄ glyph renders consistently.\n * If P is an orphan with all its edges redirected, the original is dropped.\n *\n * Mirrors v3 lines 138–221.\n */\nexport function replicateShared(\n graph: GraphModel,\n opts: ReplicateOptions = {},\n): GraphModel & { readonly replicateStats: ReplicateStats } {\n const max = opts.max ?? Infinity;\n const replicateTransitions = opts.replicateTransitions ?? false;\n\n const nodes = new Map(graph.nodes);\n const nodeToCluster = new Map(graph.nodeToCluster);\n const clusterMembers = new Map<string, string[]>();\n for (const [id, c] of graph.clusters) clusterMembers.set(id, [...c.nodes]);\n const edges = graph.edges.map(e => ({ ...e }));\n\n // 1. Compute foreign-cluster set per replicable node.\n const foreignByNode = new Map<string, Set<string>>();\n const noteForeign = (nodeId: string, otherId: string): void => {\n if (!nodeId.startsWith('p_') && !(replicateTransitions && nodeId.startsWith('t_'))) return;\n const home = nodeToCluster.get(nodeId);\n const otherCluster = nodeToCluster.get(otherId);\n if (!otherCluster) return;\n if (otherCluster === home) return;\n let s = foreignByNode.get(nodeId);\n if (!s) { s = new Set(); foreignByNode.set(nodeId, s); }\n s.add(otherCluster);\n };\n for (const e of edges) {\n noteForeign(e.src, e.dst);\n noteForeign(e.dst, e.src);\n }\n\n // 2. Emit replicas for nodes within the cap.\n const replicaMap = new Map<string, Map<string, string>>(); // orig → cluster → replicaId\n let replicatedPlaces = 0;\n let totalCopies = 0;\n for (const [placeId, foreigns] of foreignByNode) {\n if (foreigns.size === 0) continue;\n if (foreigns.size > max) continue;\n const perCluster = new Map<string, string>();\n const orig = nodes.get(placeId);\n if (!orig) continue;\n for (const clusterId of foreigns) {\n const shortName = clusterId.replace(/^cluster_/, '');\n const repId = `${placeId}__rep__${shortName}`;\n perCluster.set(clusterId, repId);\n clusterMembers.get(clusterId)!.push(repId);\n nodeToCluster.set(repId, clusterId);\n nodes.set(repId, {\n id: repId,\n kind: orig.kind,\n attrs: { ...orig.attrs },\n replica: true,\n replicaOf: placeId,\n });\n totalCopies++;\n }\n replicaMap.set(placeId, perCluster);\n replicatedPlaces++;\n // Mark the original as a shared place so the ⇄ glyph renders uniformly.\n nodes.set(placeId, { ...orig, replica: true, replicaOf: placeId });\n }\n\n // 3. Redirect cross-cluster edges to the local replica on each end.\n for (const e of edges) {\n const sMap = replicaMap.get(e.src);\n const dMap = replicaMap.get(e.dst);\n if (sMap) {\n const dCl = nodeToCluster.get(e.dst);\n if (dCl && sMap.has(dCl)) e.src = sMap.get(dCl)!;\n }\n if (dMap) {\n const sCl = nodeToCluster.get(e.src);\n if (sCl && dMap.has(sCl)) e.dst = dMap.get(sCl)!;\n }\n }\n\n // 4. Drop orphan originals whose edges all got redirected away.\n for (const [origId] of replicaMap) {\n if (nodeToCluster.has(origId)) continue; // folded — keep as primary\n const stillHasEdge = edges.some(e => e.src === origId || e.dst === origId);\n if (!stillHasEdge) nodes.delete(origId);\n }\n\n const clusters = new Map<string, ParsedCluster>();\n for (const [id, c] of graph.clusters) {\n clusters.set(id, { ...c, nodes: clusterMembers.get(id)! });\n }\n const orphans = [...nodes.keys()].filter(n => !nodeToCluster.has(n));\n\n return {\n nodes,\n clusters,\n nodeToCluster,\n orphans,\n edges,\n replicateStats: { replicatedPlaces, totalCopies },\n };\n}\n","/**\n * ELK placement + DOT pin-mode rewrite.\n *\n * Stage 2 of the C0 pipeline. Takes the {@link GraphModel} produced by\n * {@link parseLibpetriDot} → {@link foldOrphans} → {@link replicateShared},\n * runs ELKjs to compute absolute `(x, y)` per node and bounding boxes per\n * cluster, then emits a fresh DOT string with positions pinned via\n * `pos=\"x,y!\"` and `bb=\"…\"`. Downstream callers render the result through\n * `@viz-js/viz` with `engine: 'neato'` + `graphAttributes: { nop: '1' }` —\n * Graphviz uses the pinned positions verbatim and routes edges around the\n * pinned cluster boundaries.\n *\n * The two functions are pure: `elkLayout` takes only the graph; `writeBack`\n * takes (graph, layout). Neither touches the original DOT text — the model\n * after replication has nodes the original DOT doesn't, so patching the\n * original would be incorrect.\n *\n * @module viewer/layout/elk-place\n */\n\nimport ELK from 'elkjs/lib/elk.bundled.js';\nimport type {\n ElkExtendedEdge,\n ElkNode,\n} from 'elkjs/lib/elk-api.js';\nimport type { GraphModel, ParsedNode } from './preprocess.js';\n\nconst ORCHESTRATOR_CLUSTER_ID = 'cluster_orchestrator';\n\n// Visual sizing — kept proportional to the v3 reference renderer so the\n// resulting bounding box is comparable to C0-GOOD_v3.svg.\nconst PLACE_RADIUS = 22;\nconst PLACE_CHARW = 7.4;\nconst PLACE_PAD_BELOW = 16;\nconst FONT_PLACE = 13;\nconst TRANSITION_MIN_W = 180;\nconst TRANSITION_H = 40;\nconst TRANSITION_CHARW = 8.5;\nconst JUNCTION_SIZE = 28;\nconst FONT_CLUSTER = 17;\nconst ROOT_SPACING = 90;\nconst CLUSTER_SPACING = 16;\n\n/**\n * Width/height in points that ELK should reserve for a node. Mirrors\n * `nodeDims` in v3 lines 66–78 — places get extra height to leave room for\n * the xlabel underneath the circle.\n */\nfunction nodeDims(node: ParsedNode): { width: number; height: number } {\n if (node.kind === 'place') {\n const label = (node.attrs.xlabel ?? node.attrs.label ?? node.id).replace(/\\\\n/g, ' ');\n const labelWidth = label.length * PLACE_CHARW;\n const circleD = PLACE_RADIUS * 2 + 4;\n return {\n width: Math.max(circleD, labelWidth),\n height: circleD + PLACE_PAD_BELOW + FONT_PLACE,\n };\n }\n if (node.kind === 'junction') {\n return { width: JUNCTION_SIZE, height: JUNCTION_SIZE };\n }\n const label = (node.attrs.label ?? node.id).replace(/\\\\n/g, ' ');\n return {\n width: Math.max(TRANSITION_MIN_W, label.length * TRANSITION_CHARW),\n height: TRANSITION_H,\n };\n}\n\nexport interface NodePosition {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface ClusterBox {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface EdgePath {\n readonly start: { x: number; y: number };\n readonly end: { x: number; y: number };\n readonly bends: ReadonlyArray<{ x: number; y: number }>;\n}\n\nexport interface LayoutResult {\n readonly nodePositions: ReadonlyMap<string, NodePosition>;\n readonly clusterBoxes: ReadonlyMap<string, ClusterBox>;\n /** Keyed on `${src}->${dst}` — ELK-computed edge routes for `nop=2`. */\n readonly edgePaths: ReadonlyMap<string, EdgePath>;\n readonly totalWidth: number;\n readonly totalHeight: number;\n}\n\nconst CLUSTER_OPTIONS: Record<string, string> = {\n 'elk.padding': `[top=${FONT_CLUSTER + 16},left=16,bottom=16,right=16]`,\n 'elk.algorithm': 'layered',\n 'elk.direction': 'DOWN',\n 'elk.spacing.nodeNode': String(CLUSTER_SPACING),\n 'elk.layered.spacing.nodeNodeBetweenLayers': String(CLUSTER_SPACING + 6),\n 'elk.edgeRouting': 'ORTHOGONAL',\n};\n\nconst ROOT_OPTIONS: Record<string, string> = {\n 'elk.algorithm': 'org.eclipse.elk.rectpacking',\n 'elk.aspectRatio': '1.4',\n 'elk.padding': '[top=24,left=24,bottom=24,right=24]',\n 'elk.spacing.nodeNode': String(ROOT_SPACING),\n};\n\nconst ORCHESTRATOR_OPTIONS: Record<string, string> = {\n ...CLUSTER_OPTIONS,\n 'elk.aspectRatio': '2.4',\n 'elk.spacing.nodeNode': '10',\n};\n\n/**\n * Group edges by the cluster that contains both endpoints (or 'root' if\n * the edge crosses cluster boundaries).\n *\n * Orphans count as living in `cluster_orchestrator` for routing purposes,\n * matching v3's `ownerOf` (line 223).\n */\nfunction partitionEdges(graph: GraphModel): {\n byCluster: Map<string, ElkExtendedEdge[]>;\n cross: ElkExtendedEdge[];\n /** edgeId → \"src->dst\" so the layout walk can recover the original key. */\n edgeIdToKey: Map<string, string>;\n} {\n const byCluster = new Map<string, ElkExtendedEdge[]>();\n const cross: ElkExtendedEdge[] = [];\n const edgeIdToKey = new Map<string, string>();\n const ownerOf = (id: string): string =>\n graph.nodeToCluster.get(id) ?? ORCHESTRATOR_CLUSTER_ID;\n\n graph.edges.forEach((e, i) => {\n const so = ownerOf(e.src);\n const dt = ownerOf(e.dst);\n const id = `e${i}`;\n edgeIdToKey.set(id, `${e.src}->${e.dst}`);\n const elkEdge: ElkExtendedEdge = {\n id,\n sources: [e.src],\n targets: [e.dst],\n };\n if (so === dt) {\n let list = byCluster.get(so);\n if (!list) { list = []; byCluster.set(so, list); }\n list.push(elkEdge);\n } else {\n cross.push(elkEdge);\n }\n });\n return { byCluster, cross, edgeIdToKey };\n}\n\n/**\n * Run ELK layout against the C0 graph and return absolute positions.\n *\n * Orphan nodes are wrapped in a synthetic `cluster_orchestrator` so ELK\n * lays them out as a single block alongside the real subnets, which the\n * `rectpacking` root algorithm then packs.\n */\nexport async function elkLayout(graph: GraphModel): Promise<LayoutResult> {\n const { byCluster, cross, edgeIdToKey } = partitionEdges(graph);\n\n const elkChildren: ElkNode[] = [];\n for (const [clusterId, cluster] of graph.clusters) {\n elkChildren.push({\n id: clusterId,\n layoutOptions: CLUSTER_OPTIONS,\n children: cluster.nodes\n .map(id => graph.nodes.get(id))\n .filter((n): n is ParsedNode => n !== undefined)\n .map(n => ({ id: n.id, ...nodeDims(n) })),\n edges: byCluster.get(clusterId) ?? [],\n });\n }\n // Synthetic orchestrator cluster holds the remaining orphans\n elkChildren.push({\n id: ORCHESTRATOR_CLUSTER_ID,\n layoutOptions: ORCHESTRATOR_OPTIONS,\n children: graph.orphans\n .map(id => graph.nodes.get(id))\n .filter((n): n is ParsedNode => n !== undefined)\n .map(n => ({ id: n.id, ...nodeDims(n) })),\n edges: byCluster.get(ORCHESTRATOR_CLUSTER_ID) ?? [],\n });\n\n const elk = new ELK();\n const rootGraph: ElkNode = {\n id: 'root',\n layoutOptions: ROOT_OPTIONS,\n children: elkChildren,\n edges: cross,\n };\n const layout: ElkNode = await elk.layout(rootGraph);\n\n const nodePositions = new Map<string, NodePosition>();\n const clusterBoxes = new Map<string, ClusterBox>();\n const edgePaths = new Map<string, EdgePath>();\n\n const walk = (node: ElkNode, parentX: number, parentY: number): void => {\n const ax = parentX + (node.x ?? 0);\n const ay = parentY + (node.y ?? 0);\n const isCluster = node.id !== 'root' && (node.children?.length ?? 0) > 0;\n if (isCluster) {\n clusterBoxes.set(node.id, {\n x: ax, y: ay,\n width: node.width ?? 0,\n height: node.height ?? 0,\n });\n }\n if (node.id !== 'root' && !isCluster) {\n nodePositions.set(node.id, {\n x: ax, y: ay,\n width: node.width ?? 0,\n height: node.height ?? 0,\n });\n }\n // Edges inside this node — their section coords are in the parent's\n // coordinate frame, so the offset to absolutize is (parentX, parentY)\n // for root edges, or (ax, ay) for cluster-internal edges.\n const edgeOffsetX = node.id === 'root' ? parentX : ax;\n const edgeOffsetY = node.id === 'root' ? parentY : ay;\n for (const edge of node.edges ?? []) {\n const key = edge.id ? edgeIdToKey.get(edge.id) : undefined;\n const section = edge.sections?.[0];\n if (!key || !section) continue;\n edgePaths.set(key, {\n start: {\n x: edgeOffsetX + section.startPoint.x,\n y: edgeOffsetY + section.startPoint.y,\n },\n end: {\n x: edgeOffsetX + section.endPoint.x,\n y: edgeOffsetY + section.endPoint.y,\n },\n bends: (section.bendPoints ?? []).map(p => ({\n x: edgeOffsetX + p.x,\n y: edgeOffsetY + p.y,\n })),\n });\n }\n for (const child of node.children ?? []) walk(child, ax, ay);\n };\n walk(layout, 0, 0);\n\n return {\n nodePositions,\n clusterBoxes,\n edgePaths,\n totalWidth: layout.width ?? 0,\n totalHeight: layout.height ?? 0,\n };\n}\n\n/**\n * Escape an attribute value for inclusion in a DOT string literal.\n *\n * Quotes are doubled (per the DOT escape convention `\\\"`).\n */\nfunction quote(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * Render a node's attribute list — preserving the parsed attrs (including\n * libpetri's `width`/`height`, which are the *visual* shape dimensions)\n * and adding the ELK-computed `pos` so Graphviz `nop` can pin it.\n *\n * The `pos=\"x,y!\"` form (with trailing `!`) is the neato pin-mode marker.\n * Do NOT emit ELK's layout-reserved width/height to Graphviz — those are\n * the bounding boxes needed for ELK packing (which account for xlabel\n * spillover), not the visible shape sizes. libpetri's standard styles use\n * `width=0.35` for places (25pt circles); overriding with ELK's\n * ~3 inch label-padded box made Graphviz render 114pt-radius circles.\n */\nfunction nodeAttrLine(node: ParsedNode, pos: NodePosition): string {\n const attrs: string[] = [];\n // Center the pinned position on the node's bbox (ELK gives the top-left).\n const cx = pos.x + pos.width / 2;\n const cy = pos.y + pos.height / 2;\n attrs.push(`pos=${quote(`${cx.toFixed(2)},${cy.toFixed(2)}!`)}`);\n for (const [k, v] of Object.entries(node.attrs)) {\n if (k === 'pos') continue;\n attrs.push(`${k}=${quote(v)}`);\n }\n return `${node.id} [${attrs.join(', ')}];`;\n}\n\nfunction edgeAttrLine(src: string, dst: string, rawAttrs: string): string {\n // Splice libpetri's original attrs verbatim so style/penwidth/label/color\n // match `DotExporter` 1:1. We do NOT emit `pos=` for edges — under engine\n // `nop` Graphviz routes edges itself around the pinned node positions,\n // which gives proper boundary clipping (arrowheads land at the visual\n // node edge) and avoids needing a custom polyline-to-spline converter.\n // The only \"custom\" arrowhead is `arrowhead=\"odot\"` for inhibitor edges,\n // which libpetri's exporter already writes into rawAttrs.\n const body = rawAttrs.trim();\n return `${src} -> ${dst}` + (body ? ` [${body}];` : ';');\n}\n\n/**\n * Emit a Graphviz DOT string with positions pinned. Render the result with\n * `@viz-js/viz` using:\n *\n * ```ts\n * viz.renderSVGElement(dot, {\n * engine: 'nop',\n * yInvert: true,\n * });\n * ```\n *\n * `engine: 'nop'` (a.k.a. `nop1`) honours the pinned `pos=` on every node\n * and routes edges around them. We use this rather than `nop2` because\n * `nop2` would force us to provide a spline for every edge ourselves (no\n * routing) — and Graphviz's own routing produces correctly-clipped\n * arrowheads at the visual node boundary, which our ELK polylines did not\n * (ELK uses the layout-reserved bbox, our visual circle is much smaller).\n *\n * `yInvert: true` matches ELK's Y-down convention to Graphviz's Y-up.\n */\nexport function writeBack(graph: GraphModel, layout: LayoutResult): string {\n const lines: string[] = [];\n lines.push('digraph LibpetriPinned {');\n lines.push(' rankdir=TB;');\n lines.push(' overlap=\"false\";');\n lines.push(' compound=\"true\";');\n lines.push(' fontname=\"Helvetica,Arial,sans-serif\";');\n lines.push(' outputorder=\"edgesfirst\";');\n lines.push(' node [fontname=\"Helvetica,Arial,sans-serif\", fontsize=10];');\n lines.push(' edge [fontname=\"Helvetica,Arial,sans-serif\", fontsize=9];');\n\n // Clusters with their pinned bounding boxes\n for (const [clusterId, cluster] of graph.clusters) {\n const box = layout.clusterBoxes.get(clusterId);\n lines.push(` subgraph ${clusterId} {`);\n lines.push(` label=${quote(cluster.shortName)};`);\n lines.push(` style=\"rounded,dashed\";`);\n lines.push(` bgcolor=\"#FAFAFA\";`);\n lines.push(` penwidth=1.5;`);\n if (box) {\n const x1 = box.x.toFixed(2);\n const y1 = box.y.toFixed(2);\n const x2 = (box.x + box.width).toFixed(2);\n const y2 = (box.y + box.height).toFixed(2);\n lines.push(` bb=${quote(`${x1},${y1},${x2},${y2}`)};`);\n }\n for (const nodeId of cluster.nodes) {\n const node = graph.nodes.get(nodeId);\n const pos = layout.nodePositions.get(nodeId);\n if (!node || !pos) continue;\n lines.push(' ' + nodeAttrLine(node, pos));\n }\n lines.push(' }');\n }\n\n // Orphans (root-level nodes) — laid out inside the synthetic\n // orchestrator cluster but emitted at root so they sit alongside the\n // real subnets without their own labelled box.\n for (const orphanId of graph.orphans) {\n const node = graph.nodes.get(orphanId);\n const pos = layout.nodePositions.get(orphanId);\n if (!node || !pos) continue;\n lines.push(' ' + nodeAttrLine(node, pos));\n }\n\n // Edges — emit just the source -> dest pair plus libpetri's original\n // styling attrs. Graphviz `nop` routes the line itself and clips arrow\n // heads to the visual node boundary.\n for (const edge of graph.edges) {\n lines.push(' ' + edgeAttrLine(edge.src, edge.dst, edge.rawAttrs));\n }\n\n lines.push('}');\n return lines.join('\\n');\n}\n"],"mappings":";AAkEA,SAAS,aAAa,IAAsB;AAC1C,MAAI,GAAG,WAAW,IAAI,EAAG,QAAO;AAChC,MAAI,GAAG,WAAW,IAAI,EAAG,QAAO;AAChC,SAAO;AACT;AAQA,SAAS,WAAW,MAAsC;AACxD,QAAM,QAAgC,CAAC;AACvC,aAAW,KAAK,KAAK,SAAS,0CAA0C,GAAG;AACzE,UAAM,CAAC,EAAE,KAAK,GAAG,IAAI;AACrB,UAAM,IAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AACxE,UAAM,GAAG,IAAI;AAAA,EACf;AACA,SAAO;AACT;AAaO,SAAS,iBAAiB,KAAyB;AACxD,QAAM,QAAQ,oBAAI,IAAwB;AAM1C,aAAW,KAAK,IAAI,SAAS,6CAA6C,GAAG;AAC3E,UAAM,CAAC,EAAE,IAAI,IAAI,IAAI;AACrB,UAAM,IAAI,IAAI,EAAE,IAAI,MAAM,aAAa,EAAE,GAAG,OAAO,WAAW,IAAI,EAAE,CAAC;AAAA,EACvE;AAEA,QAAM,WAAW,oBAAI,IAA2B;AAChD,QAAM,gBAAgB,oBAAI,IAAoB;AAC9C,aAAW,MAAM,IAAI,SAAS,4CAA4C,GAAG;AAC3E,UAAM,CAAC,EAAE,WAAW,IAAI,IAAI;AAC5B,UAAM,YAAY,CAAC,GAAG,KAAK,SAAS,kCAAkC,CAAC,EAC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ist/render-QK57X4TP.js
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
elkLayout,
|
|
3
|
-
foldOrphans,
|
|
4
|
-
parseLibpetriDot,
|
|
5
|
-
replicateShared,
|
|
6
|
-
writeBack
|
|
7
|
-
} from "./chunk-RNWTYK5B.js";
|
|
8
|
-
|
|
9
|
-
// src/viewer/render.ts
|
|
10
|
-
import { instance as vizInstance } from "@viz-js/viz";
|
|
11
|
-
var vizPromise = null;
|
|
12
|
-
function getViz() {
|
|
13
|
-
if (!vizPromise) vizPromise = vizInstance();
|
|
14
|
-
return vizPromise;
|
|
15
|
-
}
|
|
16
|
-
async function renderDotToSvg(dotSource) {
|
|
17
|
-
const viz = await getViz();
|
|
18
|
-
return viz.renderSVGElement(dotSource, { engine: "dot" });
|
|
19
|
-
}
|
|
20
|
-
function fnv1a(input) {
|
|
21
|
-
let h = 2166136261;
|
|
22
|
-
for (let i = 0; i < input.length; i++) {
|
|
23
|
-
h ^= input.charCodeAt(i);
|
|
24
|
-
h = Math.imul(h, 16777619);
|
|
25
|
-
}
|
|
26
|
-
return (h >>> 0).toString(16);
|
|
27
|
-
}
|
|
28
|
-
var PINNED_DOT_CACHE_CAP = 16;
|
|
29
|
-
var pinnedDotCache = /* @__PURE__ */ new Map();
|
|
30
|
-
function getCachedPinnedDot(key) {
|
|
31
|
-
const hit = pinnedDotCache.get(key);
|
|
32
|
-
if (hit !== void 0) {
|
|
33
|
-
pinnedDotCache.delete(key);
|
|
34
|
-
pinnedDotCache.set(key, hit);
|
|
35
|
-
}
|
|
36
|
-
return hit;
|
|
37
|
-
}
|
|
38
|
-
function setCachedPinnedDot(key, value) {
|
|
39
|
-
pinnedDotCache.set(key, value);
|
|
40
|
-
while (pinnedDotCache.size > PINNED_DOT_CACHE_CAP) {
|
|
41
|
-
const oldest = pinnedDotCache.keys().next().value;
|
|
42
|
-
if (oldest === void 0) break;
|
|
43
|
-
pinnedDotCache.delete(oldest);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
function _clearElkLayoutCache() {
|
|
47
|
-
pinnedDotCache.clear();
|
|
48
|
-
}
|
|
49
|
-
async function renderDotToSvgWithElkLayout(dotSource) {
|
|
50
|
-
const key = fnv1a(dotSource);
|
|
51
|
-
let pinnedDot = getCachedPinnedDot(key);
|
|
52
|
-
if (pinnedDot === void 0) {
|
|
53
|
-
const graph = replicateShared(
|
|
54
|
-
foldOrphans(parseLibpetriDot(dotSource), 0.7),
|
|
55
|
-
{ max: Infinity }
|
|
56
|
-
);
|
|
57
|
-
const layout = await elkLayout(graph);
|
|
58
|
-
pinnedDot = writeBack(graph, layout);
|
|
59
|
-
setCachedPinnedDot(key, pinnedDot);
|
|
60
|
-
}
|
|
61
|
-
const viz = await getViz();
|
|
62
|
-
return viz.renderSVGElement(pinnedDot, {
|
|
63
|
-
engine: "nop",
|
|
64
|
-
yInvert: true
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
export {
|
|
68
|
-
_clearElkLayoutCache,
|
|
69
|
-
getViz,
|
|
70
|
-
renderDotToSvg,
|
|
71
|
-
renderDotToSvgWithElkLayout
|
|
72
|
-
};
|
|
73
|
-
//# sourceMappingURL=render-QK57X4TP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/viewer/render.ts"],"sourcesContent":["/**\n * DOT → SVG rendering for the canonical libpetri viewer.\n *\n * Two render paths:\n *\n * renderDotToSvg(dot) — plain Graphviz `dot` engine.\n * renderDotToSvgWithElkLayout(dot) — C0 pipeline: parse → fold →\n * replicate → ELK → writeBack →\n * Graphviz `neato` with `nop=1`\n * (pin mode). Cached by DOT hash.\n *\n * The ELK path is the default for {@link mount}; the plain-Graphviz path\n * remains as a fallback for callers that want stock layout (or for\n * environments where elkjs isn't installed).\n *\n * @module viewer/render\n */\n\nimport { instance as vizInstance } from '@viz-js/viz';\nimport {\n foldOrphans,\n parseLibpetriDot,\n replicateShared,\n} from './layout/preprocess.js';\nimport { elkLayout, writeBack } from './layout/elk-place.js';\n\ntype Viz = Awaited<ReturnType<typeof vizInstance>>;\n\nlet vizPromise: Promise<Viz> | null = null;\n\n/** Memoize the viz.js instance so the wasm loads only once per page. */\nexport function getViz(): Promise<Viz> {\n if (!vizPromise) vizPromise = vizInstance();\n return vizPromise;\n}\n\n/**\n * Render a DOT source string to an SVGSVGElement using the plain `dot`\n * engine. Deterministic across runs; libpetri exporters emit byte-stable\n * DOT per spec EXP-014 so the same DOT yields the same SVG.\n */\nexport async function renderDotToSvg(dotSource: string): Promise<SVGSVGElement> {\n const viz = await getViz();\n return viz.renderSVGElement(dotSource, { engine: 'dot' });\n}\n\n// ---- C0 / ELK pin-mode cache ---------------------------------------------\n\n/** FNV-1a 32-bit hash. Fast enough that a SHA isn't worth the import. */\nfunction fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16);\n}\n\nconst PINNED_DOT_CACHE_CAP = 16;\nconst pinnedDotCache = new Map<string, string>();\n\nfunction getCachedPinnedDot(key: string): string | undefined {\n const hit = pinnedDotCache.get(key);\n if (hit !== undefined) {\n // LRU touch: re-insert moves to most-recent position in Map ordering.\n pinnedDotCache.delete(key);\n pinnedDotCache.set(key, hit);\n }\n return hit;\n}\n\nfunction setCachedPinnedDot(key: string, value: string): void {\n pinnedDotCache.set(key, value);\n while (pinnedDotCache.size > PINNED_DOT_CACHE_CAP) {\n const oldest = pinnedDotCache.keys().next().value;\n if (oldest === undefined) break;\n pinnedDotCache.delete(oldest);\n }\n}\n\n/** Test helper — clears the pinned-DOT LRU cache between mounts. */\nexport function _clearElkLayoutCache(): void {\n pinnedDotCache.clear();\n}\n\n/**\n * Run the C0 layout pipeline against a libpetri DOT source and return the\n * rendered SVG. The expensive steps (preprocess + ELK layout + DOT rewrite)\n * are cached keyed on the input DOT's hash, so re-mounts on the same net\n * structure skip everything except the Graphviz pin-mode draw.\n *\n * Per-tick marking updates do NOT call this — they toggle classes on the\n * already-mounted SVG. ELK only runs when the net structure changes.\n */\nexport async function renderDotToSvgWithElkLayout(\n dotSource: string,\n): Promise<SVGSVGElement> {\n const key = fnv1a(dotSource);\n let pinnedDot = getCachedPinnedDot(key);\n if (pinnedDot === undefined) {\n const graph = replicateShared(\n foldOrphans(parseLibpetriDot(dotSource), 0.7),\n { max: Infinity },\n );\n const layout = await elkLayout(graph);\n pinnedDot = writeBack(graph, layout);\n setCachedPinnedDot(key, pinnedDot);\n }\n const viz = await getViz();\n return viz.renderSVGElement(pinnedDot, {\n engine: 'nop',\n yInvert: true,\n });\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAS,YAAY,mBAAmB;AAUxC,IAAI,aAAkC;AAG/B,SAAS,SAAuB;AACrC,MAAI,CAAC,WAAY,cAAa,YAAY;AAC1C,SAAO;AACT;AAOA,eAAsB,eAAe,WAA2C;AAC9E,QAAM,MAAM,MAAM,OAAO;AACzB,SAAO,IAAI,iBAAiB,WAAW,EAAE,QAAQ,MAAM,CAAC;AAC1D;AAKA,SAAS,MAAM,OAAuB;AACpC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,SAAK,MAAM,WAAW,CAAC;AACvB,QAAI,KAAK,KAAK,GAAG,QAAU;AAAA,EAC7B;AACA,UAAQ,MAAM,GAAG,SAAS,EAAE;AAC9B;AAEA,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB,oBAAI,IAAoB;AAE/C,SAAS,mBAAmB,KAAiC;AAC3D,QAAM,MAAM,eAAe,IAAI,GAAG;AAClC,MAAI,QAAQ,QAAW;AAErB,mBAAe,OAAO,GAAG;AACzB,mBAAe,IAAI,KAAK,GAAG;AAAA,EAC7B;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,KAAa,OAAqB;AAC5D,iBAAe,IAAI,KAAK,KAAK;AAC7B,SAAO,eAAe,OAAO,sBAAsB;AACjD,UAAM,SAAS,eAAe,KAAK,EAAE,KAAK,EAAE;AAC5C,QAAI,WAAW,OAAW;AAC1B,mBAAe,OAAO,MAAM;AAAA,EAC9B;AACF;AAGO,SAAS,uBAA6B;AAC3C,iBAAe,MAAM;AACvB;AAWA,eAAsB,4BACpB,WACwB;AACxB,QAAM,MAAM,MAAM,SAAS;AAC3B,MAAI,YAAY,mBAAmB,GAAG;AACtC,MAAI,cAAc,QAAW;AAC3B,UAAM,QAAQ;AAAA,MACZ,YAAY,iBAAiB,SAAS,GAAG,GAAG;AAAA,MAC5C,EAAE,KAAK,SAAS;AAAA,IAClB;AACA,UAAM,SAAS,MAAM,UAAU,KAAK;AACpC,gBAAY,UAAU,OAAO,MAAM;AACnC,uBAAmB,KAAK,SAAS;AAAA,EACnC;AACA,QAAM,MAAM,MAAM,OAAO;AACzB,SAAO,IAAI,iBAAiB,WAAW;AAAA,IACrC,QAAQ;AAAA,IACR,SAAS;AAAA,EACX,CAAC;AACH;","names":[]}
|
|
@@ -1,200 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Graph pre-processing for the C0-replicate-default layout pipeline.
|
|
3
|
-
*
|
|
4
|
-
* Three pure-ish transforms operate on a {@link GraphModel} parsed from a
|
|
5
|
-
* libpetri-exported DOT string:
|
|
6
|
-
*
|
|
7
|
-
* parseLibpetriDot(dot) → GraphModel
|
|
8
|
-
* foldOrphans(graph, threshold) → GraphModel (REASSIGN_ORPHANS)
|
|
9
|
-
* replicateShared(graph, opts) → GraphModel (REPLICATE_SHARED)
|
|
10
|
-
*
|
|
11
|
-
* The pipeline turns a flat cluster soup into a cluster-internal one by
|
|
12
|
-
* (a) folding orphan nodes whose edges concentrate in one cluster into that
|
|
13
|
-
* cluster, and (b) cloning shared places into every foreign cluster they
|
|
14
|
-
* touch so cross-cluster spaghetti disappears. The resulting GraphModel is
|
|
15
|
-
* what ELK lays out (Stage 2) and Graphviz then renders in pin-mode.
|
|
16
|
-
*
|
|
17
|
-
* Algorithm lineage: ported from
|
|
18
|
-
* `/home/db/otto-repos/nucleus_marvin/.scratch/javadoc-layout-exp/CHECKPOINTS/run16_GOOD_v3_skip-junctions.mjs`
|
|
19
|
-
* lines 14–220. The arc-type detection, replica naming
|
|
20
|
-
* (`${placeId}__rep__${clusterShortName}`), and the `__replica` /
|
|
21
|
-
* `replicaOf` markers are load-bearing — downstream stages key off them.
|
|
22
|
-
*
|
|
23
|
-
* @module viewer/layout/preprocess
|
|
24
|
-
*/
|
|
25
|
-
type ArcType = 'normal' | 'reset' | 'inhibitor' | 'read';
|
|
26
|
-
type NodeKind = 'place' | 'transition' | 'junction';
|
|
27
|
-
interface ParsedNode {
|
|
28
|
-
readonly id: string;
|
|
29
|
-
readonly kind: NodeKind;
|
|
30
|
-
readonly attrs: Record<string, string>;
|
|
31
|
-
/** True iff this node was emitted by replicateShared. */
|
|
32
|
-
readonly replica?: boolean;
|
|
33
|
-
/** For a replica, the id of the original logical place. */
|
|
34
|
-
readonly replicaOf?: string;
|
|
35
|
-
}
|
|
36
|
-
interface ParsedEdge {
|
|
37
|
-
readonly src: string;
|
|
38
|
-
readonly dst: string;
|
|
39
|
-
readonly arc: ArcType;
|
|
40
|
-
/**
|
|
41
|
-
* Raw attribute body from the libpetri DOT (between the `[…]` brackets,
|
|
42
|
-
* brackets stripped). Carries style/penwidth/label that we want to
|
|
43
|
-
* round-trip verbatim so the rendered output matches `DotExporter`'s
|
|
44
|
-
* native look.
|
|
45
|
-
*/
|
|
46
|
-
readonly rawAttrs: string;
|
|
47
|
-
}
|
|
48
|
-
interface ParsedCluster {
|
|
49
|
-
readonly id: string;
|
|
50
|
-
readonly shortName: string;
|
|
51
|
-
readonly nodes: readonly string[];
|
|
52
|
-
}
|
|
53
|
-
interface GraphModel {
|
|
54
|
-
readonly nodes: ReadonlyMap<string, ParsedNode>;
|
|
55
|
-
readonly clusters: ReadonlyMap<string, ParsedCluster>;
|
|
56
|
-
readonly nodeToCluster: ReadonlyMap<string, string>;
|
|
57
|
-
/** Node ids not in any cluster (rendered at the orchestrator root). */
|
|
58
|
-
readonly orphans: readonly string[];
|
|
59
|
-
readonly edges: readonly ParsedEdge[];
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Parse a libpetri-exported DOT string into a {@link GraphModel}.
|
|
63
|
-
*
|
|
64
|
-
* Tolerates the current exporter shape (see
|
|
65
|
-
* `java/src/main/java/org/libpetri/export/StyleConstants.java`):
|
|
66
|
-
* - inhibitor arcs use `arrowhead="odot"` + color `#dc3545`
|
|
67
|
-
* - reset arcs use `label="reset"` + color `#fd7e14`
|
|
68
|
-
* - read arcs use `label="read"` + color `#6c757d`
|
|
69
|
-
*
|
|
70
|
-
* Mirrors v3 lines 24–103.
|
|
71
|
-
*/
|
|
72
|
-
declare function parseLibpetriDot(dot: string): GraphModel;
|
|
73
|
-
/**
|
|
74
|
-
* Adopt orphan nodes into the cluster their edges most prefer.
|
|
75
|
-
*
|
|
76
|
-
* For each orphan, tally how many of its edges touch each cluster. If the
|
|
77
|
-
* dominant cluster gets at least `threshold` of the orphan's cluster-touching
|
|
78
|
-
* edges, the orphan is reassigned to that cluster.
|
|
79
|
-
*
|
|
80
|
-
* Mirrors v3 lines 105–136. Default threshold 0.7 matches REASSIGN_ORPHANS.
|
|
81
|
-
*/
|
|
82
|
-
declare function foldOrphans(graph: GraphModel, threshold?: number): GraphModel;
|
|
83
|
-
interface ReplicateOptions {
|
|
84
|
-
/**
|
|
85
|
-
* Skip places that touch more than this many foreign clusters. Per the
|
|
86
|
-
* plan's "no cap" decision, default is `Infinity`. Set to a finite value
|
|
87
|
-
* to suppress replication of hub places that would otherwise produce many
|
|
88
|
-
* copies.
|
|
89
|
-
*/
|
|
90
|
-
readonly max?: number;
|
|
91
|
-
/** If true, replicate transitions as well as places. Default false. */
|
|
92
|
-
readonly replicateTransitions?: boolean;
|
|
93
|
-
}
|
|
94
|
-
interface ReplicateStats {
|
|
95
|
-
readonly replicatedPlaces: number;
|
|
96
|
-
readonly totalCopies: number;
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* For each place P, replicate it into every foreign cluster touched by its
|
|
100
|
-
* edges, and redirect those cross-cluster edges to the local copy.
|
|
101
|
-
*
|
|
102
|
-
* Replica id convention is load-bearing: `${placeId}__rep__${shortClusterName}`.
|
|
103
|
-
* Downstream stages (mount-time tagging, overlay highlight, click-all-copies)
|
|
104
|
-
* key off this naming and the `replica: true` / `replicaOf` markers.
|
|
105
|
-
*
|
|
106
|
-
* If P has a home cluster (folded earlier), the original stays as the primary
|
|
107
|
-
* copy and is also marked as a replica so the ⇄ glyph renders consistently.
|
|
108
|
-
* If P is an orphan with all its edges redirected, the original is dropped.
|
|
109
|
-
*
|
|
110
|
-
* Mirrors v3 lines 138–221.
|
|
111
|
-
*/
|
|
112
|
-
declare function replicateShared(graph: GraphModel, opts?: ReplicateOptions): GraphModel & {
|
|
113
|
-
readonly replicateStats: ReplicateStats;
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* ELK placement + DOT pin-mode rewrite.
|
|
118
|
-
*
|
|
119
|
-
* Stage 2 of the C0 pipeline. Takes the {@link GraphModel} produced by
|
|
120
|
-
* {@link parseLibpetriDot} → {@link foldOrphans} → {@link replicateShared},
|
|
121
|
-
* runs ELKjs to compute absolute `(x, y)` per node and bounding boxes per
|
|
122
|
-
* cluster, then emits a fresh DOT string with positions pinned via
|
|
123
|
-
* `pos="x,y!"` and `bb="…"`. Downstream callers render the result through
|
|
124
|
-
* `@viz-js/viz` with `engine: 'neato'` + `graphAttributes: { nop: '1' }` —
|
|
125
|
-
* Graphviz uses the pinned positions verbatim and routes edges around the
|
|
126
|
-
* pinned cluster boundaries.
|
|
127
|
-
*
|
|
128
|
-
* The two functions are pure: `elkLayout` takes only the graph; `writeBack`
|
|
129
|
-
* takes (graph, layout). Neither touches the original DOT text — the model
|
|
130
|
-
* after replication has nodes the original DOT doesn't, so patching the
|
|
131
|
-
* original would be incorrect.
|
|
132
|
-
*
|
|
133
|
-
* @module viewer/layout/elk-place
|
|
134
|
-
*/
|
|
135
|
-
|
|
136
|
-
interface NodePosition {
|
|
137
|
-
readonly x: number;
|
|
138
|
-
readonly y: number;
|
|
139
|
-
readonly width: number;
|
|
140
|
-
readonly height: number;
|
|
141
|
-
}
|
|
142
|
-
interface ClusterBox {
|
|
143
|
-
readonly x: number;
|
|
144
|
-
readonly y: number;
|
|
145
|
-
readonly width: number;
|
|
146
|
-
readonly height: number;
|
|
147
|
-
}
|
|
148
|
-
interface EdgePath {
|
|
149
|
-
readonly start: {
|
|
150
|
-
x: number;
|
|
151
|
-
y: number;
|
|
152
|
-
};
|
|
153
|
-
readonly end: {
|
|
154
|
-
x: number;
|
|
155
|
-
y: number;
|
|
156
|
-
};
|
|
157
|
-
readonly bends: ReadonlyArray<{
|
|
158
|
-
x: number;
|
|
159
|
-
y: number;
|
|
160
|
-
}>;
|
|
161
|
-
}
|
|
162
|
-
interface LayoutResult {
|
|
163
|
-
readonly nodePositions: ReadonlyMap<string, NodePosition>;
|
|
164
|
-
readonly clusterBoxes: ReadonlyMap<string, ClusterBox>;
|
|
165
|
-
/** Keyed on `${src}->${dst}` — ELK-computed edge routes for `nop=2`. */
|
|
166
|
-
readonly edgePaths: ReadonlyMap<string, EdgePath>;
|
|
167
|
-
readonly totalWidth: number;
|
|
168
|
-
readonly totalHeight: number;
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* Run ELK layout against the C0 graph and return absolute positions.
|
|
172
|
-
*
|
|
173
|
-
* Orphan nodes are wrapped in a synthetic `cluster_orchestrator` so ELK
|
|
174
|
-
* lays them out as a single block alongside the real subnets, which the
|
|
175
|
-
* `rectpacking` root algorithm then packs.
|
|
176
|
-
*/
|
|
177
|
-
declare function elkLayout(graph: GraphModel): Promise<LayoutResult>;
|
|
178
|
-
/**
|
|
179
|
-
* Emit a Graphviz DOT string with positions pinned. Render the result with
|
|
180
|
-
* `@viz-js/viz` using:
|
|
181
|
-
*
|
|
182
|
-
* ```ts
|
|
183
|
-
* viz.renderSVGElement(dot, {
|
|
184
|
-
* engine: 'nop',
|
|
185
|
-
* yInvert: true,
|
|
186
|
-
* });
|
|
187
|
-
* ```
|
|
188
|
-
*
|
|
189
|
-
* `engine: 'nop'` (a.k.a. `nop1`) honours the pinned `pos=` on every node
|
|
190
|
-
* and routes edges around them. We use this rather than `nop2` because
|
|
191
|
-
* `nop2` would force us to provide a spline for every edge ourselves (no
|
|
192
|
-
* routing) — and Graphviz's own routing produces correctly-clipped
|
|
193
|
-
* arrowheads at the visual node boundary, which our ELK polylines did not
|
|
194
|
-
* (ELK uses the layout-reserved bbox, our visual circle is much smaller).
|
|
195
|
-
*
|
|
196
|
-
* `yInvert: true` matches ELK's Y-down convention to Graphviz's Y-up.
|
|
197
|
-
*/
|
|
198
|
-
declare function writeBack(graph: GraphModel, layout: LayoutResult): string;
|
|
199
|
-
|
|
200
|
-
export { type ArcType, type ClusterBox, type GraphModel, type LayoutResult, type NodeKind, type NodePosition, type ParsedCluster, type ParsedEdge, type ParsedNode, type ReplicateOptions, type ReplicateStats, elkLayout, foldOrphans, parseLibpetriDot, replicateShared, writeBack };
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
elkLayout,
|
|
3
|
-
foldOrphans,
|
|
4
|
-
parseLibpetriDot,
|
|
5
|
-
replicateShared,
|
|
6
|
-
writeBack
|
|
7
|
-
} from "../../chunk-RNWTYK5B.js";
|
|
8
|
-
export {
|
|
9
|
-
elkLayout,
|
|
10
|
-
foldOrphans,
|
|
11
|
-
parseLibpetriDot,
|
|
12
|
-
replicateShared,
|
|
13
|
-
writeBack
|
|
14
|
-
};
|
|
15
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/*! libpetri viewer (IIFE) — generated, do not edit; source: typescript/src/viewer/ */
|
|
2
|
-
"use strict";(()=>{var Pn=Object.create;var Le=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var In=Object.getOwnPropertyNames;var Dn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var Hn=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),lt=(t,e)=>{for(var n in e)Le(t,n,{get:e[n],enumerable:!0})},Rn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of In(e))!qn.call(t,a)&&a!==n&&Le(t,a,{get:()=>e[a],enumerable:!(r=Bn(e,a))||r.enumerable});return t};var Zn=(t,e,n)=>(n=t!=null?Pn(Dn(t)):{},Rn(e||!t||!t.__esModule?Le(n,"default",{value:t,enumerable:!0}):n,t));var ut=I((Dr,ce)=>{ce.exports=ct;ce.exports.addWheelListener=ct;ce.exports.removeWheelListener=Wn;function ct(t,e,n){t.addEventListener("wheel",e,n)}function Wn(t,e,n){t.removeEventListener("wheel",e,n)}});var gt=I((qr,ht)=>{var jn=4,$n=.001,Yn=1e-7,Un=10,Q=11,ue=1/(Q-1),Kn=typeof Float32Array=="function";function dt(t,e){return 1-3*e+3*t}function ft(t,e){return 3*e-6*t}function pt(t){return 3*t}function de(t,e,n){return((dt(e,n)*t+ft(e,n))*t+pt(e))*t}function mt(t,e,n){return 3*dt(e,n)*t*t+2*ft(e,n)*t+pt(e)}function Jn(t,e,n,r,a){var s,i,c=0;do i=e+(n-e)/2,s=de(i,r,a)-t,s>0?n=i:e=i;while(Math.abs(s)>Yn&&++c<Un);return i}function Qn(t,e,n,r){for(var a=0;a<jn;++a){var s=mt(e,n,r);if(s===0)return e;var i=de(e,n,r)-t;e-=i/s}return e}function Xn(t){return t}ht.exports=function(e,n,r,a){if(!(0<=e&&e<=1&&0<=r&&r<=1))throw new Error("bezier x values must be in [0, 1] range");if(e===n&&r===a)return Xn;for(var s=Kn?new Float32Array(Q):new Array(Q),i=0;i<Q;++i)s[i]=de(i*ue,e,r);function c(m){for(var l=0,f=1,v=Q-1;f!==v&&s[f]<=m;++f)l+=ue;--f;var b=(m-s[f])/(s[f+1]-s[f]),g=l+b*ue,S=mt(g,e,r);return S>=$n?Qn(m,g,e,r):S===0?g:Jn(m,l,l+ue,e,r)}return function(l){return l===0?0:l===1?1:de(c(l),n,a)}}});var St=I((Hr,fe)=>{var X=gt(),vt={ease:X(.25,.1,.25,1),easeIn:X(.42,0,1,1),easeOut:X(0,0,.58,1),easeInOut:X(.42,0,.58,1),linear:X(0,0,1,1)};fe.exports=er;fe.exports.makeAggregateRaf=yt;fe.exports.sharedScheduler=yt();function er(t,e,n){var r=Object.create(null),a=Object.create(null);n=n||{};var s=typeof n.easing=="function"?n.easing:vt[n.easing];s||(n.easing&&console.warn("Unknown easing function in amator: "+n.easing),s=vt.ease);var i=typeof n.step=="function"?n.step:bt,c=typeof n.done=="function"?n.done:bt,m=tr(n.scheduler),l=Object.keys(e);l.forEach(function(E){r[E]=t[E],a[E]=e[E]-t[E]});var f=typeof n.duration=="number"?n.duration:400,v=Math.max(1,f*.06),b,g=0;return b=m.next(x),{cancel:S};function S(){m.cancel(b),b=0}function x(){var E=s(g/v);g+=1,w(E),g<=v?(b=m.next(x),i(t)):(b=0,setTimeout(function(){c(t)},0))}function w(E){l.forEach(function(N){t[N]=a[N]*E+r[N]})}}function bt(){}function tr(t){if(!t){var e=typeof window<"u"&&window.requestAnimationFrame;return e?nr():rr()}if(typeof t.next!="function")throw new Error("Scheduler is supposed to have next(cb) function");if(typeof t.cancel!="function")throw new Error("Scheduler is supposed to have cancel(handle) function");return t}function nr(){return{next:window.requestAnimationFrame.bind(window),cancel:window.cancelAnimationFrame.bind(window)}}function rr(){return{next:function(t){return setTimeout(t,1e3/60)},cancel:function(t){return clearTimeout(t)}}}function yt(){var t=new Set,e=new Set,n=0;return{next:a,cancel:a,clearAll:r};function r(){t.clear(),e.clear(),cancelAnimationFrame(n),n=0}function a(m){e.add(m),s()}function s(){n||(n=requestAnimationFrame(i))}function i(){n=0;var m=e;e=t,t=m,t.forEach(function(l){l()}),t.clear()}function c(m){e.delete(m)}}});var wt=I((Rr,xt)=>{"use strict";function ir(t){ar(t);let e=or(t);return t.on=e.on,t.off=e.off,t.fire=e.fire,t}function or(t){let e=Object.create(null);return{on:function(n,r,a){if(typeof r!="function")throw new Error("callback is expected to be a function");let s=e[n];return s||(s=e[n]=[]),s.push({callback:r,ctx:a}),t},off:function(n,r){if(typeof n>"u")return e=Object.create(null),t;if(e[n])if(typeof r!="function")delete e[n];else{let a=e[n];for(let s=0;s<a.length;++s)a[s].callback===r&&a.splice(s,1)}return t},fire:function(n){let r=e[n];if(!r)return t;let a;arguments.length>1&&(a=Array.prototype.slice.call(arguments,1));for(let s=0;s<r.length;++s){let i=r[s];i.callback.apply(i.ctx,a)}return t}}}function ar(t){if(!t)throw new Error("Eventify cannot use falsy object as events subject");let e=["on","fire","off"];for(let n=0;n<e.length;++n)if(t.hasOwnProperty(e[n]))throw new Error("Subject cannot be eventified, since it already has property '"+e[n]+"'")}xt.exports=ir});var Et=I((Zr,Ct)=>{Ct.exports=sr;function sr(t,e,n){typeof n!="object"&&(n={});var r=typeof n.minVelocity=="number"?n.minVelocity:5,a=typeof n.amplitude=="number"?n.amplitude:.25,s=typeof n.cancelAnimationFrame=="function"?n.cancelAnimationFrame:lr(),i=typeof n.requestAnimationFrame=="function"?n.requestAnimationFrame:cr(),c,m,l=342,f,v,b,g,S,x,w,E;return{start:F,stop:A,cancel:N};function N(){s(f),s(E)}function F(){c=t(),g=w=v=S=0,m=new Date,s(f),s(E),f=i(_)}function _(){var y=Date.now(),L=y-m;m=y;var V=t(),T=V.x-c.x,B=V.y-c.y;c=V;var M=1e3/(1+L);v=.8*T*M+.2*v,S=.8*B*M+.2*S,f=i(_)}function A(){s(f),s(E);var y=t();b=y.x,x=y.y,m=Date.now(),(v<-r||v>r)&&(g=a*v,b+=g),(S<-r||S>r)&&(w=a*S,x+=w),E=i(h)}function h(){var y=Date.now()-m,L=!1,V=0,T=0;g&&(V=-g*Math.exp(-y/l),V>.5||V<-.5?L=!0:V=g=0),w&&(T=-w*Math.exp(-y/l),T>.5||T<-.5?L=!0:T=w=0),L&&(e(b+V,x+T),E=i(h))}}function lr(){return typeof cancelAnimationFrame=="function"?cancelAnimationFrame:clearTimeout}function cr(){return typeof requestAnimationFrame=="function"?requestAnimationFrame:function(t){return setTimeout(t,16)}}});var Tt=I((Wr,Lt)=>{Lt.exports=ur;function ur(t){if(t)return{capture:Vt,release:Vt};var e,n,r,a=!1;return{capture:s,release:i};function s(c){a=!0,n=window.document.onselectstart,r=window.document.ondragstart,window.document.onselectstart=At,e=c,e.ondragstart=At}function i(){a&&(a=!1,window.document.onselectstart=n,e&&(e.ondragstart=r))}}function At(t){return t.stopPropagation(),!1}function Vt(){}});var kt=I((jr,Gt)=>{Gt.exports=dr;function dr(){this.x=0,this.y=0,this.scale=1}});var _t=I(($r,Te)=>{Te.exports=fr;Te.exports.canAttach=Mt;function fr(t,e){if(!Mt(t))throw new Error("svg element is required for svg.panzoom to work");var n=t.ownerSVGElement;if(!n)throw new Error("Do not apply panzoom to the root <svg> element. Use its child instead (e.g. <g></g>). As of March 2016 only FireFox supported transform on the root element");e.disableKeyboardInteraction||n.setAttribute("tabindex",0);var r={getBBox:s,getScreenCTM:i,getOwner:a,applyTransform:m,initTransform:c};return r;function a(){return n}function s(){var l=t.getBBox();return{left:l.x,top:l.y,width:l.width,height:l.height}}function i(){var l=n.getCTM();return l||n.getScreenCTM()}function c(l){var f=t.getCTM();f===null&&(f=document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGMatrix()),l.x=f.e,l.y=f.f,l.scale=f.a,n.removeAttributeNS(null,"viewBox")}function m(l){t.setAttribute("transform","matrix("+l.scale+" 0 0 "+l.scale+" "+l.x+" "+l.y+")")}}function Mt(t){return t&&t.ownerSVGElement&&t.getCTM}});var Nt=I((Yr,Ge)=>{Ge.exports=pr;Ge.exports.canAttach=Ot;function pr(t,e){var n=Ot(t);if(!n)throw new Error("panzoom requires DOM element to be attached to the DOM tree");var r=t.parentElement;t.scrollTop=0,e.disableKeyboardInteraction||r.setAttribute("tabindex",0);var a={getBBox:i,getOwner:s,applyTransform:c};return a;function s(){return r}function i(){return{left:0,top:0,width:t.clientWidth,height:t.clientHeight}}function c(m){t.style.transformOrigin="0 0 0",t.style.transform="matrix("+m.scale+", 0, 0, "+m.scale+", "+m.x+", "+m.y+")"}}function Ot(t){return t&&t.parentElement&&t.style}});var Wt=I((Ur,Zt)=>{"use strict";var Ft=ut(),ke=St(),mr=wt(),hr=Et(),Ht=Tt(),gr=Ht(),vr=Ht(!0),br=kt(),zt=_t(),Pt=Nt(),yr=1,Sr=1.75,Bt=300,It=200;Zt.exports=Rt;function Rt(t,e){e=e||{};var n=e.controller;if(n||(zt.canAttach(t)?n=zt(t,e):Pt.canAttach(t)&&(n=Pt(t,e))),!n)throw new Error("Cannot create panzoom for the current type of dom element");var r=n.getOwner(),a={x:0,y:0},s=!1,i=new br;n.initTransform&&n.initTransform(i);var c=typeof e.filterKey=="function"?e.filterKey:Y,m=typeof e.pinchSpeed=="number"?e.pinchSpeed:1,l=e.bounds,f=typeof e.maxZoom=="number"?e.maxZoom:Number.POSITIVE_INFINITY,v=typeof e.minZoom=="number"?e.minZoom:0,b=typeof e.boundsPadding=="number"?e.boundsPadding:.05,g=typeof e.zoomDoubleClickSpeed=="number"?e.zoomDoubleClickSpeed:Sr,S=e.beforeWheel||Y,x=e.beforeMouseDown||Y,w=typeof e.zoomSpeed=="number"?e.zoomSpeed:yr,E=Dt(e.transformOrigin),N=e.enableTextSelection?vr:gr;xr(l),e.autocenter&&pn();var F,_=0,A=0,h=0,y=null,L=new Date,V,T=!1,B=!1,M,z,ye,Se,xe,P;"smoothScroll"in e&&!e.smoothScroll?P=wr():P=hr(Cn,Tn,e.smoothScroll);var we,U,te,ne=!1;He();var re={dispose:Gn,moveBy:Z,moveTo:Ce,smoothMoveTo:Ln,centerOn:Vn,zoomTo:se,zoomAbs:ie,smoothZoom:ae,smoothZoomAbs:zn,showRectangle:fn,pause:cn,resume:un,isPaused:dn,getTransform:mn,getMinZoom:hn,setMinZoom:gn,getMaxZoom:vn,setMaxZoom:bn,getTransformOrigin:yn,setTransformOrigin:Sn,getZoomSpeed:xn,setZoomSpeed:wn};mr(re);var ze=typeof e.initialX=="number"?e.initialX:i.x,Pe=typeof e.initialY=="number"?e.initialY:i.y,Be=typeof e.initialZoom=="number"?e.initialZoom:i.scale;return(ze!=i.x||Pe!=i.y||Be!=i.scale)&&ie(ze,Pe,Be),re;function cn(){Re(),ne=!0}function un(){ne&&(He(),ne=!1)}function dn(){return ne}function fn(o){var u=r.getBoundingClientRect(),d=q(u.width,u.height),p=o.right-o.left,C=o.bottom-o.top;if(!Number.isFinite(p)||!Number.isFinite(C))throw new Error("Invalid rectangle");var G=d.x/p,k=d.y/C,O=Math.min(G,k);i.x=-(o.left+p/2)*O+d.x/2,i.y=-(o.top+C/2)*O+d.y/2,i.scale=O}function q(o,u){if(n.getScreenCTM){var d=n.getScreenCTM(),p=d.a,C=d.d,G=d.e,k=d.f;a.x=o*p-G,a.y=u*C-k}else a.x=o,a.y=u;return a}function pn(){var o,u,d=0,p=0,C=De();if(C)d=C.left,p=C.top,o=C.right-C.left,u=C.bottom-C.top;else{var G=r.getBoundingClientRect();o=G.width,u=G.height}var k=n.getBBox();if(!(k.width===0||k.height===0)){var O=u/k.height,j=o/k.width,H=Math.min(j,O);i.x=-(k.left+k.width/2)*H+o/2+d,i.y=-(k.top+k.height/2)*H+u/2+p,i.scale=H}}function mn(){return i}function hn(){return v}function gn(o){v=o}function vn(){return f}function bn(o){f=o}function yn(){return E}function Sn(o){E=Dt(o)}function xn(){return w}function wn(o){if(!Number.isFinite(o))throw new Error("Zoom speed should be a number");w=o}function Cn(){return{x:i.x,y:i.y}}function Ce(o,u){i.x=o,i.y=u,Ee(),W("pan"),Ae()}function Ie(o,u){Ce(i.x+o,i.y+u)}function Ee(){var o=De();if(o){var u=!1,d=En(),p=o.left-d.right;return p>0&&(i.x+=p,u=!0),p=o.right-d.left,p<0&&(i.x+=p,u=!0),p=o.top-d.bottom,p>0&&(i.y+=p,u=!0),p=o.bottom-d.top,p<0&&(i.y+=p,u=!0),u}}function De(){if(l){if(typeof l=="boolean"){var o=r.getBoundingClientRect(),u=o.width,d=o.height;return{left:u*b,top:d*b,right:u*(1-b),bottom:d*(1-b)}}return l}}function En(){var o=n.getBBox(),u=An(o.left,o.top);return{left:u.x,top:u.y,right:o.width*i.scale+u.x,bottom:o.height*i.scale+u.y}}function An(o,u){return{x:o*i.scale+i.x,y:u*i.scale+i.y}}function Ae(){s=!0,F=window.requestAnimationFrame(kn)}function qe(o,u,d){if(Me(o)||Me(u)||Me(d))throw new Error("zoom requires valid numbers");var p=i.scale*d;if(p<v){if(i.scale===v)return;d=v/i.scale}if(p>f){if(i.scale===f)return;d=f/i.scale}var C=q(o,u);if(i.x=C.x-d*(C.x-i.x),i.y=C.y-d*(C.y-i.y),l&&b===1&&v===1)i.scale*=d,Ee();else{var G=Ee();G||(i.scale*=d)}W("zoom"),Ae()}function ie(o,u,d){var p=d/i.scale;qe(o,u,p)}function Vn(o){var u=o.ownerSVGElement;if(!u)throw new Error("ui element is required to be within the scene");var d=o.getBoundingClientRect(),p=d.left+d.width/2,C=d.top+d.height/2,G=u.getBoundingClientRect(),k=G.width/2-p,O=G.height/2-C;Z(k,O,!0)}function Ln(o,u){Z(o-i.x,u-i.y,!0)}function Z(o,u,d){if(!d)return Ie(o,u);we&&we.cancel();var p={x:0,y:0},C={x:o,y:u},G=0,k=0;we=ke(p,C,{step:function(O){Ie(O.x-G,O.y-k),G=O.x,k=O.y}})}function Tn(o,u){le(),Ce(o,u)}function Gn(){Re()}function He(){r.addEventListener("mousedown",Je,{passive:!1}),r.addEventListener("dblclick",Ke,{passive:!1}),r.addEventListener("touchstart",We,{passive:!1}),r.addEventListener("keydown",Ze,{passive:!1}),Ft.addWheelListener(r,nt,{passive:!1}),Ae()}function Re(){Ft.removeWheelListener(r,nt),r.removeEventListener("mousedown",Je),r.removeEventListener("keydown",Ze),r.removeEventListener("dblclick",Ke),r.removeEventListener("touchstart",We),F&&(window.cancelAnimationFrame(F),F=0),P.cancel(),et(),tt(),N.release(),Ve()}function kn(){s&&Mn()}function Mn(){s=!1,n.applyTransform(i),W("transform"),F=0}function Ze(o){var u=0,d=0,p=0;if(o.keyCode===38?d=1:o.keyCode===40?d=-1:o.keyCode===37?u=1:o.keyCode===39?u=-1:o.keyCode===189||o.keyCode===109?p=1:(o.keyCode===187||o.keyCode===107)&&(p=-1),!c(o,u,d,p)){if(u||d){o.preventDefault(),o.stopPropagation();var C=r.getBoundingClientRect(),G=Math.min(C.width,C.height),k=.05,O=G*k*u,j=G*k*d;Z(O,j)}if(p){var H=rt(p*100),G=E?J():_n();se(G.x,G.y,H)}}}function _n(){var o=r.getBoundingClientRect();return{x:o.width/2,y:o.height/2}}function We(o){if(On(o),K(),o.touches.length===1)return Fn(o,o.touches[0]);o.touches.length===2&&(xe=Ue(o.touches[0],o.touches[1]),te=!0,je())}function On(o){e.onTouch&&!e.onTouch(o)||(o.stopPropagation(),o.preventDefault())}function Nn(o){K(),!(e.onDoubleClick&&!e.onDoubleClick(o))&&(o.preventDefault(),o.stopPropagation())}function Fn(o){A=new Date;var u=o.touches[0],d=D(u);V=d;var p=q(d.x,d.y);M=p.x,z=p.y,ye=M,Se=z,P.cancel(),je()}function je(){T||(T=!0,document.addEventListener("touchmove",$e),document.addEventListener("touchend",oe),document.addEventListener("touchcancel",oe))}function $e(o){if(o.touches.length===1){o.stopPropagation();var u=o.touches[0],d=D(u),p=q(d.x,d.y),C=p.x-M,G=p.y-z;C!==0&&G!==0&&it(),M=p.x,z=p.y,Z(C,G)}else if(o.touches.length===2){te=!0;var k=o.touches[0],O=o.touches[1],j=Ue(k,O),H=1+(j/xe-1)*m,at=D(k),st=D(O);if(M=(at.x+st.x)/2,z=(at.y+st.y)/2,E){var d=J();M=d.x,z=d.y}se(M,z,H),xe=j,o.stopPropagation(),o.preventDefault()}}function K(){h&&(clearTimeout(h),h=0)}function Ye(o){if(e.onClick){K();var u=M-ye,d=z-Se,p=Math.sqrt(u*u+d*d);p>5||(h=setTimeout(function(){h=0,e.onClick(o)},Bt))}}function oe(o){if(K(),o.touches.length>0){var u=D(o.touches[0]),d=q(u.x,u.y);M=d.x,z=d.y}else{var p=new Date;if(p-_<Bt)if(E){var u=J();ae(u.x,u.y,g)}else ae(V.x,V.y,g);else p-A<It&&Ye(o);_=p,Ve(),tt()}}function Ue(o,u){var d=o.clientX-u.clientX,p=o.clientY-u.clientY;return Math.sqrt(d*d+p*p)}function Ke(o){Nn(o);var u=D(o);E&&(u=J()),ae(u.x,u.y,g)}function Je(o){if(K(),!x(o)){if(y=o,L=new Date,T)return o.stopPropagation(),!1;var u=o.button===1&&window.event!==null||o.button===0;if(u){P.cancel();var d=D(o),p=q(d.x,d.y);return ye=M=p.x,Se=z=p.y,document.addEventListener("mousemove",Qe),document.addEventListener("mouseup",Xe),N.capture(o.target||o.srcElement),!1}}}function Qe(o){if(!T){it();var u=D(o),d=q(u.x,u.y),p=d.x-M,C=d.y-z;M=d.x,z=d.y,Z(p,C)}}function Xe(){var o=new Date;o-L<It&&Ye(y),N.release(),Ve(),et()}function et(){document.removeEventListener("mousemove",Qe),document.removeEventListener("mouseup",Xe),B=!1}function tt(){document.removeEventListener("touchmove",$e),document.removeEventListener("touchend",oe),document.removeEventListener("touchcancel",oe),B=!1,te=!1,T=!1}function nt(o){if(!S(o)){P.cancel();var u=o.deltaY;o.deltaMode>0&&(u*=100);var d=rt(u);if(d!==1){var p=E?J():D(o);se(p.x,p.y,d),o.preventDefault()}}}function D(o){var u,d,p=r.getBoundingClientRect();return u=o.clientX-p.left,d=o.clientY-p.top,{x:u,y:d}}function ae(o,u,d){var p=i.scale,C={scale:p},G={scale:d*p};P.cancel(),le(),U=ke(C,G,{step:function(k){ie(o,u,k.scale)},done:ot})}function zn(o,u,d){var p=i.scale,C={scale:p},G={scale:d};P.cancel(),le(),U=ke(C,G,{step:function(k){ie(o,u,k.scale)},done:ot})}function J(){var o=r.getBoundingClientRect();return{x:o.width*E.x,y:o.height*E.y}}function se(o,u,d){return P.cancel(),le(),qe(o,u,d)}function le(){U&&(U.cancel(),U=null)}function rt(o){var u=Math.sign(o),d=Math.min(.25,Math.abs(w*o/128));return 1-u*d}function it(){B||(W("panstart"),B=!0,P.start())}function Ve(){B&&(te||P.stop(),W("panend"))}function ot(){W("zoomend")}function W(o){re.fire(o,re)}}function Dt(t){if(t){if(typeof t=="object")return(!$(t.x)||!$(t.y))&&qt(t),t;qt()}}function qt(t){throw console.error(t),new Error(["Cannot parse transform origin.","Some good examples:",' "center center" can be achieved with {x: 0.5, y: 0.5}',' "top center" can be achieved with {x: 0.5, y: 0}',' "bottom right" can be achieved with {x: 1, y: 1}'].join(`
|
|
3
|
-
`))}function Y(){}function xr(t){var e=typeof t;if(!(e==="undefined"||e==="boolean")){var n=$(t.left)&&$(t.top)&&$(t.bottom)&&$(t.right);if(!n)throw new Error("Bounds object is not valid. It can be: undefined, boolean (true|false) or an object {left, top, right, bottom}")}}function $(t){return Number.isFinite(t)}function Me(t){return Number.isNaN?Number.isNaN(t):t!==t}function wr(){return{start:Y,stop:Y,cancel:Y}}function Cr(){if(typeof document>"u")return;var t=document.getElementsByTagName("script");if(!t)return;for(var e,n=0;n<t.length;++n){var r=t[n];if(r.src&&r.src.match(/\bpanzoom(\.min)?\.js/)){e=r;break}}if(!e)return;var a=e.getAttribute("query");if(!a)return;var s=e.getAttribute("name")||"pz",i=Date.now();c();function c(){var f=document.querySelector(a);if(!f){var v=Date.now(),b=v-i;if(b<2e3){setTimeout(c,100);return}console.error("Cannot find the panzoom element",s);return}var g=m(e);console.log(g),window[s]=Rt(f,g)}function m(f){for(var v=f.attributes,b={},g=0;g<v.length;++g){var S=v[g],x=l(S);x&&(b[x.name]=x.value)}return b}function l(f){if(f.name){var v=f.name[0]==="p"&&f.name[1]==="z"&&f.name[2]==="-";if(v){var b=f.name.substr(3),g=JSON.parse(f.value);return{name:b,value:g}}}}}Cr()});var sn={};lt(sn,{getViz:()=>Br,renderDotToSvg:()=>Pr});async function Pr(t){throw new Error("libpetri viewer: static bundle has no DOT renderer. Either ship the pre-rendered SVG in the host (mount(null, container, opts)) or load the full viewer.iife.js bundle.")}function Br(){throw new Error("libpetri viewer: static bundle has no Viz instance.")}var ln=Hn(()=>{});var Fe={};lt(Fe,{DEFAULT_PANZOOM_OPTS:()=>pe,VIEWER_CSS_VARIABLES:()=>Oe,colorForPrefix:()=>ge,discoverClusters:()=>he,mount:()=>Ne});var jt=Zn(Wt(),1),pe={smoothScroll:!1,zoomDoubleClickSpeed:1,maxZoom:1e3,minZoom:.02};function $t(t,e,n){if(n)try{n.dispose()}catch{}let r={...pe,...e};return(0,jt.default)(t,r)}function he(t){let e=new Map,n=t.querySelectorAll("g.cluster");if(!n.length)return e;let r=Array.from(t.querySelectorAll("g.node"));for(let a of Array.from(n)){let s=R(a,"title");if(!s)continue;let i=s.textContent??"";if(!i.startsWith("cluster_"))continue;let c=i.slice(8);if(e.has(c))continue;let m=0;for(let l of r){if(l.getAttribute("data-instance"))continue;let f=R(l,"title");if(!f)continue;let v=(f.textContent??"").trim();me(v,c)&&(l.setAttribute("data-instance",c),m++)}e.set(c,{prefix:c,group:a,nodeCount:m,color:ge(c)})}return e}function me(t,e){return t===e||t.startsWith(`${e}/`)||t.startsWith(`p_${e}_`)||t.startsWith(`t_${e}_`)||t.startsWith(`j_${e}_`)}function ge(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e*16777619>>>0;let n=Math.floor((e/4294967296*360+e%360*.61803)%360);return n<0&&(n+=360),`hsl(${n}, 60%, 45%)`}function Yt(t){for(let e of t.values()){let n=R(e.group,"polygon")??R(e.group,"path");n&&(n.setAttribute("stroke",e.color),n.setAttribute("stroke-width","2.2"))}}function ee(t,e){let n=t.group,r=n.classList.contains("cluster-collapsed"),a=n.ownerSVGElement;if(a)if(e&&!r){n.classList.add("cluster-collapsed");let s=[];if(a.querySelectorAll(`g.node[data-instance="${Er(t.prefix)}"]`).forEach(i=>{i.classList.add("petri-collapsed-inside"),s.push(i)}),a.querySelectorAll("g.edge").forEach(i=>{let c=R(i,"title");if(!c)return;let m=(c.textContent??"").trim(),l=m.indexOf("->");if(l<0)return;let f=m.slice(0,l),v=m.slice(l+2);me(f,t.prefix)&&me(v,t.prefix)&&(i.classList.add("petri-collapsed-inside"),s.push(i))}),n._petriHiddenSiblings=s,!n._petriCollapsedBadge){let i=R(n,"text");if(i){let c=document.createElementNS("http://www.w3.org/2000/svg","text");c.setAttribute("x",i.getAttribute("x")??"0");let m=parseFloat(i.getAttribute("y")??"0");c.setAttribute("y",String(m+16)),c.setAttribute("text-anchor",i.getAttribute("text-anchor")??"middle"),c.setAttribute("font-size","11"),c.setAttribute("fill","#9ca3af"),c.setAttribute("class","cluster-collapsed-badge"),c.textContent=`(${t.nodeCount} internal node${t.nodeCount===1?"":"s"})`,n.appendChild(c),n._petriCollapsedBadge=c}}}else!e&&r&&(n.classList.remove("cluster-collapsed"),n._petriHiddenSiblings&&(n._petriHiddenSiblings.forEach(s=>s.classList.remove("petri-collapsed-inside")),n._petriHiddenSiblings=void 0),n._petriCollapsedBadge&&n._petriCollapsedBadge.parentNode===n&&(n.removeChild(n._petriCollapsedBadge),n._petriCollapsedBadge=null))}function Ut(t,e){if(e==null){t.removeAttribute("data-active-filter"),t.classList.remove("has-active-filter"),t.querySelectorAll("g.node, g.edge").forEach(n=>n.classList.remove("petri-dimmed"));return}t.setAttribute("data-active-filter",e),t.classList.add("has-active-filter"),t.querySelectorAll("g.node").forEach(n=>{let r=n.getAttribute("data-instance");!!r&&(r===e||r.indexOf(e+"_")===0||r.indexOf(e+"/")===0)?n.classList.remove("petri-dimmed"):n.classList.add("petri-dimmed")}),t.querySelectorAll("g.edge").forEach(n=>{let r=R(n,"title");if(!r)return;let a=r.textContent??"",s=a.indexOf("->");if(s<0){n.classList.remove("petri-dimmed");return}let i=a.slice(0,s),c=a.slice(s+2),m=l=>l.indexOf(e+"/")>=0||l.indexOf(e+"_")>=0||l===e;m(i)||m(c)?n.classList.remove("petri-dimmed"):n.classList.add("petri-dimmed")})}function Kt(t,e,n,r){if(n.size===0||!t)return!1;for(let a of n)if(e.has(a)&&me(r,a))return!0;return!1}function Er(t){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/[^a-zA-Z0-9_-]/g,e=>`\\${e}`)}function R(t,e){let n=e.toLowerCase();for(let r of Array.from(t.children))if(r.tagName.toLowerCase()===n)return r;return null}function _e(t){for(let e of Array.from(t.children))if(e.tagName==="title")return e.textContent??"";return""}function Ar(t){let e=t.parentElement?.closest("g.cluster");return e?_e(e).replace(/^cluster_/,""):""}function ve(t){let e=Array.from(t.querySelectorAll("g.node"));for(let r of e){let a=_e(r);if(!a)continue;r.setAttribute("data-id",a);let s=/__rep__([A-Za-z0-9_]+)$/.exec(a);if(s)r.setAttribute("data-instance",s[1]);else if(!r.hasAttribute("data-instance")){let i=Ar(r);i&&r.setAttribute("data-instance",i)}}let n=new Map;for(let r of e){let a=r.getAttribute("data-id");a&&n.set(a,r)}for(let r of Array.from(t.querySelectorAll("g.edge"))){let a=_e(r),s=a.indexOf("->");if(s<=0)continue;let i=a.slice(0,s).trim(),c=a.slice(s+2).trim();r.setAttribute("data-src",i),r.setAttribute("data-dst",c);let m=n.get(i)?.getAttribute("data-instance")??"",l=n.get(c)?.getAttribute("data-instance")??"";r.setAttribute("data-src-cluster",m),r.setAttribute("data-dst-cluster",l),r.classList.remove("intra-cluster","cross-cluster"),m!==""&&m===l?(r.classList.add("intra-cluster"),r.setAttribute("data-cluster",m)):(r.classList.add("cross-cluster"),r.removeAttribute("data-cluster"))}}var Vr="libpetri-sidebar",Lr="libpetri-sidebar-chip",Tr="is-off";function Jt(t,e,n){let r=new Set;for(let _ of e.keys())r.add(_);let a=!0,s=!0,i=()=>{n.onVisibilityChange({visibleClusters:new Set(r),includeSharedPlaces:a})},c=document.createElement("aside");c.className=Vr;let m=document.createElement("h4");m.className="libpetri-sidebar-title",m.textContent=`Subnets (${e.size})`,c.appendChild(m);let l=document.createElement("div");l.className="libpetri-sidebar-actions";let f=document.createElement("button");f.type="button",f.textContent="show all";let v=document.createElement("button");v.type="button",v.textContent="hide all",l.appendChild(f),l.appendChild(v),c.appendChild(l);let b=document.createElement("label");b.className="libpetri-sidebar-checkbox";let g=document.createElement("input");g.type="checkbox",g.checked=a,b.appendChild(g),b.appendChild(document.createTextNode(" Shared places")),g.addEventListener("change",()=>{a=g.checked,i()}),c.appendChild(b);let S=document.createElement("label");S.className="libpetri-sidebar-checkbox";let x=document.createElement("input");x.type="checkbox",x.checked=s,S.appendChild(x),S.appendChild(document.createTextNode(" Click node \u2192 highlight")),x.addEventListener("change",()=>{s=x.checked,n.onHighlightModeChange(s)}),c.appendChild(S);let w=document.createElement("div");w.className="libpetri-sidebar-hint",w.innerHTML="Click chip: toggle.<br>Shift-click: isolate.<br>Cmd/Ctrl-click: multi-select.<br>Click empty: clear highlight.",c.appendChild(w);let E=document.createElement("ul");E.className="libpetri-sidebar-chips";let N=new Map;for(let _ of e.values()){let A=document.createElement("li");A.className=Lr,A.style.borderLeftColor=_.color,A.dataset.prefix=_.prefix;let h=document.createElement("span");h.className="libpetri-sidebar-chip-dot",h.style.background=_.color;let y=document.createElement("span");y.className="libpetri-sidebar-chip-name",y.textContent=_.prefix;let L=document.createElement("span");L.className="libpetri-sidebar-chip-count",L.textContent=String(_.nodeCount),A.appendChild(h),A.appendChild(y),A.appendChild(L),A.addEventListener("click",V=>{let T=_.prefix;if(V.shiftKey){let B=[...e.keys()].every(M=>M===T?r.has(M):!r.has(M));if(r.clear(),B)for(let M of e.keys())r.add(M);else r.add(T)}else V.ctrlKey||V.metaKey?[...e.keys()].some(M=>!r.has(M))?r.has(T)?r.delete(T):r.add(T):(r.clear(),r.add(T)):r.has(T)?r.delete(T):r.add(T);F(),i()}),E.appendChild(A),N.set(_.prefix,A)}c.appendChild(E);function F(){for(let[_,A]of N)A.classList.toggle(Tr,!r.has(_))}return f.addEventListener("click",()=>{r.clear();for(let _ of e.keys())r.add(_);a=!0,g.checked=!0,F(),i()}),v.addEventListener("click",()=>{r.clear(),a=!1,g.checked=!1,F(),i()}),t.appendChild(c),i(),{root:c,dispose(){c.parentNode===t&&t.removeChild(c)}}}var Gr=["is-highlight","is-neighbor","is-faded"];function kr(t){for(let e of Gr)for(let n of Array.from(t.querySelectorAll("."+e)))n.classList.remove(e)}function Mr(t,e){let n=t.querySelector(`g.node[data-id="${be(e)}"]`);if(!n)return new Set([e]);let r=new Set([e]),a=n.getAttribute("data-replica-of")??(e.startsWith("p_")?e.slice(2):null);if(a){let s=t.querySelector(`g.node[data-id="${be("p_"+a)}"]`);if(s){let i=s.getAttribute("data-id");i&&r.add(i)}for(let i of Array.from(t.querySelectorAll(`g.node[data-replica-of="${be(a)}"]`))){let c=i.getAttribute("data-id");c&&r.add(c)}}return r}function Qt(t,e){if(kr(t),e===null)return;let n=Mr(t,e);for(let l of n){let f=t.querySelector(`g.node[data-id="${be(l)}"]`);f&&!f.classList.contains("is-hidden")&&f.classList.add("is-highlight")}let r=new Set,a=new Set,s=[],i=Array.from(n),c=new Set(n),m=Array.from(t.querySelectorAll("g.edge"));for(;i.length>0;){let l=i.shift();for(let f of m){if(f.classList.contains("is-hidden"))continue;let v=f.getAttribute("data-src"),b=f.getAttribute("data-dst");if(v!==l&&b!==l)continue;let g=v===l?b:v;g&&(s.push(f),!c.has(g)&&(c.add(g),g.startsWith("j_")?(a.add(g),i.push(g)):r.add(g)))}}for(let l of s)l.classList.add("is-highlight");for(let l of m)l.classList.contains("is-hidden")||l.classList.contains("is-highlight")||l.classList.add("is-faded");for(let l of Array.from(t.querySelectorAll("g.node"))){if(l.classList.contains("is-hidden"))continue;let f=l.getAttribute("data-id")??"";if(!n.has(f))if(r.has(f))l.classList.add("is-neighbor");else{if(a.has(f))continue;l.classList.add("is-faded")}}for(let l of Array.from(t.querySelectorAll("g.cluster:not(.cluster-orchestrator)")))l.classList.contains("is-hidden")||l.classList.add("is-faded")}function be(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Xt=/^(p_[A-Za-z0-9_]+)__rep__/;function en(t){return t.replace(/^p_/,"")}function nn(t){let e=new Set,n=Array.from(t.querySelectorAll("g.node"));for(let r of n){let a=r.querySelector("title")?.textContent??"",s=Xt.exec(a);s&&e.add(s[1])}for(let r of n){let a=r.querySelector("title")?.textContent??"",s=Xt.exec(a),i=null;s?i=en(s[1]):e.has(a)&&(i=en(a)),i!==null&&(r.classList.add("petri-replica"),r.setAttribute("data-replica-of",i),Or(r))}}var _r="http://www.w3.org/2000/svg",tn="libpetri-replica-glyph";function Or(t){if(t.querySelector(`text.${tn}`))return;let e=t.querySelector("ellipse, circle");if(!e)return;let n=0,r=0,a=0,s=0;e.tagName==="ellipse"?(n=parseFloat(e.getAttribute("cx")??"0"),r=parseFloat(e.getAttribute("cy")??"0"),a=parseFloat(e.getAttribute("rx")??"0"),s=parseFloat(e.getAttribute("ry")??"0")):(n=parseFloat(e.getAttribute("cx")??"0"),r=parseFloat(e.getAttribute("cy")??"0"),a=parseFloat(e.getAttribute("r")??"0"),s=a);let i=document.createElementNS(_r,"text");i.setAttribute("class",tn),i.setAttribute("x",(n+a+2).toFixed(2)),i.setAttribute("y",(r-s+2).toFixed(2)),i.setAttribute("text-anchor","start"),i.setAttribute("font-size","9"),i.textContent="\u21C4",t.appendChild(i)}function Nr(t,e){if(e.size===0)return new Set;let n=Array.from(t.querySelectorAll("g.node:not([data-instance])")),r=new Set;for(let v of n){let b=v.getAttribute("data-id");b&&r.add(b)}let a=new Map,s=new Map,i=(v,b,g)=>{let S=v.get(b);S||(S=new Set,v.set(b,S)),S.add(g)};for(let v of Array.from(t.querySelectorAll("g.edge"))){let b=v.getAttribute("data-src")??"",g=v.getAttribute("data-dst")??"";r.has(b)&&r.has(g)&&(i(a,b,g),i(s,g,b))}let c=new Set,m=new Set;for(let v of Array.from(t.querySelectorAll("g.edge.cross-cluster"))){let b=v.getAttribute("data-src")??"",g=v.getAttribute("data-dst")??"",S=v.getAttribute("data-src-cluster")??"",x=v.getAttribute("data-dst-cluster")??"";r.has(b)&&e.has(x)&&c.add(b),r.has(g)&&e.has(S)&&m.add(g)}let l=new Set,f=(v,b)=>{let g=[];for(let S of v)l.add(S),g.push(S);for(;g.length;){let S=g.shift(),x=b.get(S);if(x)for(let w of x)l.has(w)||(l.add(w),g.push(w))}};return f(c,s),f(m,a),l}function rn(t,e){ve(t);let{visibleClusters:n,includeSharedPlaces:r}=e;for(let i of Array.from(t.querySelectorAll("g.cluster:not(.cluster-orchestrator)"))){let m=(i.querySelector(":scope > title")?.textContent??"").replace(/^cluster_/,"");i.classList.toggle("is-hidden",!n.has(m))}for(let i of Array.from(t.querySelectorAll("g.node[data-instance]"))){let c=i.getAttribute("data-instance")??"";i.classList.toggle("is-hidden",!n.has(c))}let a=Nr(t,n);for(let i of Array.from(t.querySelectorAll("g.node:not([data-instance])"))){let c=i.getAttribute("data-id")??"";i.classList.toggle("is-hidden",!a.has(c))}if(!r)for(let i of Array.from(t.querySelectorAll("g.node.petri-replica")))i.classList.add("is-hidden");let s=new Map;for(let i of Array.from(t.querySelectorAll("g.node"))){let c=i.getAttribute("data-id");c&&s.set(c,i)}for(let i of Array.from(t.querySelectorAll("g.edge"))){let c=i.getAttribute("data-src")??"",m=i.getAttribute("data-dst")??"",l=s.get(c)?.classList.contains("is-hidden")??!1,f=s.get(m)?.classList.contains("is-hidden")??!1;i.classList.toggle("is-hidden",l||f)}}var Oe=["--lpv-bg","--lpv-header-bg","--lpv-border","--lpv-text","--lpv-muted","--lpv-cluster-bg","--lpv-cluster-bg-collapsed","--lpv-cluster-stroke-width","--lpv-cluster-stroke-dash","--lpv-cluster-fill-tint","--lpv-dim-opacity","--lpv-active-filter-outline","--lpv-legend-bg","--lpv-chip-bg","--lpv-chip-active-bg","--lpv-sidebar-bg","--lpv-sidebar-border","--lpv-sidebar-text","--lpv-sidebar-muted","--lpv-sidebar-chip-bg","--lpv-sidebar-chip-hover-bg","--lpv-sidebar-chip-off-opacity","--lpv-shared-glyph-color","--lpv-replica-fill","--lpv-replica-stroke","--lpv-highlight-stroke","--lpv-highlight-glow","--lpv-neighbor-stroke","--lpv-faded-node-opacity","--lpv-faded-edge-opacity","--lpv-faded-cluster-opacity"];var Fr=/^\s*subgraph\s+cluster_[A-Za-z0-9_]+\s*\{\s*$/,zr=/^\s*\}\s*$/;function an(t){let e=t.split(`
|
|
4
|
-
`),n=[],r=0;for(let a of e){if(Fr.test(a)){r++;continue}if(r>0){if(zr.test(a)){r--;continue}(a.includes("[")||a.includes("->"))&&n.push(on(a));continue}if(a.includes("->")&&(a.includes("ltail=")||a.includes("lhead="))){n.push(on(a));continue}n.push(a)}return n.join(`
|
|
5
|
-
`)}function on(t){return t.replace(/,\s*ltail="cluster_[^"]*"/g,"").replace(/,\s*lhead="cluster_[^"]*"/g,"").replace(/\[\s*ltail="cluster_[^"]*"\s*,\s*/g,"[").replace(/\[\s*lhead="cluster_[^"]*"\s*,\s*/g,"[").replace(/\[\s*ltail="cluster_[^"]*"\s*\]/g,"[]").replace(/\[\s*lhead="cluster_[^"]*"\s*\]/g,"[]")}async function Ne(t,e,n={}){let r=n.previousHandle??null,a=r?new Set(r.collapsedPrefixes):new Set,s=r?.activeFilter??null,i=n.subnets??r?.subnets??"show";r&&r.dispose();let c,m=e.querySelector(":scope > svg");if(t==null){if(!(m instanceof SVGSVGElement))throw new Error("mount: no DOT source and no pre-rendered SVG");c=m}else{let h=await Promise.resolve().then(()=>(ln(),sn)),y=(n.layout??"elk")==="elk",L=i==="hide"?an(t):t;c=y?await h.renderDotToSvgWithElkLayout(L):await h.renderDotToSvg(L),e.innerHTML="",e.appendChild(c)}e.classList.add("libpetri-viewer");let l=$t(c,n.panzoom),f=he(c);Yt(f);let v=n.layout??"elk";v==="elk"&&(nn(c),ve(c));let b=new Set,g=null,S=null,x=!1,w=null,E=null,N=!0;function F(){if(!n.chrome||w&&w.parentNode===e)return;w=document.createElement("div"),w.className="libpetri-viewer-chrome",w.style.position="absolute",w.style.inset="0",w.style.pointerEvents="none";let h=document.createElement("div");h.className="diagram-controls",h.style.pointerEvents="auto";let y=document.createElement("button");y.type="button",y.className="diagram-btn btn-reset",y.title="Reset view",y.textContent="Reset",y.addEventListener("click",()=>A.fit());let L=document.createElement("button");L.type="button",L.className="diagram-btn btn-fullscreen",L.title="Toggle fullscreen",L.textContent="Fullscreen",L.addEventListener("click",()=>_(e,L));let V=document.createElement("button");V.type="button",V.className="diagram-btn btn-subnets",V.title=i==="show"?"Hide subnet groupings":"Show subnet groupings",V.textContent=i==="show"?"Flat view":"Subnets view",t==null&&(V.disabled=!0,V.title="Subnet toggle unavailable for pre-rendered SVG"),V.addEventListener("click",()=>{A.toggleSubnets()}),h.appendChild(V),h.appendChild(y),h.appendChild(L),w.appendChild(h),getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(w),v==="elk"&&i==="show"&&f.size>0&&(E=Jt(e,f,{onVisibilityChange:T=>A.setVisibility(T),onHighlightModeChange:T=>{N=T,T||A.highlight(null)}}))}function _(h,y){let L=h.classList.toggle("diagram-fullscreen");y.textContent=L?"Exit fullscreen":"Fullscreen",requestAnimationFrame(()=>A.fit())}let A={svg:c,panzoom:l,clusters:f,get collapsedPrefixes(){return b},get activeFilter(){return g},get subnets(){return i},setSubnets(h){return t==null||h===i?Promise.resolve(A):Ne(t,e,{...n,previousHandle:A,subnets:h}).then(y=>(e.dispatchEvent(new CustomEvent("libpetri-viewer:remount",{bubbles:!0,detail:{handle:y,subnets:h}})),y))},toggleSubnets(){return A.setSubnets(i==="show"?"hide":"show")},collapse(h){if(x)return;let y=f.get(h);y&&(b.has(h)||(ee(y,!0),b.add(h),n.onClusterCollapse?.(h,!0)))},expand(h){if(x)return;let y=f.get(h);y&&b.has(h)&&(ee(y,!1),b.delete(h),n.onClusterCollapse?.(h,!1))},collapseAll(){if(!x)for(let h of f.values())b.has(h.prefix)||(ee(h,!0),b.add(h.prefix),n.onClusterCollapse?.(h.prefix,!0))},expandAll(){if(!x)for(let h of Array.from(b)){let y=f.get(h);y&&(ee(y,!1),b.delete(h),n.onClusterCollapse?.(h,!1))}},filter(h){x||(g=h,Ut(c,h),n.onClusterFilter?.(h))},resetZoom(){if(!x)try{l.moveTo(0,0),l.zoomAbs(0,0,1)}catch{}},fit(){if(!x)try{l.zoomAbs(0,0,1),l.moveTo(0,0)}catch{}},isInsideCollapsedCluster(h){return Kt(c,f,b,h)},get highlightedNodeId(){return S},highlight(h){x||v==="elk"&&(S=h,Qt(c,h))},setVisibility(h){x||v==="elk"&&rn(c,h)},dispose(){if(!x){x=!0;try{l.dispose()}catch{}E?.dispose(),E=null,w&&w.parentNode===e&&e.removeChild(w),w=null}}};for(let h of a)A.collapse(h);return s!==null&&A.filter(s),v==="elk"&&c.addEventListener("click",h=>{if(!N)return;let y=h.target;if(!(y instanceof Element))return;let L=y.closest("g.node");if(!L){A.highlight(null);return}let V=L.getAttribute("data-id");V&&A.highlight(V===S?null:V)}),F(),requestAnimationFrame(()=>A.fit()),A}globalThis.LibpetriViewer=Fe;})();
|