@fusion.dev/helix-graph 0.119.0 → 0.121.0

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @fusion.dev/helix-graph
2
2
 
3
- Connects the Helix `Graph` frame to whatever draws the graph: Sigma.js, or a
3
+ Connects the Helix `Graph` frame to whatever draws the graph: Sigma.js, cosmos.gl, or a
4
4
  driver of your own, colored from your tokens.
5
5
 
6
6
  ```sh
@@ -55,28 +55,193 @@ connection.disconnect()
55
55
  changes.
56
56
  - Answers the frame's pan and zoom buttons and keys, and tells the renderer which
57
57
  gestures the frame's `gestures` lets it take.
58
+ - Draws only what changed when the page hands the frame new notes or links, and
59
+ draws the frame's `signal()`s.
60
+
61
+ ## Live graphs
62
+
63
+ **Hand the frame new arrays as often as the graph changes.** The connection
64
+ compares them with what is drawn, by each note's `id` and each link's two ends,
65
+ and the renderer is told only what was added, taken away, renamed or moved. New
66
+ notes grow in and are laid out with the rest held still, and the frame stays
67
+ `:state(ready)` throughout.
68
+
69
+ ```js
70
+ socket.addEventListener('message', ({ data }) => {
71
+ const note = JSON.parse(data)
72
+ frame.nodes = [...frame.nodes, note]
73
+ frame.links = [...frame.links, { source: note.id, target: note.parent }]
74
+ })
75
+ ```
76
+
77
+ **`frame.signal(from, to, { tone })` shows something passing between two
78
+ notes**: a message, a request, a payment. It is drawn as a pulse of light
79
+ traveling from one to the other, turning from the first note's color to the
80
+ second's, or in the tone's color where it has one, over the graph and without
81
+ redrawing it, so a busy feed costs a dot each. A reader who asks for less motion
82
+ sees the link lit for a moment instead.
83
+
84
+ ```js
85
+ frame.signal('Checkout', 'Payments', { tone: 'success' })
86
+ frame.signal('Payments', 'Fraud review', { tone: 'danger' })
87
+ ```
88
+
89
+ A signal is drawn and never said: a screen reader does not hear it. Where what
90
+ passed matters to a reader, say it in the page's own words as well.
91
+
92
+ ## How notes look
93
+
94
+ Each note can say how it is drawn, in the words Helix's other components use:
95
+
96
+ | Field | Values | What it does |
97
+ |---|---|---|
98
+ | `shape` | `circle`, `square`, `diamond`, `ring` | What kind of note it is at a glance |
99
+ | `emphasis` | `solid`, `outlined`, `subtle` | Filled, a ring with the ground showing through, or a tinted fill with a ring |
100
+ | `material` | `glass`, `frosted` | A shaded sphere with a highlight and a lit rim, or a milky body with a soft fall of light |
101
+ | `tone` | `primary`, `accent`, `info`, `success`, `warning`, `danger`, `neutral` | What it means, which colors it over its group |
102
+
103
+ ```js
104
+ frame.nodes = [
105
+ { id: 'Roadmap', group: 'Product', shape: 'square' },
106
+ { id: 'Outage 14', group: 'Support', tone: 'danger', emphasis: 'outlined' },
107
+ ]
108
+ ```
109
+
110
+ `sigmaDriver(sigma, { material, shape, emphasis })` sets what a note is drawn as
111
+ where it does not say. The selected note keeps its own color and is told apart by
112
+ a ring and a glow in that color.
113
+
114
+ **A note without a `size` is as large as it is connected**, so hubs read at a
115
+ glance. Links are tinted by the note they leave, the selected note's and the
116
+ hovered note's in their color, and choosing a note in the list frames it with
117
+ its neighbors.
118
+
119
+ **Notes are named on hover**, and the selected note and its neighbors where
120
+ there is room, each name ringed in the ground's color so it reads over the
121
+ links. Each group's name is drawn over its notes, which is how a reader finds
122
+ their way. `labels: 'hubs'` names the busiest notes at rest as well, quietly,
123
+ and `labels: 'all'` every note where its name does not cover another.
124
+
125
+ ## Large graphs
126
+
127
+ **Past fifty thousand notes, draw with cosmos.gl**, which lays the graph out
128
+ and draws it on the GPU. The frame, the list, selection and signals are the
129
+ same; only the driver changes:
130
+
131
+ ```sh
132
+ bun add @cosmos.gl/graph
133
+ ```
134
+
135
+ ```js
136
+ import { Graph } from '@cosmos.gl/graph'
137
+ import { connectGraph } from '@fusion.dev/helix-graph'
138
+ import { cosmosDriver } from '@fusion.dev/helix-graph/cosmos'
139
+
140
+ const box = document.getElementById('drawing')
141
+ const graph = new Graph(box, { attribution: '', enableSimulation: true, scalePointsOnZoom: false })
142
+ connectGraph(frame, cosmosDriver(graph, box))
143
+ ```
144
+
145
+ cosmos.gl draws notes with its own shaders, so a note's `shape` is honored and
146
+ its `material` and `emphasis` are not. Each group is given a place of its own
147
+ and its notes are drawn toward it, so twenty thousand notes in twelve groups
148
+ come apart into twelve regions. The view follows the layout as it opens out,
149
+ until the reader moves it. Zoomed out, a note is a fine point and a leaf is
150
+ drawn partly clear, so a group reads as a field of points with its hubs
151
+ standing out; notes grow as the reader zooms in.
152
+
153
+ **cosmos.gl's own start reports a `ResizeObserver loop` error**, which is
154
+ harmless and shows in the console: it observes its canvas from inside
155
+ luma.gl's resize callback. Make the GPU device yourself and hand it over a
156
+ frame after its canvas is measured, and cosmos.gl starts outside any callback:
157
+
158
+ ```js
159
+ import { luma } from '@luma.gl/core'
160
+ import { webgl2Adapter } from '@luma.gl/webgl'
161
+
162
+ const canvas = Object.assign(document.createElement('canvas'), {
163
+ style: 'width:100%;height:100%',
164
+ })
165
+ box.append(canvas)
166
+ const device = luma
167
+ .createDevice({
168
+ adapters: [webgl2Adapter],
169
+ createCanvasContext: { autoResize: true, canvas, useDevicePixels: true },
170
+ type: 'webgl',
171
+ webgl: { antialias: false },
172
+ })
173
+ .then(async (made) => {
174
+ await made.canvasContext?.initialized
175
+ await new Promise((done) => requestAnimationFrame(done))
176
+ return made
177
+ })
178
+ const graph = new Graph(box, { attribution: '', enableSimulation: true }, device)
179
+ ```
180
+
181
+ Use the `@luma.gl` version `@cosmos.gl/graph` depends on, since two versions
182
+ on one page throw, and destroy the device after the graph.
183
+
184
+ **The driver is for `@cosmos.gl/graph`, which is MIT.** Cosmograph, the
185
+ product built on it, is licensed for noncommercial use only.
186
+
187
+ ## Shapes
188
+
189
+ **`stencil` draws the notes in a shape**, such as a brain or a country's
190
+ outline. Pass an SVG path and the box it is drawn in, as the SVG's `viewBox`
191
+ gives it:
192
+
193
+ ```js
194
+ connectGraph(frame, driver, {
195
+ stencil: { path: brain.getAttribute('d'), width: 220, height: 170 },
196
+ })
197
+ ```
198
+
199
+ No layout runs, so the shape is there from the first frame. Each group takes
200
+ a region of the shape, each note sits by the hub it links to, and the notes
201
+ fill the shape evenly, with borders between regions that curve. Holes are cut
202
+ by the even-odd rule, which is how the grooves of a brain show. Only a graph
203
+ with no places of its own is shaped; a note added later is placed by the
204
+ layout beside its neighbors. `stencil` also takes `inside(x, y)`, a test of
205
+ whether a point in the box is in the shape, in place of `path`, and
206
+ `fitToStencil` fits places a page has into one.
58
207
 
59
208
  ## What it exports
60
209
 
61
210
  | Import | What |
62
211
  |---|---|
63
- | `@fusion.dev/helix-graph` | `connectGraph`, `graphColorsFrom`, `seedPositions`, and the `GraphDriver` type |
212
+ | `@fusion.dev/helix-graph` | `connectGraph`, `diffGraph`, `fitToStencil`, `graphColorsFrom`, `seedPositions`, and the `GraphDriver`, `GraphChanges` and `GraphStencil` types |
64
213
  | `@fusion.dev/helix-graph/sigma` | `sigmaDriver(sigma, options)` |
214
+ | `@fusion.dev/helix-graph/cosmos` | `cosmosDriver(graph, box, options)` |
65
215
 
66
- **Neither Sigma nor graphology is a dependency.** The driver types the renderer
67
- by the calls it makes on it, so a page brings whichever version it has. A spec
68
- holds those shapes to the real classes, so a renamed method fails a typecheck
69
- here rather than a page.
216
+ **Sigma and cosmos.gl are optional peers, and graphology is the page's.** Each
217
+ driver types its renderer by the calls it makes on it, so a page brings
218
+ whichever version it has, and a spec holds those shapes to the real classes,
219
+ so a renamed method fails a typecheck here before it reaches a page. `@fusion.dev/helix-graph/sigma` imports
220
+ Sigma's rendering module for the program that draws the notes, which is why
221
+ Sigma 3 is a peer dependency.
70
222
 
71
223
  | `connectGraph` option | Default | What else it takes |
72
224
  |---|---|---|
73
225
  | `center` | `true` | `false` leaves the view where it is when a note is chosen in the list |
226
+ | `stencil` | none | A shape to draw the notes in: `{ path, width, height }` or `{ inside, width, height }` |
74
227
 
75
228
  | `sigmaDriver` option | Default | What else it takes |
76
229
  |---|---|---|
77
230
  | `layout` | none | A function that makes a layout for the graph, such as ForceAtlas2's worker |
231
+ | `material` | flat | `glass` or `frosted`, for every note that does not say |
232
+ | `shape` | `circle` | `square`, `diamond` or `ring`, for every note that does not say |
233
+ | `emphasis` | `solid` | `outlined` or `subtle`, for every note that does not say |
234
+ | `labels` | `'hover'` | `'hubs'` or `'all'`: which notes are named at rest |
235
+ | `groupLabels` | `true` | `false` leaves each group unnamed |
78
236
  | `layoutLimit` | `10000` | The longest a layout runs, in milliseconds, about where 10,000 notes settle |
79
237
 
238
+ | `cosmosDriver` option | Default | What else it takes |
239
+ |---|---|---|
240
+ | `shape` | `circle` | `square` or `diamond`, for every note that does not say |
241
+ | `groupLabels` | `true` | `false` leaves each group unnamed |
242
+ | `layoutLimit` | `15000` | The longest a layout runs, in milliseconds |
243
+ | `spaceSize` | `4096` | The size of cosmos.gl's space, as its own `spaceSize` says |
244
+
80
245
  ## Working on it
81
246
 
82
247
  ```sh
