• Joined on 2026-09-04

@jean/knotenwerk (0.2.0)

Published 2026-11-27 13:16:33 +00:00 by jean

Installation

@jean:registry=https://code.jeanavril.com/api/packages/jean/npm/
npm install @jean/knotenwerk@0.2.0
"@jean/knotenwerk": "0.2.0"

About this package

A node editor canvas for Svelte 5: your own components as nodes, ports, edges, connecting with snapping and checks, selection, pan and zoom by mouse, trackpad and touch, resizing, groups, a minimap. No runtime dependencies.

knotenwerk

A node editor canvas for Svelte 5. Your own components are the nodes; the canvas gives them ports, draws the edges between them, and does the rest of the interaction: pan and zoom by mouse, wheel, trackpad and touch, dragging one node or many, groups whose children move with them, connecting with snapping and a check of your own, a selection by click or rectangle, deleting, the arrow keys, resizing, a minimap, panels and controls. It reports what the user did and never changes your data by itself. No runtime dependencies; Svelte is the only peer. No attribution, no network.

Entry What
@jean/knotenwerk the core without Svelte: types, view, edge paths, layout, selection
@jean/knotenwerk/svelte NodeCanvas and the building blocks inside it

Install

npm install @jean/knotenwerk

The package comes from the registry on Jean's Gitea; an app maps the scope in its .npmrc:

@jean:registry=https://gitea.public.mgmt/api/packages/jean/npm/

Installing needs no token.

A first canvas

<script lang="ts">
	import { Background, Controls, MiniMap, NodeCanvas, type EdgeSpec, type NodeSpec, type Selection } from '@jean/knotenwerk/svelte';
	import Card from './card.svelte';

	let nodes = $state.raw<NodeSpec[]>([
		{ id: 'a', type: 'card', position: { x: 0, y: 0 }, data: { title: 'Source' } },
		{ id: 'b', type: 'card', position: { x: 300, y: 40 }, data: { title: 'Filter' } }
	]);
	let edges = $state.raw<EdgeSpec[]>([{ id: 'e1', source: 'a', sourcePort: 'out', target: 'b', targetPort: 'in' }]);
	let selection = $state.raw<Selection>({ nodes: [], edges: [] });
</script>

<div style="height: 600px">
	<NodeCanvas
		{nodes}
		{edges}
		bind:selection
		nodeTypes={{ card: Card }}
		fitView
		onmove={(moves) => (nodes = nodes.map((n) => ({ ...n, position: moves.find((m) => m.id === n.id)?.position ?? n.position })))}
		onconnect={(c) => (edges = [...edges, { id: crypto.randomUUID(), ...c }])}
		ondelete={(d) => {
			nodes = nodes.filter((n) => !d.nodes.includes(n.id));
			edges = edges.filter((e) => !d.edges.includes(e.id));
		}}
	>
		<Background />
		<Controls />
		<MiniMap />
	</NodeCanvas>
</div>
<!-- card.svelte -->
<script lang="ts">
	import { Port, type NodeProps } from '@jean/knotenwerk/svelte';
	let { data, selected }: NodeProps<{ title: string }> = $props();
</script>

<div class="card" class:selected style="position: relative; width: 160px; padding: 8px; border: 1px solid #999; background: white">
	{data.title}
	<Port id="in" type="input" />
	<Port id="out" type="output" />
</div>

The contract

The app owns the data, the canvas owns the interaction. Nodes and edges are input, never bound. While a gesture lasts the canvas shows a preview (positions while dragging, a box while resizing); at its end it reports an event, and the app writes its data and hands it back in. If the app does not take the change, the node goes back where it was.

A node (NodeSpec):

Field What
id, type the id, and the key into nodeTypes
position top left corner, relative to the parent's when parent is set
parent the node it belongs to: it moves with it. List parents before their children
width, height a fixed size; a missing side is measured from the drawn node
layer below 0 the node lies under the edges (groups, frames, notes), in the order of the layer; from 0 above them. Selecting never raises a node
grow while dragged past its parent's right or bottom edge, the parent grows to hold it
draggable, selectable both true by default
label what a screen reader calls it
data anything; it goes to the node's component

