npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@opsydyn/foldkit-zloz

v0.11.2

Published

Model-owned graph editing and optional Effect UI views.

Downloads

4,889

Readme

ZLOZ

Graph editing with state owned by your application. The pure TypeScript core has no runtime dependencies. The optional /effect-ui entry supplies the native graph canvas, workbench controls and composition hooks. Import /effect-ui.css for the canvas styles.

@opsydyn/foldkit-zloz is available on npm.

The four public ZLOZ packages release together, with adapters pinned to the exact core version. The release train verifies registry archives and provenance before advancing to the next package.

Install

From 0.11.1 the package is built for Effect UI. 0.11.0 and earlier are the FoldKit builds: pin 0.11.0 to stay on FoldKit.

npm install @opsydyn/foldkit-zloz
# Only for the native view:
npm install [email protected] https://pkg.pr.new/Effect-TS/ui/@effect/ui@6679263

For workspace development, use the checked local tarball described in the publication guide. ESM only, Node 22+ for tooling. The view is for browsers; pure imports do not access browser globals. Effect UI and Effect are optional peers for consumers of the view entry.

Effect UI preview

The package includes @opsydyn/foldkit-zloz/effect-ui for Effect UI hosts. Use graphSurface with @opsydyn/foldkit-zloz/effect-ui.css for the shared HTML and SVG view, or use the surfaceInput mount to own the surface markup. The host owns the editor state and routes BrowserInput events to updateEditor. The Connections workbench shows strict and loose sessions, custom port labels, and reconnection. Use the Effect UI revision pinned by the workspace for this preview. For a native v3 editor, compose groupSurfaceV3, groupInspectorV3 and groupClipboardV3 with updateGroupWorkbenchV3 and the same policy in the host.

Pass resizeHandles: true to graphSurface to expose width controls on nodes and directional handles when an expanded group is selected. Arrow keys and pointer drags use the same editor policy and Undo history. Set resizeReadout: false to hide the size display while retaining the controls. The History workbench enables the controls on its working model.

Set portAnchors to expose port position handles on selected nodes. Set edgeWaypoints.onEdit to route bend creation, removal and reset to the same editor as the canvas input. Optional anchor guides and waypoint measurements can follow the host's diagnostics settings. Set edgeWaypoints.presentation to supply a CSS class, panel heading and handle marker for the same controls.

For placement, compose placementHost with placementPalette and the graph surface, and pass placementPreview to the surface's worldOverlay. Resolve the controls with resolvePlacementControls and send the scoped input to updatePlacementControls. The host keeps the placement and editor records.

Core

import { createEditor, updateEditor, serializeGraph, parseGraph } from '@opsydyn/foldkit-zloz';
import type { ZlozGraph } from '@opsydyn/foldkit-zloz';

const graph: ZlozGraph = {
  nodes: [
    {
      id: 'source',
      label: 'Source',
      position: { x: 40, y: 40 },
      size: { width: 180, height: 90 },
      ports: [{ id: 'out', kind: 'output', side: 'right', offset: 0.5 }],
    },
  ],
  edges: [],
};
const editor = createEditor(graph);
const selected = updateEditor(editor, { type: 'NodeSelected', id: 'source', additive: false });
const moved = updateEditor(selected, { type: 'SelectionNudged', delta: { x: 20, y: 0 } });
const document = serializeGraph(moved.graph);
const restored = createEditor(parseGraph(document));

Keep the editor in your Model. Nodes have stable IDs, positions, positive dimensions and named input/output ports. Port offsets are fractions of the chosen side. Edges refer to both node and port IDs. Optional node/edge data accepts finite JSON data. Functions reject duplicate IDs, invalid sizes and missing/wrong-direction endpoints with ZlozError. JSON syntax errors remain SyntaxError.

updateEditor(state, event, { canConnect }) lets the application reject a proposed connection with a reason or accept it with null. Cycles are allowed by the core. Exact duplicate connections are ignored with a notice. The policy is supplied by the host on each update; it is not serialized into the Model.

Each completed drag, keyboard nudge, graph edit or accepted layout is one undo transaction. Escape restores the pre-drag positions. The default history limit is 100 (configurable from 0 to 1000). Measurements update dimensions without creating history entries. Undo and measurements advance the revision used to reject stale layout results. Selection, viewport, gestures and history are excluded from saved documents. Applications own storage and migration beyond document version 1.

Headless palette and external placement

Palette cards and normalized external graph fragments use the same pure contract:

import {
  createArchitecturePattern,
  createEditor,
  createPlacement,
  updatePlacement,
  resolvePlacement,
  applyPlacement,
} from '@opsydyn/foldkit-zloz';

const context = {
  scope: 'orders/editor-session-1',
  editor: createEditor({ nodes: [], edges: [] }),
};
const idle = createPlacement(context.scope);
const started = updatePlacement(idle, context, {
  type: 'PlacementStarted',
  scope: context.scope,
  generation: idle.generation,
  intent: {
    source: { type: 'palette', id: 'c4-context' },
    fragment: createArchitecturePattern('c4-context'),
    anchor: { x: 30, y: 65 },
    snapping: { grid: true, anchorDistance: 12, anchors: ['center'] },
  },
});
const positioned = updatePlacement(started, context, {
  type: 'PlacementTargetChanged',
  scope: context.scope,
  generation: started.generation,
  target: { space: 'world', point: { x: 100, y: 200 } },
});
const preview = resolvePlacement(positioned, context);
if (preview.type === 'ready') {
  const result = applyPlacement(positioned, context, preview.request);
  // On 'placed', publish result.editor and result.placement together in the host Model.
}

Use a fresh scope when replacing the editor/controller, normally from the host's model/session identity. Start captures an immutable source, not a live palette object. Cancel with PlacementCancelled carrying current scope/generation. Preview/cancel leave graph and Undo/Redo unchanged. Apply rebuilds against live context and policy; the request pins the reviewed source generation and target sample. Old callbacks, changed graph revisions and late vetoes cannot publish. Successful Apply is one Undo transaction and ends the session.

world targets need no measured surface. screen points are canvas-local CSS pixels; client points use context.origin for the current canvas origin. Both screen/client modes require editor.surface. Zoom, size and scroll-origin changes require a fresh target sample. Adapters own current DOM measurements, parsing, files/HTML transfers and normalization of additional CSS transforms. External sources supply graphs (for example from parseGraph), never executable content.

Grid snapping inherits the editor unless overridden. Opt-in visible node-frame centre/corner snapping uses a CSS-pixel radius and deterministic ties; empty anchors disables it. snapBypassed: true on a target disables both rules. Snap feedback exposes raw/resolved points and a typed anchor when attracted. It does not imply collision avoidance or automatic connections.