@@ -0,0 +1,18 @@
1
+ import type { GraphPoint, SeedLink } from './seed.js';
2
+ /** A note as the arrangement reads it: its group, if it has one. */
3
+ export interface ArrangedNode {
4
+ group?: string | undefined;
5
+ id: string;
6
+ }
7
+ /**
8
+ * Places for every note from the graph's structure alone, with no layout to
9
+ * wait for: **each group around a circle, each hub in its group, and each
10
+ * note beside the hub it hangs from**, the most connected note it links to
11
+ * in its group.
12
+ *
13
+ * Not a layout to look at, since fans overlap and nothing is pushed apart:
14
+ * it is where a stencil starts, which reads only which notes are near which,
15
+ * so the shape is drawn from the first frame with each group a region and
16
+ * each hub's notes around it.
17
+ */
18
+ export declare const arrangeByGroup: (nodes: readonly ArrangedNode[], links: readonly SeedLink[]) => Map<string, GraphPoint>;
@@ -0,0 +1,92 @@
1
+ const TURN = Math.PI * (3 - Math.sqrt(5));
2
+ const spiral = (at, spacing) => ({
3
+ x: Math.cos(at * TURN) * Math.sqrt(at + 0.5) * spacing,
4
+ y: Math.sin(at * TURN) * Math.sqrt(at + 0.5) * spacing,
5
+ });
6
+ export const arrangeByGroup = (nodes, links) => {
7
+ const groupOf = new Map(nodes.map((node) => [node.id, node.group ?? '']));
8
+ const degree = new Map();
9
+ const neighbors = new Map();
10
+ const add = (from, to) => {
11
+ degree.set(from, (degree.get(from) ?? 0) + 1);
12
+ const list = neighbors.get(from);
13
+ if (list) {
14
+ list.push(to);
15
+ }
16
+ else {
17
+ neighbors.set(from, [to]);
18
+ }
19
+ };
20
+ for (const { source, target } of links) {
21
+ if (groupOf.has(source) && groupOf.has(target)) {
22
+ add(source, target);
23
+ add(target, source);
24
+ }
25
+ }
26
+ const rank = (id) => degree.get(id) ?? 0;
27
+ const above = (one, other) => rank(one) > rank(other) || (rank(one) === rank(other) && one < other);
28
+ const parent = new Map();
29
+ for (const { id } of nodes) {
30
+ let best = id;
31
+ for (const near of neighbors.get(id) ?? []) {
32
+ if (groupOf.get(near) === groupOf.get(id) && above(near, best)) {
33
+ best = near;
34
+ }
35
+ }
36
+ parent.set(id, best);
37
+ }
38
+ const hubOf = (id) => {
39
+ let at = id;
40
+ while (parent.get(at) !== at) {
41
+ at = parent.get(at);
42
+ }
43
+ let step = id;
44
+ while (step !== at) {
45
+ const next = parent.get(step);
46
+ parent.set(step, at);
47
+ step = next;
48
+ }
49
+ return at;
50
+ };
51
+ const groups = new Map();
52
+ for (const { id } of nodes) {
53
+ const group = groupOf.get(id);
54
+ const hubs = groups.get(group) ?? new Map();
55
+ groups.set(group, hubs);
56
+ const hub = hubOf(id);
57
+ const members = hubs.get(hub) ?? [];
58
+ hubs.set(hub, members);
59
+ if (hub !== id) {
60
+ members.push(id);
61
+ }
62
+ }
63
+ const radiusOf = (hubs) => {
64
+ let count = 0;
65
+ for (const members of hubs.values()) {
66
+ count += members.length + 1;
67
+ }
68
+ return Math.sqrt(count) * 1.5;
69
+ };
70
+ const radii = [...groups.values()].map(radiusOf);
71
+ const widest = Math.max(0, ...radii);
72
+ const ring = groups.size > 1 ? (widest * 1.2) / Math.sin(Math.PI / groups.size) : 0;
73
+ const positions = new Map();
74
+ [...groups.values()].forEach((hubs, at) => {
75
+ const turn = (at / groups.size) * Math.PI * 2;
76
+ const middle = { x: Math.cos(turn) * ring, y: Math.sin(turn) * ring };
77
+ const ordered = [...hubs].sort(([, one], [, other]) => other.length - one.length);
78
+ const mean = ordered.reduce((sum, [, members]) => sum + members.length + 1, 0) / ordered.length;
79
+ ordered.forEach(([hub, members], place) => {
80
+ const spot = spiral(place, Math.sqrt(mean) * 2);
81
+ const center = { x: middle.x + spot.x, y: middle.y + spot.y };
82
+ positions.set(hub, center);
83
+ members
84
+ .sort((one, other) => rank(other) - rank(one))
85
+ .forEach((member, step) => {
86
+ const off = spiral(step + 1, 1);
87
+ positions.set(member, { x: center.x + off.x, y: center.y + off.y });
88
+ });
89
+ });
90
+ });
91
+ return positions;
92
+ };
@@ -1,21 +1,9 @@
1
1
  import { type ViewportGestureMode } from '@fusion.dev/helix-core';
