vizcraft 1.1.0 → 1.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # vizcraft
2
2
 
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [`3f55212`](https://github.com/ChipiKaf/vizcraft/commit/3f55212e56557994710d65a99fe339c6826cb2a7) Thanks [@ChipiKaf](https://github.com/ChipiKaf)! - Add new visual styling options for nodes and edges: a hand-drawn "sketch" rendering mode, configurable drop-shadow support for nodes, and node stroke dasharray (dashed strokes)
8
+
9
+ ## 1.2.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [`f72dc04`](https://github.com/ChipiKaf/vizcraft/commit/f72dc0405ccd752ad13eb746349b6a5945448c79) Thanks [@ChipiKaf](https://github.com/ChipiKaf)! - Added rich text labels to VizCraft with support for mixed formatting and line breaks. Introduced fluent .richLabel() APIs and declarative label.rich support. Improved runtime updates to keep animations stable, extended React rendering, and added test coverage. Docs and READMEs now include a live example.
14
+
3
15
  ## 1.1.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -85,6 +85,12 @@ pnpm -C packages/docs start
85
85
 
86
86
  The heart of VizCraft is the `VizBuilder`. It allows you to construct a `VizScene` which acts as the blueprint for your visualization.
87
87
 
88
+ For exporting frame snapshots during data-only playback, you can export an SVG that includes runtime overrides:
89
+
90
+ ```ts
91
+ const svg = builder.svg({ includeRuntime: true });
92
+ ```
93
+
88
94
  ```typescript
89
95
  b.view(width, height) // Set the coordinate space
90
96
  .grid(cols, rows) // (Optional) Define layout grid
@@ -92,6 +98,52 @@ b.view(width, height) // Set the coordinate space
92
98
  .edge(from, to); // Start defining an edge
93
99
  ```
94
100
 
101
+ ### Plugins
102
+
103
+ Extend the builder's functionality seamlessly using `.use()`. Plugins are functions that take the builder instance and optional configuration, allowing you to encapsulate reusable behaviors, export utilities, or composite nodes.
104
+
105
+ ```typescript
106
+ import { viz, VizPlugin } from 'vizcraft';
107
+
108
+ const watermarkPlugin: VizPlugin<{ text: string }> = (builder, opts) => {
109
+ builder.node('watermark', {
110
+ at: { x: 50, y: 20 },
111
+ rect: { w: 100, h: 20 },
112
+ label: opts?.text ?? 'Draft',
113
+ opacity: 0.5,
114
+ });
115
+ };
116
+
117
+ viz()
118
+ .view(800, 600)
119
+ .node('n1', { circle: { r: 20 } })
120
+ .use(watermarkPlugin, { text: 'Confidential' })
121
+ .build();
122
+ ```
123
+
124
+ **Event Hooks**
125
+
126
+ Plugins (or your own code) can also tap into the builder's lifecycle using `.on()`. This is particularly useful for interactive plugins that need to append HTML elements (like export buttons or tooltips) after VizCraft mounts the SVG to the DOM.
127
+
128
+ ```typescript
129
+ const exportUiPlugin: VizPlugin = (builder) => {
130
+ // Listen for the 'mount' event to inject a button next to the SVG
131
+ builder.on('mount', ({ container }) => {
132
+ const btn = document.createElement('button');
133
+ btn.innerText = 'Download PNG';
134
+ btn.onclick = () => {
135
+ /* export logic */
136
+ };
137
+
138
+ // Position the button absolutely over the container
139
+ btn.style.position = 'absolute';
140
+ btn.style.top = '10px';
141
+ btn.style.right = '10px';
142
+ container.appendChild(btn);
143
+ });
144
+ };
145
+ ```
146
+
95
147
  ### Declarative Options Overloads
96
148
 
97
149
  You can also configure nodes and edges in a single declarative call by passing an options object:
@@ -140,6 +192,20 @@ b.node('n1')
140
192
  .trapezoid(topW, bottomW, h) // Trapezoid
141
193
  .triangle(w, h, [direction]) // Triangle
142
194
  .label('Text', { dy: 5 }) // Label with offset
195
+ .richLabel((l) => l.text('Hello ').bold('World')) // Rich / mixed-format label
196
+ .image(href, w, h, opts?) // Embed an <image> inside the node
197
+ .icon(id, opts?) // Embed an icon from the icon registry (see registerIcon)
198
+ .svgContent(svg, opts) // Embed inline SVG content inside the node
199
+ .fill('#f0f0f0') // Fill color
200
+ .stroke('#333', 2) // Stroke color and optional width
201
+ .opacity(0.8) // Opacity
202
+ .dashed() // Dashed border (8, 4)
203
+ .dotted() // Dotted border (2, 4)
204
+ .dash('12, 3, 3, 3') // Custom dash pattern
205
+ .shadow() // Drop shadow (default: dx=2 dy=2 blur=4)
206
+ .shadow({ dx: 4, dy: 4, blur: 10, color: 'rgba(0,0,0,0.35)' }) // Custom shadow
207
+ .sketch() // Sketch / hand-drawn look (SVG turbulence filter)
208
+ .sketch({ seed: 42 }) // Sketch with explicit seed for deterministic jitter
143
209
  .class('css-class') // Custom CSS class
144
210
  .data({ ... }) // Attach custom data
145
211
  .port('out', { x: 50, y: 0 }) // Named connection port
@@ -174,6 +240,7 @@ b.edge('n1', 'n2')
174
240
  .arrow() // Add an arrowhead
175
241
  .straight() // (Default) Straight line
176
242
  .label('Connection')
243
+ .richLabel((l) => l.text('p').sup('95').text(' = ').bold('10ms'))
177
244
  .animate('flow'); // Add animation
178
245
 
179
246
  // Curved edge
@@ -185,6 +252,18 @@ b.edge('a', 'c').orthogonal().arrow();
185
252
  // Waypoints — intermediate points the edge passes through
186
253
  b.edge('x', 'y').curved().via(150, 50).via(200, 100).arrow();
187
254
 
255
+ // Arbitrary edge metadata (for routing flags, categories, etc.)
256
+ b.edge('a', 'b').meta({ customRouting: true, padding: 10 });
257
+
258
+ // Override edge path computation with a resolver hook
259
+ b.setEdgePathResolver((edge, scene, defaultResolver) => {
260
+ if (edge.meta?.customRouting) {
261
+ // Return an SVG path `d` string
262
+ return `M 0 0 L 10 10`;
263
+ }
264
+ return defaultResolver(edge, scene);
265
+ });
266
+
188
267
  // Per-edge styling (overrides CSS defaults)
189
268
  b.edge('a', 'b').stroke('#ff0000', 3).fill('none').opacity(0.8);
190
269
 
@@ -193,18 +272,28 @@ b.edge('a', 'b').dashed().stroke('#6c7086'); // dashed line
193
272
  b.edge('a', 'b').dotted(); // dotted line
194
273
  b.edge('a', 'b').dash('12, 3, 3, 3').stroke('#cba6f7'); // custom pattern
195
274
 
275
+ // Sketch / hand-drawn edges
276
+ b.edge('a', 'b').sketch(); // sketchy look
277
+
196
278
  // Multi-position edge labels (start / mid / end)
197
279
  b.edge('a', 'b')
198
280
  .label('1', { position: 'start' })
199
281
  .label('*', { position: 'end' })
200
282
  .arrow();
201
283
 
284
+ // Rich text labels (mixed formatting)
285
+ b.edge('a', 'b')
286
+ .richLabel((l) => l.text('p').sup('95').text(' ').bold('12ms'))
287
+ .arrow();
288
+
202
289
  // Edge markers / arrowhead types
203
290
  b.edge('a', 'b').markerEnd('arrowOpen'); // Open arrow (inheritance)
204
291
  b.edge('a', 'b').markerStart('diamond').markerEnd('arrow'); // UML composition
205
292
  b.edge('a', 'b').markerStart('diamondOpen').markerEnd('arrow'); // UML aggregation
206
293
  b.edge('a', 'b').arrow('both'); // Bidirectional arrows
207
294
  b.edge('a', 'b').markerStart('circleOpen').markerEnd('arrow'); // Association
295
+ // Self-loops (exits and enters the same node)
296
+ b.edge('n1', 'n1').loopSide('right').loopSize(40).arrow();
208
297
  b.edge('a', 'b').markerEnd('bar'); // ER cardinality
209
298
 
210
299
  // Connection ports — edges attach to specific points on nodes
@@ -228,6 +317,7 @@ b.edge('a', 'b').fromPort('right').toPort('left').arrow();
228
317
  | `.routing(mode)` | Set mode programmatically. |
229
318
  | `.via(x, y)` | Add an intermediate waypoint (chainable). |
230
319
  | `.label(text, opts?)` | Add a text label. Chain multiple calls for multi-position labels. `opts.position` can be `'start'`, `'mid'` (default), or `'end'`. |
320
+ | `.richLabel(cb, opts?)` | Add a rich / mixed-format label (nested SVG `<tspan>`s). Use `.newline()` in the callback to control line breaks. |
231
321
  | `.arrow([enabled])` | Shorthand for arrow markers. `true`/no-arg → markerEnd arrow. `'both'` → both ends. `'start'`/`'end'` → specific end. `false` → none. |
232
322
  | `.markerEnd(type)` | Set marker type at the target end. See `EdgeMarkerType`. |
233
323
  | `.markerStart(type)` | Set marker type at the source end. See `EdgeMarkerType`. |
package/dist/builder.d.ts CHANGED
@@ -1,14 +1,44 @@
1
- import type { VizScene, VizNode, VizEdge, NodeLabel, EdgeLabel, AnimationConfig, OverlayId, OverlayParams, VizGridConfig, ContainerConfig, EdgeRouting, EdgeMarkerType, NodeOptions, EdgeOptions, PanZoomOptions, PanZoomController, VizSceneMutator } from './types';
1
+ import type { VizScene, VizNode, VizEdge, NodeLabel, EdgeLabel, RichText, RichTextToken, AnimationConfig, OverlayId, OverlayParams, VizGridConfig, ContainerConfig, EdgeRouting, EdgeMarkerType, EdgePathResolver, NodeOptions, EdgeOptions, PanZoomOptions, PanZoomController, VizSceneMutator, VizPlugin, VizEventMap, LayoutAlgorithm, SvgExportOptions } from './types';
2
2
  import { OverlayBuilder } from './overlayBuilder';
3
3
  import type { AnimationSpec } from './anim/spec';
4
4
  import { type AnimationBuilder, type AnimatableProps, type TweenOptions } from './anim/animationBuilder';
5
5
  import { type PlaybackController } from './anim/playback';
6
6
  export interface VizBuilder extends VizSceneMutator {
7
+ /**
8
+ * Applies a plugin to the builder fluently.
9
+ * @param plugin The plugin function to execute
10
+ * @param options Optional configuration for the plugin
11
+ * @returns The builder, for fluent chaining
12
+ */
13
+ use<O>(plugin: VizPlugin<O>, options?: O): VizBuilder;
14
+ /**
15
+ * Applies a layout algorithm to the current nodes and edges.
16
+ * @param algorithm The layout function to execute
17
+ * @param options Optional configuration for the layout algorithm
18
+ * @returns The builder, for fluent chaining
19
+ */
20
+ layout<O>(algorithm: LayoutAlgorithm<O>, options?: O): VizBuilder;
21
+ /**
22
+ * Listen for lifecycle events (e.g. 'build', 'mount').
23
+ * @param event The event name
24
+ * @param callback The callback to execute when the event fires
25
+ * @returns An unsubscribe function
26
+ */
27
+ on<K extends keyof VizEventMap>(event: K, callback: (ev: VizEventMap[K]) => void): () => void;
28
+ /**
29
+ * Override edge SVG path computation.
30
+ *
31
+ * Intended to be installed before `mount()`. Applies to DOM reconciliation and
32
+ * `patchRuntime()`.
33
+ */
34
+ setEdgePathResolver(resolver: EdgePathResolver | null): VizBuilder;
7
35
  view(w: number, h: number): VizBuilder;
8
36
  grid(cols: number, rows: number, padding?: {
9
37
  x: number;
10
38
  y: number;
11
39
  }): VizBuilder;
40
+ /** Enable global sketch / hand-drawn rendering for all nodes and edges. */
41
+ sketch(enabled?: boolean, seed?: number): VizBuilder;
12
42
  /**
13
43
  * Fluent, data-only animation authoring. Compiles immediately to an `AnimationSpec`.
14
44
  * The compiled spec is also stored on the built scene as `scene.animationSpecs`.
@@ -34,7 +64,7 @@ export interface VizBuilder extends VizSceneMutator {
34
64
  w: number;
35
65
  h: number;
36
66
  };
37
- svg(): string;
67
+ svg(opts?: SvgExportOptions): string;
38
68
  mount(container: HTMLElement): PanZoomController | undefined;
39
69
  mount(container: HTMLElement, opts: {
40
70
  autoplay?: boolean;
@@ -66,6 +96,46 @@ export interface VizBuilder extends VizSceneMutator {
66
96
  * This avoids full DOM reconciliation and is intended for animation frame updates.
67
97
  */
68
98
  patchRuntime(container: HTMLElement): void;
99
+ /**
100
+ * Tear down a previously mounted scene.
101
+ *
102
+ * - Removes the SVG tree from the container.
103
+ * - Destroys the PanZoomController (if created).
104
+ * - Cancels any pending requestAnimationFrame / animation loops.
105
+ * - Removes any internal event listeners (resize, mutation, etc.).
106
+ *
107
+ * Safe to call multiple times (no-op after first call).
108
+ * Safe to call even if `mount()` was never called.
109
+ */
110
+ destroy(): void;
111
+ }
112
+ export interface RichLabelBuilder {
113
+ text(text: string, opts?: Partial<Omit<Extract<RichTextToken, {
114
+ kind: 'span';
115
+ }>, 'kind' | 'text'>>): RichLabelBuilder;
116
+ bold(text: string, opts?: Partial<Omit<Extract<RichTextToken, {
117
+ kind: 'span';
118
+ }>, 'kind' | 'text'>>): RichLabelBuilder;
119
+ italic(text: string, opts?: Partial<Omit<Extract<RichTextToken, {
120
+ kind: 'span';
121
+ }>, 'kind' | 'text'>>): RichLabelBuilder;
122
+ code(text: string, opts?: Partial<Omit<Extract<RichTextToken, {
123
+ kind: 'span';
124
+ }>, 'kind' | 'text'>>): RichLabelBuilder;
125
+ color(text: string, fill: string, opts?: Partial<Omit<Extract<RichTextToken, {
126
+ kind: 'span';
127
+ }>, 'kind' | 'text' | 'fill'>>): RichLabelBuilder;
128
+ link(text: string, href: string, opts?: Partial<Omit<Extract<RichTextToken, {
129
+ kind: 'span';
130
+ }>, 'kind' | 'text' | 'href'>>): RichLabelBuilder;
131
+ sup(text: string, opts?: Partial<Omit<Extract<RichTextToken, {
132
+ kind: 'span';
133
+ }>, 'kind' | 'text' | 'baselineShift'>>): RichLabelBuilder;
134
+ sub(text: string, opts?: Partial<Omit<Extract<RichTextToken, {
135
+ kind: 'span';
136
+ }>, 'kind' | 'text' | 'baselineShift'>>): RichLabelBuilder;
137
+ newline(): RichLabelBuilder;
138
+ build(): RichText;
69
139
  }
70
140
  interface NodeBuilder {
71
141
  at(x: number, y: number): NodeBuilder;
@@ -95,11 +165,75 @@ interface NodeBuilder {
95
165
  star(points: number, outerR: number, innerR?: number): NodeBuilder;
96
166
  trapezoid(topW: number, bottomW: number, h: number): NodeBuilder;
97
167
  triangle(w: number, h: number, direction?: 'up' | 'down' | 'left' | 'right'): NodeBuilder;
168
+ /** Embed an SVG <image> inside/around the node. */
169
+ image(href: string, w: number, h: number, opts?: {
170
+ dx?: number;
171
+ dy?: number;
172
+ position?: 'center' | 'above' | 'below' | 'left' | 'right';
173
+ preserveAspectRatio?: string;
174
+ }): NodeBuilder;
175
+ image(href: string, opts: {
176
+ w: number;
177
+ h: number;
178
+ dx?: number;
179
+ dy?: number;
180
+ position?: 'center' | 'above' | 'below' | 'left' | 'right';
181
+ preserveAspectRatio?: string;
182
+ }): NodeBuilder;
183
+ /** Render a registered SVG icon inside/around the node. */
184
+ icon(id: string, opts: {
185
+ size: number;
186
+ color?: string;
187
+ dx?: number;
188
+ dy?: number;
189
+ position?: 'center' | 'above' | 'below' | 'left' | 'right';
190
+ }): NodeBuilder;
191
+ /** Render inline SVG content inside/around the node. */
192
+ svgContent(content: string, w: number, h: number, opts?: {
193
+ dx?: number;
194
+ dy?: number;
195
+ position?: 'center' | 'above' | 'below' | 'left' | 'right';
196
+ }): NodeBuilder;
197
+ svgContent(content: string, opts: {
198
+ w: number;
199
+ h: number;
200
+ dx?: number;
201
+ dy?: number;
202
+ position?: 'center' | 'above' | 'below' | 'left' | 'right';
203
+ }): NodeBuilder;
98
204
  label(text: string, opts?: Partial<NodeLabel>): NodeBuilder;
205
+ /**
206
+ * Create a rich text label (mixed formatting) using nested SVG <tspan> spans.
207
+ *
208
+ * Note: Rich labels currently support explicit newlines via `l.newline()`.
209
+ */
210
+ richLabel(cb: (l: RichLabelBuilder) => unknown, opts?: Partial<Omit<NodeLabel, 'text' | 'rich'>>): NodeBuilder;
99
211
  fill(color: string): NodeBuilder;
100
212
  stroke(color: string, width?: number): NodeBuilder;
101
213
  opacity(value: number): NodeBuilder;
214
+ /** Apply a dashed stroke pattern (`8, 4`). */
215
+ dashed(): NodeBuilder;
216
+ /** Apply a dotted stroke pattern (`2, 4`). */
217
+ dotted(): NodeBuilder;
218
+ /** Apply a custom SVG `stroke-dasharray` value, or a preset name (`'dashed'`, `'dotted'`, `'dash-dot'`). */
219
+ dash(pattern: 'solid' | 'dashed' | 'dotted' | 'dash-dot' | string): NodeBuilder;
220
+ /**
221
+ * Add a drop shadow behind the node shape.
222
+ *
223
+ * Call with no arguments for a sensible default, or pass a config object.
224
+ */
225
+ shadow(config?: {
226
+ dx?: number;
227
+ dy?: number;
228
+ blur?: number;
229
+ color?: string;
230
+ }): NodeBuilder;
231
+ /** Render this node with a hand-drawn / sketchy appearance. */
232
+ sketch(config?: {
233
+ seed?: number;
234
+ }): NodeBuilder;
102
235
  class(name: string): NodeBuilder;
236
+ zIndex(value: number): NodeBuilder;
103
237
  animate(type: string, config?: AnimationConfig): NodeBuilder;
104
238
  animate(cb: (anim: AnimationBuilder) => unknown): NodeBuilder;
105
239
  /** Sugar for `animate(a => a.to(...))`. */
@@ -127,7 +261,7 @@ interface NodeBuilder {
127
261
  overlay<K extends OverlayId>(id: K, params: OverlayParams<K>, key?: string): VizBuilder;
128
262
  overlay<T>(id: string, params: T, key?: string): VizBuilder;
129
263
  build(): VizScene;
130
- svg(): string;
264
+ svg(opts?: SvgExportOptions): string;
131
265
  }
132
266
  interface EdgeBuilder {
133
267
  straight(): EdgeBuilder;
@@ -136,6 +270,12 @@ interface EdgeBuilder {
136
270
  routing(mode: EdgeRouting): EdgeBuilder;
137
271
  via(x: number, y: number): EdgeBuilder;
138
272
  label(text: string, opts?: Partial<EdgeLabel>): EdgeBuilder;
273
+ /**
274
+ * Create a rich text label (mixed formatting) using nested SVG <tspan> spans.
275
+ *
276
+ * Note: Rich labels currently support explicit newlines via `l.newline()`.
277
+ */
278
+ richLabel(cb: (l: RichLabelBuilder) => unknown, opts?: Partial<Omit<EdgeLabel, 'text' | 'rich'>>): EdgeBuilder;
139
279
  /**
140
280
  * Set arrow markers. Convenience method.
141
281
  * - `arrow(true)` or `arrow()` sets markerEnd to 'arrow'
@@ -166,14 +306,28 @@ interface EdgeBuilder {
166
306
  dotted(): EdgeBuilder;
167
307
  /** Apply a custom SVG `stroke-dasharray` value, or a preset name (`'dashed'`, `'dotted'`, `'dash-dot'`). */
168
308
  dash(pattern: 'solid' | 'dashed' | 'dotted' | 'dash-dot' | string): EdgeBuilder;
309
+ /** Render this edge with a hand-drawn / sketchy appearance. */
310
+ sketch(): EdgeBuilder;
169
311
  class(name: string): EdgeBuilder;
170
312
  hitArea(px: number): EdgeBuilder;
171
313
  animate(type: string, config?: AnimationConfig): EdgeBuilder;
172
314
  animate(cb: (anim: AnimationBuilder) => unknown): EdgeBuilder;
173
315
  /** Sugar for `animate(a => a.to(...))`. */
174
316
  animateTo(props: AnimatableProps, opts: TweenOptions): EdgeBuilder;
317
+ /** Attach arbitrary consumer-defined metadata to the edge. */
318
+ meta(meta: Record<string, unknown>): EdgeBuilder;
175
319
  data(payload: unknown): EdgeBuilder;
176
320
  onClick(handler: (id: string, edge: VizEdge) => void): EdgeBuilder;
321
+ /**
322
+ * For self-loops: which side the loop exits from.
323
+ * @default 'top'
324
+ */
325
+ loopSide(side: 'top' | 'right' | 'bottom' | 'left'): EdgeBuilder;
326
+ /**
327
+ * For self-loops: how far the loop extends from the shape boundary.
328
+ * @default 30
329
+ */
330
+ loopSize(size: number): EdgeBuilder;
177
331
  done(): VizBuilder;
178
332
  node(id: string): NodeBuilder;
179
333
  node(id: string, opts: NodeOptions): VizBuilder;
@@ -183,7 +337,7 @@ interface EdgeBuilder {
183
337
  overlay<K extends OverlayId>(id: K, params: OverlayParams<K>, key?: string): VizBuilder;
184
338
  overlay<T>(id: string, params: T, key?: string): VizBuilder;
185
339
  build(): VizScene;
186
- svg(): string;
340
+ svg(opts?: SvgExportOptions): string;
187
341
  }
188
342
  export declare function viz(): VizBuilder;
189
343
  export {};