Set parentId on a target for explicit group membership. Only fragment roots attach; internal relationships and authored bends are remapped/translated, with world coordinates preserved. By default all inserted nodes must fit and roots receive parent containment. constrainToParent: false permits unconstrained membership. No existing group is resized. A missing, hidden or collapsed parent blocks with a reason.

Pass the current ZlozPlacementPolicy to both preview and Apply. canPlace receives source metadata and the complete remapped proposal; existing canInsertPattern, connection/port and selection policies remain composed. Read-only/busy/Undo-disabled states reject without changing the editor. The source kind/ID and preview request grant no authority. Candidate copies are detached; mutating a preview cannot change the captured source or authorize an altered Apply.

Placement state is ephemeral; canonical graph/snapshot/model v1 formats remain unchanged. Native/custom palette, pointer/touch and keyboard UI adapters follow this headless slice.

Native and custom placement palettes

The Effect UI adapter composes the headless placement controller. Each catalogue entry supplies a stable ID, label and normalized placement intent.

import { resolvePlacementControls, updatePlacementControls } from '@opsydyn/foldkit-zloz';
import {
  graphSurface,
  placementHost,
  placementPalette,
  placementPreview,
} from '@opsydyn/foldkit-zloz/effect-ui';

const result = updatePlacementControls(model.placement, context, entries, input, policy);
const controls = resolvePlacementControls(model.placement, context, entries, policy);
const palette = placementPalette(h, controls, onPlacement, {
  ...diagnostics,
  entryClass: 'my-palette-card',
  renderEntry: (entry, builder) => builder.strong(entry.label),
});
const canvas = graphSurface(h, model.editor, {
  id: 'placement-canvas',
  label: 'Diagram',
  onInput,
  worldOverlay: placementPreview(h, controls) ?? null,
});
const view = placementHost(h, controls, onPlacement).children(palette, canvas);

One stable placementHost contains one canvas and its palette. It scopes the Live input resource and releases listeners/capture on unmount. Cards use native buttons with shared pointer and keyboard behavior. Drag with mouse/touch, or activate a card then tap the canvas. Releasing inside applies once; outside retains the pending placement. Escape, pointer cancellation/lost capture and window blur cancel without Undo. A plain card click keeps the centre preview available.

Keyboard activation previews at the measured canvas centre. Arrows move, Shift accelerates, Alt bypasses snapping, Enter places, Escape cancels. Apply/Cancel buttons provide explicit alternatives. Sidebar controls and editable fields keep their native keys. Unmeasured/stale projections reject; use a new target or restart. PlacementAccepted pins targetRevision so old controls cannot accept new targets.

canStartPlacement protects catalogue activation. Position-dependent canPlace and existing insertion/connection/port policies stay live at preview/Apply. A removed catalogue entry does not revoke an already captured intent; express that in the live Apply policy. Change scope on editor/controller replacement; placementForScope explicitly returns a fresh session when scope changes.

Compose placementPaletteEntry and placementAction for custom layouts. An internal frame retains touch behavior when button styles are replaced. The palette supports custom entry/status renderers (undefined falls back; null omits). placementPreview is decorative world-space artwork; use the public preview context to draw other shapes. Instructions and position/snap measurements respect passed diagnostics; protection reasons and controls remain available in minimal mode. The host chooses whether to render any part at all.

The browser adapter measures canvas origin for every pointer sample. Additional CSS transforms, native file/DataTransfer parsing and IO belong to the host; this is a normalized graph placement contract, not an OS drag-and-drop parser. No graph wire format changes. The workbench demonstrates native/custom cards and shared C4/DDD placement with live protection and one Undo.

SVG export planning

planSvgExport defines the package-owned boundary before file writing or PNG:

import { planSvgExport } from '@opsydyn/foldkit-zloz';

const plan = planSvgExport(
  { graph, viewport },
  {
    title: 'Order platform',
    description: 'Canonical architecture model',
    region: { type: 'model', padding: 24 },
    scale: 1,
    theme: { colorScheme: 'dark', tokens: { edge: '#98beff' } },
    background: { type: 'transparent' },
    font: { family: 'Inter', size: 14, weight: 400 },
    renderers: { nodes: 'built-in', edges: 'built-in' },
  },
);
// Review plan.findings. `reviewable` is a plan, not an emitted or qualified SVG.

Use { type: 'viewport', size: { width, height } } with an explicit camera for a CSS-pixel viewport crop, or { type: 'bounds', bounds: { x, y, width, height } } for a world-space crop. Viewport output dimensions retain surface pixels times scale; its world viewBox accounts for pan/zoom. All graph items remain available for crossing edges and clipping. These are canonical-model crops, not live DOM, filtered/collapsed UI or transient layout-route snapshots.

Model bounds include authored node/group boxes, edge bends and declared custom SVG bounds, then add padding. Empty models use a 1×1 world artboard. Automatic bounds are explicitly estimated: labels, strokes, port artwork and custom curves can extend beyond them. Font substitution, wrapping and ink bounds are unverified. A later writer must qualify actual files. Explicit crops are not silently enlarged.

Themes resolve shared light/dark colors into an export-specific paint subset and numeric edge width. Background is theme, transparent or { type: 'color', value: '#ffffff' }. Supported paints are literal hex, none, transparent, and space-separated numeric rgb(...) with optional alpha. Resolve CSS/Pleat variables before planning; host-dependent or unsupported values block with reasons. This contract reproduces declared paint inputs, not arbitrary host CSS. Title/description and graph labels remain literal text for a future writer to escape safely.

Renderer coverage is mandatory because core cannot infer custom UI from graph data. Node declarations cover body/port/badge artwork; edge declarations cover paths, labels and markers. Host-only overlays are outside this canonical-model contract. Use unknown for undeclared node/edge coverage. Override known items explicitly:

const renderers = {
  nodes: 'unknown',
  edges: 'built-in',
  overrides: [
    {
      target: { kind: 'node', id: 'orders' },
      renderer: {
        type: 'svg',
        id: 'orders-card',
        version: '1',
        bounds: { x: 0, y: 0, width: 240, height: 160 },
        fidelity: 'approximate',
        reason: 'Interactive HTML editor becomes static text',
      },
    },
  ],
} as const;

A svg declaration remains unverified, including declared equivalent fidelity; approximate adds a loss finding. fallback, omit and unsupported take visible reasons. Omission is per graphic; it does not remove graph nodes or rewrite their connections. Connections to omitted nodes receive a separate finding. Duplicate or missing override targets reject. These are adapter declarations, not executable SVG/HTML callbacks or proof that a renderer exists.

Declare image/font/stylesheet assets with id, kind and availability (embedded, external, missing). External/missing resources block; embedded resources still need byte/resource qualification. font.assetId must name a declared font asset. The planner never fetches resources or reads installed fonts.

Findings identify document/item/theme/asset, code, severity and reason. Unsupported findings make the plan blocked; other plans are reviewable, retaining all loss and uncertainty reports. Plans detach inputs and preserve editor/history. They are ephemeral, with no graph wire-version change. The bounded writer below implements SVG serialization. Reusable review/download controls are described below; broader visual qualification and PNG remain subsequent work.