2
+ import { type DrawnLink, type DrawnNode, type GraphChanges } from './diff.js';
2
3
  import { type GraphLooks } from './looks.js';
3
4
  import { type GraphPoint } from './seed.js';
4
- /** A note as the renderer draws it, placed. */
5
- export interface DrawnNode {
6
- id: string;
7
- label: string;
8
- /** How large it is drawn, relative to the others: the note's `size`, or 1. */
9
- size: number;
10
- x: number;
11
- y: number;
12
- }
13
- /** A link as the renderer draws it, between two notes the graph holds. */
14
- export interface DrawnLink {
15
- label?: string | undefined;
16
- source: string;
17
- target: string;
18
- }
5
+ import { type GraphStencil } from './stencil.js';
6
+ export type { DrawnLink, DrawnNode, GraphChanges } from './diff.js';
19
7
  /**
20
8
  * What a renderer has to answer for the frame to drive it, and nothing that is
21
9
  * the same for every renderer: that is the connector's.
@@ -34,6 +22,25 @@ export interface GraphDriver {
34
22
  links: DrawnLink[];
35
23
  nodes: DrawnNode[];
36
24
  }): void;
25
+ /**
26
+ * Applies what changed since the last drawing, in place: what to add, what
27
+ * to take away and which notes moved or were renamed. `animate` says
28
+ * whether the reader may watch it happen. Without one, every change is a
29
+ * whole `draw`, which is right for a graph that changes now and then and
30
+ * wasteful for one that changes on every message.
31
+ */
32
+ update?(changes: GraphChanges, animate: boolean): void;
33
+ /**
34
+ * Draws something passing from one note to another, traveling the way it
35
+ * went and arriving with a pulse, or, where `animate` is false, the link
36
+ * between them lit for a moment. It leaves in `colors.from` and arrives in
37
+ * `colors.to`, which are one color where the signal has a tone. `colors` is
38
+ * undefined while the page's colors cannot be read.
39
+ */
40
+ signal?(from: string, to: string, colors: {
41
+ from: string;
42
+ to: string;
43
+ } | undefined, animate: boolean): void;
37
44
  /**
38
45
  * How each note and link is drawn from now on, asked one at a time as the
39
46
  * renderer draws them: a selection or a theme changed.
@@ -45,6 +52,11 @@ export interface GraphDriver {
45
52
  zoomBy(direction: 1 | -1, animate: boolean): void;
46
53
  /** Brings a note into the middle of the view, where the renderer can. */
