@stacksjs/components 0.2.854 → 0.2.857

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.
Files changed (139) hide show
  1. package/dist/CodeEditor-jg4w7e15.stx +497 -0
  2. package/dist/ContextMenu-43g3w5tp.stx +188 -0
  3. package/dist/DataGrid-7rt7v865.stx +376 -0
  4. package/dist/GraphView-0t3t9mec.stx +320 -0
  5. package/dist/JsonTree-satc4010.stx +317 -0
  6. package/dist/PreviewFrame-erbgvzj8.stx +257 -0
  7. package/dist/SplitPane-7sqfdwqa.stx +159 -0
  8. package/dist/code-editor/editor.js +2166 -0
  9. package/dist/component-api/component-api.js +36 -0
  10. package/dist/components/CodeBlock.d.ts +12 -5
  11. package/dist/context-menu/context-menu.js +575 -0
  12. package/dist/data-grid/data-grid.js +1244 -0
  13. package/dist/graph-view/graph-view.js +1408 -0
  14. package/dist/index.d.ts +10 -0
  15. package/dist/index.js +34 -15
  16. package/dist/json-tree/json-tree.js +1121 -0
  17. package/dist/preview-frame/preview-frame.js +356 -0
  18. package/dist/split-pane/split-pane.js +364 -0
  19. package/dist/ui/code-editor/CodeEditor.d.ts +46 -0
  20. package/dist/ui/code-editor/controller.d.ts +103 -0
  21. package/dist/ui/code-editor/core/commands.d.ts +55 -0
  22. package/dist/ui/code-editor/core/completion.d.ts +40 -0
  23. package/dist/ui/code-editor/core/editor.d.ts +69 -0
  24. package/dist/ui/code-editor/core/highlight.d.ts +61 -0
  25. package/dist/ui/code-editor/core/history.d.ts +27 -0
  26. package/dist/ui/code-editor/core/index.d.ts +13 -0
  27. package/dist/ui/code-editor/core/keymap.d.ts +38 -0
  28. package/dist/ui/code-editor/core/selection.d.ts +30 -0
  29. package/dist/ui/code-editor/core/text.d.ts +64 -0
  30. package/dist/ui/code-editor/editor.d.ts +15 -0
  31. package/dist/ui/code-editor/index.d.ts +29 -0
  32. package/dist/ui/code-editor/tokenizer.d.ts +18 -0
  33. package/dist/ui/code-editor/view.d.ts +59 -0
  34. package/dist/ui/context-menu/ContextMenu.d.ts +14 -0
  35. package/dist/ui/context-menu/context-menu.d.ts +8 -0
  36. package/dist/ui/context-menu/core.d.ts +74 -0
  37. package/dist/ui/context-menu/index.d.ts +11 -0
  38. package/dist/ui/context-menu/view.d.ts +36 -0
  39. package/dist/ui/data-grid/DataGrid.d.ts +30 -0
  40. package/dist/ui/data-grid/core.d.ts +141 -0
  41. package/dist/ui/data-grid/data-grid.d.ts +9 -0
  42. package/dist/ui/data-grid/index.d.ts +20 -0
  43. package/dist/ui/data-grid/view.d.ts +56 -0
  44. package/dist/ui/graph-view/GraphView.d.ts +21 -0
  45. package/dist/ui/graph-view/core/edges.d.ts +34 -0
  46. package/dist/ui/graph-view/core/force.d.ts +10 -0
  47. package/dist/ui/graph-view/core/graph.d.ts +83 -0
  48. package/dist/ui/graph-view/core/index.d.ts +5 -0
  49. package/dist/ui/graph-view/core/layered.d.ts +24 -0
  50. package/dist/ui/graph-view/core/viewport.d.ts +34 -0
  51. package/dist/ui/graph-view/graph-view.d.ts +9 -0
  52. package/dist/ui/graph-view/index.d.ts +21 -0
  53. package/dist/ui/graph-view/view.d.ts +51 -0
  54. package/dist/ui/json-tree/JsonTree.d.ts +18 -0
  55. package/dist/ui/json-tree/core.d.ts +108 -0
  56. package/dist/ui/json-tree/index.d.ts +18 -0
  57. package/dist/ui/json-tree/json-tree.d.ts +10 -0
  58. package/dist/ui/json-tree/tinker.d.ts +84 -0
  59. package/dist/ui/json-tree/view.d.ts +59 -0
  60. package/dist/ui/preview-frame/PreviewFrame.d.ts +44 -0
  61. package/dist/ui/preview-frame/core.d.ts +81 -0
  62. package/dist/ui/preview-frame/index.d.ts +19 -0
  63. package/dist/ui/preview-frame/preview-frame.d.ts +8 -0
  64. package/dist/ui/preview-frame/view.d.ts +37 -0
  65. package/dist/ui/split-pane/SplitPane.d.ts +18 -0
  66. package/dist/ui/split-pane/core.d.ts +58 -0
  67. package/dist/ui/split-pane/index.d.ts +15 -0
  68. package/dist/ui/split-pane/split-pane.d.ts +8 -0
  69. package/dist/ui/split-pane/view.d.ts +27 -0
  70. package/dist/ui/virtual-table/index.d.ts +6 -0
  71. package/dist/utils/component-api.d.ts +4 -0
  72. package/dist/utils/highlighter.d.ts +19 -1
  73. package/dist/utils/highlighter.js +24 -7
  74. package/dist/utils/syntax-theme.d.ts +44 -0
  75. package/package.json +44 -4
  76. package/src/components/CodeBlock.stx +195 -17
  77. package/src/index.ts +10 -0
  78. package/src/ui/code-editor/CodeEditor.stx +497 -0
  79. package/src/ui/code-editor/README.md +135 -0
  80. package/src/ui/code-editor/controller.ts +517 -0
  81. package/src/ui/code-editor/core/commands.ts +381 -0
  82. package/src/ui/code-editor/core/completion.ts +212 -0
  83. package/src/ui/code-editor/core/editor.ts +319 -0
  84. package/src/ui/code-editor/core/highlight.ts +203 -0
  85. package/src/ui/code-editor/core/history.ts +190 -0
  86. package/src/ui/code-editor/core/index.ts +14 -0
  87. package/src/ui/code-editor/core/keymap.ts +125 -0
  88. package/src/ui/code-editor/core/selection.ts +104 -0
  89. package/src/ui/code-editor/core/text.ts +252 -0
  90. package/src/ui/code-editor/editor.ts +16 -0
  91. package/src/ui/code-editor/index.ts +46 -0
  92. package/src/ui/code-editor/tokenizer.ts +74 -0
  93. package/src/ui/code-editor/view.ts +1066 -0
  94. package/src/ui/context-menu/ContextMenu.stx +188 -0
  95. package/src/ui/context-menu/README.md +117 -0
  96. package/src/ui/context-menu/context-menu.ts +8 -0
  97. package/src/ui/context-menu/core.ts +250 -0
  98. package/src/ui/context-menu/index.ts +16 -0
  99. package/src/ui/context-menu/view.ts +540 -0
  100. package/src/ui/data-grid/DataGrid.stx +376 -0
  101. package/src/ui/data-grid/README.md +204 -0
  102. package/src/ui/data-grid/core.ts +813 -0
  103. package/src/ui/data-grid/data-grid.ts +9 -0
  104. package/src/ui/data-grid/index.ts +34 -0
  105. package/src/ui/data-grid/view.ts +806 -0
  106. package/src/ui/graph-view/GraphView.stx +320 -0
  107. package/src/ui/graph-view/README.md +210 -0
  108. package/src/ui/graph-view/core/edges.ts +180 -0
  109. package/src/ui/graph-view/core/force.ts +237 -0
  110. package/src/ui/graph-view/core/graph.ts +277 -0
  111. package/src/ui/graph-view/core/index.ts +5 -0
  112. package/src/ui/graph-view/core/layered.ts +256 -0
  113. package/src/ui/graph-view/core/viewport.ts +141 -0
  114. package/src/ui/graph-view/graph-view.ts +9 -0
  115. package/src/ui/graph-view/index.ts +35 -0
  116. package/src/ui/graph-view/view.ts +809 -0
  117. package/src/ui/json-tree/JsonTree.stx +317 -0
  118. package/src/ui/json-tree/README.md +193 -0
  119. package/src/ui/json-tree/core.ts +588 -0
  120. package/src/ui/json-tree/index.ts +28 -0
  121. package/src/ui/json-tree/json-tree.ts +10 -0
  122. package/src/ui/json-tree/tinker.ts +349 -0
  123. package/src/ui/json-tree/view.ts +665 -0
  124. package/src/ui/preview-frame/PreviewFrame.stx +257 -0
  125. package/src/ui/preview-frame/README.md +107 -0
  126. package/src/ui/preview-frame/core.ts +195 -0
  127. package/src/ui/preview-frame/index.ts +31 -0
  128. package/src/ui/preview-frame/preview-frame.ts +8 -0
  129. package/src/ui/preview-frame/view.ts +336 -0
  130. package/src/ui/split-pane/README.md +87 -0
  131. package/src/ui/split-pane/SplitPane.stx +159 -0
  132. package/src/ui/split-pane/core.ts +200 -0
  133. package/src/ui/split-pane/index.ts +24 -0
  134. package/src/ui/split-pane/split-pane.ts +8 -0
  135. package/src/ui/split-pane/view.ts +305 -0
  136. package/src/ui/virtual-table/index.ts +6 -0
  137. package/src/utils/component-api.ts +72 -0
  138. package/src/utils/highlighter.ts +121 -218
  139. package/src/utils/syntax-theme.ts +144 -0
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The shape of an edge between two node boxes. No DOM: the answer is a path
3
+ * string and a few points, which the view writes into an SVG.
4
+ */
5
+ import type { Point, ResolvedEdge, Size } from './graph'
6
+
7
+ export type EdgeCurve = 'straight' | 'bezier'
8
+
9
+ export interface EdgeEnds {
10
+ source: Point
11
+ sourceSize: Size
12
+ target: Point
13
+ targetSize: Size
14
+ }
15
+
16
+ export interface EdgeShapeOptions {
17
+ /** `bezier` leaves and enters through the sides facing the flow. Default `straight`. */
18
+ curve?: EdgeCurve
19
+ /** The flow of a layered layout, which decides the sides a bezier uses. */
20
+ direction?: 'LR' | 'TB'
21
+ /** Sideways shift, for one of several edges between the same two nodes. */
22
+ offset?: number
23
+ /** Stop this far short of the target, to leave room for an arrowhead. */
24
+ inset?: number
25
+ }
26
+
27
+ export interface EdgeShape {
28
+ /** An SVG path. */
29
+ d: string
30
+ start: Point
31
+ end: Point
32
+ /** Where a label goes: the middle of the path. */
33
+ label: Point
34
+ /** The direction the edge arrives from, in radians. An arrowhead points this way. */
35
+ angle: number
36
+ }
37
+
38
+ const round = (value: number): number => Math.round(value * 100) / 100
39
+ const at = (point: Point): string => `${round(point.x)} ${round(point.y)}`
40
+
41
+ /**
42
+ * Where the line from a box's centre towards a point leaves the box.
43
+ * The centre itself when the point is the centre.
44
+ */
45
+ export function clipToRect(centre: Point, size: Size, towards: Point): Point {
46
+ const dx = towards.x - centre.x
47
+ const dy = towards.y - centre.y
48
+ if (dx === 0 && dy === 0)
49
+ return { x: centre.x, y: centre.y }
50
+ const scaleX = dx === 0 ? Number.POSITIVE_INFINITY : (size.width / 2) / Math.abs(dx)
51
+ const scaleY = dy === 0 ? Number.POSITIVE_INFINITY : (size.height / 2) / Math.abs(dy)
52
+ const scale = Math.min(scaleX, scaleY)
53
+ return { x: centre.x + dx * scale, y: centre.y + dy * scale }
54
+ }
55
+
56
+ function pullBack(end: Point, from: Point, inset: number): Point {
57
+ const dx = end.x - from.x
58
+ const dy = end.y - from.y
59
+ const length = Math.sqrt(dx * dx + dy * dy)
60
+ if (inset <= 0 || length <= inset)
61
+ return end
62
+ return { x: end.x - (dx / length) * inset, y: end.y - (dy / length) * inset }
63
+ }
64
+
65
+ /** An edge from a node to itself: a loop off its top right corner. */
66
+ export function selfLoopShape(centre: Point, size: Size, offset = 0): EdgeShape {
67
+ const reach = 26 + Math.abs(offset)
68
+ const start = { x: centre.x + size.width / 4, y: centre.y - size.height / 2 }
69
+ const end = { x: centre.x + size.width / 2, y: centre.y - size.height / 4 }
70
+ const one = { x: start.x, y: start.y - reach }
71
+ const two = { x: end.x + reach, y: end.y }
72
+ return {
73
+ d: `M ${at(start)} C ${at(one)}, ${at(two)}, ${at(end)}`,
74
+ start,
75
+ end,
76
+ label: cubicAt(start, one, two, end, 0.5),
77
+ angle: Math.atan2(end.y - two.y, end.x - two.x),
78
+ }
79
+ }
80
+
81
+ function cubicAt(a: Point, b: Point, c: Point, d: Point, t: number): Point {
82
+ const u = 1 - t
83
+ return {
84
+ x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,
85
+ y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y,
86
+ }
87
+ }
88
+
89
+ export function edgeShape(ends: EdgeEnds, options: EdgeShapeOptions = {}): EdgeShape {
90
+ const { source, sourceSize, target, targetSize } = ends
91
+ const offset = options.offset ?? 0
92
+ const inset = options.inset ?? 0
93
+
94
+ if (source.x === target.x && source.y === target.y)
95
+ return selfLoopShape(source, sourceSize, offset)
96
+
97
+ if (options.curve === 'bezier') {
98
+ // Out of the side that faces the target along the flow, into the side that
99
+ // faces back, with the handles pulled along the flow so the curve leaves
100
+ // and arrives square to the boxes.
101
+ const horizontal = options.direction !== 'TB'
102
+ const sign = (horizontal ? target.x - source.x : target.y - source.y) >= 0 ? 1 : -1
103
+ const start = horizontal
104
+ ? { x: source.x + sign * sourceSize.width / 2, y: source.y }
105
+ : { x: source.x, y: source.y + sign * sourceSize.height / 2 }
106
+ const tip = horizontal
107
+ ? { x: target.x - sign * targetSize.width / 2, y: target.y }
108
+ : { x: target.x, y: target.y - sign * targetSize.height / 2 }
109
+ const span = Math.abs(horizontal ? tip.x - start.x : tip.y - start.y)
110
+ const handle = Math.max(span / 2, 24) * sign
111
+ const end = horizontal ? { x: tip.x - sign * inset, y: tip.y } : { x: tip.x, y: tip.y - sign * inset }
112
+ const one = horizontal ? { x: start.x + handle, y: start.y + offset } : { x: start.x + offset, y: start.y + handle }
113
+ const two = horizontal ? { x: end.x - handle, y: end.y + offset } : { x: end.x + offset, y: end.y - handle }
114
+ return {
115
+ d: `M ${at(start)} C ${at(one)}, ${at(two)}, ${at(end)}`,
116
+ start,
117
+ end,
118
+ label: cubicAt(start, one, two, end, 0.5),
119
+ angle: Math.atan2(end.y - two.y, end.x - two.x),
120
+ }
121
+ }
122
+
123
+ const start = clipToRect(source, sourceSize, target)
124
+ const tip = clipToRect(target, targetSize, source)
125
+ if (offset === 0) {
126
+ const end = pullBack(tip, start, inset)
127
+ return {
128
+ d: `M ${at(start)} L ${at(end)}`,
129
+ start,
130
+ end,
131
+ label: { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 },
132
+ angle: Math.atan2(end.y - start.y, end.x - start.x),
133
+ }
134
+ }
135
+
136
+ // One of several between the same pair: bowed to one side. The normal is
137
+ // taken from the pair in a fixed order, so A to B and B to A bow apart
138
+ // instead of onto each other.
139
+ const flip = source.x < target.x || (source.x === target.x && source.y < target.y) ? 1 : -1
140
+ const dx = (target.x - source.x) * flip
141
+ const dy = (target.y - source.y) * flip
142
+ const length = Math.sqrt(dx * dx + dy * dy) || 1
143
+ const control = { x: (start.x + tip.x) / 2 + (-dy / length) * offset * 2, y: (start.y + tip.y) / 2 + (dx / length) * offset * 2 }
144
+ const end = pullBack(tip, control, inset)
145
+ return {
146
+ d: `M ${at(start)} Q ${at(control)}, ${at(end)}`,
147
+ start,
148
+ end,
149
+ label: { x: 0.25 * start.x + 0.5 * control.x + 0.25 * end.x, y: 0.25 * start.y + 0.5 * control.y + 0.25 * end.y },
150
+ angle: Math.atan2(end.y - control.y, end.x - control.x),
151
+ }
152
+ }
153
+
154
+ /**
155
+ * A sideways shift for each edge that shares its two ends with another, so
156
+ * they are drawn beside each other. An edge alone between its nodes gets none.
157
+ */
158
+ export function parallelOffsets(edges: readonly ResolvedEdge[], spacing = 14): Map<string, number> {
159
+ const groups = new Map<string, ResolvedEdge[]>()
160
+ for (const edge of edges) {
161
+ const key = edge.source < edge.target ? `${edge.source}\u0000${edge.target}` : `${edge.target}\u0000${edge.source}`
162
+ const group = groups.get(key)
163
+ if (group)
164
+ group.push(edge)
165
+ else
166
+ groups.set(key, [edge])
167
+ }
168
+
169
+ const offsets = new Map<string, number>()
170
+ for (const group of groups.values()) {
171
+ if (group.length < 2)
172
+ continue
173
+ group.forEach((edge, position) => {
174
+ const shift = (position - (group.length - 1) / 2) * spacing
175
+ // A self-loop grows outwards instead of sideways.
176
+ offsets.set(edge.id, edge.source === edge.target ? position * spacing : shift)
177
+ })
178
+ }
179
+ return offsets
180
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * A force layout: nodes push each other apart, edges pull their ends together.
3
+ *
4
+ * Fruchterman and Reingold's scheme with a cooling temperature, written over
5
+ * flat arrays. Every pair of nodes is compared on every pass; at a few hundred
6
+ * nodes that is tens of milliseconds, so there is no spatial index to keep
7
+ * correct.
8
+ *
9
+ * It is deterministic: the only randomness is where a node with no position
10
+ * starts, and that comes from a seeded source. Given positions, it starts
11
+ * warm: nodes that already have a place keep it while the new ones find
12
+ * theirs among them, and are then moved only as far as it takes to stop two
13
+ * boxes overlapping. Adding ten nodes to a settled graph nudges the rest
14
+ * instead of throwing everything in the air.
15
+ */
16
+ import type { GraphModel, Positions } from './graph'
17
+ import { seededRandom } from './graph'
18
+
19
+ export interface ForceOptions {
20
+ /** Passes over the graph. Default 300 from cold, 80 from warm. */
21
+ iterations?: number
22
+ /** Seeds the starting positions. Default 1. */
23
+ seed?: number
24
+ /** Where nodes already are. Nodes found here start there. */
25
+ positions?: Positions | null
26
+ /** Nodes that must stay where `positions` puts them. */
27
+ pinned?: Iterable<string> | null
28
+ /** The scale of the layout. A typical edge settles at about twice this. Default 90. */
29
+ linkDistance?: number
30
+ /** Clear space kept between two nodes. Default 16. */
31
+ padding?: number
32
+ }
33
+
34
+ /**
35
+ * Every node pushes every other, so in a graph of any size the pushes add up
36
+ * and stretch the edges far past their natural length. Scaled down to this,
37
+ * two hundred nodes settle with edges around twice `linkDistance`.
38
+ */
39
+ const REPULSION = 0.15
40
+ /** A weak pull to the middle, so unconnected parts do not drift away. */
41
+ const GRAVITY = 0.06
42
+
43
+ export function forceLayout(graph: GraphModel, options: ForceOptions = {}): Positions {
44
+ const nodes = graph.nodes
45
+ const count = nodes.length
46
+ const result: Positions = new Map()
47
+ if (count === 0)
48
+ return result
49
+
50
+ const distance = options.linkDistance ?? 90
51
+ const padding = options.padding ?? 16
52
+ const random = seededRandom(options.seed ?? 1)
53
+ const given = options.positions ?? null
54
+ const pinned = new Set(options.pinned ?? [])
55
+ const index = new Map(nodes.map((node, position) => [node.id, position]))
56
+
57
+ const x = new Float64Array(count)
58
+ const y = new Float64Array(count)
59
+ const halfWidth = new Float64Array(count)
60
+ const halfHeight = new Float64Array(count)
61
+ const fixed = new Uint8Array(count)
62
+ const placed = new Uint8Array(count)
63
+ /** How much of a step a node takes: all of it when new, none when it already had a place. */
64
+ const mobility = new Float64Array(count).fill(1)
65
+ let known = 0
66
+
67
+ nodes.forEach((node, position) => {
68
+ const size = graph.size(node.id)
69
+ halfWidth[position] = size.width / 2
70
+ halfHeight[position] = size.height / 2
71
+ const at = given?.get(node.id)
72
+ if (at && Number.isFinite(at.x) && Number.isFinite(at.y)) {
73
+ x[position] = at.x
74
+ y[position] = at.y
75
+ placed[position] = 1
76
+ fixed[position] = pinned.has(node.id) ? 1 : 0
77
+ mobility[position] = 0
78
+ known++
79
+ }
80
+ })
81
+
82
+ // A node with no position starts beside a neighbour that has one, so an
83
+ // expansion grows out of the node it came from. Failing that, on a disc
84
+ // large enough to hold the graph.
85
+ const radius = distance * Math.sqrt(count) * 0.6
86
+ nodes.forEach((node, position) => {
87
+ if (placed[position])
88
+ return
89
+ const anchor = graph.neighbours(node.id).map(id => index.get(id)!).find(other => placed[other])
90
+ const angle = random() * Math.PI * 2
91
+ if (anchor !== undefined) {
92
+ x[position] = x[anchor] + Math.cos(angle) * distance * 0.5
93
+ y[position] = y[anchor] + Math.sin(angle) * distance * 0.5
94
+ }
95
+ else {
96
+ const reach = Math.sqrt(random()) * radius
97
+ x[position] = Math.cos(angle) * reach
98
+ y[position] = Math.sin(angle) * reach
99
+ }
100
+ })
101
+ // Kept apart from `placed`, which the loop above reads: two new nodes must
102
+ // not anchor on each other's guess.
103
+ const settled = Uint8Array.from(placed)
104
+
105
+ const warm = known > 0
106
+ const iterations = Math.max(0, options.iterations ?? (warm ? 80 : 300))
107
+ const links: number[] = []
108
+ const seen = new Set<number>()
109
+ for (const edge of graph.edges) {
110
+ const a = index.get(edge.source)!
111
+ const b = index.get(edge.target)!
112
+ if (a === b)
113
+ continue
114
+ const key = a < b ? a * count + b : b * count + a
115
+ if (!seen.has(key)) {
116
+ seen.add(key)
117
+ links.push(a, b)
118
+ }
119
+ }
120
+
121
+ const dx = new Float64Array(count)
122
+ const dy = new Float64Array(count)
123
+ const k = distance
124
+ // From warm, the temperature is only what a new node needs to find its place.
125
+ const start = warm ? k * 0.5 : k * 1.5
126
+
127
+ for (let pass = 0; pass < iterations; pass++) {
128
+ const temperature = start * (1 - pass / iterations)
129
+ dx.fill(0)
130
+ dy.fill(0)
131
+
132
+ for (let a = 0; a < count; a++) {
133
+ for (let b = a + 1; b < count; b++) {
134
+ // Two nodes that both had a place stay as they are to each other;
135
+ // there is nothing to work out between them.
136
+ if (settled[a] && settled[b])
137
+ continue
138
+ let ox = x[a] - x[b]
139
+ let oy = y[a] - y[b]
140
+ let length = Math.sqrt(ox * ox + oy * oy)
141
+ if (length < 0.01) {
142
+ // Exactly on top of each other: part them in a direction that
143
+ // depends only on which two they are.
144
+ const angle = ((a * 31 + b * 17) % 360) * Math.PI / 180
145
+ ox = Math.cos(angle) * 0.01
146
+ oy = Math.sin(angle) * 0.01
147
+ length = 0.01
148
+ }
149
+ // Wide nodes keep more room: the push is measured from their edges.
150
+ const reach = Math.max(1, length - (halfWidth[a] + halfWidth[b]) * 0.5)
151
+ const push = (k * k) * REPULSION / reach / length
152
+ dx[a] += ox * push
153
+ dy[a] += oy * push
154
+ dx[b] -= ox * push
155
+ dy[b] -= oy * push
156
+ }
157
+ }
158
+
159
+ for (let link = 0; link < links.length; link += 2) {
160
+ const a = links[link]
161
+ const b = links[link + 1]
162
+ if (settled[a] && settled[b])
163
+ continue
164
+ const ox = x[a] - x[b]
165
+ const oy = y[a] - y[b]
166
+ const length = Math.sqrt(ox * ox + oy * oy) || 0.01
167
+ const rest = (halfWidth[a] + halfWidth[b]) * 0.5
168
+ const stretch = Math.max(0, length - rest)
169
+ const pull = (stretch * stretch) / k / length
170
+ dx[a] -= ox * pull
171
+ dy[a] -= oy * pull
172
+ dx[b] += ox * pull
173
+ dy[b] += oy * pull
174
+ }
175
+
176
+ for (let node = 0; node < count; node++) {
177
+ if (fixed[node])
178
+ continue
179
+ if (!settled[node]) {
180
+ dx[node] -= x[node] * GRAVITY
181
+ dy[node] -= y[node] * GRAVITY
182
+ }
183
+ const length = Math.sqrt(dx[node] * dx[node] + dy[node] * dy[node])
184
+ if (length > 0) {
185
+ const step = (Math.min(length, temperature) / length) * mobility[node]
186
+ x[node] += dx[node] * step
187
+ y[node] += dy[node] * step
188
+ }
189
+ }
190
+ }
191
+
192
+ separate(x, y, halfWidth, halfHeight, fixed, padding)
193
+
194
+ nodes.forEach((node, position) => {
195
+ result.set(node.id, { x: Math.round(x[position] * 100) / 100, y: Math.round(y[position] * 100) / 100 })
196
+ })
197
+ return result
198
+ }
199
+
200
+ /**
201
+ * Push apart any two boxes that still overlap, along whichever axis needs the
202
+ * smaller move. The forces act on centres and know little about a wide label;
203
+ * this is what guarantees two nodes are never drawn over each other.
204
+ */
205
+ function separate(x: Float64Array, y: Float64Array, halfWidth: Float64Array, halfHeight: Float64Array, fixed: Uint8Array, padding: number): void {
206
+ const count = x.length
207
+ for (let pass = 0; pass < 40; pass++) {
208
+ let moved = false
209
+ for (let a = 0; a < count; a++) {
210
+ for (let b = a + 1; b < count; b++) {
211
+ const overlapX = halfWidth[a] + halfWidth[b] + padding - Math.abs(x[a] - x[b])
212
+ if (overlapX <= 0)
213
+ continue
214
+ const overlapY = halfHeight[a] + halfHeight[b] + padding - Math.abs(y[a] - y[b])
215
+ if (overlapY <= 0)
216
+ continue
217
+ if (fixed[a] && fixed[b])
218
+ continue
219
+ moved = true
220
+ const shareA = fixed[a] ? 0 : (fixed[b] ? 1 : 0.5)
221
+ const shareB = 1 - shareA
222
+ if (overlapX < overlapY) {
223
+ const sign = x[a] < x[b] || (x[a] === x[b] && a < b) ? -1 : 1
224
+ x[a] += sign * overlapX * shareA
225
+ x[b] -= sign * overlapX * shareB
226
+ }
227
+ else {
228
+ const sign = y[a] < y[b] || (y[a] === y[b] && a < b) ? -1 : 1
229
+ y[a] += sign * overlapY * shareA
230
+ y[b] -= sign * overlapY * shareB
231
+ }
232
+ }
233
+ }
234
+ if (!moved)
235
+ break
236
+ }
237
+ }
@@ -0,0 +1,277 @@
1
+ /**
2
+ * A graph: nodes, the edges between them, and who is next to whom. No DOM.
3
+ *
4
+ * Everything the layouts and the view need to ask ("what does this node
5
+ * connect to", "how big is it") is answered here, so neither of them keeps a
6
+ * second copy of the structure that could disagree with the first.
7
+ */
8
+
9
+ export interface GraphNode {
10
+ id: string
11
+ /** What is written in the node. The id when left out. */
12
+ label?: string
13
+ /** A free word the stylesheet can colour by: `model`, `object`, `array`. */
14
+ kind?: string
15
+ /** A second, quieter line under the label. */
16
+ detail?: string
17
+ /** False for a node with nothing further to load. Anything else can be expanded. */
18
+ expandable?: boolean
19
+ /** Whatever the host wants back with the node's events. */
20
+ data?: unknown
21
+ }
22
+
23
+ export interface GraphEdge {
24
+ /** Left out, it is made from the two ends and the label. */
25
+ id?: string
26
+ source: string
27
+ target: string
28
+ label?: string
29
+ /** Draws an arrowhead at the target. Default true. */
30
+ directed?: boolean
31
+ }
32
+
33
+ /** An edge once it is in a graph: it always has an id. */
34
+ export interface ResolvedEdge extends GraphEdge {
35
+ id: string
36
+ }
37
+
38
+ export interface Point {
39
+ x: number
40
+ y: number
41
+ }
42
+
43
+ export interface Size {
44
+ width: number
45
+ height: number
46
+ }
47
+
48
+ /** A box by its top left corner. */
49
+ export interface Rect extends Point, Size {}
50
+
51
+ /** How a label becomes a size. No measuring: a character is so many pixels. */
52
+ export interface NodeMetrics {
53
+ charWidth: number
54
+ paddingX: number
55
+ minWidth: number
56
+ maxWidth: number
57
+ height: number
58
+ /** Added to the height of a node that has a detail line. */
59
+ detailHeight: number
60
+ }
61
+
62
+ export const defaultNodeMetrics: NodeMetrics = {
63
+ charWidth: 7,
64
+ paddingX: 12,
65
+ minWidth: 48,
66
+ maxWidth: 220,
67
+ height: 32,
68
+ detailHeight: 14,
69
+ }
70
+
71
+ /** Positions are node centres, by node id. */
72
+ export type Positions = Map<string, Point>
73
+
74
+ export function labelOf(node: GraphNode): string {
75
+ return node.label == null || node.label === '' ? node.id : String(node.label)
76
+ }
77
+
78
+ /** The id an edge gets when it did not bring one. */
79
+ export function edgeIdOf(edge: GraphEdge): string {
80
+ return edge.id != null && edge.id !== '' ? String(edge.id) : `${edge.source}->${edge.target}${edge.label ? `:${edge.label}` : ''}`
81
+ }
82
+
83
+ /** The size of a node, from the length of what is written in it. */
84
+ export function nodeSize(node: GraphNode, metrics: NodeMetrics = defaultNodeMetrics): Size {
85
+ const longest = Math.max(labelOf(node).length, node.detail ? node.detail.length * 0.85 : 0)
86
+ // A node that says it can be expanded carries a small mark, and needs room for it.
87
+ const mark = node.expandable === true ? metrics.charWidth + 4 : 0
88
+ const width = Math.min(metrics.maxWidth, Math.max(metrics.minWidth, Math.ceil(longest * metrics.charWidth) + metrics.paddingX * 2 + mark))
89
+ return { width, height: metrics.height + (node.detail ? metrics.detailHeight : 0) }
90
+ }
91
+
92
+ /** How many characters of a label fit in a node of the widest size. */
93
+ export function maxLabelLength(metrics: NodeMetrics = defaultNodeMetrics): number {
94
+ return Math.floor((metrics.maxWidth - metrics.paddingX * 2) / metrics.charWidth)
95
+ }
96
+
97
+ /** A label cut to fit, with an ellipsis where it was cut. */
98
+ export function fitLabel(text: string, limit: number): string {
99
+ return text.length <= limit ? text : `${text.slice(0, Math.max(1, limit - 1))}…`
100
+ }
101
+
102
+ export class GraphModel {
103
+ private readonly nodeMap = new Map<string, GraphNode>()
104
+ private readonly edgeMap = new Map<string, ResolvedEdge>()
105
+ /** Edge ids touching each node, in the order they were added. */
106
+ private readonly incident = new Map<string, Set<string>>()
107
+ private readonly sizes = new Map<string, Size>()
108
+
109
+ constructor(nodes: readonly GraphNode[] = [], edges: readonly GraphEdge[] = [], readonly metrics: NodeMetrics = defaultNodeMetrics) {
110
+ this.merge(nodes, edges)
111
+ }
112
+
113
+ get nodes(): GraphNode[] {
114
+ return [...this.nodeMap.values()]
115
+ }
116
+
117
+ get edges(): ResolvedEdge[] {
118
+ return [...this.edgeMap.values()]
119
+ }
120
+
121
+ get nodeCount(): number {
122
+ return this.nodeMap.size
123
+ }
124
+
125
+ get edgeCount(): number {
126
+ return this.edgeMap.size
127
+ }
128
+
129
+ has(id: string): boolean {
130
+ return this.nodeMap.has(id)
131
+ }
132
+
133
+ node(id: string): GraphNode | undefined {
134
+ return this.nodeMap.get(id)
135
+ }
136
+
137
+ edge(id: string): ResolvedEdge | undefined {
138
+ return this.edgeMap.get(id)
139
+ }
140
+
141
+ /** False when a node with that id is already there; the first one is kept. */
142
+ addNode(node: GraphNode): boolean {
143
+ if (!node || node.id == null || node.id === '')
144
+ return false
145
+ const id = String(node.id)
146
+ if (this.nodeMap.has(id))
147
+ return false
148
+ const kept = { ...node, id }
149
+ this.nodeMap.set(id, kept)
150
+ this.incident.set(id, new Set())
151
+ this.sizes.set(id, nodeSize(kept, this.metrics))
152
+ return true
153
+ }
154
+
155
+ /** False for a duplicate, or an edge whose ends are not both in the graph. */
156
+ addEdge(edge: GraphEdge): boolean {
157
+ if (!edge)
158
+ return false
159
+ const source = String(edge.source)
160
+ const target = String(edge.target)
161
+ if (!this.nodeMap.has(source) || !this.nodeMap.has(target))
162
+ return false
163
+ const id = edgeIdOf({ ...edge, source, target })
164
+ if (this.edgeMap.has(id))
165
+ return false
166
+ this.edgeMap.set(id, { ...edge, id, source, target })
167
+ this.incident.get(source)!.add(id)
168
+ this.incident.get(target)!.add(id)
169
+ return true
170
+ }
171
+
172
+ /** Change what a node says about itself, such as `expandable` once it has been expanded. */
173
+ updateNode(id: string, patch: Partial<Omit<GraphNode, 'id'>>): boolean {
174
+ const node = this.nodeMap.get(id)
175
+ if (!node)
176
+ return false
177
+ const next = { ...node, ...patch, id }
178
+ this.nodeMap.set(id, next)
179
+ this.sizes.set(id, nodeSize(next, this.metrics))
180
+ return true
181
+ }
182
+
183
+ /** Takes the node's edges with it. */
184
+ removeNode(id: string): boolean {
185
+ if (!this.nodeMap.has(id))
186
+ return false
187
+ for (const edgeId of [...this.incident.get(id)!])
188
+ this.removeEdge(edgeId)
189
+ this.nodeMap.delete(id)
190
+ this.incident.delete(id)
191
+ this.sizes.delete(id)
192
+ return true
193
+ }
194
+
195
+ removeEdge(id: string): boolean {
196
+ const edge = this.edgeMap.get(id)
197
+ if (!edge)
198
+ return false
199
+ this.edgeMap.delete(id)
200
+ this.incident.get(edge.source)?.delete(id)
201
+ this.incident.get(edge.target)?.delete(id)
202
+ return true
203
+ }
204
+
205
+ /**
206
+ * Add what is new and ignore what is already there. This is what expanding a
207
+ * node does: the answer usually names nodes the graph has, and they must not
208
+ * be added twice. Returns the ids that were actually added.
209
+ */
210
+ merge(nodes: readonly GraphNode[] = [], edges: readonly GraphEdge[] = []): { nodes: string[], edges: string[] } {
211
+ const added = { nodes: [] as string[], edges: [] as string[] }
212
+ for (const node of nodes) {
213
+ if (this.addNode(node))
214
+ added.nodes.push(String(node.id))
215
+ }
216
+ for (const edge of edges) {
217
+ if (this.addEdge(edge))
218
+ added.edges.push(edgeIdOf({ ...edge, source: String(edge.source), target: String(edge.target) }))
219
+ }
220
+ return added
221
+ }
222
+
223
+ /** The edges touching a node, either way round. */
224
+ edgesOf(id: string): ResolvedEdge[] {
225
+ const ids = this.incident.get(id)
226
+ return ids ? [...ids].map(edgeId => this.edgeMap.get(edgeId)!) : []
227
+ }
228
+
229
+ /** The nodes one edge away, each once, without the node itself. */
230
+ neighbours(id: string): string[] {
231
+ const seen = new Set<string>()
232
+ for (const edge of this.edgesOf(id)) {
233
+ const other = edge.source === id ? edge.target : edge.source
234
+ if (other !== id)
235
+ seen.add(other)
236
+ }
237
+ return [...seen]
238
+ }
239
+
240
+ degree(id: string): number {
241
+ return this.neighbours(id).length
242
+ }
243
+
244
+ size(id: string): Size {
245
+ return this.sizes.get(id) ?? { width: this.metrics.minWidth, height: this.metrics.height }
246
+ }
247
+
248
+ /** The box around every node at the given positions. Null for an empty graph. */
249
+ bounds(positions: Positions): Rect | null {
250
+ let left = Number.POSITIVE_INFINITY
251
+ let top = Number.POSITIVE_INFINITY
252
+ let right = Number.NEGATIVE_INFINITY
253
+ let bottom = Number.NEGATIVE_INFINITY
254
+ for (const [id, point] of positions) {
255
+ if (!this.nodeMap.has(id))
256
+ continue
257
+ const size = this.size(id)
258
+ left = Math.min(left, point.x - size.width / 2)
259
+ right = Math.max(right, point.x + size.width / 2)
260
+ top = Math.min(top, point.y - size.height / 2)
261
+ bottom = Math.max(bottom, point.y + size.height / 2)
262
+ }
263
+ return Number.isFinite(left) ? { x: left, y: top, width: right - left, height: bottom - top } : null
264
+ }
265
+ }
266
+
267
+ /** A small, fast, seeded random source. The same seed gives the same layout. */
268
+ export function seededRandom(seed: number): () => number {
269
+ let state = (seed >>> 0) || 1
270
+ return () => {
271
+ state = (state + 0x6D2B79F5) >>> 0
272
+ let t = state
273
+ t = Math.imul(t ^ (t >>> 15), t | 1)
274
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
275
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
276
+ }
277
+ }
@@ -0,0 +1,5 @@
1
+ export * from './edges'
2
+ export * from './force'
3
+ export * from './graph'
4
+ export * from './layered'
5
+ export * from './viewport'