Standalone SVG writing

import { writeSvgExport } from '@opsydyn/foldkit-zloz';

const result = writeSvgExport(snapshot, exportOptions, {
  idPrefix: 'orders-diagram',
  allowLosses: false,
});
if (result.type === 'written') {
  // result.svg is standalone XML. Use a host Command/CLI adapter to save/download it.
  // Review result.findings, including unverified bounds/fonts and custom fidelity.
}

The writer rebuilds its plan from current inputs. Blocked results contain no SVG; losses need explicit allowLosses: true. A written file retains all uncertainty findings and does not claim DOM parity. Canonical group/node outlines, ports/labels, connections/arrows, authored bends and node architecture metadata use shared geometry and paints. Dimensions, background and clipping follow the chosen export region. DDD/EventStorming edge notation and side-role artwork require an adapter or explicit semantic-edge-fallback loss acknowledgement; a plain arrow is not semantic parity. Editor, camera and Undo remain unchanged. Title/description and all text/identifiers are escaped, and characters XML cannot represent block output.

Bind custom SVG declarations with adapters: [{ id, version, render }]. Exact ID/version must match. The frozen context discriminates kind: 'node' with node, or kind: 'edge' with edge, source and target; both include resolved theme and font. Render in world coordinates, returning a non-empty array of ZlozSvgPrimitive. Adapters replace the complete item, including custom port/label artwork. They must be pure synchronous host functions; the package does not sandbox arbitrary code.

Primitives support rect, circle, line, polygon, polyline, text and translated groups. Paints are supported literals; opacity, stroke width, coordinates and dimensions are validated. Text supports newlines, anchor, size and weight. Unknown fields/tags, raw markup/CSS/paths, URL paints and active/HTML content reject rather than silently omitting content. Use a declared omit for intentional omission. Mutation or callback failure blocks atomically; read result.findings for writer-level reasons.

Embedded declarations alone are insufficient: selected TrueType fonts need validated byte resources (below); images and stylesheets remain unsupported. No fetching or foreignObject is used. Font substitution, wrapping and ink bounds remain unverified. Defaults are 10,000 drawing primitives, depth 32 and 2,000,000 output UTF-16 code units, configurable through maxPrimitives, maxDepth and maxCharacters. These are output/recursion limits, not a peak-memory or rendering-speed claim. Supply unique XML-safe idPrefix values for multiple inline exports. The default prefix is suitable for separate standalone files.

Representative emitted files and browser captures are linked in the writer evidence. Resource embedding and PNG remain subsequent work.

SVG review and download controls

Core exports createSvgReview(scope), svgReviewForScope(state, scope), resolveSvgReview(state, context) and updateSvgReview(state, context, request). The context supplies the snapshot, a source revision, title, literal theme and renderer fidelity declarations. Optional catalogs configure model/viewport/custom bounds, themes and backgrounds; canDownload returns a live protection reason or null. Advance sourceRevision on every edit and Undo, or use unique immutable snapshot IDs. Use a fresh scope for each model/controller incarnation.

import { createSvgReview, resolveSvgReview, updateSvgReview } from '@opsydyn/foldkit-zloz';
import { svgReview } from '@opsydyn/foldkit-zloz/effect-ui';

const review = createSvgReview(context.scope);
const controls = resolveSvgReview(review, context);
const view = svgReview(h, controls, onReviewRequest, { idPrefix: 'diagram-svg', diagnostics });
// In update, always pass current inputs, rather than a cached controls projection:
const next = updateSvgReview(review, context, request);
// Publish next.state. Only next.payload authorizes a host Command to download its
// captured svg/fileName; report SvgDownloadSettled with its scope/generation/key/run.

Final writer findings stay visible. Unsupported output blocks download; reported losses need explicit acceptance for the exact source revision, options, bytes and findings. Settings, edit then Undo, viewport changes or changed adapter output clear approval. Whole-model camera motion does not. Live protection can deny download without revoking approval of unchanged content. Review is a host workflow, not an access-control boundary. Keys are exact strings; large-model recomputation costs remain unqualified. IO never edits the model or creates an Undo entry.

svgReview includes labeled native choices, a static SVG image preview, findings, loss checkbox, guarded download and visible status. Use renderLayout to compose these elements and renderFinding to customize individual findings. Supply distinct idPrefix values for concurrent widgets. The controller still enforces approval regardless of presentation. Diagnostic instruction/measurement settings hide optional prose/readouts, retaining findings and functional controls.

See workbench evidence and ADR 0054. Browser completion means handoff, not confirmed OS saving. Broader font formats/resources remain open. PNG is implemented below; Alchemy Domain has a separate integration review.

Embedded TrueType fonts

Supply trusted single-face TrueType sfnt bytes through fontResources, binding the selected font.assetId to an asset declared as an embedded font:

import { validateSvgFontResource, writeSvgExport } from '@opsydyn/foldkit-zloz';

const resource = { assetId: 'inter', format: 'truetype', bytes: fontBytes } as const;
const validation = validateSvgFontResource(resource);
if (validation.type === 'invalid') {
  console.log(validation.code, validation.reason);
}
const result = writeSvgExport(
  snapshot,
  {
    ...exportOptions,
    font: { family: 'Inter', size: 14, weight: 400, assetId: 'inter' },
    assets: [{ id: 'inter', kind: 'font', availability: 'embedded' }],
  },
  { fontResources: [resource], maxFontBytes: 1_048_576 },
);
// Read final result.findings. The writer revalidates bytes on every call.

Validation checks bounded file/directory structure, aligned non-overlapping table ranges, checksums, required table sizes and basic header/glyph-location consistency. A valid result exposes byteLength, tableCount, the OS/2 weight and a copied, encoded dataUrl. It is structural evidence, not a font sanitizer or proof of correct glyph programs, layout tables, browser decoding, coverage, shaping or ink bounds. Use trusted fonts you may distribute. Restricted/bitmap-only embedding flags reject; flags alone do not grant a license.

Default byte budget is 1 MiB per face; maxBytes (validator) / maxFontBytes (writer) must be safe integers from 1 to 16 MiB. The total SVG maxCharacters limit also includes base64 font data. Source bytes are copied before validation and encoding, including Buffer inputs and views with nonzero offsets. No IO, installed-font discovery, URL fetching or decompression occurs.

Only the selected declared embedded font can bind one resource. Missing bytes, duplicates and undeclared/unreferenced resources block with asset-targeted font-resource-missing / font-resource-unexpected findings. Invalid structure, unsupported formats and exceeded byte budgets produce font-resource-invalid, font-format-unsupported and font-resource-limit respectively. No partial SVG is returned, and loss acceptance cannot override these failures.