47
54
  center?(id: string, animate: boolean): void;
55
+ /**
56
+ * Frames a set of notes, the selected one and its neighbors, in the middle
57
+ * of the view at a zoom that holds them all, where the renderer can.
58
+ */
59
+ fit?(ids: readonly string[], animate: boolean): void;
48
60
  /** Calls `press` with a note's `id` when the reader presses it in the drawing. Returns what stops listening. */
49
61
  onPress?(press: (id: string) => void): () => void;
50
62
  /**
@@ -63,9 +75,26 @@ export interface GraphDriver {
63
75
  gestures?(mode: ViewportGestureMode): void;
64
76
  /** The element the renderer made focusable, which the connector takes out of the tab order. */
65
77
  focusTarget?(): HTMLElement | null;
78
+ /**
79
+ * The graph's groups, each named over its notes, which is how a reader
80
+ * finds their way while notes are named only on hover. `faded` while a note
81
+ * outside the group is selected.
82
+ */
83
+ groups?(groups: readonly GraphGroup[]): void;
66
84
  /** Removes whatever the driver added to the renderer or the page, when the connection ends. */
67
85
  stop?(): void;
68
86
  }
87
+ /** One group of notes, as the renderer names it over them. */
88
+ export interface GraphGroup {
89
+ /** The group's color, which its name is drawn in. */
90
+ color: string;
91
+ /** Whether a note outside the group is selected, which steps its name back. */
92
+ faded: boolean;
93
+ /** The notes in the group, by `id`. */
94
+ ids: readonly string[];
95
+ /** The group's name, as the notes give it. */
96
+ name: string;
97
+ }
69
98
  /** How a connection behaves where the page does not say. */