An edge (EdgeSpec): id, type (the key into edgeTypes, a plain curve without), source and sourcePort, target and targetPort, label, data. Edges always run from an output to an input.

The selection is a value of its own (bind:selection, { nodes, edges }), not a flag on each node: the app may set it, and ids that disappear fall out of it.

Events

Event When
onmove(moves, by) at the end of a drag (by is 'drag') and for each arrow key ('key', so an app can merge a run of presses into one undo step): every node that moved, with its position relative to its parent. Nothing for 0 px
onconnect(connection) a valid connection, always output → input
onconnectend({ event, from, to, valid, point }) after every drag from a port; valid is null when it ended in the empty, point is where (client coordinates) — the place for a menu of what fits
ondelete({ nodes, edges }) Delete or Backspace: the selected nodes (their children are not listed: what a parent takes along is the app's to decide), the selected edges and the edges at the nodes and their children. The canvas deletes nothing
onselectionchange(selection) each change the user makes
onpaneclick({ event, point, count }) a click on the empty canvas; count is 2 for a double click
oncontextmenu({ event, target, point, client, selection, by }) a right click, a held finger or the menu key (Shift+F10): target is { kind: 'node', id }, { kind: 'edge', id } or { kind: 'pane' }, point on the canvas, client on screen (where the app opens its menu), selection as it is after the click, by 'pointer' or 'key'. With a handler the canvas keeps the browser's menu away, except over a field and over panels and controls; nothing is reported in the middle of a drag
onnodeenter(id), onnodeleave(id) the pointer over a node
onmeasure(sizes) the sizes of all nodes, when one changes
onviewportchange(viewport) every change of the view

Options

readonly (pan, zoom and select only), minZoom, maxZoom, fitView (once the nodes are measured), connectionRadius (20 screen pixels), connectionLine ('bezier' or 'step'), isValidConnection(c) (ports that do not take an edge neither snap nor connect), extendDrag(ids) (more nodes that move along when a drag starts: a frame that carries what lies in it), labels (texts for screen readers and the controls, in the app's language), viewport (bindable), keyScope ('page', the default: Delete, Backspace and Space act anywhere on the page unless the user types, as in other node editors — so one canvas per page; 'canvas': only with the focus in the canvas).

Building blocks

Block What
Port a port in a node: id (unique in the node), type (input, output), side (left for inputs, right for outputs by default), connectable. It sits on a side of its positioned parent; the canvas measures its middle, and edges end there. Its look is yours: content and classes
EdgePath the line of an edge and a wider transparent line that takes the pointer (interactionWidth)
EdgeLabel HTML at a point of the canvas, above the nodes; a click on it selects its edge
bezierPath, stepPath the paths, with a point in the middle for a label; stepPath takes radius, offset and centerX (where the line bends)
NodeResizer handles on the corners and sides of its node; onresizeend(box). Corners lie above edges and nodes, and the sides of a node under the edges (a group, a frame) above the edges but under the nodes, so a port on the border stays in reach. Zoomed out, the handles keep their size on screen
MiniMap the graph in small with the view as a window; drag and wheel move the view; nodeColor may be a function
Controls, ControlButton zoom in, zoom out, fit, then your own buttons
Panel your own controls on six places above the canvas
Background dots or lines that move and zoom with the canvas
useCanvas() inside the canvas: viewport, connection (the edge being drawn), screenToCanvas, canvasToScreen, fitView, setViewport, boxOf, sizeOf, refresh

The component that holds the canvas gets the same through bind:this: canvas.api.fitView({ nodes: ['a'], padding: 0.2, maxZoom: 1, duration: 300 }).

Interaction

Input Does
Drag on the empty canvas, middle button, Space + drag pans
Wheel, trackpad, Ctrl + wheel, pinch with two fingers zooms around the pointer; the speed is d3-zoom's (2^(−deltaY · 0.002) per pixel)
Click selects; a click on one of several selected nodes keeps them all (a drag moves them all). Ctrl/Cmd or Shift adds and removes
Shift + drag on the empty canvas (or on a group or frame under the edges) a selection rectangle: what it touches, edges at it too; a group it is drawn inside does not count. With Ctrl it adds
Drag a node moves it and every selected node; children move with their parent; near the border the view pans along
Drag from a port draws a connection that snaps to the nearest port taking it; Escape cancels
Click a port, then another connects them
Delete, Backspace ondelete
Arrow keys (Shift: 20 px) move the selected nodes by 5 px
Ctrl+A, Escape select all, select nothing (with the focus in the canvas)
Tab, Enter focus nodes and edges, select them
Right click, menu key, Shift+F10 oncontextmenu; a node or edge not selected becomes the selection (Ctrl/Cmd or Shift: is added), a selected one keeps it, the empty canvas keeps it. With a key, the place is the middle of the focused node or edge

Keys never act while the user types in a field, nor when the page already handled them (defaultPrevented: Escape that closed a dialog). Elements with the class nodrag start no drag (on a node that cannot move anyway they pan, like the rest of it); elements with nowheel keep the wheel (a text that scrolls). The click that follows a gesture that moved (a drag, a pan, a rectangle, Escape in the middle of one) reaches nothing under the pointer. A mouse that comes back without its button (released outside the window) ends the gesture as released; leaving the window cancels it.

Colours

Every colour is a CSS variable with a default; set them on the canvas or any parent: --kw-grid, --kw-edge, --kw-edge-selected, --kw-connection, --kw-port, --kw-port-border, --kw-selection-bg, --kw-selection-border, --kw-focus, --kw-resizer, --kw-controls-bg, --kw-controls-fg, --kw-controls-border, --kw-controls-hover, --kw-minimap-bg, --kw-minimap-mask, --kw-minimap-node. The parts carry plain classes (kw-canvas, kw-node, kw-node-<type>, kw-selected, kw-edge, kw-edge-path, kw-connection, kw-port, kw-panel, kw-controls, kw-minimap, kw-edge-label, kw-resizer) with one-class selectors, so one class of your own wins. There is no stylesheet to import.

Working on the library and an app together

Change the library here, with tests, then try it in the app with a packed archive rather than a link (a link brings a second copy of Svelte):

npm run build && npm pack --pack-destination ../tmp
cd ../strategies/web && npm install ../../tmp/jean-knotenwerk-<version>.tgz --no-save
rm -rf node_modules/.vite   # Vite caches the old prebundle

Never commit the app with an archive or a link: release, then install the released version.

Releases

npm version patch           # or minor; writes the version and a tag
npm publish                 # to the Gitea registry; runs check, tests, browser tests and build first
git push --follow-tags

Publishing needs a token with write access to the registry in the npm config of the machine that publishes, never in a repository. Note user-visible changes in CHANGELOG.md.

Development

npm install
npm test               # core and canvas state, in Node
npm run test:browser   # interaction in Chrome: real pointer, wheel, key and touch input
npm run check          # svelte-check
npm run demo           # every building block on one page, http://localhost:5197
npm run build          # dist/

The browser tests run in the Chrome installed on the machine (channel: 'chrome'); no browser is downloaded. HEADED=1 shows it.

Design and history: feature 037 in the strategies repository (specs/037-own-graph-lib/), where knotenwerk replaced Svelte Flow in the strategy editor.

License

MIT

Dependencies

Development Dependencies

ID Version
@sveltejs/package ^3.0.2
@sveltejs/vite-plugin-svelte ^7.2.0
@types/node ^26.6.5
@vitest/browser-playwright 5.1.2
jsdom ^26.1.0
playwright ^1.65.1
svelte ^5.57.1
svelte-check ^4.6.0
typescript ^6.0.3
vite ^8.3.0
vitest 5.1.2

Peer Dependencies

ID Version
svelte ^5.0.0

Keywords

node-editor graph flow diagram canvas svelte svelte5
Details
npm
2026-11-27 13:16:33 +00:00
2
Jean Avril
MIT
latest
42 KiB
Assets (1)
Versions (3) View all
0.2.0 2026-11-27
0.1.1 2026-11-26
0.1.0 2026-11-26