The initial format excludes WOFF/WOFF2, collections, CFF, variable and color/bitmap fonts. Successful output uses a generated family and package-owned @font-face with a data:font/ttf;base64 source and the face's declared weight. No host family string, font name metadata, raw CSS or URL is inserted into the style block. Use distinct idPrefix values when embedding several SVGs inline so their generated font families and fragment IDs stay distinct. Style selection/synthetic weights and metrics remain unverified in findings. Changed bytes participate in the existing exact-artifact review identity, so prior loss approval cannot authorize a different embedded font.

See ADR 0055 and font qualification. PNG is implemented below; Alchemy remains separately scoped.

Default glyph coverage

inspectSvgFontCoverage(resource, text, { maxBytes?, maxCharacters? }) validates and owns font bytes, then checks a default Unicode cmap. The result is checked, unverified or invalid. Checked results expose format (4 or 12), the count of unique checked scalars, sorted missingCodePoints and unverifiedCodePoints.

import { inspectSvgFontCoverage } from '@opsydyn/foldkit-zloz';

const coverage = inspectSvgFontCoverage(resource, 'Orders 漢😀');
if (coverage.type === 'checked') {
  // Unicode numbers, not UTF-16 surrogate halves. Missing glyph index 0 is a loss.
  console.log(coverage.missingCodePoints);
} else {
  console.log(coverage.reason);
}

Selection consistently prefers one full-repertoire Unicode mapping over BMP mappings, with Windows preferred over an equivalent Unicode-platform profile. Maps are not unioned. Formats 4/12 require the matching BMP/full-repertoire profile; other formats/profiles or absent Unicode maps stay unverified. Malformed selected maps produce font-cmap-invalid, including bad bounds/order/ranges/glyph indices. CR/LF/tab delimiters are excluded. Default-ignorable scalars such as joiners and variation selectors remain unverified; they are not automatically missing glyphs. Unpaired surrogates reject with font-text-invalid. Default text limit is 2,000,000 UTF-16 code units; exceeding maxCharacters returns font-coverage-limit. Invalid budget configuration throws the existing core error. Font-byte limits still apply.

The SVG writer automatically checks emitted text, including ports, architecture metadata, edges and nested custom text primitives. Omitted/replaced labels and root title/description metadata do not generate false glyph findings. Targeted font-glyph-missing findings are losses and require existing explicit acceptance. Their structured codePoints arrays retain all unique missing scalars; reasons show the first 16. font-coverage-unverified findings retain unknown sequence or mapping status. Malformed maps block even with loss acceptance enabled. All findings participate in the existing exact-artifact SVG review identity.

A default cmap mapping proves neither shaping/sequence behavior nor actual fallback font selection or successful rendering. Glyph programs, combining-mark placement, variation handling, synthetic variants, wrapping and ink bounds remain unqualified. System fonts have no portable bytes to inspect and retain unverified findings. See coverage evidence and ADR 0056. PNG is implemented below; Alchemy remains separately scoped.

Authored edge waypoints

Named world-space bends are document data, independent of transient layout routes:

import {
  createArchitecturePattern,
  createEditor,
  resolveEdgeWaypointEdit,
  updateEditor,
} from '@opsydyn/foldkit-zloz';

const waypointEditor = createEditor(createArchitecturePattern('ddd-aggregate'));
const connection = waypointEditor.graph.edges[0];
if (!connection) throw new Error('The starter requires a connection');
const request = {
  id: connection.id,
  revision: waypointEditor.revision,
  waypoints: [{ id: 'outside-boundary', position: { x: 480, y: 240 } }],
};
const preview = resolveEdgeWaypointEdit(waypointEditor, request);
// If allowed, display preview.edge without publishing it, or discard the draft.
const next = updateEditor(waypointEditor, { type: 'EdgeWaypointsChanged', ...request });

The reducer rechecks live revision, visibility, idle state, read-only/Undo settings and canChangeEdgeWaypoints(edge, next, graph). Blockers have visible reasons; accepted replacements are detached and create one Undo entry. Preview is pure; reset with waypoints: null. A non-empty list requires unique non-blank edge-local IDs and finite coordinates. Empty lists are invalid. A no-op creates no history.

Authored bends form a polyline between live port anchors and override style/layout routing. Custom geometry policies retain final control; path and arc-length label anchor are shared by default renderers, hit targets and reconnection previews. Endpoint/group movement and layout retain world-space bends; copy/paste and pattern insertion translate them with the fragment. Collapsed endpoints temporarily use projected group geometry. Minimap, fit/reveal, culling and history include bends; edition comparison treats their identity/position as layout rather than meaning.

The optional field round-trips through existing v1 graph, snapshot, model and edition codecs. Older readers can retain it, but older renderers cannot display it. Mermaid reports waypoint geometry as projection loss. Enable waypoint editing through graphSurface:

graphSurface(h, editor, {
  id: 'architecture',
  label: 'Architecture',
  onInput,
  policy,
  edgeWaypoints: { onEdit: onEditorEvent },
});

Select a connection to add, remove or reset bends. Drag a handle to preview; release publishes one Undo transaction. Escape cancels. Arrow keys move in grid steps or world units, Shift accelerates and Alt bypasses the grid, including modifier-only updates during a drag. Each keyboard action is one Undo. Delete removes the focused bend and returns focus to the canvas. A late policy veto or graph revision change cannot publish the preview; the canonical graph and exports stay unchanged until release. Additional bends split the longest authored segment rather than stacking handles at the same anchor.

resolveEdgeWaypointControls and resolveEdgeWaypointPreview are pure core APIs. Configure edgeWaypoints.render to replace the controls. Returning null hides them and returning undefined keeps the defaults. The context includes the route anchor and panel bounds. edgeWaypoints.labelOffset controls the CSS-pixel displacement of labels near a selected handle. The default is 32px above the handle. Omitting edgeWaypoints hides controls and retains authored bends.

Headless C4 and DDD nodes

The package owns architecture semantics and outline geometry independently of the Astro example. Enable C4 and DDD artwork with the canvas architecture notation option. The package also supplies composable notation and atomic pattern builders.

import {
  createArchitectureNode,
  createEditor,
  updateEditor,
  nodeShapeGeometry,
  nodeShapeContainsPoint,
  portPosition,
} from '@opsydyn/foldkit-zloz';

const store = createArchitectureNode({
  id: 'orders-store',
  label: 'Orders',
  position: { x: 40, y: 40 },
  size: { width: 200, height: 120 },
  ports: [{ id: 'out', kind: 'output', side: 'right', offset: 0.5 }],
  architecture: {
    family: 'c4',
    role: 'container',
    technology: 'PostgreSQL',
    description: 'Stores accepted orders',
    scope: 'internal',
  },
  appearance: { shape: 'cylinder' },
  data: { owner: 'sales' },
});
const geometry = nodeShapeGeometry(store); // local SVG outline and content bounds
const endpoint = portPosition(store, 'out'); // canonical world coordinates
const hit = nodeShapeContainsPoint(store, endpoint); // inclusive world-space hit test
const editor = createEditor({ nodes: [store], edges: [] });
const changed = updateEditor(editor, {
  type: 'NodeArchitectureChanged',
  id: store.id,
  architecture: { family: 'ddd', role: 'repository' },
});
const restored = updateEditor(changed, { type: 'UndoPressed' });