70
99
  export interface ConnectGraphOptions {
71
100
  /**
@@ -74,6 +103,14 @@ export interface ConnectGraphOptions {
74
103
  * reader is already looking at it.
75
104
  */
76
105
  center?: boolean | undefined;
106
+ /**
107
+ * A shape the notes are drawn in, such as a brain or a country's outline:
108
+ * an SVG path and the box it is drawn in. **No layout runs**: each group
109
+ * takes a region of the shape and each note sits by the hub it links to,
110
+ * from the first frame. Only a graph with no places of its own is shaped;
111
+ * a note added later is placed by the layout beside its neighbors.
112
+ */
113
+ stencil?: GraphStencil | undefined;
77
114
  }
78
115
  /** A connection, which is ended rather than left to leak. */
79
116
  export interface GraphConnection {
@@ -96,7 +133,11 @@ export interface GraphConnection {
96
133
  * connection draws the frame's `nodes` and `links`, lays out the notes that
97
134
  * have no position and says where it put them in `helix-graph-layout`, answers
98
135
  * the frame's pan and zoom, keeps the selection the same in the list and the
99
- * drawing, colors the graph from the page's tokens, and tells the renderer
100
- * which gestures it may take.
136
+ * drawing, colors the graph from the page's tokens, tells the renderer which
137
+ * gestures it may take, and draws the frame's `signal()`s.
138
+ *
139
+ * **A page changes the graph by handing the frame new arrays**, as often as
140
+ * it likes: the connection compares them with what is drawn and the renderer
141
+ * is told only what changed.
101
142
  */
102
143
  export declare const connectGraph: (frame: HTMLElement, driver: GraphDriver, options?: ConnectGraphOptions) => GraphConnection;