ZlozNodeArchitecture is a discriminated union. C4 roles are person, software-system, container, component; only containers/components carry technology. DDD roles are entity, value-object, aggregate-root, aggregate, domain-event, domain-service, repository, bounded-context. Bounded contexts may classify their subdomain as core, supporting or generic. These are diagram semantics, not domain identity or executable business invariants. architectureNodePresets is a frozen typed catalogue of names and default shapes.

createArchitectureNode validates/detaches a standalone node and picks a catalogue shape when omitted. Supply IDs, dimensions, ports and kind yourself. An aggregate must be a portless group. Groups can represent C4 system/container and DDD aggregate/context boundaries; group shapes remain rectangular. A context-map bounded context can instead be a normal port-bearing node. Assemble parenting with a complete graph, rather than referencing missing parents in the factory.

architecture and appearance are optional node fields; consumer data is untouched. A role alone does not alter geometry. appearance.shape explicitly chooses rectangle, rounded-rectangle or cylinder. A Person preset uses a rounded card; a person adornment is future renderer artwork. Semantic changes preserve the selected shape. NodeAppearanceChanged edits the outline, and null on either change event removes that descriptor. Both use read-only/gesture gates, one-step Undo, revision/route invalidation and independent host policies:

import type { EditorPolicy } from '@opsydyn/foldkit-zloz';

const policy: EditorPolicy = {
  canChangeNodeArchitecture: (node, next, graph) => null,
  canChangeNodeAppearance: (node, next, graph) => 'Keep the approved notation',
};

Callbacks receive current and validated proposed nodes plus the current graph. Returning a reason vetoes the whole change. Exact no-ops do not publish a new revision/history; malformed descriptors throw ZlozError before commit.

nodeShapeGeometry returns local bounds, contentBounds and outlinePath; render the outline in that authored coordinate system. Rounded corner radius is min(12, width/2, height/2); cylinder cap radius is min(16, width/4, height/4). Its safe content sits between both cap interiors and can be empty at tiny sizes. nodeShapeBoundaryPoint(node, side, offset) projects onto the same outline in world space. Layout, marquee and grouping keep the rectangular authored envelope; nodeShapeContainsPoint is an optional precise outline hit test. No DOM state or renderer registry is persisted.

portAnchor(port, node) resolves default side/offset ports onto the selected outline. Omit the node to retain legacy rectangular normalized coordinates. Explicit port.anchor always wins, including after a shape change or resize. portBoundaryPosition projects along the routing hint onto the selected outline; ELK rejoins authored anchors and force routing leaves the conservative envelope before corridor search. Native/custom port contexts and anchor controls use the same canonical coordinates. Snapping continues to author envelope coordinates; it does not automatically constrain explicit anchors to a curved outline.

PortAnchorReset restores the same side at offset 0.5 through the existing canEditPort position policy and Undo. Hiding optional controls does not disable these package APIs or protection rules.

Version 1 documents accept the new optional descriptors and validate their reserved fields strictly. Literal old/new fixtures and the pinned pre-contract core (ce978a2) qualify retention through legacy rename/move/copy/paste/Undo and export. Older code retains the fields but uses generic rendering and rectangular geometry. Other serializers are not covered by that qualification. Run bun tools/check-zloz-architecture-compat.ts from this repository to repeat the pinned-core check. No migration or registry publication occurs here.

DDD notation

import { graphSurface } from '@opsydyn/foldkit-zloz/effect-ui';

const canvas = graphSurface(h, model.editor, {
  id: 'domain',
  label: 'Ordering domain',
  onInput: (event) => Message.ObservedZlozInput({ message: event }),
  architectureNotation: true,
  notationParts: {
    renderBadge: ({ architecture }, h) =>
      architecture.family === 'ddd' && architecture.role === 'aggregate-root'
        ? h.span.children('Consistency owner')
        : undefined,
  },
});

DDD notation renders entities, value objects, aggregate roots, aggregates, domain events, domain services, repositories, bounded contexts and read models. Aggregate and bounded-context groups are portless boundaries. Ordinary bounded contexts can connect through their ports and display their subdomain classification. Authored appearance controls geometry. Use notationParts for inert artwork and node or group shells for interactive controls.

C4 notation

import { graphSurface, zlozLightTheme, zlozDarkTheme } from '@opsydyn/foldkit-zloz/effect-ui';

const canvas = graphSurface(h, model.editor, {
  id: 'architecture',
  label: 'Order platform · system context',
  onInput: (event) => Message.ObservedZlozInput({ message: event }),
  architectureNotation: true,
  theme: model.dark ? zlozDarkTheme : zlozLightTheme,
});

The canvas draws C4 Person, Software System, Container and Component nodes and portless system/container group boundaries. Nodes without architecture retain the standard presentation. External scope uses text and dashes. Cylinders use the headless outline, decoration paths and authored bounds for paint and ports.

Use notationParts to customize inert content in the selection button. Its NativeNotationContext includes the node, its architecture, selection, and selection preview. Returning undefined keeps the default part and returning null omits it. The selection button keeps the authored node name. Supply stable callbacks and options to retain eligible artwork across updates. Ports and canvas controls use the current editor state and policies independently.

Use renderNodeShell or renderGroupShell for classes, paint and interactive content alongside the native selection button. Set controls: false in the returned shell to hide collapse, context and resize controls while keeping ports. groupHeader: (node) => spec accepts declared layout geometry or an intrinsic measurement spec. Expanded groups use that geometry and collapsed groups keep their compact headings. Use groupHeaderMeasurementProbe for intrinsic layouts.

The Astro workbench’s Open C4 system context and Open C4 container view buttons demonstrate the abstraction levels and the container view’s curved data-store anchor.

Effect UI canvas and migration

import { graphSurface } from '@opsydyn/foldkit-zloz/effect-ui';

import '@opsydyn/foldkit-zloz/effect-ui.css';

const canvas = graphSurface(h, editor, {
  id: 'workflow',
  label: 'Workflow editor',
  descriptionId: 'workflow-help',
  onInput: (input) => Message.ObservedCanvasInput({ input }),
  policy,
  resizeHandles: true,
  architectureNotation: true,
  edgeEditing: { onEdit: (event) => Message.ObservedEditorEvent({ event }), toolbar: true },
});

Map delegated BrowserInput facts to host messages and apply them through updateEditor with the current policy. The host owns the document, viewport, policies and any Commands used for layout or persistence. Use a document-unique canvas ID and provide a bounded container. The canvas measures its surface and owns its browser subscriptions.

| Earlier adapter feature | Effect UI API | | ------------------------------------------ | -------------------------------------------------------------------------------- | | graphSurface and monolithic layout slots | graphSurface and host-owned layout | | Node and group renderers | architectureNotation, notationParts, renderNodeShell, renderGroupShell | | Node and socket artwork | renderNodeShell and renderPort; the canvas owns input bindings and positions | | Canvas navigation and minimap | viewportControlActions, viewportControl, historyMinimap | | Connection and reconnection choosers | resolveConnectionCreation, resolveEdgeReconnection, endpointField | | Edge labels, actions and waypoints | edgeEditing, contextActions, edgeWaypoints | | Port anchors, guides and labels | portAnchors, portLabels, renderPortLabel | | Help, diagnostics and status | canvasHelpContext, resolveZlozDiagnostics, canvasStatusContext | | Rendering retention | Effect UI retains keyed controls and memoizes eligible artwork in the component | | Layout measurements | labelMeasurementProbe and groupHeaderMeasurementProbe |

App-specific buttons and panels send typed requests to the host. Add data-flow-no-drag to interactive world overlays so that native controls keep their keyboard and pointer behavior. See the ZLOZ demo adapter for input routing, clipboard, editing, layout, and accessible controls in one host.

Optional layout

Create a layoutRequest(editor, uniqueRequestId), store it as the active request, then run your chosen LayoutEngine in a Command. On completion pass the current active request to applyLayout(editor, active, result). The result is accepted only if the request ID and revision still match and no gesture is active. Clear the active request when loading/replacing a document; request IDs must not be reused while old results can still arrive. Rendering never starts layout work.

Manual positioning has no layout dependency. The adapter receives a detached snapshot; it cannot mutate the Model. All node positions are required exactly once. Routes are optional, keyed by edge ID; node movement invalidates them and the view uses straight lines until another arrange result is applied.

Example and checks

Run bun run --filter @opsydyn/zloz-demo dev for the Effect UI workbench. It demonstrates endpoint search and connection creation, context actions, read-only history, custom artwork, port inspection and layout measurement.

  • Use endpointField with a current creation or reconnection context. Set search to bind a host-owned query, and use groupByNode and groupLabel to customize option groups. Protected choices retain their reasons.
  • Use portInspectorContext and portAdditionContext with the current policy for independent label, position and removal decisions. Use portPositionDraft, updatePortPositionDraft, portPositionFromDraft and portPositionInput for a host-owned draft.
  • Enable port editing affordances with portAnchors. Options include guides, keyboardTargets, snapBypass, renderHandle, and renderGuide. Anchor snap settings and current policy still come from the editor and host.
  • Customize labels using portLabels, portLabelPlacement, and renderPortLabel. Default labels are decorative and use the authored port center. Ports keep their independent accessible names.
  • Use scoped themes via theme and the light and dark presets. Place custom diagrams and controls under the same CSS theme if they share tokens.

For the retired adapter's examples, see the pre-cutover package reference.

Per-node resize limits

Set optional resizeLimits on a node to customize manual resizing in graph units:

resizeLimits: { minWidth: 180, maxWidth: 520, minHeight: 120, maxHeight: 400 }

Each supplied limit must be finite and positive; a minimum cannot exceed its maximum. Partial limits are supported and survive save/load, clipboard and Undo. Cards apply width limits to pointer handles and NodeWidthChanged; card height continues to follow content. Groups apply both axes through pointer handles, GroupResizeNudged and width edits. When proportions are unlocked, only edited axes change. Group contents and parent containment can prevent a resize when there is no valid size. Existing nodes may start outside their limits; their next manual edit clamps the edited axis. Layout, Fit group to contents, measurements and ancestor expansion remain independent of manual resize limits. Omitting the field preserves default ranges.

Lock group proportions

Set keepAspectRatio: true on a group, or dispatch GroupAspectRatioToggled with its id. The package context panel offers Lock proportions; the sample also shows it beside Fit group to contents. The toggle is saved, copied and undoable. Cards cannot declare this field because their height follows content.

Manual pointer, keyboard and width edits then scale both dimensions together from the group's current proportions, keeping children fixed. Corner handles anchor the opposite corner; side handles anchor the opposite edge and preserve the perpendicular center. Corner resizing follows the larger proportional axis change. The scale is bounded by both dimensions' resize limits, contents and parent extent; conflicting bounds leave the graph unchanged. Escape cancels a pointer drag, and releasing commits once. Repeated edits at a bound do not add Undo entries. Layout and explicit fitting can establish new proportions for the next resize.

Pointer NodeResizeStarted and keyboard GroupResizeNudged accept an optional handle: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top' | 'right' | 'bottom' | 'left'. The existing corner field remains supported; handle takes precedence when both are supplied. Omitting both preserves bottom-right behavior. delta follows the moving handle's canvas direction: moving a left handle right shrinks width; moving a top handle down shrinks height. Pointer positions remain surface CSS pixels, with zoom handled by the reducer. Top handles reserve 48 units above contents for the group header; other moving boundaries reserve 24. Existing tighter bounds are preserved.

Side handles ignore perpendicular pointer movement and keyboard arrows. With proportions locked, the dragged axis drives both dimensions and the perpendicular center stays fixed. Limits, content padding and parent bounds apply to the full result, including the centered dimension. A conflicting intersection is a no-op.

Background grids

Set the canvas background to { type: 'dots' }, { type: 'squares' }, or { type: 'none' }. Presets use editor grid spacing unless an explicit positive gap is supplied. A custom background receives the surface ID, viewport, dimensions, and spacing through its renderer. Canvas snapping continues to use the editor's current grid settings.

Shared grid spacing

Initialize createEditor(graph, { gridSpacing: 32, snapToGrid: true }), or dispatch { type: 'GridSpacingChanged', spacing: 32 }. Spacing must be finite and positive; fractional units are supported. Invalid initialization throws; invalid, redundant, read-only or active-gesture changes are ignored. Changing spacing does not move nodes, change revision or add an Undo step. Undo/Redo retain the current preference.

Node drag snapping, group boundary snapping, resize keyboard steps, default dots and squares, and custom renderer context.spacing share the setting. Resize keys move one interval, or four with Shift, while snapping is enabled. Duplicate/paste placement offsets use two grid intervals. Explicit background gap remains an independent visual override. Grid spacing is editor session state, excluded from graph JSON; hosts can persist preferences separately. The sample retains it when switching examples and loading/importing diagrams.

Resize alignment guides

Enable snapToAlignment (the sample's Snap to nodes) for magnetic group resizing. Pointer drags align moving edges to nearby visible card edges and collapsed group edges within six screen pixels. Expanded boundaries and the resized group's descendants are excluded. Corner handles can align both axes; side handles align their moving axis. Keyboard sizing keeps its existing steps.

Alignment overrides the grid only on a matching axis. With locked proportions, the closest matched edge drives uniform scaling. Content, parent and size limits remain authoritative: a guide is shown only if the resulting edge reaches its target. Guides live in the resize gesture, clear when leaving the target, and vanish on release or Escape. A completed resize remains one Undo step. The Effect UI canvas draws them using the existing --flow-alignment-guide token.

Use renderAlignmentGuide(context, h) to replace the decorative SVG for either drag or resize guides. The context provides the resolved guide, start and end in graph coordinates, the gesture phase, and the viewport. Use the supplied endpoints so the decoration follows the snap result.

renderAlignmentGuide: ({ start, end }, h) =>
  h.line([
    h.X1(String(start.x)), h.Y1(String(start.y)),
    h.X2(String(end.x)), h.Y2(String(end.y)),
    h.Stroke('#0f766e'), h.StrokeWidth('2'),
    h.Style({ 'vector-effect': 'non-scaling-stroke' }),
  ], []),

Return undefined for the default dashed guide or null to omit it. ZLOZ calls the hook only for resolved guides when the effective alignmentGuides diagnostic is enabled. Guide visibility is independent of snapping.

Lock node movement

Pass canMoveNode(node, graph) in EditorPolicy to allow or block dragging and keyboard nudging. Return null to allow a node to move, or a reason to block it. A move checks the entire selection, including descendants of groups. One locked node blocks the whole move. A drag uses the graph as it was at the start of the gesture and checks the policy again before committing. Pass the same callback to graphSurface to expose the lock on node handles. Custom shells receive moveDisabledReason. The canvas keeps selection available.

Lock node dimensions

Pass canResizeNode(node, graph) in EditorPolicy to restrict explicit resizing. Return a reason to block an edit or null to allow it. The policy covers pointer resizing, keyboard resize steps, direct dimension edits, and Fit group to contents. If an edit would also grow an ancestor with locked dimensions, ZLOZ rejects the whole edit.

Pass the same callback through the canvas policy option to hide locked resize handles and disable group dimension controls. Custom node shells receive resizeDisabledReason. Movement permissions apply separately.

Control which items can be selected

Pass canSelectNode(node, graph) or canSelectEdge(edge, graph) in EditorPolicy. Return null to allow selection or a reason to exclude the item. ZLOZ checks direct selection and interactions that select an item, such as opening its context menu. An excluded group can still contain individually selectable nodes.

Pass the same callbacks through the canvas policy option so selection controls and the marquee preview agree with the reducer. Excluded items remain visible. Custom node shells, connection rows, and edge labels receive selectionDisabledReason. These callbacks govern new selection attempts. To clear a selection after changing the policy, send SelectionCleared.

Fit the selection

Set fitSelectionControl: true with viewportControls: true to show Fit selection. Custom viewport controls can render context.actions.fitSelection with viewportControl. The action emits { type: 'FitSelectionClicked' }.

Fit selection frames selected visible nodes and connections together. For edges, it uses the displayed endpoint bounds and any stored route used by the built-in path. A collapsed endpoint uses its group boundary. The camera follows the configured padding, zoom limits, and Fit view animation, including reduced motion. Selection and undo history are preserved. Custom SVG geometry can extend outside the fitted bounds.

Zoom to an area

Set zoomAreaControl: true with viewportControls: true to show Zoom to area. Custom viewport controls can use context.actions.zoomArea with viewportControl. The action emits ZoomAreaModeToggled. The next background drag fits its rectangle and returns to the previous canvas mode. Each side must span at least 5 CSS pixels. Escape on the canvas or the pressed control cancels.

The fit uses the configured padding, zoom limits, animation, and reduced motion behavior. It works in read-only views and preserves selection and undo history. Use renderZoomAreaMarquee(context, h) to paint the preview inside ZLOZ's pointer-inert frame. The context provides normalized world bounds and the viewport. Return undefined for the default or null to hide the decoration.

Back to previous view

Set previousViewControl: true with viewportControls: true to show Back to previous view. Custom controls can use context.actions.previousView with viewportControl, or send { type: 'PreviousViewClicked' } directly.

ZLOZ keeps one session checkpoint. Fit view, Fit selection, Zoom to area, and node or connection reveal capture the camera before moving it. Manual pan and zoom leave the checkpoint available. Back uses it once, respects the current zoom limits and reduced-motion preference, and works in read-only views. It preserves the current selection, group expansion, graph, and undo history. Snapshots save the current camera only.

Reveal a node

Send { type: 'NodeRevealRequested', id } to center a node. ZLOZ keeps the current zoom when the node fits and zooms out as needed within the active limits. It expands collapsed ancestors and uses the existing Fit view timing, including reduced motion. Graph edits, selection, and history are separate from this camera action.

Use revealableNodes(state) to populate a search or navigation control. It includes nodes inside collapsed groups and filters explicitly hidden nodes and descendants. Reveal requires a measured canvas and an idle gesture, and works in read-only mode.

Reveal a connection

Send { type: 'EdgeRevealRequested', id } to frame both endpoint nodes and the stored route when the edge uses it. ZLOZ opens collapsed ancestors of the endpoints, preserves selection and history, and uses the same zoom and timing rules as node reveal. The frame uses authored endpoint bounds and stored route points. Custom SVG path extensions can extend beyond that frame.

Use revealableEdges(state) for connection search. It includes edges inside collapsed groups and excludes explicitly hidden edges or edges with hidden endpoints.

Save the camera with the graph

Call serializeSnapshot({ graph, viewport }) to include pan and zoom in a version 1 document. parseSnapshot(text) validates the graph and any camera it contains. For graph-only documents, the returned snapshot omits viewport. serializeGraph and parseGraph continue to read and write the graph on its own.

const saved = serializeSnapshot(editor);
const { graph, viewport } = parseSnapshot(saved);
const reopened = createEditor(graph, viewport ? { viewport } : {});

Snapshots include the authored graph and optional camera. Selection, undo history, routes, and active gestures are session state. The viewport must have finite pan coordinates and a positive finite zoom. Hosts using custom zoom limits can bound the saved zoom before initializing the editor.

Retain artwork while controls stay live

Effect UI uses stable node and control identities by default. For expensive custom artwork, use the host builder's lazy with a stable key and all authored inputs the artwork reads. Keep policies and current port feedback in the live shell and socket options. A staged source stays mounted under culling until creation or cancellation.

Cull canvas items outside the viewport

Set viewportCulling: true on graphSurface to mount canvas items near the measured viewport. The default is off. Use { overscan: 96 } to customize the buffer in CSS pixels. Before the surface is measured, the whole canvas renders.

Focused and selected items stay mounted, along with active gesture items. Built-in edge bounds include crossing edges and routes. Authored edge labels and edges with custom geometry or drawing hooks stay mounted so their content can extend beyond the default bounds. Custom node shells can choose more overscan for content that extends outside their node frame. Offscreen shells can remount as the camera moves, so keep their durable state in the Model. The tab order includes mounted canvas controls.

Fit view, the minimap, the Connections list, world overlay inputs, and graph operations still use the full visible graph.

Hide nodes and edges

Use createEditor(graph, { visibility }) for initial visibility and send VisibilityChanged to replace it during the session. Omit either list to show those items again.

const next = updateEditor(state, {
  type: 'VisibilityChanged',
  visibility: { hiddenNodeIds: ['review'], hiddenEdgeIds: ['optional-link'] },
});

Hiding a node hides its incident edges. Hiding a group also hides its descendants. Collapsed groups still project edges between visible boundaries. The canvas, minimap, Connections list, Fit view, and marquee use the same visible items. Changing visibility clears hidden selections and cancels in-progress gestures. The underlying graph, exports, and Undo history retain the authored items. Use editor policies to restrict edits to graph data.

Protect nodes and edges from deletion

Pass a pure canDelete callback in EditorPolicy to updateEditor. It receives the nodes and edges that would be removed, including selected groups' descendants and incident edges, and the original graph. Return a reason to reject the entire deletion or null to accept it. A rejection sets the editor notice and preserves the graph, revision, and Undo/Redo history. Accepted deletions use the existing transaction boundary.

const canDelete: NonNullable<EditorPolicy['canDelete']> = ({ nodes, edges }) =>
  nodes.some((node) => node.id === 'required-step') ||
  edges.some((edge) => edge.id === 'required-link')
    ? 'This workflow step or connection is required.'
    : null;

const next = updateEditor(state, event, { canDelete });
const view = graphSurface(h, next, {
  id: 'workflow',
  label: 'Workflow',
  onInput,
  policy: { canDelete },
});

Pass the same callback through the canvas policy option for disabled Delete actions and their reason in the built-in context panels and edge toolbar. Custom controls can read disabledReason from the action descriptors or call resolveDeletion with their own targets. The policy may run during rendering and again when the editor handles a deletion, so keep it synchronous and pure. The host decides how to identify required items.

Box selection matching

Full containment is the default. To include cards that overlap only part of the marquee, initialize the editor with boxSelectionMatch: 'partial' or send { type: 'BoxSelectionMatchChanged', match: 'partial' } while idle. The setting applies to both Shift-drag and Box select. It belongs to the editor session and is separate from the saved graph and Undo history.

Partial matching requires positive-area overlap. Touching an edge or drawing a zero-area rectangle selects no items by overlap. Expanded group frames still require full containment, so a marquee inside a group can select its children independently. Collapsed groups match using their visible bounds, and hidden descendants stay excluded. Selection is applied on release.

Live box-selection preview

While drawing a marquee, ZLOZ highlights the nodes that would be selected on release. The preview uses the same match rule, collapsed-group projection, and ancestor selection as the final selection. Pressed states and selection actions continue to reflect the committed selection until release. Escape clears the preview and keeps the prior selection.

Custom node and group shells receive selectionPreview for their own highlight styling. Set selectionPreviewHighlights: false to disable node highlights. The marquee hook still receives previewNodeIds so a host can show its own feedback. Preview remains available in minimal mode.

Custom box-selection marquee

Use renderSelectionMarquee(context, h) to replace the decoration during a box-selection gesture. The context contains normalized bounds in graph coordinates, the current viewport, the matching rule, and previewNodeIds. ZLOZ positions and sizes the frame using the same bounds as selection on release. Use decorative content that fills the frame.

renderSelectionMarquee: (_, h) =>
  h.div([h.Style({
    position: 'absolute',
    inset: '0',
    border: '2px dashed #0f766e',
    background: 'rgb(20 184 166 / 0.15)',
  })], []),

Return undefined for the default outline or null to omit the decoration. The frame ignores pointer input and stays available during selection in minimal mode.

Live resize dimensions

The Effect UI canvas shows a width × height readout in the canvas's lower-left corner during pointer resizing. With resizeHandles: true, it also stays visible for a single selected, expanded group so keyboard resizing has the same feedback. Card readouts are transient. Read-only views and collapsed/hidden groups omit it. Set resizeReadout: false to disable the readout. To replace its appearance, use renderResizeReadout(context, h) with the host's Effect UI builder.

renderResizeReadout: ({ node, widthText, heightText }, h) =>
  h.div([h.Class('dimensions')], [
    node.label + ' · Width ' + widthText + ' · Height ' + heightText,
  ]),

The renderer receives the node with raw Model dimensions, the formatted values, and the resizing or selected-group phase. ZLOZ keeps placement and the polite status region. Return undefined for the default badge or null to omit an eligible readout. The renderer runs only when the effective measurements diagnostic and the readout option allow it.

Values come from the current Model in graph units, including snapping, limits, locked proportions and measured card height. Up to two decimal places are shown; this never rounds authored geometry. The badge stays the same screen size while zooming, ignores pointer input, and uses a native polite status region. Releasing keeps a selected group's result visible; Escape restores its original dimensions. Selection clearing hides it. Theme it with --flow-resize-readout-background and --flow-resize-readout-color, alongside existing node border/color tokens.

Numeric group dimensions

With contextActions configured, open a group's More actions panel to edit Width and Height in graph units. Each field applies on native change (for example, leaving the field), creating one Undo step. The panel stays open for sequential edits and displays the resulting dimensions after grid snapping, size/content limits, parent containment or expansion, and locked proportions. Controls are disabled for collapsed groups and unavailable in read-only views. Escape closes the panel; changes already applied remain undoable.

Hosts can dispatch { type: 'GroupDimensionChanged', id, dimension: 'height', value: 320 } (or dimension: 'width'). Numeric edits anchor the group's top-left corner and keep child positions fixed. With proportions locked, changing either dimension also scales the other. Invalid/non-positive values and active-gesture edits are ignored; repeated clamped values add no history. NodeWidthChanged continues to support group width through the same geometry path. The fields trim floating-point display noise without rounding authored geometry.

Canvas help, status, and diagnostics

Use canvasHelpContext and canvasStatusContext to derive host copy. Set the graph surface's descriptionId to the mounted help element. Use visuallyHidden for help and polite status announcements that remain available to assistive technology when suppressed visually.

resolveZlozDiagnostics combines minimalMode with individual options for measurements, alignment guides, zoom level, status, instructions, overview and the connection list. Feed those flags into host presentation and the canvas's alignmentGuides, resizeReadout, and contextActions.measurements options. Graph data, editing and Undo use the same Model independently of the presentation flags.

Shared custom edge geometry

Use ZlozEdgeGeometryPolicy and resolveEdgeGeometry from the dependency-free root entry, or pass a policy as graphSurface's `edgeGeometr