# Vyuh Diagram > API reference and examples for creating, editing, saving, and exporting drawings. Use vyuh_diagram_flutter for Flutter or vyuh_diagram_core for headless Dart. Core values live in vyuh_diagram_types; JSON and SVG have separate codec packages. Start with Getting Started and the DiagramController API. --- # Agents Give your coding agent these references to create, edit, save, and export drawings using the toolkit. | Resource | Use | | --- | --- | | [Package skill](/agent-docs/agents/package-skill.md) | Install version-matched Vyuh Diagram guidance into Codex or another coding agent. | | [llms.txt](/llms.txt) | A compact index for finding the relevant API and examples. | | [llms-full.txt](/llms-full.txt) | The complete consumer reference in one text file. | The references include package setup, API signatures, runnable examples, supported capabilities, validation errors, and persistence contracts. Use the index when your agent can fetch individual pages, or the full reference when supplying context directly. Start with the package skill when the agent is working inside a Flutter project. It supplies focused integration rules automatically; the text references remain useful for deeper API lookup and retrieval-based agent systems. ## Editing a drawing at runtime A runtime agent edits through its own `DiagramController` on the shared diagram, with the same [verbs](/agent-docs/api/verbs.md) as the canvas and inspector. 1. **Discover.** `controller.verbs(ids)` lists the verbs on those elements (none for diagram verbs such as `createShape`). Each description has a `name`, `label`, `parameters` and `availability`; each parameter has a `name`, `type`, `isRequired`, a `description` and, for scalars, a `schema` that is a `ValueField` with its bounds or options. 2. **Check.** `controller.canPerform(ids, verb, args)` returns the result `perform` would, without changing anything. 3. **Perform.** `controller.edits.perform(ids, verb, args)` returns a `EditResult`; a creating verb reports the new ID in `id`. Denials, including invalid arguments, return a `code` and `reason` instead of throwing. Arguments take a JSON form: an enum or route by name, a color as an ARGB integer, a point as `{x, y}`, a size as `{width, height}` and a rectangle as `{left, top, width, height}`. ```dart final revision = agent.document.revision; final result = agent.perform(['task-1'], 'setStyle', { 'stroke': 0xFFB45309, 'strokeStyle': 'dashed', 'expectedRevision': revision, }); ``` Pass the `expectedRevision` read before awaiting the model: if anyone changed the document meanwhile, the verb is denied with `DiagramDenialCode.conflict` instead of overwriting their edit. Every verb is a setter, one half of a pair (such as `group`/`ungroup`), or derived from a setter (such as `align` from `setElementBounds`), so an agent can always state the reverse edit. There are no toggles; undo is history, not a reverse verb. See [collaboration](/agent-docs/api/collaboration.md) for sharing a diagram with a user. --- # Install the Vyuh Diagram agent skill `vyuh_diagram_flutter` ships an Agent Skills package that teaches coding agents how to use the current SDK correctly. It covers canvas setup, canonical controller edits, extensions, persistence, output, and revision-safe agent proposals. The skill follows the open Agent Skills format. It works with Codex and other compatible coding agents supported by Dart's `package:skills` tool. ## Install it in a Flutter project Add `vyuh_diagram_flutter` as a direct dependency, resolve the project, then run: ```sh dart run skills@ get \ -p vyuh_diagram_flutter \ -s vyuh-diagram-flutter-integration ``` The command reads the skill bundled with the resolved package version and copies it into the detected agent directory. For Codex and generic Agent Skills clients, that is normally: ```text .agents/skills/vyuh-diagram-flutter-integration/ ``` The installed directory includes the main `SKILL.md` and a focused reference for safe asynchronous agent or LLM edits. ## Use it with an agent Codex can select the skill automatically when a request matches its description. You can also invoke it explicitly: ```text $vyuh-diagram-flutter-integration add a custom review shape and persist it ``` Example requests that should activate the skill include: - “Mount an editable Vyuh Diagram canvas in this Flutter screen.” - “Create and connect these shapes through `DiagramController`.” - “Register an extension and its Flutter renderer.” - “Accept an asynchronous LLM proposal without overwriting intervening edits.” - “Export JSON and SVG from one revision-matched snapshot.” The skill guides the coding agent; it does not give a runtime model access to a user's diagram. A product that embeds an LLM must still define its own tools, authentication, authorization and proposal-acceptance boundary. The [verbs](/agent-docs/api/verbs.md) supply the edit schema: `controller.verbs(ids)` describes each verb's parameters and availability, and `controller.edits.perform(ids, verb, args)` accepts JSON-form arguments and an `expectedRevision`. See [runtime agents](/agent-docs/agents/index.md#editing-a-drawing-at-runtime) and [Controllers, agents and collaboration](/agent-docs/api/collaboration.md) for those runtime contracts. ## Keep the skill current Run the same command after updating `vyuh_diagram_flutter`: ```sh dart run skills@ get \ -p vyuh_diagram_flutter \ -s vyuh-diagram-flutter-integration ``` The tool compares the installed copy with the skill from the resolved package and offers the matching update. Use `dart run skills@ list` to inspect managed skills and `dart run skills@ prune` after removing dependencies. If your team commits `.agents/skills/`, also commit `.config/dart_skills/` so everyone shares the same installed versions and update tracking. If agent files are local-only, ignore both locations and let each developer install the skill. ## When to use the text references The package skill is concise and prescriptive. Use [llms.txt](/llms.txt) when an agent can retrieve individual documentation pages, or [llms-full.txt](/llms-full.txt) when a system requires one combined context file. Those references complement the skill; they are not required for ordinary Codex use after installation. --- # The drawing API The API reference now has separate pages for each object and capability. [Open the API reference](/agent-docs/api/index.md) or learn the [vocabulary](/agent-docs/guide/vocabulary.md) it uses. - [Diagram and controller](/agent-docs/api/controller.md) - [Verbs](/agent-docs/api/verbs.md) - [Extensions and options](/agent-docs/api/configuration.md) - [Shapes and registries](/agent-docs/api/shapes.md) - [Connectors](/agent-docs/api/connectors.md) - [Canvas](/agent-docs/api/canvas.md) - [Navigation and motion](/agent-docs/api/navigation-and-motion.md) - [Embedded widgets](/agent-docs/api/widgets.md) - [Grids](/agent-docs/api/grids.md) - [Text](/agent-docs/api/text.md) - [Undo and redo](/agent-docs/api/history.md) - [Rules and changes](/agent-docs/api/hooks.md) - [Verbs and keyboard bindings](/agent-docs/guide/verbs.md) - [Complete custom-library recipe](/agent-docs/guide/build-a-library.md) --- # Build your first shape library Follow this path: [first canvas](/agent-docs/guide/getting-started.md) → this library recipe → [composition rules](/agent-docs/guide/shape-composition.md) → [verbs](/agent-docs/guide/verbs.md). Use the [common tasks](/agent-docs/guide/common-tasks.md) page for command outcomes and persistence; open the API reference when you need individual options. This complete example imports `vyuh_diagram_flutter`, its extension authoring library `package:vyuh_diagram_flutter/extension_api.dart` (shape definitions, verbs, tool definitions and key bindings) and the editor, `vyuh_diagram_extension_editor`. Paste it into `lib/main.dart` after installing both. The shape has a fixed-height title and a flexible body. The button and a shortcut perform the card's own `setRevision` verb, which updates declared data and width together in one Undo step. Editing body text uses the normal text editor. ```dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final reviewLibrary = ShapeLibrary( id: 'review', name: 'Review shapes', shapes: [ ShapeDefinition( type: 'review.card', name: 'Review', size: const DiagramSize(240, 140), verbs: [setRevision], values: { 'revision': const NumberValueField( defaultValue: 0, minimum: 0, integer: true, ), }, body: ShapeColumn([ ShapeSized( extent: 36, child: const ShapeText( 'title', text: 'Review', textType: PlainTextDefinition(maxLines: 1), ), ), const ShapeText('body', text: 'Describe the review'), ]), ), ], ); /// Sets a card's revision; each revision widens the card by 20. Performing it /// with the previous revision restores both. final setRevision = DiagramVerb.update( id: 'setRevision', label: 'Revision', target: DiagramVerbTarget.element, parameters: [DiagramVerbParameter.integer('revision', minimum: 0)], update: (card, call) { final revision = call.arg('revision'); final frame = card.frame; return card.copyWith( values: {...card.values, 'revision': revision}, frame: DiagramRect.fromLTWH( frame.left, frame.top, frame.width + 20 * (revision - revisionOf(card)), frame.height, ), ); }, ); int revisionOf(DiagramElement? card) => switch (card) { ShapeElement(:final values) => (values['revision'] as num? ?? 0).toInt(), _ => 0, }; /// The portable half: shapes with a palette tool each. final reviewExtension = DiagramExtension( id: 'app.review', shapes: reviewLibrary.shapes, tools: DiagramToolDefinition.forShapes(reviewLibrary.shapes, group: 'review'), ); /// The Flutter half: a keyboard shortcut for the same verb. It installs the /// portable half as its dependency. final reviewShortcuts = DiagramFlutterExtension( id: 'app.review_keys', dependencies: [reviewExtension], shortcuts: [ DiagramKeyBinding( verb: 'setRevision', args: (controller, id) => { 'revision': revisionOf(controller.elementById(id ?? '')) + 1, }, key: LogicalKeyboardKey.keyR, modifiers: const {DiagramKeyModifier.command, DiagramKeyModifier.shift}, scope: DiagramKeyScope.selection, shapeType: 'review.card', ), ], ); DiagramController createReviewController() => DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), reviewShortcuts], ), ); void main() => runApp(const MaterialApp(home: ReviewCanvas())); class ReviewCanvas extends StatefulWidget { const ReviewCanvas({super.key}); @override State createState() => _ReviewCanvasState(); } class _ReviewCanvasState extends State { late final controller = createReviewController(); late final String card = controller.createShape('review.card', at: const DiagramPoint(300, 200)); @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Scaffold( body: Column( children: [ TextButton( onPressed: () => controller.perform( [card], 'setRevision', {'revision': revisionOf(controller.elementById(card)) + 1}, ), child: const Text('Revise and widen'), ), Expanded(child: DiagramCanvas(controller: controller)), ], ), ); } ``` The declared `revision` value is persisted data; it is not automatically rendered as text. Use [embedded controls](/agent-docs/api/widgets.md) to display domain values, or use `controller.edits.setText(id, value, slot: 'body')` for an explicit text edit. Plain-text editing does not require manipulating paragraphs, run offsets or selections. That separate command is its own Undo operation. Keep the same library and its verbs registered when reopening saved JSON. Libraries define shape types; the registry combines the chosen libraries and validates IDs. Documents store instances and content, not verbs or other callbacks. For a separate package, export your `ShapeLibrary` from its public Dart entry point; depend on layout/types for portable declarations, and keep Flutter controls in the host. ## Check your integration 1. Add a card and edit its title and body independently. 2. Activate Revise and widen; confirm one Undo restores both value and width. `controller.edits.perform([card], 'setRevision', {'revision': 0})` does the same as a forward edit. 3. Save with `controller.save(DiagramJsonCodec.new)` and reopen with the same extensions. 4. Try a locked target: the verb returns a denied result with `DiagramDenialCode.locked`; handle it, or `DiagramChangeDenied` from `requireAllowed()`, at your UI boundary. 5. Unmount and dispose the controller. The repository's executable recipe check verifies verbs, Undo, persistence and denials. It is not evidence that an unfamiliar developer has completed onboarding. Hosted installation and observed novice onboarding remain separate release checks. --- # Canvas, camera, and grids Configure the camera, grid and minimap without changing document content. Import the Flutter package, plus the editor and minimap extension packages when you install them: ```dart import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_minimap/vyuh_diagram_extension_minimap.dart'; ``` Everything a canvas does is configured on its controller. The canvas takes the controller and an optional theme, and uses the extensions installed on that controller: ```dart final controller = DiagramController( document: document, configuration: DiagramConfiguration( extensions: [ EditorExtension(), GridExtension(visible: true, snap: true), MinimapExtension(), ], ), ); DiagramCanvas(controller: controller, theme: DiagramTheme.light); ``` Install `EditorExtension()` to edit. Without an editor the canvas is view-only: people pan, zoom and select, but cannot edit on the canvas. For an editable canvas without the palette, inspector and toolbar, install `EditorExtension(palette: false, inspector: InspectorPlacement.none, toolbar: false)`. Each extension owns its options. Read the current value with `controller.options()` and change it with `controller.edits.setOptions(value)`; observers of `options()` rebuild when it changes. Options changes apply to every controller of the diagram and are not undoable. ## Move the viewpoint Pan and zoom without rewriting shape coordinates. Fit the document or selection, or travel to an element after the canvas has mounted: ```dart await controller.view.show( ViewTarget.element(elementId), motion: const Motion(duration: Duration(milliseconds: 500)), ); ``` `controller.view.show` also targets points, rectangles, regions, the selection and the whole diagram, with or without motion. User navigation interrupts a move. A canvas is infinite by default. The bounds are core configuration: pass `DiagramConfiguration(bounds: CanvasBounds.fit(padding: 48))` to start bounded, or change them later: ```dart controller.edits.setBounds(const CanvasBounds.fit(padding: 48)); ``` `controller.bounds` is observable. A fit canvas is the diagram's content extent plus `padding` viewport pixels, growing and shrinking with the content, and it keeps the camera within it. An empty document gets a viewport-sized canvas around the origin. ## Choose a grid The grid is always installed. Its `GridOptions` hold `visible`, `snap`, `size` and `pattern`. Visibility and snapping are independent: showing a grid does not turn snapping on, and snapping can stay enabled while the grid is hidden. Set the initial values by installing `GridExtension(...)`, which replaces the default grid: ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ GridExtension( visible: true, snap: true, pattern: DiagramGridPattern.dots, ), ], ), ); final grid = controller.options(); controller.edits.setOptions(grid.copyWith(size: 40)); ``` Choose `dots`, `lines`, or `layered`. Layered grids combine fine and major lines. Every pattern uses the same grid spacing as snapping. At distant zoom levels, the painter thins visible grid marks while preserving the snapping interval. ## Compose your own pattern Custom patterns use the same dot, line, and cross productions as the defaults. Colors, screen-space mark sizes, and spacing multiples belong to each layer: ```dart final engineeringGrid = DiagramGridPattern( id: 'engineering', label: 'Engineering', layers: [ DiagramDotGridLayer(color: DiagramColor(0xFFBBC9E8), size: 2), DiagramLineGridLayer(spacingMultiple: 5, color: DiagramColor(0xFF8296C7)), ], ); controller.edits.setOptions( controller.options().copyWith(pattern: engineeringGrid), ); ``` To offer it in the property panel's grid type list, pass it to `GridExtension(patterns: [...DiagramGridPattern.presets, engineeringGrid])`; the list is `GridOptions.patterns`, and duplicate pattern ids throw an `ArgumentError`. Patterns are validated, immutable compositions. A custom pattern changes the painted grid, not the document geometry or snapping rules. Arbitrary custom renderer callbacks are not part of this grid contract. ## Set the minimap detail policy The minimap defaults to shape outlines and fills, without connections. It uses resolved shape geometry and clipping; text, handles and detailed editing chrome are omitted. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), MinimapExtension( initiallyExpanded: true, policy: DiagramMinimapPolicy( shapeAppearance: DiagramMinimapShapeAppearance.outlines, showConnections: false, ), ), ], ), ); // Hide or show it at runtime, keeping its other options. controller.edits.setOptions( controller.options().copyWith(visible: false), ); ``` Use `outlinesAndFills` for colored silhouettes, or opt into `showConnections`. A policy can provide `shapePainterForType` for custom registered types. Thumbnail painters receive resolved geometry and must remain deterministic; replacing the policy refreshes external thumbnail inputs. They affect presentation only. Camera movement reuses a recorded scene picture. Document or policy changes rebuild that picture, so a changed scene still costs work proportional to its shapes. Thousands of shapes are not automatically a constant-cost or 120 fps minimap; measure the representative document and chosen thumbnail policy. ## Particle count and size Count controls the number of particles evenly distributed along a path. It does not shrink their dimensions. Size is the radius for circles and polygons; character particles use a font scale of twice that value. Dash length is eight times size, capped only by total path length, while width sets dash thickness. The configured screen/world scaling policy controls zoom behavior. Dense particles can overlap. --- # Common tasks Start with `vyuh_diagram_flutter` in Flutter, or `vyuh_diagram_core` in a Dart service. Both expose the same verbs. Keep one controller for the editing lifetime; widgets observe it rather than owning a second document. New to the toolkit? [Hello world](/agent-docs/guide/hello-world.md) shows the six core concepts in one program. The snippets below assume the package's main library. The ones that declare shapes (`ShapeDefinition`, value fields) also need its `extension_api.dart`; see [libraries](/agent-docs/api/index.md#libraries). | Task | Start here | | --- | --- | | Mount a drawing | `DiagramController` and `DiagramCanvas(controller: controller)` | | Create content with registry defaults | `createShape`, `createText` | | Insert an already-authored record | `add` | | Connect existing objects | `connect` | | Add a label | `addConnectorLabel(text: ...)` | | Rename text | `controller.setText` | | Preserve rich formatting while editing | `controller.replaceText` | | Save content | `controller.save(DiagramJsonCodec.new)` | | Observe edits for autosave | `controller.diagram.changes` | | Open saved content | `DiagramController.open(json, format: DiagramJsonCodec.new, configuration: DiagramConfiguration(extensions: [...]))` with the original extensions installed | | Discover what an element accepts | `controller.verbs([id])`, `controller.canPerform` | | Undo or redo | `undo().requireAllowed()`, `redo().requireAllowed()` | | Customize shapes and label grammar | A `DiagramExtension` with `shapes`, `textTypes` and `connectors` | | Show the grid, the minimap or other extension options | `controller.options()` and `controller.edits.setOptions(...)` | | Customize canvas appearance and UI | Extensions in `DiagramController(configuration: DiagramConfiguration(extensions: [...]))` and `DiagramCanvas(theme: ...)` | ## Create, connect and rename ```dart final source = controller.createShape( Shapes.rectangle, at: const DiagramPoint(100, 100), text: 'Draft', ); final target = controller.createText(at: const DiagramPoint(400, 100), text: 'Review'); final connector = controller.connect(source, target); controller.edits.addConnectorLabel(connector, text: 'Ready\nfor review'); controller.setText(source, 'Proposal'); ``` `setText` preserves story identity and replaces formatting with ordinary paragraphs. Newline sequences become paragraph boundaries, including a final empty line. Text that looks like a list remains Plain Text. Rich Text replacement is available when you need to retain marks or list structure. For a connector with several labels, pass the desired label's `story.id` as `storyId`. An ambiguous connector is denied rather than silently editing its first label. The same canonical admission checks enforce single-line regions, locks and the application's rules. Authored content that violates grammar is rejected; it is not silently truncated. For a story with several text slots, also pass `slot`. The edit preserves role and slot bindings and leaves all other slots unchanged. Omitting the slot for an ambiguous story is denied. ## Handle verb outcomes Use this convention consistently in your host: - Calls through `controller.edits` return an `EditResult`; a creating verb reports the new identity in `id`. Inspect the result, or call `requireAllowed()` to throw `DiagramChangeDenied` on a denial. - Unknown verbs, missing or invalid arguments, unknown targets, locks and stale revisions are denials with a `DiagramDenialCode`, not exceptions. - Selection, camera and extension options change through plain controller methods such as `select`, `setCamera` and `setOptions`; they are not verbs, are not undoable or admitted, and have their own preconditions. - Invalid authored data that is not a verb argument and invalid lifecycle calls can throw `ArgumentError`, `StateError` or format errors. Do not catch those as ordinary rule denials. ```dart try { controller.setText(source, 'Approved'); } on DiagramChangeDenied catch (error) { onDenied(error.result); // Your host's feedback callback. // Use error.result.code to choose host messaging or localization. // error.result.reason is optional human-readable detail. } ``` `DiagramDenialCode` provides stable categories. Rules that return `EditResult.denied(reason: ...)` have the `policy` code. Use `EditResult.denied(code: code, reason: ...)` to supply a category explicitly. Never parse the reason string. A successful verb is one undoable operation; several statements in a try block are not an atomic batch. Wrap them in `controller.edits.batch(label, () {...})` when they must undo together. ### One error-handling boundary Direct creation calls return the new ID. Other direct edits complete or throw `DiagramChangeDenied` on refusal. Calls through `controller.edits` return an `EditResult`. For an application that handles denials with exceptions, call `requireAllowed()` on results and catch `DiagramChangeDenied` once at the initiating UI boundary. Read a created identity from `id` after checking the result. Your own [verbs](/agent-docs/guide/verbs.md), and the key bindings and regions that perform them, use this same result contract, including typed denial codes. For several changes that must undo together, use `controller.batch`, or declare a [verb](/agent-docs/guide/verbs.md) whose implementation performs them. Use `setValues` for declared data, `resize` or `setElementBounds` for dimensions and `setStyle` for appearance. For a single ordinary text edit, use `controller.setText` with a `slot`; manual text-story replacement is an advanced escape hatch. ## Show the grid and other options Each extension owns its options, such as the grid's `GridOptions`. Read the current value and replace it; the change reaches every controller of the diagram and is not an undo step: ```dart final grid = controller.options(); controller.edits.setOptions(grid.copyWith(visible: true, snap: true, size: 24)); ``` Start with other values by installing the extension with them, for example `DiagramController(configuration: DiagramConfiguration(extensions: [GridExtension(visible: true)]))`. See [extensions and options](/agent-docs/api/configuration.md). ## Choose the correct owner | Concern | Owner | Lifetime | | --- | --- | --- | | Shapes, ports, text regions, label block grammar | Extension contributions, assembled into the `ShapeRegistry` | Establish when creating a controller; reuse for saved documents. | | Creation and connection rules | `DiagramController(configuration: DiagramConfiguration(rules: DiagramRules(canCreate: ..., canConnect: ...)))` | Canonical admission for API and interactive edits. | | Before-change approval and document validation | `DiagramRules(beforeChange: ...)` | Canonical admission, including loads and history. | | Grid, navigation, editor, minimap and widget builders | Extensions in `DiagramController(configuration: DiagramConfiguration(extensions: [...]))`, each with its own options | Read with `options()`, change with `setOptions`; not undoable. | | Font metrics | Text-layout engine | Choose before creating a controller that will be mounted. | | Autosave | Document-change listener | Subscribe once, remove before host disposal. | | Pointer preview and camera feedback | General/presentation observation | Do not treat transient previews as committed autosave data. | ## Platform capabilities | Capability | Portable controller | Flutter controller, unmounted | Flutter controller, mounted | | --- | --- | --- | --- | | Create/edit/history/JSON | Yes | Yes | Yes | | Text metrics | Explicit backend; default fixed metrics | Flutter shaping | Flutter shaping | | SVG | Prepared image/font resources | Flutter output adapter | Flutter output adapter | | PNG | Requires raster output adapter | Supported by Flutter output | Supported by Flutter output | | Navigate or read viewport | No mounted viewport | Requires attachment | Supported | | Pointer, keyboard and IME | No | No | Supported | Native shaping is available through the separate Pango library; native resources and fonts need their own setup and disposal. Fixed metrics are useful for deterministic headless work, but do not promise font-accurate output. `DiagramController(diagram: controller.diagram, participant: DiagramParticipant.agent(id: 'agent', name: 'Agent'))` joins the same diagram as another actor with its own selection, camera and undo history. Configure Flutter text layout before mounting. Disposing the owning controller disposes the diagram and every controller joined to it. ## Progress to custom definitions Follow [shapes](/agent-docs/api/shapes.md), then [connectors](/agent-docs/api/connectors.md), [text](/agent-docs/api/text.md), [embedded widgets](/agent-docs/api/widgets.md) and [ownership](/agent-docs/api/ownership.md). Add one concern at a time: outline, ports, text regions, declared values, widget slots, then custom tools. Keep content in declared values and stories; a widget builder is a projection and performs verbs through its bounded context. An `enabled` snapshot is presentation feedback, not permission to bypass live admission. ## A small starting surface For a new Flutter host, start with: `import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart';` This entry point exposes the everyday canvas, controller, verbs, document model, options, style and error contracts. Custom geometry, tools, verbs, effects, text grammars and output backends are extension authoring types in a second library; add it when the task calls for those capabilities: `import 'package:vyuh_diagram_flutter/extension_api.dart';` Both libraries re-export the same objects as `vyuh_diagram_core`, not another implementation. ## Draw lines without coordinate bookkeeping ```dart final line = controller.createLine( start: const DiagramPoint(40, 60), end: const DiagramPoint(240, 160), ); controller.edits.createPolyline( points: const [ DiagramPoint(300, 60), DiagramPoint(460, 60), DiagramPoint(380, 180), ], closed: true, ); final corner = controller.addPathPoint(line, after: 'node-0'); controller.setPathHandleMode(line, corner, DiagramPathHandleMode.smooth); ``` Points are in world coordinates. The controller computes the frame, normalizes nodes, applies parent placement and records one undo step. `createPath` remains available for authored Bézier nodes, tangent offsets and explicit frames. Creation and edits return an `EditResult` you can inspect, read the new identity from, or promote to an exception with `requireAllowed()`. ## Declare a custom shape and its inspector A rectangle with editable text needs only `ShapeDefinition(type: 'task')`. Standard defaults supply its rectangle outline, padded `body` text part, size and behavior. Declare only the differences: ```dart final task = ShapeDefinition( type: 'task', name: 'Task', values: { 'progress': const NumberValueField( defaultValue: 0, minimum: 0, maximum: 100, ), 'status': TextValueField( defaultValue: 'Draft', allowedValues: ['Draft', 'Ready'], ), }, ); final taskController = DiagramController( configuration: DiagramConfiguration( extensions: [commonTasksExtension(task)], ), ); taskController.createShape( 'task', at: const DiagramPoint(100, 100), text: 'Review proposal', ); ``` Declare the extension at the top level of your Dart file: ```dart top-level DiagramExtension commonTasksExtension(ShapeDefinition task) => DiagramExtension( id: 'app.tasks', shapes: [task], ); ``` The inspector's standard editors follow from the shape's anatomy: fill and stroke from its outline, text from its text parts and one control per value. `definition.propertyEditors` lists them in order; add your own with `properties:`. Visibility does not change edit permissions. Path and gradient controls use the same declarations. --- # Build a custom shape from scratch Build a review card with a title, description, embedded table, typed property and connection ports. Set up the canvas using [Set up the canvas](/agent-docs/guide/flowchart-canvas.md), then replace `lib/main.dart` with this example. No custom painter or editor is needed. The Flutter import exposes the anatomy and port declarations; tables and UI are explicit optional imports. ```dart import 'package:material_ui/material_ui.dart'; import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_table/vyuh_diagram_extension_table.dart'; import 'package:vyuh_diagram_extension_table_flutter/vyuh_diagram_extension_table_flutter.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final reviewDefinition = ShapeDefinition( type: 'tutorial.reviewTable', name: 'Review table', size: const DiagramSize(320, 240), minimumSize: const DiagramSize(200, 160), behavior: const ShapeBehavior(textSizing: ShapeTextSizing.growHeight), values: { 'priority': const NumberValueField( defaultValue: 1, minimum: 1, maximum: 5, integer: true, ), }, connection: ShapeConnectionDefinition.fixedPorts([ PortDefinition.onSide(id: 'input', side: PortSide.left), PortDefinition.onSide(id: 'output', side: PortSide.right), ]), body: ShapeColumn([ ShapeSized( extent: 40, child: ShapeSurface( style: const ShapeStyle(fill: DiagramColor(0xFFEAF1FF)), child: const ShapeText( 'title', text: 'Review', textType: PlainTextDefinition(maxLines: 1), ), ), ), ShapeSized( extent: 48, child: const ShapeText( 'description', text: 'Describe the review', verticalPadding: 8, ), ), const ShapeTable('items', rows: 2, columns: 2), ]), ); DiagramController createReviewTableController() { final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ // This screen mounts its own inspector beside the canvas. EditorExtension(inspector: InspectorPlacement.none), TableFlutterExtension(), customShapeTutorialExtension(), ], ), ); controller.createShape(reviewDefinition.type, at: DiagramPoint.zero); return controller; } void main() => runApp( MaterialApp( theme: ThemeData(splashFactory: InkRipple.splashFactory), home: const Scaffold(body: ReviewTableEditor()), ), ); class ReviewTableEditor extends StatefulWidget { const ReviewTableEditor({super.key}); @override State createState() => _ReviewTableEditorState(); } class _ReviewTableEditorState extends State { late final controller = createReviewTableController(); @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Row( children: [ Expanded(child: DiagramCanvas(controller: controller)), SizedBox(width: 280, child: DiagramInspector(controller: controller)), ], ); } DiagramExtension customShapeTutorialExtension() => DiagramExtension(id: 'tutorial.review', shapes: [reviewDefinition]); ``` ## 1. Choose the element boundary This is one shape. Its title, description and table share transforms and history. `ShapeSurface` is artwork inside the shape, not a separately selectable child. Use frames or groups for independently selectable document elements. Definitions declare the anatomy and defaults. Instances own geometry, values and editable stories. Rebuilding a definition does not reset authored text. ## 2. Compose the body `ShapeColumn` gives the title and description fixed heights; the table fills the remaining region. Nest `ShapeRow`, `ShapePadding` and `ShapeStack` for richer layouts. `ShapeSurface` parts with polygon or path outlines add portable artwork. See [shape anatomy](/agent-docs/guide/shape-composition.md). Named text slots become regions of the owner's canonical story, not separate editing controllers. `ShapeTable` contributes a table to that story. Cells own styled body paragraphs; headings, lists and nested tables are forbidden. Content minimums can grow the table and its owner. A fixed description region can overflow; use a flexible region when it should share available space. ## 3. Declare properties and inspector behavior `priority` is persisted and constrained to integers from 1 to 5. The inspector discovers declared values and the appearance and text editing its anatomy supports: fill, stroke and corner radius from its default rectangle outline, text from its text parts and table. Keep constraints in the definition rather than copying them into private forms. The standard editors always follow the shape's anatomy and never replace table controls. Add domain properties, nested records and custom editors with `properties:`; see [properties and the inspector](/agent-docs/guide/properties.md). Domain values are not automatically rendered as text. Update a slot explicitly with `controller.edits.setText(id, text, slot: 'title')`, or display values through a `ShapeWidget` part. Declare [a verb](/agent-docs/guide/verbs.md) on the shape for a domain edit that belongs in one Undo step. ## 4. Connect and save This shape uses ports-only connections. Pass `fromPort: 'output'` or `toPort: 'input'` to `controller.connect`. The framework places the ports and routes the connectors. Save `controller.save(DiagramJsonCodec.new)` and restore with the same registry. Documents contain values and content, not executable callbacks. Keep type and slot identities stable; a document only loads against the grammar that admits it. ## 5. Add controls through the shared owners | Need | Existing integration | | --- | --- | | Properties outside the canvas | `DiagramInspector` and the properties that perform your verbs | | Flutter controls inside a region | A `ShapeWidget` part and Flutter widget builders; see [embedded controls](/agent-docs/api/widgets.md) | | Toolbar above the canvas | Host UI performing verbs | Paint-only [effects](/agent-docs/api/effects.md) inside or around a shape are visuals, not interactive controls. Embedded widgets are shape content, not selection-only buttons outside the shape. A general declarative interactive overlay grammar is not yet available. Do not draw fake buttons in `ShapeSurface` and expect controls. See the proposed [API reference](/agent-docs/api/index.md). ## 6. Handle failures and test Check `EditResult.allowed` and show its reason for expected denials. Creation helpers can throw `DiagramChangeDenied`; malformed imports can throw `FormatException`; stale edits can raise revision conflicts. Keep user messages at the host boundary and technical diagnostics in logging. Never silently retry a stale command against the latest revision. Test title and cell editing, growth, minimum size, ports, locking, Undo/Redo, JSON reopening, rotation and export. Invalid property values must leave content and history unchanged. The repository compiles this tutorial alongside its other public learning examples. --- # Create custom shapes A custom type is a registry definition, not a new painter or a private drag implementation. Definitions and their parts are extension authoring types: import `package:vyuh_diagram_flutter/extension_api.dart` beside the main library. Declare its [anatomy](/agent-docs/guide/shape-composition.md)—outline, body, values, connection and behavior—and the shared runtime resolves its geometry and handles editing. ## Declare a node ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ShapeDefinition reviewNode() => ShapeDefinition( type: 'example.review', outline: const ShapeOutline.rect(), body: const ShapeText('body', horizontalPadding: 16, verticalPadding: 16), minimumSize: const DiagramSize(140, 80), size: const DiagramSize(220, 120), style: const ShapeStyle(cornerRadius: 12), behavior: const ShapeBehavior( rotatable: false, textSizing: ShapeTextSizing.growHeight, ), connection: ShapeConnectionDefinition.fixedPorts([ PortDefinition.onSide( id: 'input', side: PortSide.left, ), PortDefinition.onSide( id: 'output', side: PortSide.right, ), ]), ); final reviewExtension = customShapesExtension(); DiagramExtension customShapesExtension() => DiagramExtension( id: 'example.review', shapes: [reviewNode()], ); ``` The rounded rectangle outline gives the node editable fill, stroke and corner radius; its `body` text part makes its text editable. Install `reviewExtension` in the configuration's extensions: `DiagramController(configuration: DiagramConfiguration(extensions: [reviewExtension]))`. Before or after mounting, create an instance using the registered type: ```dart String insertReview(DiagramController controller) => controller.createShape('example.review', at: const DiagramPoint(320, 240)); ``` The `createShape` verb uses definition defaults and the canonical text-story factory. The instance participates in shared selection, text editing, history and routing. ## Keep one definition per type Extensions add unique types; two non-core extensions contributing the same type are rejected. The core extensions are always installed first as defaults: an installed contribution with the same key, such as a `ShapeDefinition` of type `Shapes.rectangle`, a text definition of type `text` or a `DiagramConnectorDefinition()` for `connector`, replaces the core one. To give a shape a palette button, add `DiagramToolDefinition.forShapes([shape], group: ...)` to the same extension's `tools`. ## Declare behavior `ShapeBehavior` declares selection, movement, deletion, resizing, rotation and how text sizes the shape. Containers add `ShapeContainer` for child ownership, clipping and child scaling. Everything else a person can edit—fill, stroke, corner radius, text and values—follows from the anatomy. See [shape behavior](/agent-docs/guide/shape-capabilities.md). Per-instance locks use `controller.edits.setLocked(locked, ids: ids)` and inherit through owners; shared admission enforces them across commands. The visible rotation handle is opt-in per definition. Keep rotation enabled while choosing whether to show its stem-and-circle control: ```dart const rotationBehavior = ShapeBehavior(rotationHandle: true); ``` `rotationHandle` defaults to `false`. Desktop corner rotation remains available when `rotatable` is true. Setting `rotatable: false` suppresses every rotation control, including the visible handle. ## Embed paragraph content A text part uses the same Rich Text story and editor as a text box. Declare its slot and place it in the body; the engine owns input, selection, layout and undo. Several paragraph blocks can flow through one slot. ```dart final described = ShapeDefinition( type: 'example.described', behavior: const ShapeBehavior(textSizing: ShapeTextSizing.growHeight), body: ShapePadding( 16, child: const ShapeText( 'description', horizontalPadding: 0, verticalAlignment: DiagramTextVerticalAlignment.top, placeholder: 'Add a description…', ), ), ); ``` Multiline plain text is the default; `textType: PlainTextDefinition(maxLines: 1)` restricts a short title region to one line, and a `RichTextDefinition` allows formatting. `ShapeTextSizing.growHeight` grows the shape to accommodate content. Fixed-size regions retain their declared bounds. A title and body are two `ShapeText` parts in one column, not two text editors. Text boxes created with a click start in automatic-width mode: Enter adds a new paragraph, while the box grows horizontally as you type. Drag to create a wrapping box, or resize its width afterward. Its height grows to fit the paragraphs. Paragraphs retain canonical runs, marks, list kind, nesting and alignment. Shapes and connector labels share story ownership, layout and editing commands; a host should not add an independent text field with a second copy of the content. Connections can be disabled, outline-bound, fixed-port, default-side-port, or instance-port based. `ShapePortLayout.distribute` spaces multiple ports evenly along a side. ## Keep domain meaning above geometry The names `input` and `output` in this example are stable port IDs. They do **not** automatically enforce workflow direction or payload compatibility. A domain package declares those meanings and supplies a `canConnect` rule in `DiagramRules` to enforce them. Custom type IDs are open. Outlines are deliberately finite: rectangle, ellipse, polygon, fixed or computed path, regular polygon, editable path and ink. Body parts are a small closed set, with `ShapeContentPart` as the one extension point for content such as tables. Adding a genuinely new geometry or interaction primitive requires extending that shared grammar and resolution contract, not bypassing it with shape-specific painting. Embed native controls with a `ShapeWidget` part and Flutter builders registered in `DiagramFlutterExtension.widgets`. Their values remain canonical shape content; the host supplies a portable fallback part for unmounted and output projections. See [widgets inside shapes](/agent-docs/api/widgets.md) for the complete declaration, editing and lifecycle API. See [capability status](/agent-docs/reference/capabilities.md) before relying on embedded controls, port labels, or connector-label editing. ## Shared text regions Every text-capable shape uses the same story, block, run, and resolved-line pipeline. Define separate text regions for a card title and body rather than mounting private text editors. A single-line region accepts one paragraph with inline formatting. Enter finishes editing that region. Multiline regions support paragraph blocks, ordered and unordered list items, nested lists, and checklist items. Typing `[] ` or `[ ] ` at the beginning of a multiline paragraph creates a checklist item. The default line-height multiplier is 1.3. Lines reflow within the region width after accounting for list indentation. Empty paragraphs still resolve a full line and caret. The declared text sizing policy controls whether the owner grows or retains its bounds; rendering and editing consume the same line geometry. Checklist markers use resolved geometry for painting and clicking. Clicking a checkbox toggles its canonical block state, preserves text selection, and can be undone. Paragraph alignment applies only to ordinary paragraphs. Bulleted lists, numbered lists, and checklists remain left-aligned in their region, including nested items. Markers reserve their measured width plus a half-em gap before the item text. ## Standalone text Use `TextElement` for text that does not belong to a shape. Text elements are a core concept: every installed text type (plain `text`, or `richText` from `RichTextExtension()`) is a type of standalone text, whose element `type` is the text type's name, with the core's standard placeholder, sizes and behavior. An extension adds a text type through `textTypes`. It shares `FramedElement` transforms and the same rich-text story machinery as cards, but exposes no shape style, ports, image, or child ownership. The reserved `text` type is not a custom shape definition. See [the text API](/agent-docs/api/text.md#standalone-text) for an insertion example. --- # Build a flowchart editor ::: info Commercial extension tutorial This tutorial builds on the free Core + Flutter foundations and uses commercial SDK extensions for its ready-made editor controls, specialized shapes and routing. The controller, document, history and canvas are foundation APIs; the supplied palette, toolbar and inspector come from `EditorExtension`. Start with [Hello world](/agent-docs/guide/hello-world.md) for the foundation-only example, then [Extending it with extensions](/agent-docs/guide/extending-with-extensions.md) for the transition. ::: Learn Vyuh Diagram by building one Flutter editor, a step at a time. Start with an empty canvas and finish with a toolbar that follows editing state, a properties panel, connected custom nodes, saving/loading and keyboard shortcuts. Editing comes from installing `EditorExtension()` in the configuration's `extensions`. By default it also supplies a tool palette, inspector and bottom toolbar around the canvas; its `container` callback rearranges that UI, and `palette:`, `inspector:` and `toolbar:` turn parts off. This tutorial keeps the editor's palette and composes its own toolbar and inspector to explain their shared controller contract. See [editor composition](/agent-docs/api/canvas.md#compose-an-editor). ## The ideas behind the SDK **One controller drives editing.** `DiagramController` creates a `Diagram`, which holds the committed document and history, and keeps its own selection, tool and camera. Your canvas, toolbar and property editors use that same controller. Host UI performs verbs and observes results. **Content is immutable; the controller is reactive.** After an accepted edit, read a new document snapshot. Live editing notifications, completed document events and camera notifications serve different purposes. Step 4 shows how to subscribe from your own UI without depending on an internal state-management library. **Edits can be refused.** Capabilities, locks and host rules are checked before a change is published. `allowed` tells you the outcome; `requireAllowed()` throws when that outcome is a denial. Neither is an extra approval step. Step 3 introduces both with real toolbar callbacks. **Definitions supply behavior.** Register geometry, text, ports and capabilities once. Instances share the SDK's interaction, routing, undo and persistence machinery. ## Follow the tutorial Each page continues the same `lib/main.dart` from step 1. Code blocks tell you what to add or replace; checkpoints tell you what to try before moving on. | Step | What you build | | --- | --- | | [1. Set up the canvas](/agent-docs/guide/flowchart-canvas.md) | A controller and bounded Flutter canvas. | | [2. Register and create shapes](/agent-docs/guide/flowchart-shapes.md) | Start, process and decision nodes. | | [3. Create the toolbar](/agent-docs/guide/flowchart-toolbar.md) | Creation and history buttons; meaningful denial handling. | | [4. Connect reactive state to your UI](/agent-docs/guide/flowchart-reactivity.md) | Subscriptions that keep your own controls current. | | [5. Show properties and connections](/agent-docs/guide/flowchart-properties.md) | An inspector, custom selection control and attached connectors. | | [6. Save and load the drawing](/agent-docs/guide/flowchart-persistence.md) | A JSON round trip and an autosave integration boundary. | | [7. Add a custom review node](/agent-docs/guide/flowchart-custom-shapes.md) | A review node with declared text, ports and behavior. | | [8. Share verbs and shortcuts](/agent-docs/guide/flowchart-actions.md) | One edit shared by a button and a keyboard binding. | | [9. Control the canvas and grid](/agent-docs/guide/flowchart-canvas-controls.md) | Grid, snapping and camera controls. | Package installation and registry access are covered in [step 1](/agent-docs/guide/flowchart-canvas.md#package-access). For commercial onboarding, see [SDK licensing](/agent-docs/guide/sdk-licensing.md). [Start with the canvas →](/agent-docs/guide/flowchart-canvas.md) ## Find, connect and arrange The default editor toolbar includes **Commands**, **Search drawing**, **Arrange drawing** and **Check drawing**. Press **Cmd+K** on macOS or **Ctrl+K** to search installed commands; select an element first for its actions. Command forms use the declared parameter types and show the reason for a denial. Search drawing finds text, element types and stable identities, and reveals collapsed owners before focusing the match. Arrange drawing lays out the whole drawing regardless of the current selection. Container contents retain their local arrangement. Install `LayoutExtension()` to enable the five layout algorithms: Layered, Tree, Grid, Circular and Force. Arrange drawing opens these choices in a menu without a search field. Pull a port into empty space to choose the next shape and create its incoming connection. Undo removes both together. Check drawing runs installed domain checks; each suggested repair uses one undo entry and a stale report is denied. Select several shapes to edit their shared properties. Mixed values remain explicit and choices or numeric ranges must be valid for every selected kind. For a custom shell, use the exported `showDiagramCommands`, `showDiagramOutline`, `showDiagramLayout`, `showDiagramDiagnostics` and `showConnectedShapePicker` functions. Custom floating toolbars can include `...diagramAuthoringActions(context, controller)` in their `items` to share the standard commands, drawing search, arrangement and diagnostic controls. The playground keeps only Search drawing (the search icon) and Arrange drawing in its authoring toolbar. Commands and drawing checks remain available for custom SDK editors. --- # Extending it with extensions Keep the controller and canvas from [Hello world](/agent-docs/guide/hello-world.md). Extensions add capabilities to that same diagram; you do not switch to a different document model. ::: info Foundation and commercial extensions Hello World uses the free foundations. This tutorial adds commercial SDK extensions for the ready-made editor, specialized shapes and advanced connector routing. You can also build your own shapes, tools and Flutter extensions using the foundation APIs. ::: ## What an extension adds An extension contributes named capabilities. `EditorExtension` adds the palette, toolbar and inspector. `ShapesExtension` adds specialized shape libraries. `ConnectorsExtension` adds routing and arrowhead choices. Install extensions in one `DiagramConfiguration.extensions` list. Each extension takes its own options and installs the dependencies it needs. ## Add the editor first Install `vyuh_diagram_extension_editor` using the [package setup guide](/agent-docs/guide/package-access.md), then import it: ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; ``` Replace Hello World's controller declaration with this configuration. Its shape creation code and canvas stay the same. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension()], ), ); ``` The canvas now has an editing interface. The tools use the same controller, document and undo history. ## Add specialized shapes and routes Install the shapes and connectors packages before adding their imports. Then extend the same configuration: ```dart import 'package:vyuh_diagram_extension_shapes/vyuh_diagram_extension_shapes.dart'; import 'package:vyuh_diagram_extension_connectors/vyuh_diagram_extension_connectors.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), ShapesExtension(), ConnectorsExtension(), ], ), ); ``` Shapes adds libraries such as flowchart symbols. Connectors adds elbow/orthogonal, quadratic and Bézier routing, plus additional arrowheads. Existing straight connectors keep their routing until you change it. ## Continue building - [All extensions](/agent-docs/api/extensions.md): available packages and contributions. - [Configuration and options](/agent-docs/api/configuration.md): configure extensions and change options. - [Build a flowchart editor](/agent-docs/guide/editor-getting-started.md): the commercial extension tutorial. - [Custom shapes](/agent-docs/guide/custom-shape-tutorial.md): contribute application-specific content. - [Widgets inside shapes](/agent-docs/api/widgets.md): embed regular Flutter widgets with the foundations. --- --- prev: text: '7. Add a custom review node' link: /guide/flowchart-custom-shapes next: text: '9. Control the canvas and grid' link: /guide/flowchart-canvas-controls --- # 8. Share verbs and shortcuts A verb is a named edit that a button, a shortcut, the inspector and an agent all perform the same way. Add this import: ```dart import 'package:flutter/services.dart'; ``` Declare the verb on the review node, and bind a shortcut to it in the review extension. The shape and its shortcut travel together in one `DiagramFlutterExtension`, installed in the diagram's configuration: ```dart late final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(inspector: InspectorPlacement.none, toolbar: false), reviewExtension(), ], ), ); DiagramFlutterExtension reviewExtension() => DiagramFlutterExtension( id: 'tutorial.review', shapes: [reviewNode()], shortcuts: const [ DiagramKeyBinding( verb: 'grow', key: LogicalKeyboardKey.keyG, modifiers: {DiagramKeyModifier.command, DiagramKeyModifier.shift}, scope: DiagramKeyScope.selection, ), ], ); /// Grows a review node by 40 × 20. It derives a new size, so `resize` with /// the previous size expresses its reverse. final growReview = DiagramVerb( id: 'grow', label: 'Grow', symmetry: const DiagramVerbSymmetry.derived(reversedBy: 'resize'), target: DiagramVerbTarget.element, perform: (call) { final frame = call.document.shapeById(call.id)!.frame; return call.controller.edits.perform( [call.id], 'resize', {'size': DiagramSize(frame.width + 40, frame.height + 20)}, ); }, ); ShapeDefinition reviewNode() => ShapeDefinition( type: 'tutorial.review', verbs: [growReview], // ...the rest of the review node from step 7 ); ``` Add this method and include `buildGrowButton()` in the reactive toolbar: ```dart Widget buildGrowButton() { final selection = controller.selection; final ids = selection is ElementSelection ? selection.elementIds : {}; final id = ids.length == 1 ? ids.single : null; return TextButton( onPressed: id != null && controller.canPerform([id], 'grow').allowed ? () => showDecision(controller.edits.perform([id], 'grow')) : null, child: const Text('Grow review'), ); } ``` The verb belongs to the review node, so only review nodes offer it: `canPerform` denies it on a diamond, and on a locked review node. Availability is checked again when the verb runs. The verb performs the core `resize` verb, so it is one admitted edit and one Undo entry; a denial changes nothing. Every verb is two-way. `grow` computes a new size, and `resize` with the previous size is its reverse, so it declares `DiagramVerbSymmetry.derived(reversedBy: 'resize')`. A verb that sets a value, such as a count, is a setter instead: a button that increments passes the next value rather than calling a one-way `increment`. Here `command` maps to Meta on macOS and Control elsewhere. Selection-scoped bindings belong to object selection, not active text editing or a focused host text field. Choose a chord that does not collide with your application's shortcuts. **Checkpoint:** select a review node and use Grow review, then Command/Ctrl+Shift+G with canvas focus. Both grow it and Undo reverses each operation. Select a diamond: Grow review disables. [Verbs and shortcuts](/agent-docs/guide/verbs.md) covers canvas/text scopes and painted regions. --- --- prev: text: '8. Share verbs and shortcuts' link: /guide/flowchart-actions next: text: 'Explore the flowchart example' link: /examples/flowchart --- # 9. Control the canvas and grid Finish with view controls. These change presentation and interaction options without rewriting the saved flowchart. The grid is always installed, and its `GridOptions` belong to the grid extension. Add a toggle to the reactive toolbar; the toolbar's `Observer` reads `controller.options()`, so it rebuilds when the options change: ```dart FilterChip( label: const Text('Grid'), selected: controller.options().visible, onSelected: (visible) => controller.edits.setOptions( controller.options().copyWith( visible: visible, snap: visible, ), ), ), ``` This UI deliberately toggles visibility and snapping together. `visible` and `snap` are independent. When visible, direct manipulation snaps to displayed grid spacing; when hidden with snapping enabled, it uses the configured base interval. Zooming out can reduce grid density. Add two more toolbar controls: ```dart TextButton( onPressed: () => controller.view.show(const ViewTarget.selection()), child: const Text('Fit selection'), ), TextButton( onPressed: () => controller.view.show(const ViewTarget.point(DiagramPoint.zero, zoom: 1)), child: const Text('Reset view'), ), ``` Navigation needs a mounted, laid-out canvas. These callbacks run after mounting. For initial navigation, use a post-frame callback and verify that the State is still mounted and the controller attached (`controller.isAttached`). For a zoom percentage, read `controller.camera.zoom` inside an `Observer`; it rebuilds as the camera moves. Document changes will not update a zoom label. The default canvas is infinite. Pass `DiagramConfiguration(bounds: CanvasBounds.fit(padding: 48))`, or call `controller.edits.setBounds(const CanvasBounds.fit(padding: 48))`, if your editor needs a bounded workspace: the canvas then fits the content plus that padding in screen pixels. Bounds and options changes preserve document and history; `copyWith` keeps the other grid options intact across your toggle. For a minimap, add the `vyuh_diagram_extension_minimap` package and install `MinimapExtension()` in the configuration's `extensions`. It owns `MinimapOptions`, so a toolbar toggle is one call: ```dart final minimap = controller.options(); controller.edits.setOptions(minimap.copyWith(visible: !minimap.visible)); ``` **Checkpoint:** select nodes and fit the selection, change the grid, pan and zoom. Saving still captures authored world coordinates; camera movement creates no document Undo entry. ## Where to go next You now have a flowchart canvas, a registry, reactive host controls, an inspector, connections, a JSON boundary, a custom node and a shared keyboard shortcut. Your application supplies storage, authorization and domain semantics around those boundaries. Try the [interactive flowchart example](/agent-docs/examples/flowchart.md), then use [Common tasks](/agent-docs/guide/common-tasks.md) for focused recipes or [Build a library](/agent-docs/guide/build-a-library.md) to package your domain shapes. [Navigation and motion](/agent-docs/api/navigation-and-motion.md) and [Grids](/agent-docs/api/grids.md) cover the remaining view controls. --- --- prev: text: 'Tutorial overview' link: /guide/editor-getting-started next: text: '2. Register and create shapes' link: /guide/flowchart-shapes --- # 1. Set up the canvas Start with an empty Flutter app. By the end of this page you will have a bounded, interactive canvas and a controller whose lifetime belongs to your screen. ::: info Package access You need access to the Vyuh package registry at `https://pub.vyuh.tech` with your designated access token to install `vyuh_diagram_flutter` and its companion packages. Register your token before fetching dependencies: ```sh dart pub token add https://pub.vyuh.tech ``` Enter your designated token when prompted. Keep it private; do not commit it to your repository or include it in application source. Enterprise licenses are allocated manually after onboarding and payment through Paddle. Our team provisions your company and package access, then sends your designated registry token. A Paddle payment receipt is not a registry token. Once your token is installed, follow the dependency setup below and run `flutter pub get` to download the package. If access is denied, contact the onboarding team to check your allocation. **Don't have a license yet? [Contact us for a license](/#licensing).** ::: ## What you need Use Flutter 3.47 or later with Dart 3.13 or later. Add `vyuh_diagram_flutter` to your application: ```yaml dependencies: material_ui: ^1.1.0 vyuh_diagram_flutter: hosted: https://pub.vyuh.tech version: ^3.11.0 vyuh_diagram_extension_editor: hosted: https://pub.vyuh.tech version: ^3.11.0 ``` Run `flutter pub get`. `vyuh_diagram_flutter` provides the canvas and controller; `vyuh_diagram_extension_editor` provides the editor extension that makes the canvas editable. Declare each UI, codec or extension package that your application imports. For a headless Dart service, use `vyuh_diagram_core` instead. It exposes `DiagramController` as the headless application entry point. See [API reference](/agent-docs/api/index.md) for the complete package list. This editor tutorial uses `material_ui` for its `MaterialApp`, `Scaffold` and buttons. Keep this import throughout the tutorial so the editor controls share the matching theme. Your application can use its own Flutter UI with the controller. ## Mount the controller Replace `lib/main.dart` with this complete app. All later steps edit this file. Keep the same `DiagramSurface` and its State throughout the tutorial. ```dart import 'package:material_ui/material_ui.dart'; import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; void main() => runApp( MaterialApp( theme: ThemeData(splashFactory: InkRipple.splashFactory), home: const Scaffold(body: DiagramSurface()), ), ); class DiagramSurface extends StatefulWidget { const DiagramSurface({super.key}); @override State createState() => _DiagramSurfaceState(); } class _DiagramSurfaceState extends State { late final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(inspector: InspectorPlacement.none, toolbar: false), ], ), ); @override void initState() { super.initState(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => SizedBox.expand(child: DiagramCanvas(controller: controller)); } ``` Everything the diagram can do is installed in the configuration's one `extensions` list. `EditorExtension` makes the canvas editable and adds a tool palette; this tutorial builds its own toolbar and inspector, so it turns the editor's toolbar and inspector off. Without an editor installed, the same canvas is view-only: it navigates and selects but does not edit. The empty `initState` is where we will seed the flowchart next. Create the controller once, outside `build`, and dispose it with its owner. Each controller supports one mounted canvas. Child toolbars and panels receive that controller; they do not dispose it. The canvas needs finite layout constraints. `Scaffold.body` provides them here; inside a Column use `Expanded`. Content commands work before mounting, but camera commands need a mounted, laid-out canvas. **Checkpoint:** run `flutter run`. You should see an empty canvas without layout errors. --- --- prev: text: '6. Save and load the drawing' link: /guide/flowchart-persistence next: text: '8. Share verbs and shortcuts' link: /guide/flowchart-actions --- # 7. Add a custom review node Now give our flowchart a reusable review node with left and right ports. Shape definitions are extension authoring types, so first add their library beside the existing imports: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; ``` Then add this top-level definition below the app classes: ```dart ShapeDefinition reviewNode() => ShapeDefinition( type: 'tutorial.review', outline: const ShapeOutline.rect(), body: const ShapeText('body', horizontalPadding: 16, verticalPadding: 16), minimumSize: const DiagramSize(140, 80), size: const DiagramSize(220, 120), style: const ShapeStyle(cornerRadius: 12), behavior: const ShapeBehavior( rotatable: false, textSizing: ShapeTextSizing.growHeight, ), connection: ShapeConnectionDefinition.fixedPorts([ PortDefinition.onSide(id: 'input', side: PortSide.left), PortDefinition.onSide(id: 'output', side: PortSide.right), ]), ); ``` Install it through one extension on the controller. Replace the controller initializer: ```dart late final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(inspector: InspectorPlacement.none, toolbar: false), reviewExtension(), ], ), ); DiagramFlutterExtension reviewExtension() => DiagramFlutterExtension(id: 'tutorial.review', shapes: [reviewNode()]); ``` In both the initial process creation and `addProcess`, replace `Shapes.rectangle` with `'tutorial.review'`. Hot restart because the controller is created once. Existing saved rectangles do not automatically become the new type. Before restarting, also replace the two connection calls in `initState`. A ports-only review node requires an explicit port ID on its endpoint: ```dart controller.edits.connect(startId, processId, toPort: 'input'); controller.edits.connect(processId, decisionId, fromPort: 'output'); ``` The other endpoints still bind to the standard shapes' outlines. Omitting a review port is invalid; the SDK does not silently choose an outline attachment for a ports-only shape. The definition is the node's anatomy: a rounded rectangle outline (so fill, stroke and corner radius are editable), one padded `body` text part, two fixed ports and its behavior. The instance owns its ID, position and text. Shared code handles text editing, hit testing, movement, port placement, routing, saving and history. You do not implement a second painter/drag pipeline. ## Behavior, locks and host permissions | Mechanism | Question it answers | Example | | --- | --- | --- | | Definition anatomy and behavior | What edits does this type support? | Review nodes cannot rotate. | | Instance locks | Is this object currently locked? | A finalized node cannot move. | | Host admission | Is this candidate edit permitted now? | The current user has read-only access. | Unlocking a node does not grant an edit its definition does not support. All three can affect the result returned by an edit. This is why handling `allowed` belongs in custom controls too. Pass `DiagramController(configuration: DiagramConfiguration(rules: DiagramRules(beforeChange: ...)))` when you need host-wide admission; return `EditResult.denied(reason: 'This drawing is read-only.')` or `const EditResult.allow()`. It is synchronous and read-only, and it runs for every edit from any controller of the diagram. Server authorization remains your backend's responsibility. Check fixed domain invariants in the same rule against the proposed document: `beforeChange: (proposal) => validate(proposal.after)`; see [hooks](/agent-docs/api/hooks.md). **Checkpoint:** add a review node, edit its text, connect through its ports and save/load it. It has no rotation interaction. For richer compositions and native controls, continue later with [Build a library](/agent-docs/guide/build-a-library.md). --- --- prev: text: '5. Show properties and connections' link: /guide/flowchart-properties next: text: '7. Add a custom review node' link: /guide/flowchart-custom-shapes --- # 6. Save and load the drawing Save the committed document, not widget state or resolved routes. Add this field and these methods to the State for a storage-free round trip: ```dart String? savedJson; void saveDrawing() { savedJson = controller.save(DiagramJsonCodec.new); } void loadDrawing() { final json = savedJson; if (json == null) return; showDecision(controller.edits.load( json, format: DiagramJsonCodec.new, expectedRevision: controller.diagram.document.revision, )); } ``` Add Save and Load buttons to `buildToolbar` using these callbacks. This intentionally keeps the saved text in memory; connect the same JSON boundary to your file picker or backend for durable storage. ## Observe completed edits For autosave, register a dedicated listener in `initState`: ```dart controller.diagram.changes.addListener(onDocumentChanged); ``` Add its callback and remove it in `dispose`, before disposing the controller: ```dart void onDocumentChanged() { final change = controller.diagram.changes.value; if (change == null) return; // final json = DiagramJsonCodec(controller.diagram.registry.codecs) // .encode(change.after); // Enqueue json in your host's debounced, ordered persistence queue. // Keep file/network work outside this synchronous notification. } // In dispose(): // controller.diagram.changes.removeListener(onDocumentChanged); ``` Wire the queue when you choose storage; the callback above only illustrates the subscription. Completed changes include Undo and Redo. A canceled drag produces no completed edit to save. Order asynchronous writes so an older request cannot overwrite a newer revision, and surface storage failures in your application. ## Loading after asynchronous work Capture `controller.diagram.document.revision` **before** awaiting a file or network read, then pass that captured value as `expectedRevision`. If editing occurred while waiting, the SDK denies the stale replacement with a result whose `code` is `DiagramDenialCode.conflict`. Let the user retry or choose how to reconcile the content. Do not simply substitute the latest revision to bypass this check. The in-memory Load above is synchronous, so capturing at invocation is sufficient. For external input, handle decode/validation errors as well as policy denial and revision conflicts. A new controller can open JSON with `DiagramController.open(json, format: DiagramJsonCodec.new, configuration: DiagramConfiguration(extensions: [...]))`. Install the same extensions used to create it; the codec persists the content and text each installed extension owns. Definitions, verbs, key bindings, host widgets and runtime presentation are not serialized into the document. Reinstall them when reopening. **Checkpoint:** Save, move a node, Load. The saved drawing returns; Undo can reverse the accepted replacement. See [persistence](/agent-docs/api/persistence.md) for codecs and the format version. --- --- prev: text: '4. Connect reactive state to your UI' link: /guide/flowchart-reactivity next: text: '6. Save and load the drawing' link: /guide/flowchart-persistence --- # 5. Show properties and connections The optional inspector is supplied by `vyuh_diagram_extension_editor`. It uses the same `DiagramController` as the canvas. You can also build your own properties panel using the custom control pattern below. Keep the toolbar above the canvas. Replace its Expanded canvas child with a bounded row: ```dart Expanded( child: Row(children: [ Expanded(child: DiagramCanvas(controller: controller)), SizedBox(width: 280, child: DiagramInspector(controller: controller)), ]), ), ``` The inspector observes the same controller and shows properties applicable to the selection. Each change is one edit through the same admission and undo history. On a narrow screen, put it in a drawer instead of reserving 280 pixels. To add, replace or hide properties, see [properties and the inspector](/agent-docs/guide/properties.md). ## Connect our flowchart Append these calls to `initState` after creating all three nodes and before subscribing: ```dart controller.edits.connect(startId, processId); controller.edits.connect(processId, decisionId); ``` Connections retain endpoint identities. Moving a node updates its connectors automatically; the toolbar does not recalculate connector coordinates. Connection mode and port policy come from registered definitions. Port names alone do not enforce workflow direction or business rules. ## Write a custom property control A custom panel follows the same read/perform/observe loop. Add this method to the State: ```dart Widget buildSelectionTools() { final selection = controller.selection; final ids = selection is ElementSelection ? selection.elementIds : {}; return TextButton( onPressed: ids.length == 1 ? () => showDecision(controller.edits.move(const DiagramPoint(20, 0), ids: ids)) : null, child: const Text('Move selected right'), ); } ``` Add `buildSelectionTools()` to the toolbar children. Its existing reactive builder refreshes this control when selection changes. For an appearance field, read `controller.document.shapeById(id)` and call `setStyle([id], fill: ...)`, which changes only the parts you pass; for registered domain fields use `setValues(id, patch)`. Do not mutate the returned element. See [shape properties](/agent-docs/api/shapes.md) and [verbs](/agent-docs/api/verbs.md) for those signatures. Selection can represent text or a connector label as well as objects, so handle the selection variant before treating it as a set of node IDs. A disabled button is a usability hint; admission checks still run at execution. **Checkpoint:** select a node, edit it in the inspector, drag it and undo. Its connections remain attached, and your custom selection button follows the selection. Import `package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart` to use `DiagramInspector`; add the UI package as a direct dependency. The canvas itself does not depend on UI. --- --- prev: text: '3. Create the toolbar' link: /guide/flowchart-toolbar next: text: '5. Show properties and connections' link: /guide/flowchart-properties --- # 4. Connect reactive state to your UI Diagram state reaches your UI through MobX: the controller exposes read-only MobX-observable getters, and an `Observer` that reads them rebuilds when they change. Completed document edits also arrive as events on `controller.diagram.changes`. Documents remain immutable snapshots; a document reference you saved earlier never changes in place. ## From an action to a visible update Canvas gestures and toolbar verbs go through the same controller. The controller validates each edit and then publishes the new document, geometry and selection together, so observers see one consistent update per edit. The canvas and its renderer follow the controller through lightweight internal notifiers; your own controls observe the same values through the public getters. ## Rebuild the toolbar Add `flutter_mobx: ^2.4.0` to your app dependencies, run `flutter pub get`, and import `package:flutter_mobx/flutter_mobx.dart`. Replace `buildToolbar()` in the Column's children with: ```dart Observer( builder: (context) => buildToolbar(), ), ``` Inside `buildToolbar`, use the current history state: ```dart // Undo button: onPressed: controller.canUndo ? () => showDecision(controller.edits.undo()) : null, // Redo button: onPressed: controller.canRedo ? () => showDecision(controller.edits.redo()) : null, ``` Reads of `selection`, `activeTool`, `canUndo`, `canRedo`, `isInteracting`, `isAttached`, `document`, `scene`, `camera` and `elementById(id)` on the controller, of `controller.options()`, of `document`, `scene`, `snapshot` and `bounds` on `controller.diagram`, and of `controller.effects.playing`, inside an Observer are tracked. Only changes to the values that it reads rebuild it. Read those values during the builder's execution, not exclusively in a button's later `onPressed` callback. Nested child widgets need their own Observer when those children perform the reads. There is no manual subscription or revision counter to dispose. Observer manages its own reaction; your screen still owns and disposes the controller after unmounting its canvas. Avoid wrapping the whole editor when a small toolbar or property control is sufficient. ## Choose the right subscription | Your requirement | Subscribe with | Read | | --- | --- | --- | | Toolbar availability, selection or active tool | `Observer` / MobX `reaction` | Tracked controller getters | | Save, audit or synchronize completed edits | `controller.diagram.changes.addListener` | `changes.value!.after`, `.elements` | | Zoom label or camera overlay | `Observer` | `controller.camera` | ### Subscribe to one element Read `controller.elementById(id)` inside an `Observer` or MobX reaction when a control depends on one shape or connector. Unlike reading `controller.document`, this does not rebuild the control when a different element changes. Removal returns null; Undo can restore the element and notify the same subscription. Outside Flutter, `reaction((_) => controller.elementById(id), ...)` from `package:mobx` observes the same element; dispose the reaction when its consumer is done. Document, scene, selection, tool, history, interaction, camera and options changes are observed separately, so a control that reads only the selection is not rebuilt when a shape moves. Built-in controls such as the inspector and diagnostics panel work the same way. The controller's `document` and `scene` include its own in-progress preview, so observers of them also see interaction previews and provisional text edits; `controller.diagram.document`, `scene` and `snapshot` retain committed content while a gesture is previewing. A rebuild therefore does not mean there is a new document to save. Completed change events on `diagram.changes` exclude canceled gestures, selection and camera movement; any number of consumers can add and remove their own listeners. ## Bring your own state management A MobX `reaction` over the controller's getters, or a `diagram.changes` listener, can update a Riverpod provider, BLoC stream or your own observable projection. Keep document edits as controller verbs; do not maintain a second mutable diagram in your state store. Subscribe when the consumer attaches and unsubscribe when it detaches. If a widget accepts a replaceable controller, move subscriptions in `didUpdateWidget` as well. Observers may read state and update host UI, but cannot synchronously issue another diagram edit during notification. Schedule any follow-up verb after delivery and re-read current state then. **Checkpoint:** Undo disables after exhausting history, and Redo updates after canvas edits as well as toolbar clicks. No manual refresh call is needed. --- --- prev: text: '1. Set up the canvas' link: /guide/flowchart-canvas next: text: '3. Create the toolbar' link: /guide/flowchart-toolbar --- # 2. Register and create shapes A registry describes **kinds of shapes**: their geometry, text regions, connection sites and supported edits. A document contains **instances** with stable IDs, positions and content. Register a type once; create as many instances as needed. Use the shared Flutter entry point throughout this tutorial: ```dart import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ``` Keep the controller from step 1. Its registry, assembled from the installed extensions and the always-installed core, already registers rectangles, polygons and ellipses, so there is no need to redefine them; `controller.diagram.registry` holds it. A four-sided polygon supplies our decision diamond. Add these fields and replace `initState`: ```dart late final String startId; late final String processId; late final String decisionId; @override void initState() { super.initState(); startId = controller.createShape( Shapes.ellipse, at: const DiagramPoint(-240, 0), text: 'Start', ); processId = controller.createShape( Shapes.rectangle, at: DiagramPoint.zero, text: 'Review request', ); decisionId = controller.createShape( Shapes.polygon, values: {'sides': 4}, at: const DiagramPoint(260, 0), text: 'Approved?', ); } ``` Positions are world coordinates. Panning and zooming change how you view them, not their saved positions. Direct creation returns the new shape's ID. Creation through `controller.edits` returns an `EditResult` with that ID in `id`. We retain those IDs to connect the nodes later. **Checkpoint:** move the three shapes and double-click their text. The registry supplies editing behavior without host drag handlers. [Step 7](/agent-docs/guide/flowchart-custom-shapes.md) adds our own registered type. --- --- prev: text: '2. Register and create shapes' link: /guide/flowchart-shapes next: text: '4. Connect reactive state to your UI' link: /guide/flowchart-reactivity --- # 3. Create the toolbar ## What belongs to the free foundations? The toolbar in this step is ordinary Flutter UI. `createShape()`, `undo()`, `redo()`, `EditResult` and `DiagramCanvas` are available in the free Core + Flutter packages, so you can use this pattern in a foundation-only application. The complete tutorial continues the setup from step 1, which installs the commercial `EditorExtension` for interactive editing and its supplied editor controls. Building your own buttons does not require that extension; using its ready-made palette, inspector and editing tools does. See [Hello World](/agent-docs/guide/hello-world.md) for a complete foundation-only application, or [Extending it with extensions](/agent-docs/guide/extending-with-extensions.md) for the next layer. ## Build your toolbar The host owns the toolbar layout; the controller owns its edits. Add these methods inside `_DiagramSurfaceState`: ```dart void showDecision(EditResult decision) { if (!decision.allowed && mounted) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text(decision.reason ?? 'This edit is unavailable.'), )); } } void addProcess() { showDecision(controller.edits.createShape( Shapes.rectangle, at: const DiagramPoint(0, 180), text: 'New process', )); } Widget buildToolbar() => Wrap( spacing: 8, children: [ TextButton(onPressed: addProcess, child: const Text('Add process')), TextButton(onPressed: () => showDecision(controller.edits.undo()), child: const Text('Undo')), TextButton(onPressed: () => showDecision(controller.edits.redo()), child: const Text('Redo')), ], ); @override Widget build(BuildContext context) => Column( children: [ buildToolbar(), Expanded(child: DiagramCanvas(controller: controller)), ], ); ``` Replace the old `build` method with this one. New processes start at the same teaching position; move one aside before adding another. ## Why does an edit return “allowed”? An edit is a request. A shape may be locked, a capability may forbid resizing, a target may have disappeared, or your host may reject changes. The SDK checks the request before publishing it. Toolbar clicks, canvas gestures and API calls pass through shared admission and history. Use `controller.edits` when controls need to inspect an `EditResult`. Direct creation returns the new ID; other direct edits complete or throw on refusal. Read `allowed` to handle refusal in your UI, as above. Use `code` for program logic and `reason` for a human-readable explanation. ```dart void moveProcess() { controller.move(const DiagramPoint(20, 0), ids: [processId]); } ``` `requireAllowed()` checks the **returned result** and throws `DiagramChangeDenied` if denied. It neither asks permission nor forces the edit through. Use it when refusal should propagate as an exception, such as setup code or a test; handle the result for ordinary UI feedback. Creation verbs report the new ID in the result's `id`, which is null when the edit was denied. An allowed result can be a no-op; it does not promise that content changed. Invalid verb arguments return a denial with `DiagramDenialCode.unsupportedOperation`. **Checkpoint:** add a process, undo it and redo it. Next we will make history buttons reflect availability. --- # Getting started Vyuh Diagram gives your Flutter application a canvas for shapes, text and connections. The Apache-2.0 public foundations are free for commercial and open-source applications. Start with an interactive diagram, then add optional commercial extensions for specialized content and ready-made editing controls. See [all packages](/packages) for the package list and registry version badges. ## Understand the pieces Before writing code, there are three pieces to know: - **The document** holds the elements, their positions, styles and connections. - **The controller** owns the document and changes it through methods such as `createShape`, `connect` and `move`. It also manages selection and undo/redo. - **The canvas** is the Flutter widget that displays the controller's diagram and handles the viewport. Keep one controller for the lifetime of your screen and dispose it when the screen closes. Flutter rebuilds do not require recreating your document. ## What the foundations include | Capability | What you can build | | --- | --- | | Shapes | Rectangles, ellipses, polygons, cards, comments, groups, frames, images, vector paths and standalone lines. | | Text | Text boxes and plain text inside shapes, with paragraph alignment and text sizing. | | Connections | Straight connectors bound to elements or named ports, labels and basic arrowheads. Endpoints follow their owners. | | Freehand | Stroke color and width, smoothing, pressure handling, and pen, brush and marker presets. | | Edits and history | Create, move, resize, rotate and delete through controller methods; selection, undo/redo and grouped edits. | | Flutter canvas | Pan and zoom, a configurable grid, rendering and interactive editing with `DiagramFlutterExtension(editable: true)`. | | Custom content | Define shapes, compose their contents and embed regular Flutter widgets in declared slots. | | Document formats | JSON save/reopen and SVG output through the foundation codecs. | Core is independent of Flutter, so its document and controller APIs also work in a headless Dart application. Flutter adds the canvas and widget hosting. JSON and SVG are separate foundation codec packages. ## Create a Flutter project Use `vyuh_diagram_flutter` as the entry point. It exposes the canvas and shared controller APIs. ```sh flutter create diagram_example cd diagram_example flutter pub add vyuh_diagram_flutter ``` Next, follow [Hello world](/agent-docs/guide/hello-world.md) to put two shapes and a connector on an editable canvas. The [complete public package example](https://pub.dev/packages/vyuh_diagram_flutter/example) also runs with only free dependencies. ## Build up gradually 1. [Hello world](/agent-docs/guide/hello-world.md): the free foundation example, from controller to interactive editing and saving. 2. [Extending it with extensions](/agent-docs/guide/extending-with-extensions.md): add the optional editor, shape libraries and routing. 3. [Shape anatomy](/agent-docs/guide/shape-composition.md): compose your own shapes. 4. [Widgets inside shapes](/agent-docs/api/widgets.md): host interactive Flutter controls. The [vocabulary](/agent-docs/guide/vocabulary.md) and [controller verbs](/agent-docs/api/verbs.md) explain the API in more detail. --- # Hello world This example uses only the **free Core + Flutter foundations**. They are Apache-2.0 licensed and free for commercial and open-source applications. We will create two shapes, connect them and enable interactive editing. Start with the Flutter project from [Getting started](/agent-docs/guide/getting-started.md). ## 1. Create the controller The controller owns the document and edit history. Standard shapes and straight connectors are already installed. Enable the Flutter editing tools with an editable extension. Import `package:vyuh_diagram_flutter/extension_api.dart` alongside the Flutter entry point. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ const DiagramFlutterExtension(id: 'hello.editing', editable: true), ], ), ); ``` Keep it in your screen's state rather than creating it inside `build`. ## 2. Add two shapes A shape needs a type and a position. `DiagramPoint` specifies its center in diagram coordinates. `createShape` returns the new shape's ID directly. ```dart final hello = controller.createShape( Shapes.rectangle, at: DiagramPoint.zero, text: 'Hello', ); final world = controller.createShape( Shapes.ellipse, at: const DiagramPoint(240, 0), text: 'World', ); ``` Use these IDs to refer to the shapes in later edits. Diagram coordinates describe the world, rather than pixels relative to the Flutter screen. Use `controller.edits.createShape` instead when you need to check whether an edit was allowed. See [When you need to check an edit](#when-you-need-to-check-an-edit) below. ## 3. Connect them The connector binds its endpoints to the two elements and follows them when they move or resize. ```dart controller.connect(hello, world); ``` This uses the standard straight route. Controller methods can also add labels and change the connector's stroke style. ## 4. Mount the canvas `DiagramCanvas` displays the controller. Give it bounded space, such as the body of a `Scaffold` or an `Expanded` inside a column. ```dart DiagramCanvas(controller: controller) ``` With `DiagramFlutterExtension(editable: true)`, the free canvas supports interactive editing with the installed tools. Select and drag a shape to move it, and use its handles to resize or rotate it. No private packages or package token are needed. The paid editor extension adds the ready-made toolbar, palette and property inspector. These controls are optional; your application can build its own controls around the free controller APIs. For another complete application, see the [published Flutter package example](https://pub.dev/packages/vyuh_diagram_flutter/example). ## 5. Run the complete example The JSON codec saves the initial document as a string. A Reset button loads that snapshot back into the controller. This is also the save/load API your application can use with its own storage. Replace `lib/main.dart` with this application, then run `flutter run`. Content is created once in `initState`; the host disposes the controller when the screen closes. ```dart import 'package:flutter/material.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; void main() => runApp(const MaterialApp(home: Scaffold(body: HelloDiagram()))); class HelloDiagram extends StatefulWidget { const HelloDiagram({super.key}); @override State createState() => _HelloDiagramState(); } class _HelloDiagramState extends State { final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ const DiagramFlutterExtension(id: 'hello.editing', editable: true), ], ), ); late final String saved; @override void initState() { super.initState(); final hello = controller.createShape( Shapes.rectangle, at: DiagramPoint.zero, text: 'Hello', ); final world = controller.createShape( Shapes.ellipse, at: const DiagramPoint(240, 0), text: 'World', ); controller.connect(hello, world); saved = controller.save(DiagramJsonCodec.new); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Column( children: [ TextButton( onPressed: () => controller.load(saved, format: DiagramJsonCodec.new), child: const Text('Reset'), ), Expanded(child: DiagramCanvas(controller: controller)), ], ); } ``` ## 6. Group edits and use history Each controller edit is undoable. Wrap several edits in a batch when they should count as one action—for example, creating both shapes and their connection together. ```dart controller.batch('Add greeting', () { final hello = controller.createShape( Shapes.rectangle, at: DiagramPoint.zero, text: 'Hello', ); final world = controller.createShape( Shapes.ellipse, at: const DiagramPoint(240, 0), text: 'World', ); controller.connect(hello, world); }); controller.undo(); controller.redo(); ``` Use this batch in place of the creation code in `initState`. A refused direct edit throws `DiagramChangeDenied` and rolls back the batch. Use `controller.edits` when your application needs to inspect `allowed` and `reason` instead. ## 7. Save and reopen The JSON codec converts the document to a string. Store that string wherever your application saves documents. Loading it replaces the controller's content. ```dart final saved = controller.save(DiagramJsonCodec.new); controller.load(saved, format: DiagramJsonCodec.new); ``` The Flutter entry point exposes the JSON codec, so this needs no additional import. Selection and the camera are view state rather than document edits. Next: [Extending it with extensions](/agent-docs/guide/extending-with-extensions.md). ## When you need to check an edit There are two ways to create a shape. Call `controller.createShape` directly for the new ID. Use `controller.edits.createShape` when your application needs to handle a refused edit. Both use the same document and undo history. ```dart final result = controller.edits.createShape( Shapes.rectangle, at: DiagramPoint.zero, ); if (result.allowed) { controller.select([result.id!]); } else { print(result.reason); } ``` --- # Live data Dashboards drive shapes from live domain data: a charger card shows its current kW, a load bar grows with demand, a gauge follows a battery's charge. There are two ways to show live data, and a dashboard often uses both. | Path | What changes | Use it when | | --- | --- | --- | | [Document edits without history](#document-edits-without-history) | The diagram document: text, style, bounds. | The value belongs in the diagram: it is saved and exported, agents and rules see it, connectors follow a resized shape, and the canvas animates it. | | [Widget slots](#widget-slots) | Nothing in the document; a Flutter widget inside a shape rebuilds. | The value is presentation only, changes often, or needs a rich control such as a gauge or chart. Exports show the slot's fallback. | Both read the data from one place: a store that the feed writes into. ## Connect the feed through a store Keep the transport, a WebSocket, a polling client or a message bus, out of the diagram. It writes readings into a MobX store; the diagram and widgets observe the store. Every snippet on this page uses these imports: ```dart import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:mobx/mobx.dart' hide Listenable; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; /// One reading from the charging site. class ChargerReading { const ChargerReading({required this.kw, required this.capacityKw}); final double kw; final double capacityKw; double get load => (kw / capacityKw).clamp(0, 1); } /// The latest reading, written by whatever feed is connected. class ChargerStore { final reading = Observable(null); StreamSubscription? _subscription; void connect(Stream feed) { _subscription?.cancel(); _subscription = feed.listen( (next) => runInAction(() => reading.value = next), ); } void dispose() => _subscription?.cancel(); } ``` Any source becomes a `Stream`. A WebSocket delivers messages; a polling API is fetched on an interval: ```dart /// Readings from WebSocket [messages], each a JSON object. Stream webSocketReadings(Stream messages) => messages.map((message) { final json = jsonDecode(message as String) as Map; return ChargerReading( kw: (json['kw'] as num).toDouble(), capacityKw: (json['capacityKw'] as num).toDouble(), ); }); /// Readings from [fetch], called every [interval]. Stream polledReadings( Future Function() fetch, { Duration interval = const Duration(seconds: 2), }) async* { while (true) { yield await fetch(); await Future.delayed(interval); } } ``` ## Document edits without history A `reaction` on the store writes each reading into the diagram with `batch(label, build, history: false)`: ```dart /// Mirrors [telemetry] into [controller]. Dispose the reaction before the /// controller. ReactionDisposer bindCharger( ChargerStore telemetry, DiagramController controller, ) => reaction( (_) => telemetry.reading.value, (ChargerReading? reading) { if (reading == null || controller.isDisposed) return; controller.edits.batch('Charger telemetry', () { final card = controller.document.shapeById('charger'); if (card == null) return; // The user deleted it. controller.edits.setText('charger', '${reading.kw.round()} kW', slot: 'body'); controller.edits.setStyle( ids: ['charger'], fill: DiagramColor(reading.load > .8 ? 0xFFFFE3DC : 0xFFE8F5EC), ); controller.edits.setElementBounds( 'charger-load', DiagramRect.fromLTWH( card.frame.left, card.frame.bottom + 8, card.frame.width * reading.load, 24, ), motion: Motion.smooth, ); }, history: false); }, // Throttle: at most one diagram edit per 100 ms, with the latest value. delay: 100, ); ``` What `history: false` gives you: - **No undo entries.** The user's undo stack holds only the user's edits, and the redo stack survives live updates. - **Undo stays correct.** Undoing an earlier edit restores the fields that edit changed and keeps the live values: if the user recoloured the charger and a reading then changed its text, Undo restores the colour and keeps the kW. A later live write to the same field wins. - **Interactions continue.** Updates apply while the user drags or types. A dragged shape keeps the frame the user is moving and shows the live text and colour; you don't need to pause the feed. - **The ordinary pipeline.** Locks, rules and agents see the edit, connectors re-route, and `diagram.changes` reports it with `history` false. ### Batching and throttling Put everything one reading changes into one batch: one publication, one change event and one resolution, however many shapes it touches. Don't open a batch per field. When the feed is faster than the eye, throttle before the diagram, with the reaction's `delay` as above, or by sampling the stream. Each batch resolves only the shapes it changed and the connectors attached to them. ### Animated bounds `setElementBounds`, `move`, `resize` and `layout` take a `motion`. The document takes the final bounds at once, so hit testing, saving and agents see them; the canvas animates the shape, its text and ports, and its connectors there. A new reading mid-animation retargets smoothly. With the platform's reduce-motion setting, shapes jump. See [animated geometry](/agent-docs/api/navigation-and-motion.md#animated-geometry). ### Autosave Live edits are not the user's work. Skip them when marking the document dirty or autosaving; the next user edit saves the latest live values with it: ```dart /// Saves every edit the user can undo. VoidCallback autosave(Diagram diagram, void Function(DiagramDocument) save) { void listener() { final change = diagram.changes.value; if (change == null || !change.history) return; save(change.after); } diagram.changes.addListener(listener); return () => diagram.changes.removeListener(listener); } ``` ## Widget slots A shape can host a Flutter widget in a slot. Bind the slot with `DiagramFlutterExtension(widgets:)` and rebuild it with an `Observer`: the widget follows the store without editing the document. Exports and hosts without the widget show the slot's fallback. ```dart /// A gauge shape whose dial follows [telemetry]. DiagramFlutterExtension chargerGauge(ChargerStore telemetry) => DiagramFlutterExtension( id: 'charger.gauge', shapes: [ ShapeDefinition( type: 'charger.gauge', name: 'Charger gauge', size: const DiagramSize(180, 56), body: ShapePadding( 8, child: const ShapeWidget( 'charger.gauge.dial', id: 'dial', fallback: ShapeText( 'caption', text: 'Charger load', editable: false, textType: PlainTextDefinition(maxLines: 1), ), ), ), ), ], widgets: { 'charger.gauge.dial': (context, slot) => Observer( builder: (_) => LinearProgressIndicator( value: telemetry.reading.value?.load ?? 0, ), ), }, ); ``` ## Own and dispose The widget that owns the controller owns the store and the reaction too. Dispose in reverse: stop the feed, dispose the reaction, then the controller. ```dart class ChargerDashboard extends StatefulWidget { const ChargerDashboard({super.key, required this.feed}); final Stream feed; @override State createState() => _ChargerDashboardState(); } class _ChargerDashboardState extends State { final telemetry = ChargerStore(); late final controller = DiagramController( configuration: DiagramConfiguration(extensions: [chargerGauge(telemetry)]), document: chargerDocument(), ); late final ReactionDisposer binding; @override void initState() { super.initState(); binding = bindCharger(telemetry, controller); telemetry.connect(widget.feed); } @override void dispose() { telemetry.dispose(); binding(); controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => DiagramCanvas(controller: controller); } DiagramDocument chargerDocument() => DiagramDocument( id: 'charging-site', revision: 0, elements: [ ShapeElement( id: 'charger', type: Shapes.card, frame: const DiagramRect.fromLTWH(0, 0, 180, 92), textStory: TextStory( id: 'charger-story', blocks: [ TextParagraph( id: 'charger-title', slotId: 'title', role: TextRole.title, runs: [TextRun('EV charger')], ), TextParagraph( id: 'charger-kw', slotId: 'body', role: TextRole.body, runs: [TextRun('Awaiting data')], ), ], ), ), ShapeElement( id: 'charger-load', type: Shapes.rectangle, frame: const DiagramRect.fromLTWH(0, 100, 24, 24), ), ShapeElement( id: 'charger-gauge', type: 'charger.gauge', frame: const DiagramRect.fromLTWH(0, 140, 180, 56), ), ], ); ``` The [live energy flow](/agent-docs/examples/path-effects.md) example streams simulated telemetry through a store into both paths, with a switch to pause the feed. Edit or drag its assets while it runs: Undo undoes only your edits. --- # Package access Use Flutter 3.47 or later with Dart 3.13 or later. See [all packages](/packages) to choose what you need. ## Core For a Flutter app: ```sh flutter pub add vyuh_diagram_flutter ``` For a Dart service or agent: ```sh dart pub add vyuh_diagram_core ``` Core packages come from pub.dev. No token is needed. ## Extensions 1. Copy your package token from [your Diagram account](https://pub.vyuh.tech/diagram). 2. Register it and enter the token when prompted: ```sh dart pub token add https://pub.vyuh.tech ``` 3. Add the extension to your `pubspec.yaml`. For example: ```yaml dependencies: vyuh_diagram_extension_editor: hosted: https://pub.vyuh.tech version: ^3.11.0 ``` 4. Fetch the packages: ```sh flutter pub get ``` Use `dart pub get` for a Dart project. Keep the token out of your source code. Continue with [Getting started](/agent-docs/guide/getting-started.md) or [adding extensions](/agent-docs/guide/extending-with-extensions.md). --- # Properties and the inspector Everything a person can edit in the inspector is a **property**: a key, a label, a group, how to read its value from a subject, the [verb](/agent-docs/api/verbs.md) that sets a new one and how the value is presented. Built-in styles, shape value fields, connector route options, tables, rich text and your own domain data all use the same property grammar, so they share one inspector, one layout and one undo history. The inspector shows the properties that apply to the current selection. A change is always one undoable controller edit, even when several elements are selected. When selected elements disagree, the property shows as **Mixed**. Shared fields intersect the selected kinds' ranges and choices. Incompatible ranges are disabled with a reason; a mixed choice has no active option. Application code uses typed keys from the main application import: ```dart final fill = controller.properties().require(ShapeProperties.fill); if (fill.isEnabled) fill.set(const DiagramColor(0xff2457ff)).requireAllowed(); final score = controller.properties(ids: ['service']).find( ShapeProperties.value('score'), ); ``` `find` returns null when a field does not apply to every affected item; `require` reports that case clearly. Fields capture a revision, so resolve them again after an edit. Shape-specific declarations belong in `ShapeDefinition(properties: [...])`; each kind retains its own read function and verb arguments when shared fields edit several kinds together. Showing the inspector takes only the editor's main library. Declaring properties uses the property grammar (`DiagramProperty`, `DiagramPropertyGroup`, `DiagramPropertyScope`, `DiagramProperties`, `DiagramPropertySource`) and custom editors use `DiagramPropertyEditor`, all from `package:vyuh_diagram_flutter/extension_api.dart`. Controls for custom editors, such as `DiagramNumericProperty`, are in `package:vyuh_diagram_extension_editor/controls.dart`. `DiagramPropertyField`, `DiagramPropertyGesture` and typed keys are in `vyuh_diagram_flutter.dart` or the headless `vyuh_diagram_core.dart`. The `DiagramPropertyEditor.of` callback receives a field of type `T` directly. ```dart Row(children: [ Expanded(child: DiagramCanvas(controller: controller)), SizedBox(width: 280, child: DiagramInspector(controller: controller)), ]) ``` Import `DiagramInspector` from `package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart`. The property grammar itself is part of `vyuh_diagram_core` and has no Flutter dependency. ## Presentations Each constructor pairs a value type with its presentation: | Constructor | Value | Presentation | | --- | --- | --- | | `DiagramProperty.text` | `String` | A text field | | `DiagramProperty.number` | `double` | `min`, `max`, `step`, `unit`, `precision` and a stepper, field, slider, percentage or cell `style`; `bounds` narrows the range per subject | | `DiagramProperty.toggle` | `bool` | A switch, a compact switch, or with an `icon` a toolbar button or a button in the section header | | `DiagramProperty.choice` | `T` | The `options` a subject offers, as swatches, a menu or buttons | | `DiagramProperty.color` | `DiagramColor` | A color with alpha | | `DiagramProperty.fill` | `DiagramFill` | No fill, a solid color or a gradient | | `DiagramProperty.point`, `DiagramProperty.size` | `DiagramPoint`, `DiagramSize` | An x/y or width/height pair | | `DiagramProperty.action` | none | A verb performed without a value | | `DiagramProperty.custom` | `T` | An editor chosen by `T` | | `DiagramProperty.forValue` | as stored | The standard control of a `ValueField` | The inspector draws a choice's swatches by the option values' type: stroke patterns, routes, arrowheads, ink presets, grid patterns, text directions, label presentations and font families each have their own swatch; other options show their icon or label. A property reads a **subject** and names the verb that sets a new value and the verb's arguments for that value: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; DiagramProperty.number( 'shape-corner-radius', label: 'Corner radius', group: DiagramPropertyGroup.style, read: (shape) => shape.style.cornerRadius, verb: 'setStyle', args: (shape, radius) => {'cornerRadius': radius}, max: 48, unit: 'px', ) ``` The subject type decides where the property applies: `ShapeElement`, `ConnectorElement`, `TextElement` or `DiagramElement` for selected elements, `ConnectorLabel` for a selected label, `DiagramTextSubject` for the text being edited, and an options type such as `GridOptions`, or `CanvasBounds`, for the canvas. `visible` and `enabled` predicates receive the same subject. A property applies to every selected subject of its type, so a multi-selection edits them together. Properties of elements take `verb:` and `args:`. Properties of values that are not elements, such as `GridOptions`, a `ConnectorLabel` or a `DiagramTextSubject`, take `update: (subject, value) => newSubject` instead. The inspector then applies the new value through its owner: options through `controller.setOptions`, the canvas bounds through `controller.setBounds`, a label through `setConnectorLabel` and text through `replaceText`. `editLabel` names the undo entry for a value. A locked element offers only its lock, and a creation tool only the fill, stroke and corners of the shapes it will create. ## Shape properties A shape's properties follow from its anatomy: fill and stroke from its outline, corner radius from a rounded outline, sides from a polygon, points from an editable path, an image from an image value, text from its text parts and one standard control per declared value through `DiagramProperty.forValue`. Route options are value fields too, so a route's options get the same controls. Add your own properties from a `DiagramPropertySource`. This **Asset** shape stores an owner, picked from a host list: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; const assetGroup = DiagramPropertyGroup( 'asset', label: 'Asset', after: 'appearance', ); final owner = DiagramProperty.custom( 'asset-owner', label: 'Owner', group: assetGroup, read: (shape) => Owner(shape.values['owner']! as String), verb: 'setValues', args: (shape, owner) => { 'values': {'owner': owner.name}, }, check: (owner) => owner.name.trim().isEmpty ? 'Choose an owner' : null, ); final class AssetProperties implements DiagramPropertySource { @override Iterable> propertiesFor( DiagramPropertyScope scope, ) => [owner]; } final asset = ShapeDefinition( type: 'asset', name: 'Asset', values: {'owner': TextValueField(defaultValue: 'Unassigned')}, ); ``` `check` rejects a value before its verb is performed; the inspector shows the reason under the control. A property compares values with `==` to detect a mixed selection; pass `equals` for values such as case-insensitive names. ## Write an editor A custom property's value type chooses its editor. Register an editor for `Owner`. It receives the resolved field: its value, whether the selection is mixed, whether it is enabled, and `set` to perform the property's verb through the controller. An editor can render inline or open its own dialog, sheet or route: ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final class Owner { const Owner(this.name); final String name; @override bool operator ==(Object other) => other is Owner && other.name == name; @override int get hashCode => name.hashCode; } const owners = ['Ada', 'Grace', 'Linus']; final ownerPicker = DiagramPropertyEditor.of((context, field) { return TextButton( onPressed: field.isEnabled ? () async { final revision = field.revision; final chosen = await showDialog( context: context, builder: (context) => SimpleDialog( title: const Text('Owner'), children: [ for (final name in owners) SimpleDialogOption( onPressed: () => Navigator.pop(context, name), child: Text(name), ), ], ), ); if (chosen == null) return; final result = field.set( Owner(chosen), expectedRevision: revision, ); if (result.code == DiagramDenialCode.conflict) { // The diagram changed while the dialog was open. } } : null, child: Text(field.isMixed ? 'Mixed' : field.value!.name), ); }); DiagramInspector( controller: controller, properties: DiagramProperties(sources: [AssetProperties()]), editors: [ownerPicker], ) ``` The captured field revision is checked by default; `expectedRevision` can make that guard explicit when the value is chosen after asynchronous work. If the diagram changed in the meantime, `set` returns a denial with `DiagramDenialCode.conflict` and changes nothing. For continuous input such as a drag, call `field.begin()`, `preview` each value and `commit` once (or `cancel`): the gesture performs the verb on an interaction lease, each preview starting over from the baseline, and the drag is one undo entry. The inspector places a custom editor beside its label by default. Pass `layout: DiagramPropertyLayout.stacked` for a label above, or `full` when the editor draws its own label. Without an editor for its type, a custom property shows its `summary`. ## Groups A `DiagramPropertyGroup` is a section. The inspector shows each group once, in the order its first property appears. A property contributed to an existing group joins its end; a new group starts `after` the group it names. Its `label` titles the section, and its `spacing` sets the gaps before the section, under its title and after it. Icons are `DiagramIcon` values: a symbolic `name` plus an optional portable `svg` glyph. Give a property or option `icon: const DiagramIcon('asset')` and pass `icons: {'asset': Icons.inventory_2}` to the inspector to resolve the name. The inspector uses a host icon for the name first, then the editor's icon for core names, and otherwise draws the declared glyph with `DiagramIconGlyph`, so an extension that ships its own glyph, such as rich text's `RichTextIcons`, needs no host mapping. Set `searchable: true` to offer a filter by property label. ## Contribute from an extension An extension contributes properties by overriding `propertiesFor(scope)`. The grid extension offers **Show grid**, **Grid type**, **Snap to grid** and the grid size for its own `GridOptions` in the canvas group. Anything an extension installs can contribute too by implementing `DiagramPropertySource`: a connector route provider, a content provider or a text formatting object. The connectors extension surfaces each route's options in the **Routing** section, rich text adds marks, headings and lists, and the table extension adds its **Table** section after **Appearance**. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final class ReviewRoute extends DiagramConnectorRouteProvider implements DiagramPropertySource { // ... @override Iterable> propertiesFor( DiagramPropertyScope scope, ) => [reviewLaneProperty]; } ``` A Flutter extension renders its custom properties by listing an editor for each value type in `propertyEditors:`; the inspector finds them in the extensions installed in the diagram's configuration: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; DiagramFlutterExtension( id: 'app.assets', shapes: [asset], propertyEditors: [ownerPicker], ) ``` ## Without the inspector The grammar works headlessly. Resolve the fields for the current selection and set values through them, for example from a command palette or a test: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final fields = DiagramProperties().resolve(DiagramPropertyScope(controller)); final width = fields.firstWhere((field) => field.key == 'shape-stroke-width'); width.set(4).requireAllowed(); ``` See the [property inspector](/agent-docs/api/inspector.md) reference for the built-in sections and standard controls. --- # SDK licensing The five foundation packages—types, core, Flutter, JSON and SVG—are available from pub.dev under Apache-2.0. They have no commercial package dependencies. Start with [the free Flutter canvas](/agent-docs/guide/getting-started.md). UI and optional extension packages retain commercial licensing. Production use requires an Indie, Team or Enterprise license. ## Package licensing map ![Public Apache-2.0 foundations and commercially licensed toolkit extensions](/package-licensing.svg) All public package listings point to this toolkit website for documentation and support. Commercial extensions depend on the foundations; the foundations do not depend on commercial extensions. ## Choose your plan | Plan | Coverage | | --- | --- | | Free | Public foundation packages for free and open-source applications. Apache-2.0 also permits commercial use of these foundations. | | Indie | One individual developer and one named commercial application. | | Team | Unlimited developers working on one named commercial application. | | Enterprise | Negotiated application coverage, support and integration requirements. | Indie and Team include unlimited customers, end users and diagrams. See [pricing](/pricing) for current annual prices. Contact is needed only for Enterprise. Standard purchases accept the [commercial agreement](/commercial-agreement) during checkout; the purchase retains a permanent record of the accepted terms and named application. ## Commercial license benefits | Benefit | What you get | | --- | --- | | Diagram SDK | The complete Diagram package set under one annual application license. See [licensing](/licensing) for current pricing. | | Commercial use | One named application, including its web, desktop and mobile editions. | | Developers | One individual developer for Indie; unlimited employees and contractors for Team. | | Customers | Unlimited customers, end users and diagrams within the licensed application, with no runtime royalties. | | SDK updates | Updates during your active subscription. | | Technical support | Email assistance with installation, documented APIs and SDK bug investigation. | | Custom integrations | Build your own shapes, widgets and integrations through the public APIs. | Custom development and dedicated support arrangements are quoted separately. Purchase Indie or Team from [pricing](/pricing). For Enterprise requirements, contact [licensing@vyuh.tech](mailto:licensing@vyuh.tech). Your agreement records the developer scope, named application and support commitments. Already-shipped application versions retain deployment rights after the subscription ends. New SDK development, updates and support require renewal. Private package access expires at the end of the verified paid period. Changes to commercial SDK source require written authorization. This restriction does not apply to the Apache-2.0 foundation packages. Separately licensed third-party components retain their own terms. ## Purchases and refunds Paddle is our Merchant of Record and authorized reseller for purchases through Paddle. Paddle handles payment, applicable sales taxes, billing and refunds under the [Paddle Buyer Terms](https://www.paddle.com/legal/buyer-terms). Vyuh Technologies Private Limited provides the SDK, license and product support. All purchases through Paddle, including renewals and custom or enterprise purchases, qualify for a full refund when requested within 14 days, with no exceptions. No reason or prior support conversations are required. Your written commercial agreement cannot reduce this guarantee. See our [Refund Policy](/refund-policy), [Terms and Conditions](https://vyuh.tech/terms/) and [Privacy Policy](https://vyuh.tech/privacy/). After 14 days, discretionary refund requests are considered when multiple support conversations and reasonable attempts to help establish that the toolkit cannot meet your needs. These requests are reviewed individually and refunds are not guaranteed, without limiting the 14-day guarantee or statutory rights. --- # Shape behavior What a person can do to a shape comes from its definition in pure Dart. The engine and the Flutter canvas read the same declaration; an overlay never decides on its own whether an operation is allowed. Part of it you declare as `behavior`; the rest follows from the shape's [anatomy](/agent-docs/guide/shape-composition.md). ## Declare behavior ```dart import 'package:vyuh_diagram_core/extension_api.dart'; import 'package:vyuh_diagram_core/vyuh_diagram_core.dart'; final note = ShapeDefinition( type: 'app.note', size: const DiagramSize(240, 120), behavior: const ShapeBehavior( rotatable: false, textSizing: ShapeTextSizing.fitHeight, ), body: const ShapeText('body', text: 'Height follows the text'), ); ``` The note cannot rotate, and its height follows its text, so only its left and right resize handles show. | `ShapeBehavior` property | Default | Effect | | --- | --- | --- | | `selectable` | `true` | Whether the shape can be selected. | | `deletable` | `true` | Whether the shape can be deleted. | | `movable` | `true` | Whether the shape can be moved. | | `resizable` | `true` | Whether the shape can be resized; `false` shows no resize handles. | | `rotatable` | `true` | Whether the shape can be rotated, from a corner or the rotation handle. | | `rotationHandle` | `false` | Shows a stem-and-circle rotation control above a rotatable shape. | | `textSizing` | `ShapeTextSizing.fixed` | `fixed` keeps the authored frame; `growHeight` treats the authored height as a minimum and grows downward; `fitHeight` makes the height follow the content exactly. | Resize handles follow from these: all eight when resizable, only the left and right sides when the height fits the content, and none when not resizable. `behavior.resizeHandles` lists them. Handle names describe the shape's local sides; their positions follow shape rotation. The rotation stem is presentation only: it cannot enable rotation when `rotatable` is false. ## What follows from the anatomy Editing is not declared with flags. It follows from what the shape is made of: | The shape has | So a person can edit | Read it as | | --- | --- | --- | | An `outline` | Fill and stroke | `definition.paintsSurface` | | An outline that rounds its corners (`rect()`, `regularPolygon()`, `editablePath()`, or a path with `cornerRadius: true`) | Corner radius | `definition.cornerRadiusEditable` | | An editable `ShapeText`, or content such as a table | Text | `definition.textEditable` | | A `PathValueField` read by an editable path outline | Points | `definition.pathValue` | | A regular polygon outline | Its number of sides | `definition.sidesValue` | | An `ImageValueField` | The image | `definition.imageValue` | | Any other value | That value, with one control each | `definition.customValues` | `definition.propertyEditors` lists the resulting inspector sections in order. To remove a control, change the anatomy: a shape with `outline: null` has no fill or stroke, `ShapeOutline.rect(cornerRadius: false)` has square corners, a `ShapeText(..., editable: false)` is text people cannot edit on the canvas, and `body: null` hosts no text. ## Containers A shape that owns child elements declares a `container`: ```dart import 'package:vyuh_diagram_core/extension_api.dart'; final lane = ShapeDefinition( type: 'app.lane', container: const ShapeContainer(clips: true, resizesChildren: false), behavior: const ShapeBehavior(rotatable: false), ); ``` | `ShapeContainer` property | Default | Effect | | --- | --- | --- | | `clips` | `false` | Instances may clip their children to the outline with `clipContent`. A clipping container always shows its border, so its extent stays visible. | | `resizesChildren` | `true` | Whether resizing the container scales its children. Movement and rotation always carry them. | A container may also declare `collapse: ShapeCollapseDefinition(...)` for a compact presentation. See [frames and ownership](/agent-docs/examples/containment.md). ## Definition policy versus instance state Behavior is fixed on each registered definition; there is no per-instance behavior callback. Locking an instance keeps it selectable but stops moving, resizing, rotating, deleting and editing it, while preserving its appearance. A collapsed container cannot resize or rotate, and its text does not size it. Content can narrow behavior too: a table whose controls disable `resizeTable` makes its shape not resizable. `resolved.behavior` on a resolved shape combines all of these. Command admission additionally checks the diagram's `DiagramRules` and operation preconditions. For a different permanent behavior, register another shape definition. Do not replace a loaded registry definition or hide handles in an overlay as a substitute for engine policy. See [shape anatomy](/agent-docs/guide/shape-composition.md) to package this definition in an extension and [Canvas foundations](/agent-docs/guide/getting-started.md) to render it. --- # Shape anatomy A shape has an **outline** and a **body**. The outline supplies its fill, border and connection boundary. The body arranges text, images, widgets and smaller surfaces inside it. ![Shape anatomy: fill, border, padding, title and body slots, a nested surface, and row, column and stack layouts.](/diagrams/shape-anatomy.svg) ## Compose a shape This approval card places an icon beside its title, with a body below. All parts move, resize and rotate as one shape. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final approval = ShapeDefinition( type: 'app.approval', name: 'Approval', size: const DiagramSize(240, 140), body: ShapePadding(12, child: ShapeColumn([ ShapeSized(extent: 32, child: ShapeRow([ ShapeSized(extent: 32, child: const ShapeSurface( outline: ShapeOutline.ellipse(), style: ShapeStyle(fill: DiagramColor(0xFFDBEAFE)), )), const ShapeText( 'title', text: 'Approval', textType: PlainTextDefinition(maxLines: 1), ), ], gap: 8)), const ShapeText('body', text: 'Describe the decision'), ], gap: 8)), ); final approvalExtension = DiagramExtension( id: 'app.approvals', shapes: [approval], ); ``` Install your definition once, then create it like any other shape: ```dart void main() { final controller = DiagramController( configuration: DiagramConfiguration(extensions: [approvalExtension]), ); final id = controller.createShape( 'app.approval', at: const DiagramPoint(200, 150), ); controller.setText(id, 'Approved', slot: 'title'); } ``` ## Arrange the body | Part | What it does | | --- | --- | | `ShapeRow` | Places parts side by side. | | `ShapeColumn` | Places parts top to bottom. | | `ShapeStack` | Layers parts back to front. | | `ShapePadding` | Leaves room around a part. | | `ShapeSized` | Gives a part a fixed size or a share of the remaining space. | | `ShapeText` | Adds a named text slot. | | `ShapeSurface` | Paints a smaller surface with its own style. | | `ShapeImage` | Displays an image. | | `ShapeWidget` | Hosts a Flutter widget with a portable fallback. | Rows and columns accept a `gap`. Flexible children share the remaining space; fixed-size children keep their extent. Nest rows and columns for grid-like arrangements. These are diagram parts, not Flutter layout widgets. ## Choose the outline The default is a rectangle. Use `ShapeOutline.ellipse()` for an ellipse, `ShapeOutline.polygon(...)` for straight edges, or a path for a custom contour. Fill, stroke and corner radius come from the shape's style. ## Add behavior and data Shapes support selection, movement, resizing, rotation and text editing. Configure these with [shape behavior](/agent-docs/guide/shape-capabilities.md). Declare typed `values` for instance data and `adjustments` for on-canvas handles. Use `connection` for attachment rules and `container` to own child elements. See the [shape API](/agent-docs/api/shapes.md) for the full set of parts, outlines, values, ports and libraries, or [widgets inside shapes](/agent-docs/api/widgets.md) for Flutter content. --- # Plain text and rich text Plain text is included in Core. Rich text adds bold, italic, headings, lists and checklists through the Rich Text extension. Both share selection, editing, undo and persistence. ## Create rich text ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), RichTextExtension()], ), ); final id = controller.createRichText( at: const DiagramPoint(200, 120), text: 'Edit this Rich Text', ); // Mount DiagramCanvas(controller: controller). Leave EditorExtension out // for a view-only canvas. // Dispose the controller when its owner is disposed. ``` Install `RichTextExtension()` once. Then call `createRichText` directly, or `controller.edits.createRichText` to inspect the edit outcome. Ordinary `createText` calls and existing shape slots stay plain. ## Rich text inside a shape ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final note = ShapeDefinition( type: 'app.note', body: ShapeColumn([ const ShapeText( 'title', text: 'Plain title', textType: PlainTextDefinition(maxLines: 1), ), const ShapeText( 'body', text: 'Formatted body', textType: RichTextDefinition(grammar: RichTextGrammar(headings: false)), ), ]), ); final notes = DiagramExtension(id: 'app.notes', shapes: [note]); final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), RichTextExtension(), notes], ), ); ``` Each slot selects its own text and editing behavior; a slot without `textType` holds plain text. A table chooses the text of all its cells with `ShapeTable(..., textType: ...)`, and a connector its labels with `ConnectorLabelingCapability(textType: ...)`. Admission rejects paragraphs a slot's text does not admit, such as a list item in a plain slot or a second paragraph in a single-line slot. A shape's declaration need not name its text at all. To give the core Comment, rectangle or card rich text, or a plain shape of your own, install `RichTextExtension()` and a copy made with `ShapeDefinition.withText`; see [Rich text in shapes](/agent-docs/api/rich-text.md#rich-text-in-shapes). ## Configure text Use `maxLines: 1` for a single line, or `0` for unlimited paragraphs. `RichTextGrammar` chooses which marks, headings and lists a rich slot allows. Use `withText(const RichTextDefinition())` to give a core shape rich text. See the [rich-text API](/agent-docs/api/rich-text.md) for formatting, grammar and shortcuts. --- # Theming A `DiagramTheme` decides how a canvas looks: its background and grid, selection chrome, the styles that new shapes and connectors start with, how authored colors paint in dark mode, and whether it is light or dark. It is composed of small sub-themes, one per concern. The chrome an extension adds, such as the minimap, takes its colors from that extension's options, with a light or dark default chosen by the theme's brightness. ```dart DiagramCanvas( controller: controller, theme: DiagramTheme.dark, ) ``` ## Install a theme There are two places to set it; the canvas wins over the host theme. | Where | Scope | | --- | --- | | `ThemeData(extensions: [DiagramTheme.dark])` | Every canvas below the host `Theme`. `DiagramTheme` is a `ThemeExtension`, so it follows `MaterialApp`'s `theme`/`darkTheme` switch. | | `DiagramCanvas(theme: ...)` | One canvas and the chrome its extensions add around it, such as the editor's toolbar and inspector. | Without either the canvas uses `DiagramTheme.light`, the default look. Read the active theme anywhere below a canvas with `DiagramTheme.of(context)`. ```dart MaterialApp( theme: ThemeData(extensions: const [DiagramTheme.light]), darkTheme: ThemeData.dark().copyWith( extensions: const [DiagramTheme.dark], ), home: DiagramCanvas(controller: controller), ); ``` ## Presets | Preset | Look | | --- | --- | | `DiagramTheme.light` | The default canvas. Documents paint exactly in their authored colors. | | `DiagramTheme.dark` | A dark canvas with brighter selection chrome. Authored colors are adapted so that dark strokes and text stay readable; see [dark mode](#dark-mode). | Start from a preset and replace what you need with `copyWith`: ```dart final brand = DiagramTheme.light.copyWith( canvas: const CanvasTheme(background: Color(0xFFF7F7F2)), selection: const SelectionTheme( color: Color(0xFF0A7D5A), marquee: Color(0xFF0A7D5A), ), ); ``` Themes interpolate with `lerp`, so a host `Theme` animates between light and dark as it does for Material colors. ## Sub-themes | Sub-theme | Field | Controls | | --- | --- | --- | | `CanvasTheme` | `canvas` | `background`; `gridMinor` and `gridMajor` override the document grid's colors when set. `DiagramTheme(canvas: CanvasTheme(background: color))` sets the canvas color. | | `SelectionTheme` | `selection` | Selection and hover outlines (`color`), `handleFill`, `handleHover`, the `marquee` and the selected-`text` highlight while editing. | | `ShapeTheme` | `shapes` | Styles for new shapes, how authored shape and text colors paint (`adapt`), the `collapseControl` glyphs of frames and the eraser's `erasePreview` fade. | | `ConnectorTheme` | `connectors` | The style of new connectors, how authored connector and label colors paint (`adapt`), connection feedback (`accepted`, `rejected`) and the `bundleBadge` fill. | ## Styles for new content `ShapeTheme` and `ConnectorTheme` give content created on the canvas its starting style: shapes drawn with a tool, dropped from a palette, created by connected creation, and shapes and connectors added through the controller while the canvas is mounted. ```dart DiagramTheme( shapes: ShapeTheme( style: ShapeStyle(fill: DiagramColor(0xFFF8FAFC)), types: { Shapes.card: ShapeStyle(fill: DiagramColor(0xFFFFF4CC)), }, ), connectors: ConnectorTheme( style: ConnectorStyle(color: DiagramColor(0xFF334155), strokeWidth: 1.5), ), ) ``` - `types` styles one shape type; `style` covers every other type. Leave both out to keep each shape type's own default. - A style the user picks for future shapes (for example in the inspector while a creation tool is active) takes precedence over the theme. - These are starting styles only. They are written into the document when the content is created, and changing the theme later does not restyle existing content. ## Dark mode A document stores its own colors, and most documents are drawn for a light background: black strokes and text, white fills. On a dark canvas those colors would disappear, so `ShapeTheme.adapt` and `ConnectorTheme.adapt` re-map authored colors while painting: | Adaptation | Effect | | --- | --- | | `ColorAdaptation.none` | Colors paint as authored. Used by `DiagramTheme.light`. | | `ColorAdaptation.dark` | Flips lightness and keeps hue, saturation and opacity: black ink turns near-white and white fills become dark surfaces, while a red stays red. Used by `DiagramTheme.dark`. | Adaptation changes only what the canvas and minimap show. The document keeps its authored colors, so saving, collaboration and undo are unaffected, and the same document looks right in both themes. Images and shape shadows are not adapted. Exports stay in authored colors. To render a PNG as the dark canvas shows it, pass the theme to `exportDiagramPng(publication, options: ..., theme: DiagramTheme.dark)`. For a different mapping, subclass `ColorAdaptation` and implement `call`. It runs while painting, so keep it fast and free of side effects. ```dart final class Grayscale extends ColorAdaptation { const Grayscale(); @override Color call(Color color) { final l = color.computeLuminance(); return Color.from(alpha: color.a, red: l, green: l, blue: l); } } ``` ## Extension themes Extensions that add chrome to the canvas own its colors in their own options. Each takes an optional theme in its constructor; without one it picks its `light` or `dark` default by the canvas `DiagramTheme.brightness`, so installing the extension is enough for a light or a dark canvas: | Theme | Set with | Controls | | --- | --- | --- | | `MinimapTheme` | `MinimapExtension(theme: ...)` (`MinimapOptions.theme`) | Minimap surface and visible-area outline, and the zoom panel's background, border, shadow, icons, text and control states. | | `EditorTheme` | `EditorExtension(theme: ...)` (`EditorOptions.theme`) | The editor's chrome, in two parts: `ToolbarTheme` and `InspectorTheme`. | | `SnapGuideTheme` | `SnapGuidesExtension(theme: ...)` (`SnapGuidesOptions.theme`) | Snapline color. | | `TableTheme` | `TableFlutterExtension(theme: ...)` (`TableFlutterOptions.theme`) | The table controls over the canvas: the range actions' surface and text, the row and column controls, and the selected cell-range color, which follows the canvas selection color when absent. | `EditorTheme` holds the colors of each part of the editor: | Part | Controls | | --- | --- | | `EditorTheme.toolbar` (`ToolbarTheme`) | The floating toolbar, the tool palette and the history toolbar: surface, border, shadow, icons, the hairlines between groups, hover, and the active tool's background and icon. The active tool follows the canvas selection color unless `selected` and `selectedIcon` are set. | | `EditorTheme.inspector` (`InspectorTheme`) | The inspector panel and the shape libraries in it: surface, text, labels and section labels, fields, control outlines, dividers, hover, error text, the floating panel's shadow and corner radius, and the accent of switches, sliders and selected options, which follows the canvas selection color unless `accent` is set. | The editor applies these colors to every control it builds, including menus and tooltips opened from its toolbars, so a light application can show a dark canvas with dark editor chrome, and the other way around. The defaults meet WCAG AA contrast for text and icons. Shape library thumbnails paint with the canvas theme's content adaptation, as the canvas paints the shapes they create. Start a custom theme from the package's `light` or `dark` value: ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension( theme: EditorTheme.dark.copyWith( inspector: InspectorTheme.dark.copyWith(accent: Colors.teal), ), ), MinimapExtension( theme: MinimapTheme.dark.copyWith(viewport: Colors.teal), ), ], ), ); DiagramCanvas(controller: controller, theme: DiagramTheme.dark); ``` Because the theme is part of the extension's options, it can change at runtime like any other option: ```dart controller.edits.setOptions( controller.options().copyWith(theme: MinimapTheme.light), ); ``` ### Define one for your extension Put the theme in your extension's options, and when it is null pick a light or dark default from `DiagramTheme.of(context).brightness` where the extension builds its chrome: ```dart import 'package:flutter/widgets.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; @immutable final class BadgeTheme { const BadgeTheme({this.fill = const Color(0xFFFFD60A)}); static const light = BadgeTheme(); static const dark = BadgeTheme(fill: Color(0xFFB08900)); final Color fill; @override bool operator ==(Object other) => other is BadgeTheme && other.fill == fill; @override int get hashCode => fill.hashCode; } final class BadgesOptions { const BadgesOptions({this.theme}); /// Badge colors, or null for the default by the canvas brightness. final BadgeTheme? theme; @override bool operator ==(Object other) => other is BadgesOptions && other.theme == theme; @override int get hashCode => theme.hashCode; } final class BadgesExtension extends DiagramFlutterExtension { BadgesExtension({BadgeTheme? theme}) : super(id: 'app.badges', options: BadgesOptions(theme: theme)); @override Widget build(BuildContext context, DiagramCanvasExtensionHost host) => Observer( builder: (context) { final theme = host.controller.options().theme ?? (DiagramTheme.of(context).brightness == Brightness.dark ? BadgeTheme.dark : BadgeTheme.light); return Badges(host.controller.scene, fill: theme.fill); }, ); } ``` `DiagramTheme` itself has no list of extension themes: it holds the canvas, selection, shape and connector sub-themes and the `brightness` extensions follow. Open the [playground](/playground/) and use the toolbar's dark canvas toggle to see a light and dark canvas with the editor installed. --- # Verbs and keyboard bindings A verb is a named, typed edit. Buttons, shape regions, keyboard shortcuts, the inspector and agents all perform the same verbs, so a shortcut and a button can never disagree. Declare a shape's own verbs on its definition; perform them through `controller.edits.perform([id], 'verb', args)`. Install the same definitions when reopening a document: verbs are host behavior, not serialized content. See [verbs](/agent-docs/api/verbs.md) for the full contract. ```dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration(extensions: [counterFlutterExtension()]), ); final canvas = DiagramCanvas(controller: controller); /// Sets a counter's value. Performing it with the previous count reverses it. final setCount = DiagramVerb.update( id: 'setCount', label: 'Count', target: DiagramVerbTarget.element, parameters: [DiagramVerbParameter.integer('count', minimum: 0)], update: (shape, call) => shape.copyWith( values: {...shape.values, 'count': call.arg('count')}, ), ); /// Sets the count back to zero; `setCount` expresses the reverse. final resetCount = DiagramVerb( id: 'resetCount', label: 'Reset count', symmetry: const DiagramVerbSymmetry.derived(reversedBy: 'setCount'), target: DiagramVerbTarget.element, perform: (call) => call.controller.edits.perform([call.id], 'setCount', {'count': 0}), ); ShapeDefinition counterShape() => ShapeDefinition( type: 'app.counter', size: const DiagramSize(160, 96), values: const { 'count': NumberValueField(defaultValue: 0, minimum: 0, integer: true), }, verbs: [setCount, resetCount], body: ShapeColumn([ ShapeSized( extent: 24, child: const ShapeSurface( id: 'reset', style: ShapeStyle( fill: DiagramColor(0xFFF1F5F9), strokeWidth: 0, cornerRadius: 0, ), onInteract: 'resetCount', child: ShapeText( 'reset-label', text: 'Reset', editable: false, alignment: ParagraphAlignment.center, ), ), ), const ShapeText('body', horizontalPadding: 12, verticalPadding: 12), ]), ); /// The portable half: a headless host installs this one alone. DiagramExtension counterExtension() => DiagramExtension(id: 'app.counter', shapes: [counterShape()]); int countOf(DiagramController controller, String? id) => switch (controller.document.elementById(id ?? '')) { ShapeElement(:final values) => (values['count'] as num? ?? 0).toInt(), _ => 0, }; /// The Flutter half: key bindings, installing the counter shape with it. DiagramFlutterExtension counterFlutterExtension() => DiagramFlutterExtension( id: 'app.counter_keys', dependencies: [counterExtension()], shortcuts: [ DiagramKeyBinding( verb: 'setCount', args: (controller, id) => {'count': countOf(controller, id) + 1}, key: LogicalKeyboardKey.equal, modifiers: const {DiagramKeyModifier.command, DiagramKeyModifier.shift}, scope: DiagramKeyScope.selection, shapeType: 'app.counter', ), ], ); ``` A button checks the same verb with `canPerform` and performs it on activation. Availability is checked again when the verb runs; unknown verbs, missing targets and locked targets are denied. Read availability inside an `Observer` so a control refreshes when the document or selection changes. ```dart Widget incrementButton(DiagramController controller, String id) { final next = {'count': countOf(controller, id) + 1}; return TextButton( onPressed: controller.canPerform([id], 'setCount', next).allowed ? () => controller.edits.perform([id], 'setCount', next) : null, child: Text('Count ${countOf(controller, id)}'), ); } ``` ## Setters, not toggles Every verb is two-way, so an agent can always state the reverse edit. A verb declares its symmetry: | Symmetry | Use it for | Example | | --- | --- | --- | | `DiagramVerbSymmetry.setter` | A verb that sets a value; performing it with the previous value reverses it. `DiagramVerb.update` declares one. | `setCount(count)` | | `DiagramVerbSymmetry.pair('counterpart')` | Half of an insert/remove pair. | `insertRow` / `removeRow` | | `DiagramVerbSymmetry.derived(reversedBy: 'setter')` | A verb that computes new values a setter expresses. | `resetCount`, reversed by `setCount` | There is no `increment` or `toggle` verb. A control that increments computes the next value and performs the setter, as the key binding above does; a toggle performs the setter with the opposite of the current value. Building the diagram rejects a verb whose counterpart or setter is not installed. ## One edit, one Undo Each `perform` is one admitted edit and one undo entry, however many elements it changes. A verb that composes other verbs, such as `resetCount`, still records one entry; use `controller.edits.batch(label, () {...})` to group several performs from your own code. A denial changes nothing. `DiagramVerb.update` covers setters that replace their target element. For anything else, `DiagramVerb(perform: ...)` receives a `DiagramVerbCall` with the controller, the target `ids` and the decoded `args`; compose other verbs with `call.controller.perform`, or submit a transaction with `call.submit`. Verbs are synchronous. Fetch external data before performing a verb, and pass the `expectedRevision` you captured before the `await` so an edit prepared against an older document is denied as a conflict. Publication automatically resolves and renders affected shapes. Rows and columns reflow within updated dimensions; they do not implicitly resize every container. The shape's declared `textSizing` policy can grow a text body automatically, or a verb can explicitly resize it. No refresh method is needed. ## Keyboard ownership Bindings have three scopes, `DiagramKeyScope`: | Scope | Eligible input owner | | --- | --- | | `canvas` | Canvas with an empty selection | | `selection` | Canvas with an object selection | | `text` | The active diagram text editor | A binding performs its `verb` on the selected element, or on the diagram in canvas scope. `args` computes the arguments from the controller and that element when the chord is pressed. The verb must be installed: the canvas rejects a binding whose verb no installed extension, shape or part offers. Use `shapeType` to restrict a binding to one shape type and `slotId` to restrict a text binding to one named slot. A slot restriction requires `scope: text`. More specific matching bindings win: slot and shape, then slot, then shape, then the unrestricted scope. Duplicate scope/chord declarations are rejected. `command` means Meta on macOS and Control elsewhere. Modifier matching is exact. Bindings receive initial key-down events, not repeats. A matched binding consumes its chord even when its verb is unavailable; an unmatched key retains the normal editor behavior. Escape, active IME composition, pointer gestures, and focused embedded controls retain their existing input ownership. Selection and canvas bindings never run in diagram text editing. The playground binds Command+Enter on a selected entity to its `primary.insertRow` part verb, with the row count as `at`. It appends a row to the entity's primary section. Tab retains normal editor behavior and does not add rows. ## Buttons and interactive regions Any Flutter control can perform a verb. The playground Count button performs `setCount` with the next count; Command+Shift+= performs the same verb on a selected controls card. Embedded controls continue to own their own focused keystrokes. For an interactive region, give a `ShapeSurface` in the shape's body an `onInteract` naming one of the shape's verbs. The pointer shows a click cursor over it. The verb is performed without arguments on pointer release inside the same region, so name a verb that needs none, such as `resetCount`; cancel or release outside does not perform it. A region interaction is always a verb, so it is admitted, undoable and available to agents like any other edit. No repeatable-content grammar or runtime body insertion is introduced by this API. The verb decides how to change the existing canonical data. --- # Vocabulary The API uses a small set of nouns and verbs, and the same word always means the same thing. Once you know them, most calls read like a sentence: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final service = ShapeDefinition.labeled( 'acme.service', name: 'Service', size: const DiagramSize(180, 100), ); final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ DiagramExtension( id: 'library.acme', shapes: [service], tools: DiagramToolDefinition.forShapes([service], group: 'acme'), ), ], ), ); final api = controller.createShape('acme.service', at: DiagramPoint.zero); final db = controller.createShape('acme.service', at: const DiagramPoint(300, 0)); controller.connect(api, db); controller.move(const DiagramPoint(0, 40), ids: [db]); controller.select([api, db]); ``` ## Nouns | Word | Meaning | | --- | --- | | Document | The saved content: shapes, text and connectors. It never changes in place. | | Diagram | The shared, committed document with its one undo history, installed extensions and rules. | | Controller | One actor editing a diagram, with its own selection, tool and camera. Every change goes through a controller. | | Canvas | The Flutter widget that shows a controller's diagram; with the editor installed, people edit it there. | | View | The visible part of a mounted canvas; `controller.view` moves it. | | Effects | Short-lived visuals on a canvas, such as a flowing path; `controller.effects` plays them. | | Element | Anything in a document: a shape, standalone text or a connector. | | Shape | An element with a registered type, a frame and optional text. | | Connector | An element joining two endpoints, optionally through ports, along a route. | | Port | A named attachment point declared on a shape. | | Route | How a connector's path is drawn: straight, orthogonal (elbow), quadratic or Bezier. | | Label | Text owned by a connector. | | Definition | Describes one shape type as its anatomy: outline, body, values, connection and behavior, plus its size and style. | | Library | A named set of definitions you can install together. | | Extension | A bundle of definitions, tools and behavior, installed in the configuration's `extensions` list. It brings its own configuration. | | Options | An extension's runtime configuration, such as the grid's `GridOptions`, read with `controller.options()` and changed with `controller.setOptions`. | | Rules | The application's decisions about which changes, creations and connections to admit (`DiagramRules`). | | Theme | Colors and styles for a canvas and the chrome around it. | | Batch | Several verbs made one atomic, undoable change with `controller.batch`. | | Verb | A named, typed edit, performed with `controller.perform(ids, name, args)` or a typed method such as `controller.move`. See [verbs](/agent-docs/api/verbs.md). | | Result | The `EditResult` returned by calls through `controller.edits`: allowed, or denied with a `code` and `reason`; a creating verb's new ID is its `id`. | | View state | Selection, camera, tool and extension options: state that is not document content, changed through plain controller methods such as `select`, `setCamera`, `setTool` and `setOptions`, which are not undoable. | | Interaction | A continuous edit, such as a slider drag, started with `controller.beginInteraction`. | ## Shape anatomy A shape definition is made of these parts. See [shape anatomy](/agent-docs/guide/shape-composition.md). | Word | Meaning | | --- | --- | | Outline | The shape's own surface: the contour it paints, hit-tests and attaches connectors to. A shape without one paints no surface of its own. | | Body | The parts laid out inside or beside the outline. | | Part | One piece of a body: a layout part (row, column, stack, sized, padding, outside) or a leaf (text, surface, divider, image, widget or content such as a table). | | Slot | The name of a text part; text in a shape's story belongs to a slot, such as `title` or `body`. | | Surface | A painted region inside the body with its own outline and fixed style, or an unpainted interactive area. | | Values | An instance's typed data, declared by value fields: a path, an image, a polygon's sides or a domain field. | | Adjustment | An on-canvas handle bound to a numeric value. | | Container | A shape that owns child elements, and may clip or scale them. | | Behavior | What a person may do to a shape: select, move, resize, rotate, delete and edit its text. | | Layers | What a body compiles to, in paint order; read by renderers, never authored. | ## Verbs | Verb | Meaning | | --- | --- | | `create…` | Make a new element of a registered type, starting from its definition's size, style and text. | | `add` | Insert an element you built yourself, exactly as given. | | `connect` | Join two elements with a new connector. | | `move`, `resize`, `rotate`, `reparent`, `delete` | Change or delete the elements you name, together with what they contain. | | `select` | Choose what is selected. Selection is not a verb and not part of undo history. | | `set…` | Replace one setting, such as `setLocked`, `setStyle` or `setConnectorRoute`. Performing it with the previous value reverses it. | | `reroute`, `layout`, `align`, `distribute` | Compute new positions or paths for many elements at once. | | `show` | Move the view to a target. | | `play` | Start an effect. | ## Conventions - Methods do not repeat what the receiver already says: a controller moves elements with `controller.move(delta, ids: …)`. - A parameter has the same name everywhere: `at` for where a new element is centred, `from` and `to` for a connection's ends, `fromPort` and `toPort` for its ports, `route` for its route, and `name`, `size`, `style` and `connection` on every definition. - Verbs read the same inside and outside a `batch`, so `controller.createShape(type, at: …)` and `controller.connect(from, to)` are the same calls either way. - Calls through `controller.edits` return an `EditResult`; call `requireAllowed()` to turn a refusal into an exception. - There are no toggles: a control that toggles performs the setter with the opposite value, such as `setLocked(!locked, ids: ids)`. Undo is history, not a reverse verb. - Each setting has one place to set it. A canvas theme, for example, is set on `DiagramCanvas(theme: …)` or on the app's `Theme`, and the grid only through `GridExtension` and its `GridOptions`. --- # Appearance and painting The inspector is a projection of what each registered element's anatomy makes editable. A setting that is absent may be fixed by the definition or inapplicable to that kind of element. Styling changes participate in the same undo/redo history as canvas edits. ## Surface and outline | Property | What you can control | Limits | | --- | --- | --- | | Fill | None, solid color, linear or radial gradient | Shapes with an outline | | Gradient | Stops, stop colors and positions; direction or radial center/radius | Supported by filled shapes | | Border/stroke | Color, width, solid/dashed/dotted and supported hand-drawn treatment | Shapes with an outline | | Corners | Corner radius | Outlines that round their corners: rectangles, regular polygons and editable paths | | Polygon | Number of sides | Regular polygon geometry | | Freehand ink | Preset, color and width | Ink behavior differs by preset | | Table borders | None/solid/dashed/dotted, width and color | Separate table and divider controls | | Image | Source and contain/cover/fill fit | No ordinary fill/border controls on the standard image | Colors include alpha. The standard inspector does not expose a separate universal opacity or shadow control. Definitions can declare paint-only shadows and fixed surface layers. A layer fixed in the registry is not automatically an editable per-instance property; the comment fold and card header are examples. ## Text appearance Where text is permitted, the shared text controls cover registered fonts, font size, color, bold, italic, underline, strikethrough, superscript/subscript, clear formatting, direction and alignment. Paragraph controls depend on the region's content grammar. Table cells intentionally exclude headings and lists. ## Connectors and effects Connector appearance includes stroke settings and independent start/end arrowheads. Labels have their own text formatting and optional badge appearance. Route-specific controls are shown only when applicable. The effect registry can expose animation options such as particle appearance, count, size, speed, waveform, repeat count, color/gradient, scale mode and direction; each effect shows only the settings it advertises. Shapes offer their effects the same way. See [Animation & effects](/agent-docs/api/effects.md). ## One inspector control system Numeric and text fields, dropdowns, color controls, switches, action menus and segmented tabs use CDX controls and theme values. The Table/Row/Column selector and shape-library tabs are CDX segmented tabs. Compact inspector rows share control height, typography and spacing. Diagram-specific swatches preview actual geometry; their button chrome uses the shared theme. ## Resize is not repaint Side/corner resizing clamps to the declared and content-derived minimum. Crossing the minimum must not flip the element or move its opposite edge. Rotation is capability-controlled. Paths expose point editing instead of regular resize handles; connectors expose routing handles; frames resize their boundary while groups resize their children. See [the capability matrix](/agent-docs/elements/index.md#at-a-glance). Select a regular polygon to reveal a control handle on the selection rectangle’s top edge, offset from the top-right resize handle. Hover for instructions. Its position stays stable as sides change. Tap it to add a side, or drag right/left to increase/decrease the side count. The control stays in place during the drag, and the whole gesture is one undo step. The side count stays within the supported range; it cannot go below three. Custom paths instead show midpoint `+` handles on hover for inserting points. --- # Frames and groups ## Frame ![Frame containing two shapes](/elements/frame.svg) A frame is a painted container. Its children remain independently selectable and editable. Moving the frame moves the subtree; resizing it changes only the frame boundary, preserving child sizes and positions. The standard definition disables rotation. A custom frame definition can explicitly enable it. The title sits above the top edge. For a collapsible frame, the collapse icon aligns with the frame's left edge and the title follows it. A non-collapsible definition can align its title directly to that edge. Double-click the title region to edit it; double-clicking the frame body must not capture the title editor. The inspector exposes clipping where the definition supports it. Collapsing a frame preserves the expanded geometry and presents its collapsed registration; collapsed frames do not expose resize/rotation handles. See [frames and ownership](/agent-docs/examples/containment.md). ## Group ![Two grouped shapes](/elements/group.svg) A group is a logical owner with no painted rectangle, title or connection ports. Moving and rotating a group carry its children. Resizing scales their geometry together, including any nested frame. This is intentionally different from resizing a frame boundary. ## Shared ownership rules Children have stable identities and one owner. Parent transforms and clipping are resolved once and shared by rendering, hit testing and export. Host APIs and pointer gestures use the same containment and transform policies. See [ownership](/agent-docs/api/ownership.md) and [shape behavior](/agent-docs/guide/shape-capabilities.md). --- # Elements Choose an element by what it needs to do: hold text, connect other elements, organize a drawing, or display an image. The standard registry supplies the following elements without an optional shape library. [Browse the illustrated catalog](/agent-docs/elements/standard.md) · [Appearance](/agent-docs/elements/appearance.md) · [Text and regions](/agent-docs/elements/text-regions.md) · [Tables](/agent-docs/elements/tables.md) · [Frames and groups](/agent-docs/elements/containers.md) ## At a glance | Element | Editable appearance | Text | Resize and structure | | --- | --- | --- | --- | | Rectangle | Fill, border, rounded corners | One region | Side and corner handles | | Ellipse | Fill and border | One inset region | Side and corner handles | | Polygon | Fill, border, corners, side count | One inset region | Side and corner handles | | Path | Fill, stroke, corners; open or closed geometry | None | Edit individual anchors and Bézier handles | | Drawing | Ink color, width, preset and supported fill | One region | Resize the authored drawing | | Card | Fill, border and rounded corners | Optional tag, title and description | Text can grow its height; four side ports | | Comment | Fixed yellow paper and folded corner | Editable body | Text can grow its height | | Table | Fill, border and corners; outer, row and column borders | Body text in each cell | Shape handles and row/column dividers | | Frame | Fill, border and rounded corners | Title above the frame | Resize boundary; child positions stay intact | | Group | No painted surface | None | Resize children together | | Image | Source and fit | None | Resize image bounds | | Text | Text formatting; no shape fill or border | Rich Text | Width controls wrapping; content can grow height | | Connector | Stroke, routing, arrowheads, labels and effects | Label stories | Endpoints, bends and curve controls | These are the **standard definitions**. A host can register a different anatomy—outline, body regions, values, behavior, minimum sizes and ports. Locks and application admission rules can further restrict editing. The inspector only exposes properties allowed by the selected element's definition. ## Beyond the standard toolkit The optional [Shapes library](/agent-docs/api/extension-shapes.md) adds registered shapes such as start, end, decision and entity. They use the same drawing, selection, text, connection and history machinery. For example, the entity uses a title and embedded table sections rather than introducing a second text editor. See [building a library](/agent-docs/guide/build-a-library.md). `Shapes.line` remains available to read older drawings. It is not a separate creation tool: use **Path (`P`)** for authored lines and curves, or **Connector (`L`)** for connections between elements. ## What is configured where? - **Inspector:** appearance and supported structural settings of the selected element. - **Canvas:** placement, selection, resizing, path points, text and table editing. - **Shape definition:** the shape's anatomy—outline, body parts (text regions, surfaces, images, widgets), values, ports, behavior and minimum/default sizes. Adding another text region is a change to the definition's body, not an inspector operation. The default element catalog is not a promise that every element supports every property. --- # Standard element catalog These illustrations show the standard elements selected, with blue selection outlines and editing handles. They are drawn from the same definitions and selection chrome as the editor. They show sample content; the image element shows its empty image placeholder, and the group example shows two grouped children because a group has no painted surface. ## Rectangle ![Rectangle with rounded corners](/elements/rectangle.svg) A general-purpose block with one inset text region. Change its fill, border color, width and style, and corner radius. Resize from sides or corners and rotate it. ## Ellipse ![Ellipse](/elements/ellipse.svg) A circle or ellipse with a proportionally inset text region. Supports fill and border styling. Width and height are independent; equal dimensions produce a circle. ## Polygon ![Five-sided polygon](/elements/polygon.svg) A regular polygon with an editable side count, fill, border and corner radius. Text occupies an inset region. Connections can use the resolved outline; these anchors are different from authored, named ports. ## Path ![An open path with four anchors](/elements/path.svg) An authored path for straight segments and Bézier curves. Select individual anchors, move or delete them, add points, and toggle open/closed geometry. Double-click an anchor to cycle corner, smooth and symmetric point types. Deleting an endpoint of a two-point path removes the path. It has no text region or ordinary bounding-box resize handles. Shortcut: **P**. ## Drawing ![Freehand drawing](/elements/freehand.svg) A freehand stroke with authored points. The inspector exposes ink presets, color and width. Pen strokes can carry varying widths; presets determine the ink behavior. The standard definition also permits a text region. Drawing is distinct from editing Bézier anchors on a Path. ## Card ![Card with a title and body](/elements/card.svg) Independently addressable text regions: an optional tag, a single-line title and a plain-text description (`body`). The tag shows only while it has text; the editor offers an add or remove tag button beside a selected card. The header has a fixed background surface. The card supports editable surface styling, rounded corners, height growth from content, and named ports on its four sides. ## Comment ![Yellow comment with a folded top-right corner](/elements/comment.svg) A text note with fixed yellow paper, outline and dog-ear fold. Its body is editable and can grow the shape vertically. Fill and border controls are deliberately absent: the paper and fold are fixed surfaces in its body, and the comment has no outline of its own. Shortcut: **N**. ## Table ![Three-by-three table with task, owner and status columns](/elements/table.svg) A nested text structure with editable cells and independently resizable rows and columns. Configure outer borders, all row/column dividers, or a particular divider. It can stand alone or fill a declared region of another shape. See [Tables](/agent-docs/elements/tables.md). ## Frame ![Frame with a title and two contained shapes](/elements/frame.svg) A visible container with a title above its top edge. Moving it moves its children; resizing changes the boundary without scaling them. Clipping and collapse are supported. Standard frames do not rotate. See [Frames and groups](/agent-docs/elements/containers.md). ## Group ![Two shapes in a logical group](/elements/group.svg) A logical container with no painted fill, border or title. Moving, rotating or resizing the group transforms its contents together. It is created through grouping, rather than serving as another visible rectangle. ## Image ![Empty image element placeholder](/elements/image.svg) An image source displayed inside resizable bounds. Choose a file or URL and set contain, cover or fill fitting. The demo file picker accepts PNG, JPEG, GIF, WebP, BMP and SVG. SVG images are drawn as images; the original source remains in the document. This does not promise vector-preserving image export or support for every SVG feature. No built-in caption or surface fill/border controls are provided. ## Text ![Standalone text](/elements/text.svg) Rich Text without a shape surface. Supports font, size, color, inline marks, alignment, paragraphs, headings and lists. Click-created text starts with automatic width; a width-constrained text box wraps content. See [Text and regions](/agent-docs/elements/text-regions.md). ## Connector ![Orthogonal connector with an arrowhead](/elements/connector.svg) A relationship between free endpoints or attached elements/ports. Choose straight, orthogonal, quadratic or Bézier routing. Edit stroke color, width/style, end markers, label placement and supported path effects. Moving attached shapes updates the connection. Shortcut: **L**. See [connector API](/agent-docs/api/connectors.md). --- # Tables ![Standalone table](/elements/table.svg) A table can be a standard standalone element or a `ShapeTable` within another shape's body. It is part of the text grammar, so editing, selection, undo/redo and layout use the same canonical story machinery. ## Editing and navigation | Input | Behavior | | --- | --- | | Double-click text | Enter editing and select the tapped word | | Double-click blank cell space | Enter editing with a caret in that cell | | Click an unselected table | Select the whole table; dragging moves it | | Click a cell in a selected table | Enter cell selection | | Drag in cell selection | Select a rectangular range, without a modifier key | | Click the selected cell again | Enter text editing | | Escape | Step back from text editing to cell selection, then to table selection | | Drag while editing text | Select text; does not select cells | | Delete with cells selected | Clear their contents, preserving the table structure and formatting | | Tab | Next cell in row order; wrap to the next row; append a row at the table end | | Shift+Tab | Previous cell in row order | | Enter | Insert a row below and continue in the same column | | Shift+Enter | Add a line within the current cell | | Up/Down | Move through lines, then cells in the same column | | Left/Right | Move through text and adjacent cells in row order | Cells support styled body text. They do not support headings, lists or nested tables. ## Sizing Columns start equally sized within the allocated width unless explicit widths are authored. Cell content determines minimum sizes. Text can wrap; rows grow to fit content. Minimum column widths preserve at least a character and padding; minimum row heights preserve a line and padding. These are measured constraints, not a promise that arbitrarily long text will keep every column equal. Hover a divider and drag to change that row's height or column's width. The inspector's **Rows & columns** section provides the same explicit sizes. Resizing a track preserves the neighboring track's size and changes the table extent, subject to the resolved minimums and the containing body's layout. An embedded table can therefore increase the required size of its containing shape. ## Structure and borders Selected tables expose editing controls that rotate with the table. **Full** shows only the row and column intersecting the hovered cell. Gutter handles select an entire row or column without opening a menu. Dots at the adjacent boundaries become plus buttons on hover and insert tracks there. Moving into the gutter keeps the controls reachable. **Minimal** shows one domain-specific actions menu, using the active cell as its row/column target. **Off** hides this chrome without disabling editing or inspector commands. Embedded tables retain their declared capabilities; a properties-only table can omit all column controls. Pop-up menus remain upright. Configure this when installing `TableFlutterExtension`; its arguments build its `TableFlutterOptions`: ```dart TableFlutterExtension( standalone: TableOverlayMode.full, embedded: TableOverlayMode.off, // Optional per-owner/table policy; no document content is changed. resolve: (owner, table) => owner.isLocked ? TableOverlayMode.off : TableOverlayMode.full, ) ``` Omit `resolve` to use the shape's declared presentation and the standalone/embedded defaults. The table behavior reads the options live, so `controller.edits.setOptions(controller.options().copyWith(...))` changes them at runtime. Embedded regions are hidden by default. Only the active table shows controls. Locked tables do not show editing controls. Add, insert and delete actions use the same undoable commands as the inspector, and do not override text deletion shortcuts. An embedded component declares its own vocabulary and structural permissions: ```dart const ShapeTable('properties', rows: 2, columns: 1, controls: ShapeTableControls( presentation: ShapeTableControlPresentation.compact, columns: false, rowLabel: 'property', renameRows: true, ), ) ``` This exposes **Add property**, **Rename property**, and **Remove property**. Rename selects the current property's text for editing. Column actions are absent from the overlay and inspector, and column commands reject changes. The entity shape's sections use a similar compact, column-free declaration. Hosts can still hide the entire overlay through `resolve`. ### Operation capabilities `ShapeTableControls.capabilities` declares the operations the component permits. `ShapeTableCapabilities` independently controls `mergeCells`, `mergeRows`, `unmergeCells`, `addRows`, `removeRows`, `addColumns`, `removeColumns`, `resizeRows`, `resizeColumns`, and `resizeTable`. Each defaults to `true`. The existing `rows: false` and `columns: false` switches remain broad restrictions on their respective track operations. For an embedded property list that permits adding and removing properties: ```dart const ShapeTable('properties', rows: 2, columns: 1, controls: ShapeTableControls( presentation: ShapeTableControlPresentation.compact, columns: false, rowLabel: 'property', renameRows: true, capabilities: ShapeTableCapabilities( mergeCells: false, mergeRows: false, unmergeCells: false, resizeRows: false, ), ), ) ``` Overlays and the inspector omit unsupported operations. Commands reject them without changing the document; keyboard-driven row creation uses the same policy. Changing overlay visibility does not change these permissions. `mergeRows` applies to a selection spanning every column of one or more rows; `mergeCells` applies to other rectangular ranges. Both produce one merged cell, preserving the underlying tracks and content for unmerging. They do not delete rows. `resizeTable: false` disables explicit resizing of the owning shape, including its resize handles. Content-driven growth still follows the shape's layout grammar. For embedded tables, leave it enabled if the containing component should resize and let its table fill the resulting bounds. The inspector inserts or removes tracks, retaining at least one row and one column. Choose **Table**, **Row**, or **Column** to choose the scope of the border controls beneath the tabs: - **Table:** outer border, all row dividers, or all column dividers. - **Row:** the divider below the selected row. - **Column:** the divider after the selected column. The same style, width and color fields load the chosen scope's values. Switching scope does not edit the document. An individual divider override can be reset to the table default. The last row and column have no following inner divider; use the outer border to edit the table edge. Cell-selection mode supports ordinary dragging; the row and column gutter handles select their whole track. The selected range has one outer selection outline and a subtle tint, while normal internal table dividers remain unchanged. Use **Merge cells** for a rectangular selection and **Unmerge** to restore its individual cells. Merging preserves existing row heights unless the combined content requires more space. Empty cells do not add extra blank paragraphs. The **Clear** action (eraser icon) clears selected cell contents, preserves the selection and merges, and can be undone. Cell-selection mode uses a crosshair; text editing retains the text cursor. [Open the Tables example](/agent-docs/examples/tables.md) --- # Text, regions and anatomy Text belongs to an element's canonical story. A region is a named place in that story with resolved bounds, text rules and layout behavior. It is not a separate floating editor laid on top of the shape. ## Built-in regions | Element | Default text arrangement | | --- | --- | | Rectangle, ellipse, polygon and drawing | One body region | | Card | Single-line title and multiline body | | Comment | Body inside the folded paper | | Frame | Title above the boundary | | Table | A body-text region for each cell | | Standalone text | One body region, no shape surface | | Connector | One or more label stories | | Image, path and group | No built-in text region | Double-click cell text to select a word. Double-click empty space inside a cell to place a caret in that cell. A frame's title is edited from its title region; its body remains available for selecting contained elements. ## Multiple regions A custom definition places several `ShapeText` parts in its body, each with a unique slot identity, initial text, text role, single-line behavior, padding, vertical alignment and placeholder. Rows, columns, stacks, padding, surfaces and `ShapeTable` arrange them. The body compiles into the resolved geometry used by painting, hit testing and editing. Regions can occupy padded space, fixed bands in a row or column, or a band outside the frame (`ShapeOutside`), as a frame's title does. The standard Card demonstrates a title and body; a class can use a title plus a single-column table for members. Add regions in a registered definition, rather than inventing new canvas elements or duplicating text-editing logic. See [shape anatomy](/agent-docs/guide/shape-composition.md) and [custom shapes](/agent-docs/guide/custom-shapes.md) for the declaration APIs. ## Content and size `ShapeTextSizing.fixed` keeps the authored shape geometry authoritative. `ShapeTextSizing.growHeight` treats authored height as a minimum and lets content increase the resolved height downward. Cards, comments and tables opt into height growth. Text is never clipped to the shape's outline; each region clips to its own bounds. Standalone text also has automatic-width and fixed-width sizing modes. Changing width affects wrapping; text layout determines the required height. Region bounds, caret placement, selection and export consume the same resolved text layout. ## Embedded tables `ShapeTable('members', rows: 2, columns: 1)` declares a table in the space allocated by its parent part. It fills that region and participates in content sizing. A table's cells are nested text elements. A cell may contain styled body paragraphs, but cannot contain another table, a heading or a list. See [Tables](/agent-docs/elements/tables.md). --- # DiagramCanvas Mount a controller inside a bounded Flutter layout. The canvas owns no second document or configuration. For content inside an individual shape, see the [visual shape anatomy guide](/agent-docs/api/widgets.md#compose-a-shape-visually). ```dart Expanded(child: DiagramCanvas(controller: controller)) ``` `DiagramCanvas({required controller, DiagramTheme? theme})` takes only the controller and an optional theme. It uses the Flutter extensions installed on the controller. A canvas edits when an editable extension, such as `EditorExtension()`, is installed; otherwise it navigates and selects only. Host code can always use admitted controller verbs to update the document. ## Compose an editor The optional editor package supplies `EditorExtension()`, the editable Flutter extension that makes the canvas edit and wraps it in the editing shell: a tool palette on the left, an inspector panel with any shape libraries, a toolbar below the canvas and the on-canvas affordances shapes declare. ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration(extensions: [EditorExtension()]), ); DiagramCanvas(controller: controller); ``` | Argument | Default | Meaning | | --- | --- | --- | | `tools` | every installed tool | The tools offered, in order. The default tool is `select`. | | `palette`, `toolbar` | `true` | Turn the tool palette or the history toolbar off; the shell follows `EditorOptions` at runtime. | | `inspector` | `InspectorPlacement.docked` | Where the inspector panel shows: `docked` beside the canvas on wide layouts, which narrows the canvas; `floating` as a card over the canvas on any layout; `none` to hide it. | | `inspectorSide` | `InspectorSide.right` | The side of the canvas the inspector panel takes. | | `inspectorWidth` | `280` | The panel's width, from 240 to 520. Users resize it by dragging its inner edge, the hairline facing the canvas when docked, and double-click that edge to restore 280. | | `libraries` | none | `ShapeLibrary` tabs above the inspector: click a shape to add it at the center of the view, or drag it onto the canvas. | | `container` | the default shell | `(context, controller, canvas)` builder that replaces the whole shell. | | `rotationSnap`, `connectionSnapRadius` | `15`, `10` | Editing snaps; zero radius disables connection magnets. | | `theme` | light or dark by `DiagramTheme.brightness` | `EditorTheme` colors of the toolbars and the inspector panel; see [theming](/agent-docs/guide/theming.md#extension-themes). | Every argument except `tools` and `container` builds the editor's `EditorOptions`, changeable at runtime with `setOptions`; see [extensions and options](/agent-docs/api/configuration.md). The panel's header has the same switch: its button shows whether the panel is docked or floating and toggles it. ```dart controller.edits.setOptions( controller.options().copyWith( inspector: InspectorPlacement.floating, ), ); ``` An editable canvas without chrome turns every region off: ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension( tools: [DiagramTools.select, DiagramTools.rectangle], palette: false, inspector: InspectorPlacement.none, toolbar: false, ), ], ), ); ``` To compose your own layout, pass `container: (context, controller, canvas)`. Returning `canvas` keeps editing without surrounding chrome. Tool palettes and toolbars accept `direction: Axis.vertical` or `Axis.horizontal`; their position is determined by your container. For example, use a `Row` containing a vertical toolbar, an expanded canvas, and an inspector, or rearrange those widgets to choose another side. `DiagramToolPalette`, `DiagramToolbar`, `DiagramShapeLibraries` and `DiagramInspector` can also be composed individually around that same canvas and controller; each takes its colors from the editor's `EditorTheme`. `DiagramFloatingToolbar` tool buttons expose their name and shortcut as one accessible button. Shift shortcuts display a Shift icon while their accessible name spells out the modifier, for example `Table — Shift+T`. Flutter extensions may contribute a container around the supplied canvas; containers wrap deterministically in installation order. Do not create a second canvas or controller inside the container. Try the composition choices in the Playground. The optional [property inspector](/agent-docs/api/inspector.md), `DiagramInspector(controller: controller)`, uses the same registry and options. A controller supports one mounted canvas at a time; unmount before `controller.dispose()`. To show the same diagram in a second canvas, give it its own controller on that diagram; see [collaboration](/agent-docs/api/collaboration.md). Unmounting cancels an unfinished canvas gesture and restores its content baseline without adding an undo entry. Late pointer events cannot change a subsequent edit. This applies to registered custom tools as well as the default tools. The canvas clips scene paint and its local overlays to the allocated viewport. Shapes, text, connector markers and selection chrome cannot paint over adjacent host widgets. This screen-space clip does not alter document geometry or export bounds; frame/shape content clipping remains a separate world-space rule. Set the canvas background with `DiagramTheme(canvas: CanvasTheme(background: color))`. ## On this page | Category | What you can do | | --- | --- | | [Canvas bounds](#canvas-bounds) | Choose an infinite canvas or one that fits the content. | | [Embedded controls](#arbitrary-flutter-widgets-inside-a-node) | Mount interactive content inside elements. | | [Affordances](#shape-affordances) | Declare buttons beside selected shapes that perform verbs. | | [Key bindings](#key-bindings) | Bind key chords to verbs. | | [Shape regions](#shape-regions) | Perform a shape's verb from a tapped region. | | [Accessibility](#accessibility) | Expose content and actions to assistive tools. | | [Touch navigation](#touch-navigation) | Configure touch input behavior. | ## View-only diagrams A controller without an editable extension gets a lightweight selectable view with pan, scroll and zoom. It mounts shared scene painting without editor gesture controllers, text editing or IME. ```dart final controller = DiagramController(document: document); DiagramCanvas(controller: controller); ``` The diagram remains the document authority: host code can still update content. A view-only canvas restricts edits through user interaction, not programmatic access. Installed native widgets render read-only; without their Flutter builders, shapes use portable painted fallbacks. Leaf Flutter extensions such as minimaps can render and use the shared demand-driven frame clock. Animated path effects use the edit surface; the view surface paints canonical static path geometry. See the [view-only example](/agent-docs/examples/view-only.md). ## Canvas bounds Bounds are core configuration, shared by every controller on the diagram. The canvas is infinite unless `DiagramConfiguration(bounds: ...)` says otherwise. | API | Contract | | --- | --- | | `CanvasBounds.infinite` | Unrestricted camera positioning within the configured zoom range. The default. | | `CanvasBounds.fit({double padding = 0})` | The canvas is the content extent plus `padding` viewport (screen) pixels on every side, so the room looks the same at every zoom. It grows and shrinks with the content; an empty document gets a viewport-sized canvas around the origin. | | `controller.bounds` | The current bounds. Observable. | | `controller.edits.setBounds(bounds)` | Replaces the bounds for every controller of the diagram and re-clamps every camera. Not undoable. Throws `ArgumentError` for a padding that is negative or not finite. | `CanvasBounds` is sealed: switch over `InfiniteCanvasBounds()` and `FitCanvasBounds(:final padding)` to tell them apart. ```dart final controller = DiagramController( configuration: DiagramConfiguration(bounds: CanvasBounds.fit(padding: 64)), ); controller.edits.setBounds(CanvasBounds.infinite); final label = switch (controller.bounds) { InfiniteCanvasBounds() => 'Infinite', FitCanvasBounds(:final padding) => 'Fit, $padding px', }; ``` Bounds changes do not rewrite document coordinates or enter undo history. The inspector's Finite canvas toggle switches between `CanvasBounds.infinite` and `CanvasBounds.fit(padding: 48)`. Try the [bounds example](/agent-docs/examples/bounds.md). ## Arbitrary Flutter widgets inside a node Use declared widget slots for sliders, dropdowns, buttons and text fields inside shapes. The slot is part of the shape definition; Flutter builders are registered once through `DiagramFlutterExtension(widgets: {...})` installed in the configuration. | Object | Responsibility | | --- | --- | | `ShapeWidget` | A body part: the slot's place in the shape, builder key and portable fallback part. | | `DiagramFlutterExtension.widgets` | Maps builder keys to Flutter controls. | | `ShapeElement.values` | Canonical, validated control values. | | `ShapeWidgetContext` | Reads values and performs `setValues` through admission and history. | The canvas applies owner transforms, clipping, visibility and paint ordering to native slots. Controls own interactive gestures; non-interactive slot space participates in shape selection and movement. Host overlays remain useful for canvas chrome, but are not the embedding mechanism for node content. See [Widgets inside shapes](/agent-docs/api/widgets.md) for declarations, builder lifetime, value-edit gestures, focus ownership and export fallbacks. SVG uses the declared fallback rather than serializing an arbitrary Flutter subtree. Very dense scenes with hundreds of native widgets can be slow to draw when zoomed out to an overview; prefer declared fallbacks or adaptive visual detail for those views. ## Shape affordances A shape declares the on-canvas controls it offers beside its single selection in `ShapeDefinition.affordances`. Each performs a [verb](/agent-docs/api/verbs.md) as one undoable edit and shows only while that verb is available: | Affordance | Performs | | --- | --- | | `ShapeValueToggleAffordance(verb:, argument:, valueKey:, label:)` | The boolean setter `verb` with `argument` set to the opposite of the value `valueKey`, such as `showSecondarySection` with `shown`. | | `ShapeOptionalSlotAffordance(slotId:, anchorSlotId:, label:, initialText:, enabledValueKey:)` | The pair `addSlot` / `removeSlot` for the optional text slot `slotId`, placed beside `anchorSlotId`. | | `ShapeAspectLockAffordance(lockLabel:, round:)` | `setAspectLocked`; locking squares the frame first. Drawn as a circle handle on the selection's top edge, left of the top-right resize handle: filled while locked, an outline while free. | The core card declares its tag (`diagramTagAffordance`), rectangles and ellipses their aspect lock, and the shapes package's entity its tag and secondary section. `EditorExtension()` draws whatever the selected shape declares, without naming slots, values or shape types. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final entity = ShapeDefinition( type: 'app.entity', verbs: [showSecondarySection], // A DiagramVerb that sets 'secondaryEnabled'. affordances: const [ ShapeValueToggleAffordance( verb: 'showSecondarySection', argument: 'shown', valueKey: 'secondaryEnabled', label: 'secondary section', ), ShapeAspectLockAffordance(), ], ); ``` ## Key bindings A `DiagramKeyBinding` (from `package:vyuh_diagram_flutter/extension_api.dart`) binds one exact key chord to an installed verb. Register bindings through `DiagramFlutterExtension(shortcuts: [...])`; assembly rejects a binding whose verb is not installed. A matched binding performs the verb on the selected element, or on the diagram in canvas scope, with the arguments `args` computes. A setter bound to a key passes the value it sets. The playground's controls card declares a `setCount` setter (`apps/demo/lib/playground/widget_card.dart`), and its key binding passes the next count (`apps/demo/lib/playground/actions.dart`): ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; DiagramKeyBinding( verb: 'setCount', args: (controller, elementId) => { 'count': playgroundCount(controller, elementId) + 1, }, key: LogicalKeyboardKey.equal, scope: DiagramKeyScope.selection, shapeType: playgroundControlsType, modifiers: const {DiagramKeyModifier.command, DiagramKeyModifier.shift}, ) ``` | Argument | Meaning | | --- | --- | | `verb`, `args` | The verb to perform, and a function of `(controller, elementId)` returning its arguments. | | `key`, `modifiers` | The chord; `DiagramKeyModifier.command` is Meta on macOS and Control elsewhere. Repeats are ignored. | | `scope` | `DiagramKeyScope.canvas`, `.selection` or `.text`; text never falls through to canvas or selection bindings. | | `shapeType`, `textType`, `slotId` | Restrict the binding to a shape type, the active text slot's text type (text scope only) or a slot. | ## Shape regions A `ShapeSurface` in a shape's body can name an interaction with `onInteract`. When it names a verb of the shape, a tap that ends inside the region performs that verb with no arguments. The standard image shape's `choose-image` region is not a verb: the canvas opens the image source picker for an image without a source. Choose the picker with `ImagesExtension(picker: ...)`. ## Accessibility When Flutter semantics are enabled, visible canvas objects expose their type and available text and lock state. Selectable objects also expose selection state and an activation action through the same `controller.setSelection` selection path as pointer selection. Setting `selectable: false` keeps the content readable without a selection action or selection hint; it does not hide the content from assistive technology. Semantic bounds follow the camera and intersect the resolved ancestor clip paths. Offscreen and fully clipped objects and connector labels are omitted. Removing a clip makes the content available again, including through undo and redo. Partially clipped content uses the bounding rectangle of the remaining region, since semantic bounds are rectangular. Set `ShapeDefinition.name` to give custom shapes a readable kind name in both the inspector and screen-reader labels. The host can localize that name when constructing its registry. The canonical type ID remains unchanged. While editing text, the shared paragraph component exposes the active block as a text field, including its current value and selection. Accessibility text and selection changes use the same canonical editing pipeline as the IME and remain subject to change admission and undo/redo. The mounted text input follows the canonical story selection. Switching to a different story switches the input target; an object selection exits text mode. Undo that restores an editable story selection restores text input, and remounting the canvas retains that selection. If the target becomes non-editable, selection falls back to the object when selectable, or clears otherwise. This is initial support, not a complete screen-reader editing contract. Traversal between offscreen objects and paragraph/list blocks, custom localized object descriptions, richer editing actions, and assistive-technology compatibility remain under development. ## Touch navigation Two fingers pan and zoom the viewport. The second contact cancels any active object preview, exits text editing, and transfers ownership to camera navigation. A combined sample publishes one camera state, respects zoom limits and finite-canvas bounds, and does not add an undo entry. After one finger lifts, the remaining contact cannot become an object drag; release every contact before starting another single-finger interaction. A third contact does not change the active pair until one of that pair ends. Contact cancellation releases ownership just like lifting a finger. --- # Controllers, agents and collaboration ## Sharing a drawing A `Diagram` holds the committed document, its installed extensions and rules, and one history. Each actor that edits it, such as a person at a canvas, an agent or a script, gets its own `DiagramController` with its own selection, active tool, camera and in-progress edit. ```dart final human = DiagramController(document: document); final agent = DiagramController( diagram: human.diagram, participant: DiagramParticipant.agent(id: 'agent', name: 'Agent'), ); ``` `DiagramController(document:, configuration: DiagramConfiguration(extensions:))` creates and owns a diagram; its participant defaults to `DiagramParticipant.local` (id `local`, name `You`). `DiagramController(diagram:, participant:)` joins an existing one; each participant's `id` must be unique among the controllers attached to that diagram. ## Participants A `DiagramParticipant` names one actor: | Member | Meaning | | --- | --- | | `DiagramParticipant({required id, required name, kind = human, color})` | A person. `id` is the stable attribution for edits, history and locks; `name` is for display. | | `DiagramParticipant.agent({required id, required name, color})` | An automated agent (`kind` is `DiagramParticipantKind.agent`). | | `DiagramParticipant.local` | The default participant, id `local`, name `You`. | | `color` | An optional presence color, or null for the host's choice. | `controller.participant` is the actor a controller edits as. The diagram resolves ids for presence and attribution: | Diagram member | Meaning | | --- | --- | | `diagram.participants` | The participants of the attached controllers, in attachment order. | | `diagram.participantById(id)` | The participant with `id`, attached now or earlier, or null, so an entry recorded before an actor detached still resolves. | ```dart // Presence: who is on this drawing. final names = [for (final p in human.diagram.participants) p.name]; ``` History entries and document changes stay id-based: they record `participantId`, which `participantById` resolves to a name, kind and color. Rules see the whole participant on `DiagramChangeProposal.participant`. | Scenario | Behavior | | --- | --- | | User and in-process agent on one diagram | Give each its own controller. Both use the same verbs, admission and history, with independent selections and previews. | | Undo and redo | One shared history; `undo()` and `redo()` revert only that controller's own edits. | | Simultaneous edits | Allowed on different elements. An edit to an element another controller is previewing is denied. | | Remote collaborators | No built-in transport or remote conflict reconciliation. Controllers share one diagram in one process; `diagram.participants` lists the in-process actors. | | Server-side agent | Use `DiagramController` from `vyuh_diagram_core` with an appropriate text backend. Verbs match the Flutter controller. | A participant records attribution and scopes undo. It is not authentication or authorization. ## Element leases While a controller previews an interaction, such as a drag, a text edit or a `beginInteraction` lease, the elements that preview changes are leased to it. Another controller's edit touching those elements returns a denial with `DiagramDenialCode.conflict`; edits to other elements proceed. ```dart final result = agent.setStyle(ids: ['task-1'], fill: fill); if (result.code == DiagramDenialCode.conflict) { // The user is editing task-1. Retry after their gesture ends. } ``` When a controller commits, every other controller's in-progress preview is rebased onto the new committed document, so its own commit keeps the other actor's edits. A preview that the commit changed indirectly is cancelled rather than merged. ## Stale revisions An actor that decides an edit from content it read earlier, such as an agent awaiting a model response, passes the revision it read as `expectedRevision`. Every verb accepts it; if any controller changed the document meanwhile, the verb is denied with `DiagramDenialCode.conflict` instead of overwriting that edit. Admission owns this check along with lock checks, so it applies the same way to typed verbs, `perform` and `load`. ```dart final revision = agent.document.revision; final plan = await askModel(agent.document); final result = agent.perform(['task-1'], 'setText', { 'text': plan.title, 'expectedRevision': revision, }); if (result.code == DiagramDenialCode.conflict) { // Read the document again and re-plan. } ``` See [verbs](/agent-docs/api/verbs.md#results). ## Observing every actor `controller.document` and `controller.scene` are that actor's live view, including its own preview. `diagram.document`, `diagram.scene` and `diagram.snapshot` are the committed content every actor shares. `diagram.changes` lives on the diagram and reports every controller's completed edits. `change.participantId` is the id of the actor that made it; resolve it with `diagram.participantById`: ```dart final changes = human.diagram.changes; changes.addListener(() { final actor = human.diagram.participantById(changes.value!.participantId); if (actor?.kind == DiagramParticipantKind.agent) { // Highlight or log the agent's edit, attributed to actor.name. } }); ``` ## Mounting a Flutter canvas `DiagramCanvas(controller: controller)` mounts one controller; a controller supports one mounted canvas at a time. Any controller can be mounted, including one created headlessly; mounting installs the Flutter text layout backend when the diagram has no text layout of its own. Mount a second canvas for another actor by giving it its own controller on the same diagram. Supported font choices and the default font are part of the diagram's shared configuration (`DiagramConfiguration(fonts: ..., defaultFontFamily: ...)`), read with `controller.configuration` and changed with `controller.setFonts` and `controller.setDefaultFontFamily`. Every controller and canvas sees the same font choices, and changing them does not edit document content or add undo entries. Dispose the canvas before its controller. Disposing a controller that joined a diagram releases its selection, previews and listeners and leaves the document and history available. Disposing the controller that created the diagram disposes the diagram and every controller on it. --- # Extensions and options A diagram is configured in one place: its `DiagramConfiguration`, passed to the controller. Everything the diagram can do, from shapes and tools to the editor and the minimap, is an extension in its one `extensions` list, and each extension brings its own configuration. Beside the extensions it holds what the diagram as a whole is and allows: the canvas bounds, the fonts, the rules and the license. The canvas takes the controller and, optionally, a theme. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), MinimapExtension(), GridExtension(visible: true, snap: true), ], ), ); DiagramCanvas(controller: controller, theme: DiagramTheme.dark); ``` ## Configuration ```dart const DiagramConfiguration({ List extensions = const [], CanvasBounds bounds = CanvasBounds.infinite, DiagramFontChoices fonts = const DiagramFontChoices.empty(), String? defaultFontFamily, DiagramRules rules = const DiagramRules(), String? license, }) ``` | Parameter | Default | Purpose | | --- | --- | --- | | `extensions` | none | Every extension the diagram installs beside the core ones, portable and Flutter alike: shapes, text, connectors, [verbs](/agent-docs/api/verbs.md), tools, the editor, overlays and their options. | | `bounds` | `CanvasBounds.infinite` | How far the canvas extends; see [bounds](#bounds). | | `fonts` | no choices | The font families the property panel offers; see [fonts](#fonts). | | `defaultFontFamily` | the text layout's default | The family text uses unless a run names its own. | | `rules` | admit everything | `DiagramRules`: which changes, creations and connections the application admits; see [rules](/agent-docs/api/hooks.md). | | `license` | none | A license token; it removes the canvas attribution. See [license](/agent-docs/api/license.md). | A configuration is immutable and shared per document. The shared `Diagram` holds the document, its configuration, one undo history and the participants; each `DiagramController` is one actor on it, with its own selection, tool and camera. `controller.configuration` reads the current configuration and is observable. The runtime setters replace it with a changed copy for every controller of the diagram, without replacing content or undo history, and none of them is undoable: | Change | Call | | --- | --- | | Canvas bounds | `controller.edits.setBounds(bounds)` | | Font choices | `controller.edits.setFonts(fonts)` | | Default font family | `controller.edits.setDefaultFontFamily(family)` | | Rules | `controller.diagram.setRules(rules)` | The installed extensions and the license never change: the extensions establish the document's grammar, so to change them, create a new controller. `copyWith(bounds:, fonts:, defaultFontFamily:, rules:)` builds a changed copy for a new diagram. ## Controller ```dart DiagramController({ DiagramConfiguration? configuration, DiagramDocument? document, Diagram? diagram, DiagramParticipant participant = DiagramParticipant.local, }) ``` | Parameter | Purpose | | --- | --- | | `configuration` | The new diagram's `DiagramConfiguration`; defaults to an empty one. | | `document` | Starting content. | | `diagram` | Join an existing shared `Diagram` instead of creating one; do not pass `configuration` or `document` with it. See [collaboration](/agent-docs/api/collaboration.md). | | `participant` | Who this actor is, a `DiagramParticipant`; defaults to the local user. | `DiagramController.open(data, format: DiagramJsonCodec.new, configuration: DiagramConfiguration(extensions: [...]))` opens saved content as a new controller. `Diagram(document: ..., configuration: ...)` creates a diagram that several controllers share. `controller.diagram.extensions` lists the installed extensions and `controller.diagram.registry` is their assembled grammar; see [extension reference](/agent-docs/api/extensions.md). ## Install extensions The core extensions are always installed: base shapes and port markers, Plain Text, the grid, the default `connector` type with straight routes, base arrowheads, the interaction tools and the core verbs. Add everything else to `extensions`: - **Dependencies install themselves.** An extension declares the extensions it needs, such as `ShapesExtension` needing `TableExtension`. Each dependency is installed with its defaults unless the application installs an extension with the same id, in which case the application's instance is used. - **A core id replaces the core default.** `GridExtension` (`vyuh.core.grid`) is installed by default; installing one with other arguments replaces the default. - **Ids are unique.** Installing two different extensions with one id, or two non-core extensions contributing the same shape type, tool or other key, is rejected with an `ArgumentError`. Order does not matter, and each feature is one class: a Flutter extension that needs a portable one declares it as a dependency, so list only `TableFlutterExtension()`, not `TableExtension()` beside it. ## Options Options are an extension's runtime configuration, such as whether the grid shows. Canvas bounds and fonts are not options: they belong to the [configuration](#configuration). They are typed, immutable values: - **Keyed by Dart type, with exactly one owner.** An extension declares one options value holding all of its settings, and its flat constructor arguments build the initial value: `super(id: 'vyuh.core.grid', options: GridOptions(...))`. - **Conflicts fail at assembly.** If two installed extensions declare the same options type, creating the diagram throws an `ArgumentError` naming both extensions. - **Read with `controller.options()`.** It returns the current value and is observable, so an `Observer` that reads it rebuilds when it changes. It throws a `StateError` when no installed extension owns `T`. - **Change with `controller.edits.setOptions(value)`.** The controller finds the owner by `value.runtimeType` and replaces its options for every controller of the diagram. The change is not an edit: it records no undo entry and rules do not admit it. When no installed extension owns that type it changes nothing and returns a denied `EditResult` with the reason `": no installed extension owns these options"`. There are no string keys and no lookup of extension instances; the options type is the key. The grid is the pattern every extension follows: ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [GridExtension(visible: true, size: 24)], ), ); final grid = controller.options(); controller.edits.setOptions(grid.copyWith(snap: true)); ``` ```dart Observer( builder: (_) => Switch( value: controller.options().visible, onChanged: (visible) => controller.edits.setOptions( controller.options().copyWith(visible: visible), ), ), ) ``` | Extension (owner) | Options | Settings it holds | | --- | --- | --- | | `GridExtension` (core, `vyuh.core.grid`) | `GridOptions` | `visible`, `snap`, `size`, `pattern`, `patterns` (the patterns the property panel offers; duplicate ids throw an `ArgumentError`); see [grids](/agent-docs/api/grids.md) | | `EditorExtension` | `EditorOptions` | `palette`, `toolbar` (which shell regions show), `inspector` (`InspectorPlacement.none`, `floating` or `docked`), `inspectorSide`, `inspectorWidth`, `inspectorDockedMinimumWidth` (900 by default; 0 allows compact docking), `libraries` (shape library tabs in the inspector panel), `rotationSnap` (degrees Shift snaps rotation to), `connectionSnapRadius` (screen pixels; zero disables connection magnets), `theme` (`EditorTheme`) | | `NavigationExtension` | `NavigationOptions` | `edgePanEnabled`, `edgePadding`, `maximumPanSpeed`, `keyboardStep`, `shiftMultiplier`, `fitOnAttach`; see [navigation](/agent-docs/api/navigation-and-motion.md) | | `ImagesExtension` | `ImagesOptions` | `limits`, `picker`; see [images](#images) | | `RenderingExtension` (`adapter.dart`) | `RenderingOptions` | `lod`, `render`; see [visual detail](#visual-detail) | | `MinimapExtension` | `MinimapOptions` | `visible`, `policy`, `initiallyExpanded`, `alignment`, `margin`, `theme` | | `SnapGuidesExtension` | `SnapGuidesOptions` | `enabled`, `policy`, `tolerance`, `theme` | | `TableFlutterExtension` | `TableFlutterOptions` | `standalone`, `embedded`, `resolve` (per-table overlay modes, read with `modeFor`), `theme`; see [tables](/agent-docs/api/tables.md) | Each options class of the Flutter extensions has `copyWith`, so a runtime change keeps the other settings: ```dart controller.edits.setOptions( controller.options().copyWith(visible: false), ); ``` `EditorOptions` implements the core `DiagramSnapSettings` interface the engine reads while editing. Without an editor installed, the engine uses `DiagramSnapSettings.standard` (15° and 10 pixels); without the navigation, images or rendering extension installed, the canvas uses those options' defaults. A canvas reads `ImagesOptions` and `RenderingOptions` when it mounts; the other options apply live. An extension of your own declares options the same way: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final class Badges { const Badges({this.visible = true}); final bool visible; } final class BadgesExtension extends DiagramFlutterExtension { BadgesExtension({bool visible = true}) : super(id: 'app.badges', options: Badges(visible: visible)); } // controller.edits.setOptions(const Badges(visible: false)); ``` Give an options class value equality (`==` and `hashCode`) so observers rebuild only when a value actually changes. ### Options in the property panel An extension contributes its options to the inspector by overriding `propertiesFor(scope)`. The grid extension offers its show-grid toggle, pattern and size in the canvas group this way, and the editor offers its rotation snap. Core offers the finite-canvas toggle for the canvas bounds. A property typed on an options class reads and updates that options value: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; @override Iterable> propertiesFor( DiagramPropertyScope scope, ) sync* { yield DiagramProperty.toggle( 'show-badges', label: 'Show badges', group: DiagramPropertyGroup.canvas, read: (badges) => badges.visible, update: (badges, visible) => Badges(visible: visible), ); } ``` See the [property grammar](/agent-docs/guide/properties.md). ## Editing A canvas edits when an editable extension is installed; `EditorExtension()` is the editable extension. Without one, the canvas is view-only: it navigates and selects, and the controller's verbs still edit programmatically. `EditorExtension()` also wraps the canvas in a tool palette, an inspector panel and a toolbar. Turn a region off with `palette: false`, `inspector: InspectorPlacement.none` or `toolbar: false`, dock or float the inspector with `InspectorPlacement.docked` or `floating`, and change any of them at runtime through its `EditorOptions`, or replace the whole shell with `container`. `tools: [...]` limits and orders the palette; by default every installed tool the grammar supports is offered and the default tool is `select`. See [editor composition](/agent-docs/api/canvas.md#compose-an-editor). ## Rules ```dart DiagramController( configuration: DiagramConfiguration( rules: DiagramRules( beforeChange: (proposal) => readOnly ? const EditResult.denied(reason: 'This drawing is read-only.') : const EditResult.allow(), canConnect: (intent) => intent.source == intent.target ? const EditResult.denied(reason: 'No loops') : const EditResult.allow(), ), ), ); ``` `beforeChange` sees every proposed change from any controller: verbs, gestures, loads, undo and redo. `canCreate` admits prepared shapes and text elements, and `canConnect` admits connections from the first port hover to the commit. A denied edit publishes nothing and the verb returns the denial. The initial document is not checked. See [rules](/agent-docs/api/hooks.md). ## Bounds The canvas is infinite by default. `CanvasBounds.fit(padding: ...)` bounds it to the content: ```dart final controller = DiagramController( configuration: DiagramConfiguration(bounds: CanvasBounds.fit(padding: 64)), ); controller.edits.setBounds(CanvasBounds.infinite); ``` A fit canvas is the content extent plus `padding` viewport (screen) pixels on every side, so the room around the content looks the same at every zoom. It grows and shrinks with the content and keeps the camera within it; an empty document gets a viewport-sized canvas around the origin. Read the current bounds with the observable `controller.bounds` and change them with `controller.edits.setBounds(...)`. See [canvas bounds](/agent-docs/api/canvas.md#canvas-bounds). ## Themes `DiagramCanvas(theme: ...)` sets the `DiagramTheme` for one canvas; without it the canvas reads the host `Theme`'s `DiagramTheme`, or `DiagramTheme.light`. The chrome an extension adds is themed by that extension's own options: each Flutter extension takes an optional theme in its constructor, and without one picks its light or dark default by `DiagramTheme.brightness`: ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(theme: EditorTheme.dark), MinimapExtension( theme: MinimapTheme.dark.copyWith(viewport: Colors.teal), ), SnapGuidesExtension(theme: const SnapGuideTheme(color: Colors.teal)), TableFlutterExtension( theme: TableTheme.dark.copyWith(range: Colors.teal), ), ], ), ); DiagramCanvas(controller: controller, theme: DiagramTheme.dark); ``` A table theme without a `range` color uses the canvas selection color. The canvas background is `DiagramTheme(canvas: CanvasTheme(background: ...))`. See [theming](/agent-docs/guide/theming.md). ## Fonts The configuration holds the font catalog the inspector offers for standalone text, shape stories and connector labels, and the family text inherits: ```dart final controller = DiagramController( configuration: DiagramConfiguration( fonts: DiagramFontChoices(const [ DiagramFontFamily(family: 'IBM Plex Sans', label: 'Sans serif'), DiagramFontFamily(family: 'Shantell Sans', label: 'Handwritten'), ]), defaultFontFamily: 'Shantell Sans', ), ); ``` | Value | Meaning | | --- | --- | | `DiagramFontFamily.family` | Exact registered family name. | | `DiagramFontFamily.label` | Display and accessibility label. | Read them from `controller.configuration.fonts` and `controller.configuration.defaultFontFamily`. The host bundles or loads the font files; extensions do not download fonts. Explicit text-run families override the inherited one, and imported families do not expand the catalog. `controller.edits.setFonts(fonts)` replaces the catalog, and `controller.edits.setDefaultFontFamily(family)` reflows text without editing document content. Headless output must use the same family and font resources; see [headless text](/agent-docs/api/headless-text.md). ## Canvas tuning Three Flutter extensions tune how a canvas behaves. Each is optional; without it the canvas uses its defaults. Their constructor arguments build their options (`NavigationOptions`, `ImagesOptions`, `RenderingOptions`). | Extension | Configures | | --- | --- | | `NavigationExtension({edgePanEnabled, edgePadding, maximumPanSpeed, keyboardStep, shiftMultiplier, fitOnAttach})` | Edge auto-pan, keyboard movement and fitting content when the canvas first has a viewport; see [navigation](/agent-docs/api/navigation-and-motion.md). | | `ImagesExtension({limits, picker})` | Image loading limits and the image tool's source picker. | | `RenderingExtension({lod, render})` | Level of detail at low zoom and experimental retain and raster switches. A renderer tuning extension: import it from `package:vyuh_diagram_flutter/adapter.dart`. | ### Images ```dart ImagesExtension( limits: DiagramImageConfiguration( maximumConcurrentLoads: 2, retentionBytes: 128 * 1024 * 1024, ), picker: () async => pickMyImage(), ) ``` `DiagramImageConfiguration({maximumConcurrentLoads = 4, loadTimeout = 30 s, retentionBytes = 256 MiB})` values must be positive. The timeout begins when a load is admitted, excluding queue time. `retentionBytes` is a soft limit for retained decoded resources; visible images stay pinned. The `picker` returns a `DiagramImageSource`, or `null` to cancel; the default uses the platform file picker. Export uses its explicit [output options](/agent-docs/api/output.md). ### Visual detail ```dart import 'package:vyuh_diagram_flutter/adapter.dart'; RenderingExtension( lod: DiagramLodPolicy( adaptive: true, compactBelowPixels: 32, thumbnailBelowPixels: 10, ), ) ``` Full detail is the default. With adaptive detail enabled, projected size selects compact or thumbnail rendering. At thumbnail size, connector markers, connector labels and ports are omitted as well. Interaction-critical elements retain full detail. This changes only how the canvas draws, not document geometry or output content. `DiagramRenderPolicy({retainContent, rasterContent})` switches are experimental and off unless the matching `--dart-define` (`DIAGRAM_RETAIN_CONTENT`, `DIAGRAM_RASTER_CONTENT`) is set. They can make large, mostly static drawings cheaper to repaint at the cost of memory; they never change what is drawn or exported. ## Text layout and output A mounted Flutter canvas supplies text layout and SVG and PNG output. Without a canvas, an extension supplies them; at most one installed extension supplies each: | Host | Extension | | --- | --- | | Flutter, exporting before a canvas mounts | `DiagramExtension(id: 'app.backends', textLayout: FlutterDiagramTextLayoutEngine(), output: FlutterDiagramOutput())`, both from `package:vyuh_diagram_flutter/extension_api.dart` | | Dart service, SVG | `SvgExtension()` from `package:vyuh_diagram_codec_svg/vyuh_diagram_codec_svg.dart` | | Dart VM service, native text shaping | `PangoTextLayoutExtension(fontFiles: [...], defaultFontFamily: ...)` from `package:vyuh_diagram_core/vyuh_diagram_pango.dart` | Replacing a backend does not introduce a second document or scene authority. See [output](/agent-docs/api/output.md) and [headless text](/agent-docs/api/headless-text.md). ## Key bindings and verbs Edit document content by performing controller verbs. Extensions and shape definitions declare verbs, and keyboard shortcuts are `DiagramKeyBinding`s, contributed through `DiagramFlutterExtension(shortcuts: [...])`, that name an installed verb. See [canvas key bindings](/agent-docs/api/canvas.md#key-bindings). --- # Connectors and labels ## On this page | Category | What you can do | | --- | --- | | [Routing](#change-a-route) | Choose the path between connected elements. | | [Appearance](#change-connector-style) | Set stroke color, width, pattern and arrowheads. | | [Connect elements](#connect-and-label-shapes) | Create connections and add labels. | | [Label capabilities](#connectorlabelingcapability) | Declare allowed label behavior. | | [Label appearance](#style-one-label) | Set the appearance of an individual label. | | [Creation defaults](#creation-defaults) | Configure initial connection appearance. | | [Effects](#effects) | Send particles or a pulse along a connection. | ## Change connector style ```dart controller.setConnectorStyle( connectorId, color: const DiagramColor(0xFF3355FF), strokeWidth: 3, strokeStyle: StrokeStyle.dashed, ); ``` The same method works in Flutter and pure Dart. Only supplied fields change. | Argument | Type | Meaning | | --- | --- | --- | | `connectorId` | `String` | Existing connector ID. | | `color` | `DiagramColor?` | Stroke color. | | `strokeWidth` | `double?` | Stroke width in world units. | | `strokeStyle` | `StrokeStyle?` | Solid, dashed or dotted stroke. | Omitted fields retain their current values. Endpoints, routing, arrowheads and labels are preserved. The counterpart through `controller.edits` returns an allowed or denied `EditResult`; a successful change creates one undo step. Missing or locked connectors and host admission can deny the edit, and invalid values are denied with `DiagramDenialCode.unsupportedOperation`. An unchanged style publishes nothing. The inspector performs this same verb. ### Arrowheads Each end marker has its own setter: ```dart controller.edits.setEndArrowhead(connectorId, kind: ArrowheadKind.filledTriangle); controller.edits.setStartArrowhead(connectorId, kind: ArrowheadKind.none); controller.edits.setEndArrowhead(connectorId, width: 14, height: 10); ``` | Argument | Type | Meaning | | --- | --- | --- | | `kind` | `ArrowheadKind?` | An installed arrowhead kind, such as `none`, `triangle` or `filledTriangle`. By name (`'triangle'`) through `perform`. | | `width`, `height` | `double?` | Marker size in world units; nonnegative. | Only supplied parts change. Each call is one undo step. See [verbs](/agent-docs/api/verbs.md). ## Reroute connections Use `controller.edits.reroute()` to find clear paths for elbow connections. Pass `ids` to reroute a subset. The verb replaces manual elbow bends and saves all resulting paths in one undoable document edit. If any requested path cannot be found, nothing changes; show the returned result's `reason` in your application. Moving unrelated shapes does not change a saved path. Moving an endpoint keeps the saved path while it stays usable and clear of its owners and nearby obstacles. Otherwise the connector falls back to normal routing and its resolved `routeDiagnostic` reports a stale route (`isRouteStale`), so an application can offer **Reroute connections** again. Straight and curved routes are excluded from the default reroute. Connections rerouted together are spread apart where they would otherwise run along the same channel. Routing does not bundle links, avoid every crossing, or guarantee a globally shortest route. Group interiors are not obstacles, and owned connections stay inside every clipping ancestor. Locked connections, blocked terminals, or no route inside the clips reject the whole edit. Try [the crowded network](/agent-docs/examples/dense-network.md). ## Change a route `controller.edits.setConnectorRoute(connectorId, {route, portSpacing, options})` changes how one connector is routed. Use its counterpart through `controller.edits` for an `EditResult`. Everything supplied changes together, in one undo step. | Argument | Type | Meaning | | --- | --- | --- | | `connectorId` | `String` | ID of an existing, unlocked connector. | | `route` | `ConnectorRoute?` | New route kind: core's `ConnectorRoute.straight`, or an installed route such as `ConnectorRoutes.orthogonal`, `quadratic` or `bezier` from the connectors extension. Switching kinds clears the previous kind's control points and options; undo restores them. | | `portSpacing` | `double?` | World-space gap between connectors that share a port. Applies to every route. | | `options` | `Map` | Values declared by the route's options schema. The elbow (`orthogonal`) route declares `cornerRadius` (default `8`) and `terminalExtension` (default `24`). A null value removes the option, restoring its schema default. | ```dart controller.setConnectorRoute('connection', route: ConnectorRoutes.bezier); controller.setConnectorRoute( connectorId, portSpacing: 8, options: {'terminalExtension': 24, 'cornerRadius': 12}, ); ``` Core defines only `ConnectorRoute.straight`. The elbow and curved identities, `ConnectorRoutes.orthogonal`, `ConnectorRoutes.quadratic` and `ConnectorRoutes.bezier`, come from `vyuh_diagram_extension_connectors` beside the providers that implement them; a route is available once its extension is installed. Any connector may select any installed route. An option the route does not declare, or a value its schema rejects, denies the entire edit. The verb preserves endpoints, labels and appearance. Missing or locked connectors and uninstalled routes are denied; an unchanged update is a no-op. The inspector edits routes through the same rules. Route providers declare typed options in a `DiagramRouteOptionsSchema`: each `DiagramRouteOption` has a key, a label, an optional unit and a `ValueField`, the same declaration a shape uses for its values. Every route, including the elbow route, stores its values in `ConnectorElement.routeOptions`, which JSON saves verbatim and document admission validates against the installed schema. Absent options take the schema's defaults; read a connector's effective elbow values from `connector.routeOptions`, falling back to those defaults. ```dart final connector = ConnectorElement( id: 'connection', start: start, end: end, route: ConnectorRoutes.orthogonal, routeOptions: const {'cornerRadius': 12, 'terminalExtension': 32}, ); ``` A route that mixes in `DiagramRouteOptionProperties` from the connectors extension shows one inspector control per option, the same control a shape value of that field gets, as the elbow route does; see [properties](/agent-docs/guide/properties.md). ## Connect and label shapes Use `controller.edits.connect(from, to)` to connect existing elements. The controller assigns a fresh connector ID and reports it as the result's `id`. Shapes and text boxes use the same connection rules; optional ports select specific anchors. ```dart final connectionId = controller.connect( sourceId, targetId, fromPort: 'output', toPort: 'input', route: ConnectorRoutes.bezier, ); controller.edits.reconnect( connectionId, atStart: false, endpoint: BoundEndpoint(elementId: anotherTargetId, portId: 'input'), ); final labelId = controller.addConnectorLabel(connectionId, text: 'Next step', fraction: 0.5); ``` `fromPort` and `toPort` default to `null`; `route` defaults to `ConnectorRoute.straight`, and `select` defaults to `true`. An accepted connection is one undoable edit. Invalid ports and denied connections return a denied result, with no `id`, without inserting a connector. Use `add(ConnectorElement(...))` for authored IDs, free endpoints, custom anchors, or initial appearance fields. The example assumes those IDs and ports exist. Omit `portId` for a shape anchor or use `FreeEndpoint` for an unbound endpoint. Connection verbs apply the diagram's connection policy; reconnection retains the other connection properties. Routing supports straight, elbow (`orthogonal`), quadratic and cubic Bezier paths. Dragging an endpoint onto a portless, whole-shape-connectable object creates a point anchor at the drop position. `BoundEndpoint.anchorMode` is `ConnectorAnchorMode.point`, with `normalizedAnchor` measured relative to the owner's frame. The anchor follows movement, resizing and rotation, and survives undo, copying and save/reopen. The visible stroke and arrowhead are clipped to the contour; selecting the connector reveals its actual interior endpoint. Port-only shapes continue to use declared ports. `connectionSnapRadius` is a screen-pixel radius shared by ports and virtual targets; zero disables magnets. Portless shapes offer a center, four side midpoints and four projected corners. Away from magnets, drops preserve the chosen anchor. Port-only shapes require a nearby declared port. Moving the other endpoint preserves the source port. For the same behavior through the API: ```dart controller.edits.reconnect( connectionId, atStart: false, endpoint: BoundEndpoint( elementId: targetId, normalizedAnchor: const DiagramPoint(0.23, 0.71), anchorMode: ConnectorAnchorMode.point, ), ); ``` Coordinates range from 0 to 1 in each axis: `(0, 0)` is the frame's top-left and `(1, 1)` is its bottom-right. Point mode cannot be combined with `portId`. Whole-shape bindings default to `ConnectorAnchorMode.outline` and a center anchor. Straight and curved routes aim at the center and clip at the outline; elbows choose a facing axis. Ports and explicit side anchors keep their directions. Handles show the attachment; visible strokes end at the outline. Port bindings use the same owner-contour fitting as whole-shape anchors. A port is a routing anchor, not permission to draw through its owner. Straight, quadratic and Bézier paths stop at the first occupied owner contour, with the complete arrowhead and stroke kept outside disjoint endpoint owners. Elbows add orthogonal route negotiation before that shared fitting step. Overlapping owners retain the existing overlap exception. Labels are attachments owned by the connector. Their fraction ranges from 0 to 1 along resolved path length; they also have offset, size and a shared text story. The label verbs `addConnectorLabel`, `setConnectorLabel` and `removeConnectorLabel` add, change and remove labels; `controller.setSelection(ConnectorLabelSelection(connectorId: c, labelId: l))` selects one. The registry's connector labeling capability controls availability and maximum count. ## Arrange labels ```dart controller.arrangeLabels(); controller.arrangeLabels(ids: ['connection-id'], spacing: 12); ``` `requireAllowed()` throws if the editor rejects the edit, for example because a connector is locked. It does not request permission from a user. To show a message instead, handle the returned result: ```dart final result = controller.edits.arrangeLabels(); if (!result.allowed) { // Display result.reason in your application's feedback area. } ``` Find nearby positions using measured label geometry, avoiding leaf shapes and other labels. Omit `ids` to arrange all labels; labels outside a supplied subset stay fixed and remain obstacles. `spacing` is the minimum gap in world units (default 8; finite and nonnegative). Connectors owned by expanded frames, lanes, or groups can arrange their labels. Candidates must fit inside every active ancestor clip, including spacing. Clipping disabled on a container imposes no boundary. Rotated and custom outlines use conservative containment checks; if no candidate can be proven to fit, the whole arrangement is rejected without changing content or history. Bulk label arrangement and rerouting skip connections hidden by collapsed frames. Explicitly targeting a hidden connection asks you to expand its frame first. Visible external connections use the same collapsed-frame endpoint in previews, rerouting and the canvas; their saved child/port bindings stay intact. Valid placements near their path anchors are retained. Detached labels are returned to the path or placed immediately beside it. The bounded search tries positions along the connector instead of moving labels progressively farther away. All changes share one undo entry and are stored as ordinary label fractions and offsets, so save/load, hit testing and output consume the same positions. A repeated call with nothing to move adds no history. The bounded search can fail even when a distant placement exists. On failure nothing changes; the result explains that more room is needed. Label movement must be enabled, and requested connectors must exist, be unlocked and have no group owner. Finish active edits first. This verb does not avoid all connector crossings or solve global label optimization. See the [crowded-label example](/agent-docs/examples/connector-labels.md). ## `ConnectorLabelingCapability` The default connector label is Plain Text, centered on its path anchor. It grows to fit its longest line and expands vertically for additional paragraphs. It admits no lists or marks, and it has no resize handles by default. | Property | Default | Contract | | --- | --- | --- | | `maximumLabels` | `2` | One or two attachments on a connector. | | `endInset` | `0.15` | Default distance from each end, as a fraction of the route. | | `defaultFontFamily` | `sans-serif` | Label font, independent of node typography. | | `defaultFontSize` | `14` | Inherited label text size in logical pixels; explicit run sizes take precedence. | | `textType` | `PlainTextDefinition()` | The text filling every label: multiline plain paragraphs. Use `maxLines: 1` for Enter to exit editing, or a `RichTextDefinition` for formatted labels. | | `resizable` | `false` | No resize handles, and `setConnectorLabel` denies `size`, by default. | | `movable` | `true` | Dragging projects the label onto the visible path, between fractions 0 and 1. | | `textEditable` | `true` | Double-click creates or edits a label. | | `deletable` | `true` | A selected label can be removed independently. | | `defaultSize` | `DiagramSize(120, 32)` | Authored box; plain labels fit their longest line, reserving one character when empty. Height grows for additional lines. | | `minimumSize` | `DiagramSize(24, 16)` | Admission limit for authored label geometry. | Select a connector and press **Enter**, or double-click its path, to create a label when capacity remains. With two-label capacity, defaults place labels near opposite ends: at route fractions `endInset` and `1 - endInset` (`0.15` and `0.85`). With one-label capacity, the default is the midpoint. Explicit API `fraction` values remain supported. At capacity, path activation does nothing; it never switches to an arbitrary existing label. Select a specific label and press **Enter**, or double-click that label, to edit its text. Label selection retains its identity even when another label exists. `maximumLabels` accepts 1 or 2. `endInset` must be finite and in `[0, 0.5)`. `defaultFontFamily` defaults to `sans-serif`, independently of the node font; `defaultFontSize` remains 14. Explicit inline font choices override these defaults. These interactions are built into the connector labeling capability. Locked connectors, disabled labeling, or `textEditable: false` prevent entry. Merely entering an existing label creates no document/history change. Enter adds a paragraph; Escape exits editing. The padded editing outline stays visible while typing. Clearing text removes visible ink and the idle hit box; reactivation can reopen the existing empty attachment. Labels accept plain paragraphs, not lists. Use `controller.addConnectorLabel` explicitly for additional labels, up to the configured limit. Hosts can opt into single-line or resizable labels through a custom capability. The default inherited font size is **14 px**, shared by measurement, painting, caret geometry, the inspector and size shortcuts. Explicit `TextRun.fontSize` values are preserved. Set `ConnectorLabelingCapability(defaultFontSize: ...)` to customize the inherited size for a registry. ## Style one label Select a label to show **Connector label** in the inspector. Its font size, text color and inline marks affect that attachment only. The connector stroke and other labels keep their own styles. Plain labels expose text properties; choosing **Badge** also exposes fill, border color/style/width, radius and padding. Single-line labels do not show list or paragraph-alignment controls. Text styling uses the shared `TextRun` fields (`fontSize`, `color`, `fontFamily`, `marks`), not a separate label-only text model. For example: ```dart controller.edits.setConnectorLabel( connectionId, labelId, story: TextStory( id: existingStory.id, blocks: [ for (final block in existingStory.blocks) block.copyWith(runs: [ for (final run in block.runs) run.copyWith(fontSize: 20, color: const DiagramColor(0xff2454d8)), ]), ], ), presentation: const BadgeLabelPresentation( fill: DiagramColor(0xffffffff), stroke: DiagramColor(0xff2454d8), strokeWidth: 2, cornerRadius: 8, padding: 6, ), ); ``` `existingStory` is the selected attachment's current story. Preserve its IDs and other run properties when restyling. A text change and presentation change in the same call publish and undo together. ### `controller.setConnectorLabel` ```dart EditResult setConnectorLabel( String connectorId, String labelId, { TextStory? story, double? fraction, DiagramPoint? offset, DiagramSize? size, LabelPresentation? presentation, }) ``` | Argument | Contract | | --- | --- | | `connectorId`, `labelId` | Required positional identities. Missing or locked connectors reject the operation. | | `story` | Shared paragraph/run content. Requires text editing capability. | | `fraction` | Position along resolved path length, from `0` to `1`; requires movement capability. | | `offset` | World-space displacement from the path anchor; requires movement capability. | | `size` | Authored label size; requires resize capability, disabled by default. | | `presentation` | Plain Text or badge surface. Omitted fields preserve their current values. | All named arguments default to `null`, meaning unchanged. The method returns an `EditResult`; a missing capability (`unsupportedOperation`), a missing connector (`unavailableTarget`) or host admission returns a denied result, and `requireAllowed()` converts it into `DiagramChangeDenied`. A missing label (`unavailableTarget`) or a value the label model rejects (`unsupportedOperation`) is denied too. No partial update occurs. By name, the verb is `perform([connectorId], 'setConnectorLabel', {'label': labelId, ...})`. ### `LabelPresentation` | Production | Contract | | --- | --- | | `const PlainLabelPresentation()` | Text only. No fill, border, radius or padding properties. | | `const BadgeLabelPresentation(...)` | Rounded backing surface with the fields below. | | Badge property | Type | Default | | --- | --- | --- | | `fill` | `DiagramColor` | `0xffffffff` (white). Use transparent for a border-only badge. | | `stroke` | `DiagramColor` | `0xff94a3b8` (muted slate). | | `strokeWidth` | `double` | `0` (no border). | | `strokeStyle` | `StrokeStyle` | `solid`; also supports `dashed` and `dotted`. | | `cornerRadius` | `double` | `4`. | | `padding` | `double` | `4`. | Dimensions must be finite and nonnegative. Padding must leave a valid text interior. `copyWith` returns a new badge value; equality includes every field. Border geometry is centered on the backing surface. Resolved `visualBounds` include its half-width bleed for hit testing, selection and scene bounds; text layout continues to use the padded interior. A visible badge fill or border reserves its area from path effects so particles cannot paint over it. These styles are saved in JSON and rendered by the shared canvas/PNG painter. ## Creation defaults A `DiagramConnectorDefinition(...)` contributed through an extension's `connectors` configures connector creation and labeling. Without a `type` it replaces the core `connector` type; `DiagramConnectorDefinition(type: 'k', ...)` adds another connector type that `DiagramConnectorTool(connectorType: 'k')` creates. | Property | Type | Default | Behavior | | --- | --- | --- | --- | | `defaultEndOffset` | `DiagramPoint` | `(160, 0)` | Canvas-space displacement from the start when the connector tool is clicked without dragging. Must be finite and nonzero. Grid snapping still applies. Dragging uses the pointer endpoint. | | `labeling` | `ConnectorLabelingCapability?` | Default labeling capability | Configures label creation and editing; `null` disables labels. | ### Inspector editing ranges `DiagramConnectorDefinition.editing` accepts `DiagramConnectorEditing`. These bounds configure the built-in inspector; they do not rewrite authored route values or change the geometry admission rules. | Property | Default | | --- | --- | | `minimumStrokeWidth` / `maximumStrokeWidth` | `1` / `32` | | `minimumArrowSize` / `maximumArrowSize` | `4` / `64` | | `maximumPortSpacing` | `64` | | `maximumPortExtension` | `160` | | `maximumCornerRadius` | `64` | All values must be finite and positive, and each minimum must not exceed its maximum. Registry construction validates the declaration. Spacing, extension, and radius controls retain a zero lower bound. Route capabilities determine which controls are shown; quadratic and Bezier routes do not acquire extension controls simply because an editing maximum exists. `addConnectorLabel(text: ...)` assigns story and paragraph identities. Supply either plain `text` or a structured `story`, never both. Registered label rules still apply: labels accept multiline plain paragraphs, while list content is rejected without publishing a label or changing undo history. ## Editing elbow segments Select an elbow connector to show a circular handle at the midpoint of each nonzero horizontal or vertical segment. Drag a horizontal segment up or down, or a vertical segment left or right. Adjacent parallel runs snap within eight screen pixels and fuse into one segment. Moving outside the snap region during the same drag restores the jog; only pointer release commits the simplified route. Zero-length and collinear vertices are removed before handles are generated, so each continuous run has exactly one circular handle. Rounded corners remain a rendering setting; handles use the unrounded route geometry. Dragging a terminal segment adds orthogonal return legs instead of moving the bound endpoint. During a drag, invalid positions near a bound terminal clamp to the nearest valid position rather than triggering automatic rerouting. A short terminal run is retained (up to eight world units, limited by the original run); valid fusion into a direct route remains allowed. Moving back from the limit responds immediately from the original gesture baseline. One drag is one undo step; cancelling restores the previous route. Manually edited routes save `routedPoints` with `preserveRoute: true` in JSON; set them from code with `controller.edits.setRouteGeometry(connectorId, routedPoints: [...], preserveRoute: true)`, which also sets `route`, `bend` and `controlPoints`. Endpoint movement reconnects the route to the saved interior corridors; moving both endpoints equally translates the route. Explicit **Reroute** clears manual preservation and computes a new obstacle-avoiding route. Manual routes express placement intent, not an automatic guarantee of obstacle clearance after arbitrary shape movement. Reroute when the surrounding layout changes and a saved corridor is no longer appropriate. Saved positions are hints: if they would create a crossing or a wrong-way terminal, normal routing takes precedence. Collinear backtracking is removed before corners are rounded. Zero-length segments have no handle, and collapsed connection bundles must be expanded before editing. ## Effects A connector plays transient effects on a mounted canvas: particles or marching dashes that flow along its route (`Effect.flow`), a pulse or blink of its stroke (`Effect.pulse`), or a fade to a dim level (`Effect.fade`). Effects never change the document or history. ```dart final flow = controller.effects.play( const Effect.flow(particle: EffectParticle.arrow(), count: 4), on: connectorId, ); // Blink the route three times, then stop. controller.effects.play( const Effect.pulse( target: EffectTarget.stroke, waveform: Waveform.step, period: Duration(milliseconds: 500), repeat: 3, ), on: connectorId, ); flow.stop(); ``` See [Animation & effects](/agent-docs/api/effects.md) for every effect, its values and custom effects, and the [connector effects](/agent-docs/examples/connector-effects.md) example. --- # Controller reference Everything a `DiagramController` offers, grouped by purpose: its members, the verbs of every Vyuh Diagram extension, and the `view` and `effects` of a mounted canvas. See [diagram and controller](/agent-docs/api/controller.md) for how they fit together and [verbs](/agent-docs/api/verbs.md) for performing, checking and writing verbs. A **verb** is a named, undoable edit. Every verb can be performed by name with `controller.perform(ids, name, args)`, and most have a typed Dart method of the same name. Each verb entry gives its name, what it targets and its arguments; `?` marks an optional one. Members without a verb do not change the document. Under each member is the package that provides it, and the library to import when it is not the package's main library. This page is generated from the API and the installed verb registry. Use direct methods for everyday edits: creation returns the new ID, and refused edits throw `DiagramChangeDenied`. Use the same method names through `controller.edits` when you need an `EditResult` to inspect `allowed`, `id`, `code` and `reason`. Both paths share the document and undo history. | Group | What it covers | | --- | --- | | [Construct and open](#construct-and-open) | Create a controller with a new diagram, join an existing one, or open saved data. | | [Document and state](#document-and-state) | Read what this actor sees, including its own in-progress preview. | | [Verbs and discovery](#verbs-and-discovery) | Perform any verb by name, check it first, and discover what a target accepts. | | [Create and delete](#create-and-delete) | Add elements with registry defaults, remove them, and copy them. | | [Select](#select) | Change this actor's selection. Selection is not part of the document or history. | | [Arrange and transform](#arrange-and-transform) | Move, size, rotate and order elements. | | [Structure](#structure) | Group, frame and reparent elements. | | [Style and shape](#style-and-shape) | Appearance, visibility, locking, values and type of elements. | | [Text](#text) | Plain text, paragraph settings and a shape's text parts. | | [Rich text](#rich-text) | Formatting of rich text stories, over the whole story or a range. | | [Connections and ports](#connections-and-ports) | Connect elements, route and style connectors, label them, and set ports. | | [Paths](#paths) | Edit the nodes and handles of an editable path. | | [Tables](#tables) | Rows, columns, cells and borders of table content. Shapes with several tables qualify these verbs by part, such as `primary.insertRow`. | | [Layout](#layout) | Arrange root-level nodes automatically with an installed layout algorithm. | | [History and interactions](#history-and-interactions) | Undo this actor's own edits, group verbs into one step, and preview continuous edits. | | [Persistence and output](#persistence-and-output) | Save and load documents, and export images. | | [Canvas and view](#canvas-and-view) | The camera, tools, and the viewport of the mounted canvas. | | [Effects](#effects) | Transient effects on the mounted canvas. They never change the document or history. | | [Configuration and options](#configuration-and-options) | The diagram's shared configuration, applied to every controller on it. | | [Participants](#participants) | The shared diagram and the actor this controller edits as. | | [Extension authoring](#extension-authoring) | Engine hooks for verb implementations, from the adapter library. | | [Lifecycle](#lifecycle) | Mounting and disposal. | ## Construct and open Create a controller with a new diagram, join an existing one, or open saved data. | Member | What it does | | --- | --- | | `DiagramController({DiagramConfiguration? configuration, DiagramDocument? document, Diagram? diagram, DiagramParticipant participant = DiagramParticipant.local})`
vyuh_diagram_core | A controller of a new diagram of `document`, configured by `configuration`. | | `static DiagramController open(T data, {required DiagramDocumentCodec Function(DiagramModelCodecs) format, DiagramConfiguration configuration = const DiagramConfiguration(), DiagramParticipant participant = DiagramParticipant.local})`
vyuh_diagram_core | A controller of a new diagram opened from `data` saved in `format`, such as `DiagramJsonCodec.new`, decoded over the configured extensions' codecs. | ## Document and state Read what this actor sees, including its own in-progress preview. | Member | What it does | | --- | --- | | `DiagramDocument document`
vyuh_diagram_core | The document this actor sees, including its own in-progress preview. | | `ResolvedScene scene`
vyuh_diagram_core | The resolved geometry of `document`. | | `DiagramElement? elementById(String id)`
vyuh_diagram_core | The element `id` as this actor sees it. | | `ResolvedElement? resolvedElementById(String id)`
vyuh_diagram_core | Live geometry of one identity, observed independently of the whole scene. | ## Verbs and discovery Perform any verb by name, check it first, and discover what a target accepts. | Member | What it does | | --- | --- | | `DiagramEdits edits`
vyuh_diagram_core | The shared diagram this controller edits. | | `void perform(Iterable ids, String verb, [Map args = const {}])`
vyuh_diagram_core | Performs the edit; throws when denied. | | `EditResult canPerform(Iterable ids, String verb, [Map args = const {}])`
vyuh_diagram_core | Whether `perform` would run `verb` on `ids` with `args`, and why not. | | `List verbs([Iterable ids = const []])`
vyuh_diagram_core | The verbs available on `ids`, with their schemas and whether each can run now. | | `DiagramVerbDescription? verb(Iterable ids, String name)`
vyuh_diagram_core | The verb `name` on `ids` with its schema and availability, or null when no such verb applies to them. | | `DiagramElementAnatomy? describe(String id)`
vyuh_diagram_core | What element `id` is made of: its text slots, value schema, ports, structured content and whether it owns children. | | `DiagramPropertyFields properties({Iterable? ids})`
vyuh_diagram_core | The inspector's properties of element `id`, with current values. | | `void setProperty(Iterable ids, String key, Object? value)`
vyuh_diagram_core | Performs the edit; throws when denied. | | `DiagramDiagnostics checkDiagnostics({Iterable Function(DiagramDocument)> rules = const []})`
vyuh_diagram_core | Checks the installed domain rules against one document snapshot. | | `void fixDiagnostic(DiagramDiagnostics report, DiagramDiagnosticFix fix)`
vyuh_diagram_core | Performs the edit; throws when denied. | | `DiagramElement? applyTo(DiagramElement element, String verb, [Map arguments = const {}])`
vyuh_diagram_core | What setter `verb` with `args` would make of `element`, an element outside the document such as the next shape a creation tool makes. | ## Create and delete Add elements with registry defaults, remove them, and copy them. | Member | What it does | | --- | --- | | `String createShape(String type, {required DiagramPoint at, String? id, DiagramSize? size, ShapeStyle? style, Map? values, String? text, TextStory? textStory, DiagramTextSizingMode? textSizingMode, List? ports, DiagramShapeParentPlacement? parent, bool select = true, int zIndex = 0})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `createShape` on the diagram: `type: text, at: point, id?: text, size?: size, style?: style, values?: values, text?: text, textStory?: story, textSizingMode?: choice, ports?: ports, parent?: parent, select?: boolean, zIndex?: integer` | | `String createText({String type = Shapes.text, required DiagramPoint at, String? id, DiagramSize? size, String? text, TextStory? textStory, DiagramTextSizingMode? textSizingMode, DiagramShapeParentPlacement? parent, bool select = true, int zIndex = 0})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `createText` on the diagram: `at: point, type?: text, id?: text, size?: size, text?: text, textStory?: story, textSizingMode?: choice, parent?: parent, select?: boolean, zIndex?: integer` | | `String createPath({required DiagramVectorPath path, required DiagramPoint at, DiagramSize? size, ShapeStyle? style, String? id, DiagramShapeParentPlacement? parent, bool select = true})`
vyuh_diagram_core | Creates and returns the identity; throws when denied. | | `String createLine({required DiagramPoint start, required DiagramPoint end, ShapeStyle? style, String? id, DiagramShapeParentPlacement? parent, bool select = true})`
vyuh_diagram_core | Creates and returns the identity; throws when denied. | | `String createPolyline({required Iterable points, bool closed = false, ShapeStyle? style, String? id, DiagramShapeParentPlacement? parent, bool select = true})`
vyuh_diagram_core | Creates and returns the identity; throws when denied. | | `String createConnected({required ConnectorEndpoint source, required FramedElement element, String? toPort, String? connectorId, String connectorType = 'connector', ConnectorRoute route = ConnectorRoute.straight, int connectorZIndex = -1, bool select = true})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `createConnected` on the diagram: `source: endpoint, element: element, toPort?: text, connectorId?: text, connectorType?: text, route?: route, connectorZIndex?: integer, select?: boolean` | | `String createConnectedShape(String type, {required BoundEndpoint source, required DiagramPoint at, String? toPort, ConnectorRoute route = ConnectorRoute.straight, int? expectedRevision})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `createConnectedShape` on the diagram: `type: text, source: endpoint, at: point, toPort?: text, route?: route` | | `void add(DiagramElement element, {bool select = true})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `add` on the diagram: `element: element, select?: boolean` | | `String allocateId(String prefix)`
vyuh_diagram_core | A fresh element identity with `prefix`, unused in the document. | | `void delete({Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `delete` on elements | | `DiagramClipboardPayload copy({Iterable? ids})`
vyuh_diagram_core | Captures `ids`, or the selection, for `paste`. | | `void paste(DiagramClipboardPayload payload, {DiagramPoint offset = const DiagramPoint(24, 24)})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `paste` on the diagram: `payload: clipboard, offset?: point` | | `void duplicate({Iterable? ids, DiagramPoint offset = const DiagramPoint(24, 24)})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `duplicate` on elements: `offset?: point` | ## Select Change this actor's selection. Selection is not part of the document or history. | Member | What it does | | --- | --- | | `DiagramSelection selection`
vyuh_diagram_core | This actor's selection. | | `void select(Iterable ids)`
vyuh_diagram_core | Selects `ids`, replacing the current selection. | | `void selectAll({String? ownerId})`
vyuh_diagram_core | Selects every element owned by `ownerId`, or every element. | | `void clearSelection()`
vyuh_diagram_core | Clears this actor's selection. | | `void setSelection(DiagramSelection selection)`
vyuh_diagram_core | Replaces this actor's selection. | ## Arrange and transform Move, size, rotate and order elements. | Member | What it does | | --- | --- | | `void move(DiagramPoint delta, {Iterable? ids, Motion? motion})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `move` on elements: `delta: point, motion?: motion` | | `void resize(DiagramSize size, {Iterable? ids, bool fromCenter = false, bool preserveAspectRatio = false, Motion? motion})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `resize` on elements: `size: size, fromCenter?: boolean, preserveAspectRatio?: boolean, motion?: motion` | | `void rotate({Iterable? ids, required DiagramPoint pivot, required double radians})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `rotate` on elements: `pivot: point, radians: number` | | `void setElementBounds(String id, DiagramRect bounds, {Motion? motion})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setElementBounds` on one element: `bounds: rect, motion?: motion` | | `void align(DiagramAlignment alignment, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `align` on elements: `alignment: choice` | | `void distribute(DiagramDistribution distribution, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `distribute` on elements: `distribution: choice` | | `void reorder(DiagramLayerOrder order, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `reorder` on elements: `order: choice` | | `void setZIndex(int zIndex, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setZIndex` on elements: `zIndex: integer` | | `void arrangeLanes({Iterable? ids, DiagramLaneDirection direction = DiagramLaneDirection.rows, DiagramSize? laneSize, double gap = 0})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `arrangeLanes` on elements: `direction?: choice, laneSize?: size, gap?: number` | ## Structure Group, frame and reparent elements. | Member | What it does | | --- | --- | | `void group({Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `group` on elements | | `void ungroup({Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `ungroup` on elements | | `void frame({Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `frame` on elements | | `void unframe({Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `unframe` on elements | | `void reparent({Iterable? ids, String? parentId, DiagramPoint delta = DiagramPoint.zero})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `reparent` on elements: `parent?: text, delta?: point` | | `void setFrameCollapsed(String id, bool collapsed)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setFrameCollapsed` on one element: `collapsed: boolean` | ## Style and shape Appearance, visibility, locking, values and type of elements. | Member | What it does | | --- | --- | | `void setStyle({Iterable? ids, DiagramFill? fill, DiagramColor? stroke, double? strokeWidth, double? cornerRadius, StrokeStyle? strokeStyle, InkPreset? inkPreset})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setStyle` on elements: `fill?: fill, stroke?: color, strokeWidth?: number, cornerRadius?: number, strokeStyle?: choice, inkPreset?: choice` | | `void setOpacity(double opacity, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setOpacity` on elements: `opacity: number` | | `void setVisible(bool visible, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setVisible` on elements: `visible: boolean` | | `void setLocked(bool locked, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setLocked` on elements: `locked: boolean` | | `void setAspectLocked(bool locked, {Iterable? ids, bool square = false})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setAspectLocked` on elements: `locked: boolean, square?: boolean` | | `void setPolygonSides(int sides, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setPolygonSides` on elements: `sides: integer` | | `void setClipContent(bool clip, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setClipContent` on elements: `clip: boolean` | | `void setImage(String id, DiagramImageSource? image)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setImage` on one element: `image?: image` | | `void setValues(String id, Map values)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setValues` on elements: `values: values` | | `void setType(String id, String type)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setType` on one element: `type: text` | | `ShapeStyle shapeCreationStyle(String type)`
vyuh_diagram_core | Appearance for subsequent creations of this registered shape type. | | `void setShapeCreationStyle(String type, ShapeStyle style)`
vyuh_diagram_core | Sets the appearance of future shapes of `type`. | | `void showSecondarySection(String id, bool shown)`
vyuh_diagram_extension_shapes | Shows or hides the secondary section of entity `id`.
Verb `showSecondarySection` on one element: `shown: boolean` | ## Text Plain text, paragraph settings and a shape's text parts. | Member | What it does | | --- | --- | | `void setText(String id, String text, {String? slot, String? storyId})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setText` on one element: `text: text, storyId?: text` | | `void setTextAlignment(String id, ParagraphAlignment alignment, {String? storyId, int start = 0, int? end})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setTextAlignment` on one element: `alignment: choice, storyId?: text, start?: integer, end?: integer` | | `void setTextDirection(String id, ParagraphDirection direction, {String? storyId, int start = 0, int? end})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setTextDirection` on one element: `direction: choice, storyId?: text, start?: integer, end?: integer` | | `perform(ids, 'replaceText', {…})`
vyuh_diagram_core | Replaces story before with after, which keeps its identity. Editors and formatting build on it.
Verb `replaceText` on one element: `before: story, after: story, label?: text, selectionAfter?: selection` | | `perform(ids, 'setTextStory', {…})`
vyuh_diagram_core | Sets a shape's whole text story, such as the one its definition starts text with, or removes it.
Verb `setTextStory` on one element: `story?: story` | | `void addSlot(String id, String slot, {String? text})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `addSlot` on one element: `slot: text, text?: text` | | `void removeSlot(String id, String slot)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `removeSlot` on one element: `slot: text` | | `void setTitle(String id, String title)`
vyuh_diagram_core | Sets the title of card `id`.
Verb `setTitle` on one element: `title: text` | | `void setDescription(String id, String description)`
vyuh_diagram_core | Sets the description of card `id`.
Verb `setDescription` on one element: `description: text` | | `void setTag(String id, String? tag)`
vyuh_diagram_core | Shows the tag of card `id` with `tag`, or hides it when `tag` is null.
Verb `setTag` on one element: `tag?: text` | ## Rich text Formatting of rich text stories, over the whole story or a range. | Member | What it does | | --- | --- | | `String createRichText({required DiagramPoint at, String? id, DiagramSize? size, String? text, TextStory? textStory, DiagramTextSizingMode? textSizingMode, DiagramShapeParentPlacement? parent, bool select = true, int zIndex = 0})`
vyuh_diagram_extension_rich_text | Creates rich text and returns its ID. | | `void setMark({required String elementId, required TextMark mark, required bool on, String? storyId, int start = 0, int? end})`
vyuh_diagram_extension_rich_text | Turns `mark`, such as bold, on or off over the story or a range.
Verb `setMark` on one element: `mark: choice, on: boolean, storyId?: text, start?: integer, end?: integer` | | `void setHeading({required String elementId, required HeadingLevel heading, String? storyId, int start = 0, int? end})`
vyuh_diagram_extension_rich_text | Makes the touched paragraphs headings at `heading`, or body text.
Verb `setHeading` on one element: `heading: choice, storyId?: text, start?: integer, end?: integer` | | `void setList({required String elementId, required ParagraphKind kind, String? storyId, int start = 0, int? end})`
vyuh_diagram_extension_rich_text | Makes the touched paragraphs list items of `kind`, or ordinary paragraphs with `ParagraphKind.paragraph`.
Verb `setList` on one element: `kind: choice, storyId?: text, start?: integer, end?: integer` | | `void changeIndent({required String elementId, required int delta, String? storyId, int start = 0, int? end})`
vyuh_diagram_extension_rich_text | Indents the touched paragraphs by `delta` levels, or outdents them.
Verb `changeIndent` on one element: `delta: integer, storyId?: text, start?: integer, end?: integer` | | `void adjustFontSize({required String elementId, required double delta, String? storyId, int start = 0, int? end})`
vyuh_diagram_extension_rich_text | Steps font sizes by `delta` within the target's font size range.
Verb `adjustFontSize` on one element: `delta: number, storyId?: text, start?: integer, end?: integer` | | `void clearFormatting({required String elementId, String? storyId, int start = 0, int? end})`
vyuh_diagram_extension_rich_text | Removes marks and paragraph formatting from the story or a range.
Verb `clearFormatting` on one element: `storyId?: text, start?: integer, end?: integer` | | `void setChecked({required String elementId, required String blockId, required bool checked, String? storyId})`
vyuh_diagram_extension_rich_text | Checks or unchecks checklist item `blockId`.
Verb `setChecked` on one element: `block: text, checked: boolean, storyId?: text` | ## Connections and ports Connect elements, route and style connectors, label them, and set ports. | Member | What it does | | --- | --- | | `String connect(String from, String to, {String? fromPort, String? toPort, String type = 'connector', ConnectorRoute route = ConnectorRoute.straight, bool select = true})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `connect` on the diagram: `from: text, to: text, fromPort?: text, toPort?: text, type?: text, route?: route, select?: boolean` | | `void reconnect(String connectorId, {required bool atStart, required ConnectorEndpoint endpoint})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `reconnect` on one element: `atStart: boolean, endpoint: endpoint` | | `void setConnectorStyle(String connectorId, {DiagramColor? color, double? strokeWidth, StrokeStyle? strokeStyle})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setConnectorStyle` on elements: `color?: color, strokeWidth?: number, strokeStyle?: choice` | | `void setStartArrowhead(String connectorId, {ArrowheadKind? kind, double? width, double? height})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setStartArrowhead` on elements: `kind?: arrowhead, width?: number, height?: number` | | `void setEndArrowhead(String connectorId, {ArrowheadKind? kind, double? width, double? height})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setEndArrowhead` on elements: `kind?: arrowhead, width?: number, height?: number` | | `void setConnectorRoute(String connectorId, {ConnectorRoute? route, double? portSpacing, Map options = const {}})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setConnectorRoute` on elements: `route?: route, portSpacing?: number, options?: values` | | `void setRouteGeometry(String connectorId, {ConnectorRoute? route, double? bend, List? controlPoints, List? routedPoints, bool? preserveRoute})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setRouteGeometry` on one element: `route?: route, bend?: number, controlPoints?: points, routedPoints?: points, preserveRoute?: boolean` | | `void reroute({Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `reroute` on the diagram: `connectors?: ids` | | `String addConnectorLabel(String connectorId, {TextStory? story, String? text, double? fraction, DiagramPoint offset = DiagramPoint.zero, DiagramSize? size})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `addConnectorLabel` on one element: `text?: text, story?: story, fraction?: number, offset?: point, size?: size` | | `void setConnectorLabel(String connectorId, String labelId, {TextStory? story, double? fraction, DiagramPoint? offset, DiagramSize? size, LabelPresentation? presentation})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setConnectorLabel` on one element: `label: text, story?: story, fraction?: number, offset?: point, size?: size, presentation?: labelPresentation` | | `void removeConnectorLabel(String connectorId, String labelId)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `removeConnectorLabel` on one element: `label: text` | | `void arrangeLabels({Iterable? ids, double spacing = 8})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `arrangeLabels` on the diagram: `connectors?: ids, spacing?: number` | | `void setConnectorCreationRoute(ConnectorRoute route)`
vyuh_diagram_core | The route kind new connectors use. | | `void setPorts(List ports, {Iterable? ids})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setPorts` on elements: `ports: ports` | ## Paths Edit the nodes and handles of an editable path. | Member | What it does | | --- | --- | | `void setPathClosed(String elementId, bool closed)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setPathClosed` on one element: `closed: boolean` | | `void setPathHandleMode(String elementId, String nodeId, DiagramPathHandleMode mode)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setPathHandleMode` on one element: `node: text, mode: choice` | | `void setPathSegmentKind(String elementId, String nodeId, DiagramPathSegmentKind kind)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `setPathSegmentKind` on one element: `node: text, kind: choice` | | `String addPathPoint(String elementId, {required String after, double t = .5, String? id})`
vyuh_diagram_core | Creates and returns the identity; throws when denied.
Verb `addPathPoint` on one element: `after: text, t?: number, id?: text` | | `void removePathNodes(String elementId, Set nodeIds)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `removePathNodes` on one element: `nodes: ids` | | `void movePathControl(String elementId, String nodeId, DiagramPathControl control, DiagramPoint position)`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `movePathControl` on one element: `node: text, control: choice, position: point` | ## Tables Rows, columns, cells and borders of table content. Shapes with several tables qualify these verbs by part, such as `primary.insertRow`. | Member | What it does | | --- | --- | | `void insertRow(String id, {required int at, int? focusColumn, String? part})`
vyuh_diagram_extension_table | Inserts a row at index `at` of the table in shape `id`.
Verb `insertRow` on one element: `at: integer, focusColumn?: integer` | | `void removeRow(String id, {required int at, String? part})`
vyuh_diagram_extension_table | Removes the row at index `at` of the table in shape `id`.
Verb `removeRow` on one element: `at: integer` | | `void insertColumn(String id, {required int at, String? part})`
vyuh_diagram_extension_table | Inserts a column at index `at` of the table in shape `id`.
Verb `insertColumn` on one element: `at: integer` | | `void removeColumn(String id, {required int at, String? part})`
vyuh_diagram_extension_table | Removes the column at index `at` of the table in shape `id`.
Verb `removeColumn` on one element: `at: integer` | | `void removeTracks(String id, {required String anchor, required String focus, required bool rows, String? part})`
vyuh_diagram_extension_table | Removes the rows, or the columns, a cell range spans.
Verb `removeTracks` on one element: `anchor: text, focus: text, rows: boolean` | | `void resizeRow(String id, {required int index, required double height, String? part})`
vyuh_diagram_extension_table | Sets the height of row `index`.
Verb `resizeRow` on one element: `index: integer, size: number` | | `void resizeColumn(String id, {required int index, required double width, String? part})`
vyuh_diagram_extension_table | Sets the width of column `index`.
Verb `resizeColumn` on one element: `index: integer, size: number` | | `void mergeCells(String id, {required String anchor, required String focus, String? part})`
vyuh_diagram_extension_table | Merges the cells from `anchor` to `focus` into one cell.
Verb `mergeCells` on one element: `anchor: text, focus: text` | | `void splitCell(String id, {required String cell, String? part})`
vyuh_diagram_extension_table | Splits the merged cell containing `cell` back into its cells.
Verb `splitCell` on one element: `cell: text` | | `void setCellText(String id, {required String cell, required String text, String? part})`
vyuh_diagram_extension_table | Replaces the text of `cell` with `text`, one plain paragraph per line.
Verb `setCellText` on one element: `cell: text, text: text` | | `void clearCells(String id, {required String anchor, required String focus, String? part})`
vyuh_diagram_extension_table | Empties the text of the cells from `anchor` to `focus`.
Verb `clearCells` on one element: `anchor: text, focus: text` | | `void setBorders(String id, {DiagramBorder? outer, DiagramBorder? rows, DiagramBorder? columns, String? part})`
vyuh_diagram_extension_table | Sets the table's `outer`, `rows` and `columns` borders.
Verb `setBorders` on one element: `outer?: border, rows?: border, columns?: border` | | `void setRowBorder(String id, {required int index, DiagramBorder? border, String? part})`
vyuh_diagram_extension_table | Sets the border after row `index`, or clears it when `border` is null so the table's row border applies.
Verb `setRowBorder` on one element: `index: integer, border?: border` | | `void setColumnBorder(String id, {required int index, DiagramBorder? border, String? part})`
vyuh_diagram_extension_table | Sets the border after column `index`, or clears it when `border` is null so the table's column border applies.
Verb `setColumnBorder` on one element: `index: integer, border?: border` | | `void selectTableCells(String elementId, String tableId, String anchorCellId, String focusCellId)`
vyuh_diagram_extension_table/extension_api.dart | Selects the cells from `anchorCellId` to `focusCellId` of table `tableId`. | | `void focusTableCell(String elementId, String tableId, String cellId)`
vyuh_diagram_extension_table/extension_api.dart | Selects the text of cell `cellId`, or of the merged cell containing it. | | `bool navigateTableCell(String elementId, String cellId, {bool backward = false})`
vyuh_diagram_extension_table/extension_api.dart | Row-major cell navigation; forward navigation at the end appends one row. | | `bool enterTableCell(String elementId, String cellId)`
vyuh_diagram_extension_table/extension_api.dart | Enter inserts below the active cell, preserving its column and editing focus. | | `ResolvedTable? resolvedTable(String elementId, String tableId)`
vyuh_diagram_extension_table/extension_api.dart | The laid-out table `tableId` of element `elementId`, or null. | | `ShapeTableControls tableControls(String elementId, String tableId)`
vyuh_diagram_extension_table/extension_api.dart | The table edits the shape's definition permits for table `tableId`. | | `DiagramToolGesture tableResizeGesture(String elementId, String tableId, {required bool row, required int index, required DiagramPoint pointerOrigin})`
vyuh_diagram_extension_table/extension_api.dart | A gesture that resizes row or column `index` as the pointer moves from `pointerOrigin`. | ## Layout Arrange root-level nodes automatically with an installed layout algorithm. | Member | What it does | | --- | --- | | `Future layout(Layout layout, {Iterable? nodeIds, String? ownerId, Motion? motion})`
vyuh_diagram_core | Performs the edit; throws when denied. | | `void cancelLayout()`
vyuh_diagram_core | Cancels a pending `layout`: its computation may finish, but its result is not applied. | | `perform(ids, 'applyLayout', {…})`
vyuh_diagram_core | Places sibling nodes at the given frames, as a graph layout computed them.
Verb `applyLayout` on the diagram: `frames: frames, label?: text, motion?: motion` | ## History and interactions Undo this actor's own edits, group verbs into one step, and preview continuous edits. | Member | What it does | | --- | --- | | `void undo()`
vyuh_diagram_core | Performs the edit; throws when denied. | | `void redo()`
vyuh_diagram_core | Performs the edit; throws when denied. | | `bool canUndo`
vyuh_diagram_core | Whether this controller has an edit of its own to undo. | | `bool canRedo`
vyuh_diagram_core | Whether this controller has an undone edit to redo. | | `void batch(String label, void Function() build, {bool history = true})`
vyuh_diagram_core | Performs the edit; throws when denied. | | `DiagramInteractionLease beginInteraction(String label, {bool cumulative = false})`
vyuh_diagram_core | Starts a continuous edit, such as a drag: each preview replaces the last, `DiagramInteractionLease.commit` records one undo entry and `DiagramInteractionLease.cancel` restores the start. | | `void cancelInteraction()`
vyuh_diagram_core | Cancels this controller's active interaction, restoring its start without a history entry. | | `bool isInteracting`
vyuh_diagram_core | Whether this controller holds an interaction, such as a drag. | ## Persistence and output Save and load documents, and export images. | Member | What it does | | --- | --- | | `T save(DiagramDocumentCodec Function(DiagramModelCodecs) format)`
vyuh_diagram_core | The current document encoded in `format`, such as `DiagramJsonCodec.new`, over the installed extensions' codecs so the content and text they own persist. | | `void load(T data, {DiagramDocumentCodec Function(DiagramModelCodecs)? format, int? expectedRevision, String label = 'Import diagram'})`
vyuh_diagram_core | Performs the edit; throws when denied.
Verb `load` on the diagram: `document: document, label?: text` | | `Future exportSvg(SvgOptions options, {Object Function(DiagramImageSource)? imageProvider})`
vyuh_diagram_core | Exports the committed snapshot as SVG, through the installed or mounted output. | | `Future exportPng(PngOptions options, {Object Function(DiagramImageSource)? imageProvider})`
vyuh_diagram_core | Exports the committed snapshot as PNG, through the installed or mounted output. | ## Canvas and view The camera, tools, and the viewport of the mounted canvas. | Member | What it does | | --- | --- | | `DiagramCameraState camera`
vyuh_diagram_core | This actor's viewport. | | `void setCamera(DiagramCameraState camera)`
vyuh_diagram_core | Moves this actor's viewport. | | `DiagramPoint screenToWorld(DiagramPoint point)`
vyuh_diagram_core | The world point under a screen point of the mounted canvas. | | `DiagramPoint globalToWorld(Offset globalPosition)`
vyuh_diagram_flutter | The world point under a global screen position of the mounted canvas. | | `DiagramTool activeTool`
vyuh_diagram_core | The tool this actor has active. | | `DiagramToolRegistry tools`
vyuh_diagram_core | The tools this controller can activate. | | `void setTool(DiagramTool tool)`
vyuh_diagram_core | Activates `tool`, one of `DiagramController.tools`. | | `DiagramView view`
vyuh_diagram_flutter | Moves the viewport of the mounted canvas. | | `Future view.show(ViewTarget target, {Motion? motion})`
vyuh_diagram_flutter | Shows `target`, jumping when `motion` is null. | | `void view.stop()`
vyuh_diagram_flutter | Interrupts the current move, if any. | | `TextRun? view.typingStyle`
vyuh_diagram_flutter | The style new typing takes at the caret of the canvas's text editor, or null when no text is being edited. | | `bool view.formatTextSelection(String label, TextRun Function(TextRun) format)`
vyuh_diagram_flutter | Applies `format` to the edited text's selected range, or to future typing at a caret. | ## Effects Transient effects on the mounted canvas. They never change the document or history. | Member | What it does | | --- | --- | | `DiagramEffects effects`
vyuh_diagram_flutter | Plays transient effects on the mounted canvas. | | `EffectHandle effects.play(Effect effect, {required String on})`
vyuh_diagram_flutter | Plays `effect` on the element with id `on` and returns its handle. | | `void effects.stopAll({String? on})`
vyuh_diagram_flutter | Stops every effect, or only those playing on the element with id `on`. | | `List effects.playing`
vyuh_diagram_flutter | Every playing effect. | | `List effects.playingOn(String id)`
vyuh_diagram_flutter | The effects playing on the element with `id`. | | `EffectRegistry effects.registry`
vyuh_diagram_flutter | The effects this canvas can play. | ## Configuration and options The diagram's shared configuration, applied to every controller on it. | Member | What it does | | --- | --- | | `DiagramConfiguration configuration`
vyuh_diagram_core | The diagram's configuration, with its current bounds, fonts, default font family and rules. | | `CanvasBounds bounds`
vyuh_diagram_core | How far the canvas extends. | | `void setBounds(CanvasBounds bounds)`
vyuh_diagram_core | Performs the edit; throws when denied. | | `void setFonts(DiagramFontChoices fonts)`
vyuh_diagram_core | Performs the edit; throws when denied. | | `void setDefaultFontFamily(String? family)`
vyuh_diagram_core | Performs the edit; throws when denied. | | `T options()`
vyuh_diagram_core | The current options of type `T`, owned by one installed extension, such as `GridOptions`. | | `void setOptions(Object value)`
vyuh_diagram_core | Performs the edit; throws when denied. | ## Participants The shared diagram and the actor this controller edits as. | Member | What it does | | --- | --- | | `Diagram diagram`
vyuh_diagram_core | The shared diagram this controller edits. | | `DiagramParticipant participant`
vyuh_diagram_core | The actor this controller edits as; history and locks refer to its id. | ## Extension authoring Engine hooks for verb implementations, from the adapter library. | Member | What it does | | --- | --- | | `void dispatch(DiagramTransaction transaction, {int? expectedRevision})`
vyuh_diagram_core | Performs the edit; throws when denied. | | `DiagramControllerInternals internals`
vyuh_diagram_core/adapter.dart | Engine access for platform adapters, such as the mounted canvas. | | `DiagramEditorState state`
vyuh_diagram_core/adapter.dart | What this actor sees, including its own in-progress preview. | ## Lifecycle Mounting and disposal. | Member | What it does | | --- | --- | | `bool isAttached`
vyuh_diagram_core | Whether a canvas is mounted for this controller. | | `bool isDisposed`
vyuh_diagram_core | Whether this controller, or its diagram, is disposed. | | `void dispose()`
vyuh_diagram_core | Ends this controller. | --- # Diagram and controller Two objects hold all diagram state. A `Diagram` is the shared thing: the committed document and its geometry, one undo history, its participants and its immutable `DiagramConfiguration`: the installed extensions, canvas bounds, fonts, rules and license. A `DiagramController` is one actor on a diagram, such as a person at a canvas, an agent or a script. It owns its selection, active tool, camera and in-progress edit, and every verb that edits the diagram. Content verbs work without a canvas; camera and visual-effect members use the mounted `DiagramCanvas`. See [collaboration](/agent-docs/api/collaboration.md) for several actors on one diagram. For every member and verb in one place, grouped by purpose, see the [controller reference](/agent-docs/api/controller-reference.md). ## On this page | Category | What you can do | | --- | --- | | [Construction](#construction) | Create a controller with its own diagram, or join an existing one. | | [Multiple actors](#multiple-actors) | Share a diagram, undo per actor and respect element leases. | | [Reading state](#reading-state) | Read the live view or the committed document. | | [Verbs](#verbs) | Perform, check and discover edits: create, style, transform, connect and remove. | | [Selection, camera and tool](#selection-camera-and-tool) | Selection, camera, tool, creation styles and options. | | [Batch](#batch) | Group verbs into one undo step. | | [Interactions](#interactions) | Preview a continuous edit, then commit or cancel it. | | [Discovery](#discovery) | Describe an element and edit its inspector properties. | | [Extension verbs](#extension-verbs) | How verb implementations submit their edits. | | [Observing changes](#observing-changes) | Watch state, listen to the controller or to committed changes. | | [Navigation and motion](#navigation-and-motion) | Show targets and play effects on a mounted canvas. | | [Lifetime and errors](#lifetime-and-errors) | Dispose safely and handle denied edits. | ## Construction ```dart DiagramController({ DiagramConfiguration? configuration, DiagramDocument? document, Diagram? diagram, DiagramParticipant participant = DiagramParticipant.local, }) ``` A diagram is configured in one place, its `DiagramConfiguration`; see [configuration](/agent-docs/api/configuration.md#configuration). Without `diagram`, a controller creates and owns a new `Diagram` from `document` and `configuration`. Disposing that controller disposes the diagram and every other controller on it. ```dart final controller = DiagramController( document: DiagramDocument.empty('my-drawing'), configuration: DiagramConfiguration( extensions: [EditorExtension(), GridExtension(visible: true, snap: true)], ), ); final id = controller.createShape(Shapes.rectangle, at: DiagramPoint.zero); controller.move(const DiagramPoint(40, 20), ids: [id]); final json = controller.save(DiagramJsonCodec.new); controller.dispose(); ``` With `diagram`, the controller joins an existing diagram as another actor. Supplying `document` or `configuration` as well throws `ArgumentError`, because the diagram already has them. ```dart final agent = DiagramController( diagram: controller.diagram, participant: DiagramParticipant.agent(id: 'agent', name: 'Agent'), ); ``` | Argument | Type | Default / behavior | | --- | --- | --- | | `diagram` | `Diagram?` | Joins this diagram. When omitted, the controller creates and owns one. | | `document` | `DiagramDocument?` | A new empty drawing with a unique ID when omitted. | | `configuration` | `DiagramConfiguration?` | The new diagram's extensions, canvas bounds, fonts, rules and license; an empty configuration when omitted. See [configuration](/agent-docs/api/configuration.md#configuration). | | `participant` | `DiagramParticipant` | The actor this controller edits as: `DiagramParticipant({id, name, kind, color})`, `DiagramParticipant.agent(id:, name:)`, or the default `DiagramParticipant.local` (id `local`, name `You`). Its `id` must be nonempty and unique on the diagram; attribution, not authentication. | Canvas bounds are part of the configuration: `DiagramConfiguration(bounds: CanvasBounds.fit(padding: 64))`; see [canvas bounds](/agent-docs/api/canvas.md#canvas-bounds). To open saved JSON as a new controller, use `DiagramController.open(json, format: DiagramJsonCodec.new, configuration: DiagramConfiguration(extensions: [...]))`, which also takes `participant`. The format decodes over the installed extensions' codecs, so it covers the content and text they own. Opening validates the content without creating an undo entry. See [persistence](/agent-docs/api/persistence.md) for loading into a live controller. Every installed tool the grammar supports is available to `setTool`; the default tool is `select`. A canvas edits only when an editable extension such as `EditorExtension()` is installed. For accurate headless geometry install an extension carrying a font-aware `textLayout`; Flutter supplies text layout automatically. See [headless text](/agent-docs/api/headless-text.md). ### The diagram | Member | Type | Meaning | | --- | --- | --- | | `Diagram({document, configuration})` | | Creates a diagram directly, for several controllers to share; its creator disposes it. | | `document`, `scene` | `DiagramDocument`, `ResolvedScene` | The last committed content and geometry, without any controller's preview. | | `snapshot` | `DiagramSnapshot` | Committed document and matching geometry as one value, for saving and output. | | `extensions` | `List` | Installed extensions: the core defaults an application extension does not replace, then the application's extensions and their dependencies. | | `registry` | `DiagramExtensionRegistry` | The assembled shapes, tools, verbs, codecs and options of `extensions`. `DiagramExtensionRegistry` is in `extension_api.dart`. | | `configuration` | `DiagramConfiguration` | The shared configuration: extensions, bounds, fonts, rules and license. Observable. | | `setRules(rules)` | | Replaces `configuration.rules` for every later edit. | | `resolver` | `DiagramResolver` | The installed grammar (`resolver.registry`) and text layout. `DiagramResolver` is in `adapter.dart`. | | `controllers` | `List` | Attached controllers, in attachment order. | | `participants` | `List` | The participants of the attached controllers, in attachment order; for presence. | | `participantById(id)` | `DiagramParticipant?` | The participant with `id`, attached now or earlier, or null. Resolves the ids history entries and changes record. | | `refreshLayout()` | `void` | Re-resolves geometry after the host's text backend changes fonts or layout revision. Content and history are unchanged. | | `changes` | `ValueListenable` | Committed changes from every controller; see [observing changes](#observing-changes). | | `isDisposed` / `dispose()` | | Disposing a diagram disposes every controller on it. | Mounted Flutter canvases observe font loading automatically. Headless hosts call `diagram.refreshLayout()` after preparing fonts; it does not download fonts itself. ## Multiple actors Every controller on a diagram edits the same committed document and records into the one diagram history. - **Per-actor undo.** `undo()` and `redo()` replay only the calling controller's own edits. Another actor's edits remain. - **Own participant state.** Selection, active tool, camera and creation styles belong to each controller. - **Element leases.** While one controller previews an interaction, such as a drag, other controllers' edits that touch the elements it changes are denied with `DiagramDenialCode.conflict` and a reason naming the holder. Edits to other elements proceed, and the preview is rebased onto them. When the holder commits or cancels, the lease ends. - **Shared configuration.** `diagram.setRules`, `controller.setBounds`, `controller.setFonts`, `controller.setDefaultFontFamily`, `controller.setOptions` and `refreshLayout` apply to every controller and refresh their previews. ```dart final human = DiagramController(document: document); final agent = DiagramController( diagram: human.diagram, participant: DiagramParticipant.agent(id: 'agent', name: 'Agent'), ); agent.batch('Add review', () { final review = agent .createShape(Shapes.card, at: const DiagramPoint(400, 0)) .id!; agent.setTitle(review, 'Review').requireAllowed(); }); human.undo(); // undoes only the human's own edits ``` A controller mounts one canvas. Each simultaneous canvas needs its own controller on the same diagram. Controllers share a diagram in one process; remote collaboration needs its own transport. ## Reading state A controller reads what its actor sees, including its own in-progress preview. The diagram reads committed content that every actor shares. The two are equal unless this controller holds an active interaction or batch. | Controller member | Type | Meaning | | --- | --- | --- | | `diagram` | `Diagram` | The shared diagram. | | `participant` | `DiagramParticipant` | The actor whose edits this controller attributes, by `participant.id`. | | `document` | `DiagramDocument` | Live content, including this controller's preview. | | `scene` | `ResolvedScene` | Live geometry matching `document`. | | `elementById(id)` | `DiagramElement?` | One element as this actor sees it. | | `selection` | `DiagramSelection` | Current selection. | | `activeTool` / `tools` | `DiagramTool` / `DiagramToolRegistry` | Current tool and the tools this controller can activate (`tools.definitions`). | | `camera` | `DiagramCameraState` | This actor's viewport. | | `canUndo`, `canRedo` | `bool` | Whether this controller has an edit to undo or redo. | | `isInteracting` | `bool` | Whether this controller holds an interaction. | | `configuration` | `DiagramConfiguration` | The diagram's shared configuration: extensions, bounds, fonts, default font family, rules and license. | | `bounds` | `CanvasBounds` | How far the canvas extends: `CanvasBounds.infinite` or `CanvasBounds.fit(padding:)`. | | `options()` | `T` | The current options of type `T`, such as `GridOptions`, shared by every controller on the diagram. `StateError` when no installed extension owns `T`. | | `isDisposed`, `isAttached` | `bool` | Lifecycle, and whether a canvas is mounted. | Availability of an edit on the current selection comes from the verbs: `controller.canPerform(ids, 'group').allowed`, or `controller.verb(ids, 'align')?.isAvailable` for a control that also needs the verb's label and parameters. Save, export and synchronize from `diagram.document` or `diagram.snapshot`, so an edit that may still be cancelled is excluded. `exportSvg` and `exportPng` already capture the committed snapshot. A `DiagramDocument` provides `elements`, `elementsById`, `elementById`, `shapeById`, `connectorById` and `textById`. Keeping a document retains that snapshot, not a live view of later edits; change content through verbs. An element's saved frame describes its authored size. Text that grows to fit its content can have larger visible bounds; read `diagram.scene.elementById(id)?.bounds`, and use one captured snapshot when combining content and geometry. ## Verbs A verb is a named, typed edit, and the only way anything changes a diagram. Canvas gestures, the inspector, overlays, key bindings, agents and your code all perform verbs. Every verb applies the diagram's admission and rules, records one undo entry. Direct calls complete or throw on refusal; calls through `controller.edits` return an `EditResult`. See [verbs](/agent-docs/api/verbs.md) for discovery, symmetry and writing your own. | Member | Returns | Behavior | | --- | --- | --- | | `perform(ids, verb, [args])` | `EditResult` | Performs `verb` on `ids` as one undoable edit. No ids targets the diagram, as for `createShape`. | | `canPerform(ids, verb, [args])` | `EditResult` | Whether `perform` would run, and why not. Nothing is published. | | `verbs([ids])` / `verb(ids, name)` | `List` / `DiagramVerbDescription?` | The verbs available on `ids`, with parameter schemas and availability. | ```dart controller.perform([id], 'setOpacity', {'opacity': .5}); if (controller.canPerform([id], 'setLocked', {'locked': true}).allowed) { controller.edits.setLocked(true, ids: [id]); } ``` The tables below list the typed extensions core ships on `DiagramController`; each is a thin wrapper over `perform` with the verb of the same name unless noted. Creating verbs report the new identity in the result's `id`. Verbs that act on several elements take a named `ids:` parameter and default to the current selection when it is omitted; verbs that act on one element take its identity first. Every verb also accepts an `expectedRevision` argument; see [results](/agent-docs/api/verbs.md#results). ### Create | Verb | `id` | Behavior | | --- | --- | --- | | `createShape(type, {required at, id, size, style, values, text, ...})` | shape | Registry defaults, parent discovery; [full arguments](/agent-docs/api/shapes.md#controller-createshape). | | `createText({type, required at, text, ...})` | text element | Standalone text; [full arguments](/agent-docs/api/shapes.md#controller-createtext). | | `createPath`, `createPolyline`, `createLine` | path shape | Editable paths from authored nodes or world points. | | `createConnected({required source, required element, ...})` | connector | A target and its incoming connector together; the element keeps the identity you gave it. [Creation](/agent-docs/api/shapes.md#controller-createconnected). | | `add(element, {select})` | element | Inserts an authored record without creation defaults. A connector added this way is admitted by the `canConnect` rule. | | `allocateId(prefix)` | — | Returns a fresh identity unused in the document; not a verb. | ```dart final result = controller.edits.createShape(Shapes.card, at: DiagramPoint.zero); if (result.allowed) controller.edits.setTitle(result.id!, 'Orders'); ``` ### Structure and clipboard | Verb | Behavior | | --- | --- | | `delete({ids})` | Removes elements with owned contents and bound connectors. Without ids, deletes the selection: elements, a connector label, path points or structured content. | | `group({ids})` / `ungroup({ids})` | Wraps siblings in a group, or removes groups while keeping children. | | `frame({ids})` / `unframe({ids})` | Wraps siblings in a frame, or unwraps frames while keeping their contents. | | `reparent({ids, parentId, delta})` | Moves elements under another owner, or to the root. | | `setFrameCollapsed(id, collapsed)` | Collapses or expands a frame. | | `copy({ids})` / `paste(payload, {offset})` / `duplicate({ids, offset})` | `copy` captures an immutable `DiagramClipboardPayload`; paste and duplicate allocate fresh identities and remap internal references. The host owns clipboard storage. | Group boundaries enclose their current children, including during previews and after undo or redo. Frames keep their authored size. ### Transform and arrange | Verb | Behavior | | --- | --- | | `move(delta, {ids})` | Translates roots and owned contents once. | | `resize(size, {ids, fromCenter, preserveAspectRatio})` | Resizes through registered minima. | | `rotate({ids, required pivot, required radians})` | Rotates around a world pivot. | | `setElementBounds(id, rect)` | Places an element at an unrotated frame, resizing and moving it as one step. | | `align(alignment, {ids})` / `distribute(distribution, {ids})` / `reorder(order, {ids})` | Arrange elements. An already satisfied arrangement adds no history. | | `setZIndex(zIndex, {ids})` | Sets the paint order that `reorder` derives. | | `arrangeLanes({ids, direction, laneSize, gap})` | Lays swimlane frames out in rows or columns. | | `layout(layout, {nodeIds})` / `cancelLayout()` | Automatic layout, such as `Layout.tree()`, with the installed algorithm for it; see [layout](/agent-docs/api/layout.md). | ### Appearance, values and type | Verb | Behavior | | --- | --- | | `setStyle({ids, fill, stroke, strokeWidth, cornerRadius, strokeStyle, inkPreset})` | Changes only the given parts of each shape's appearance. | | `setOpacity(opacity, {ids})` / `setVisible(visible, {ids})` / `setLocked(locked, {ids})` | Whole-element opacity (0–1), visibility and locking. Locked owners protect descendants. | | `setAspectLocked(locked, {ids, square})` / `setPorts(ports, {ids})` | Aspect lock, and instance ports on shapes that accept them. | | `setValues(id, patch)` | Patches registered values, validated by the shape's schema; [values](/agent-docs/api/shapes.md#custom-values). | | `setImage(id, source)` | Sets image content, or removes it with `null`; [image content](/agent-docs/api/shapes.md#image-content). | | `setClipContent(clip, {ids})` / `setPolygonSides(sides, {ids})` | Content clipping, and the side count of polygon shapes. | | `setType(id, type)` | Converts a shape to another registered type, keeping frame, style, ownership and matching text. | ### Text and slots | Verb | Behavior | | --- | --- | | `setText(id, text, {slot, storyId})` | Replaces text with plain paragraphs, one per line. `slot` names a shape's text part, such as a card's `title` (the verb `title.setText`); `storyId` picks a connector label. | | `setTextAlignment(id, alignment, {storyId, start, end})` / `setTextDirection(...)` | Paragraph alignment or direction for a story or range. | | `perform([id], 'replaceText', {'before': before, 'after': after})` | Replaces a story that keeps its identity; `setText` is the typed text setter. | | `addSlot(id, slot, {text})` / `removeSlot(id, slot)` | Shows or hides an optional slot, such as a card's tag. | | `setTitle(id, title)` / `setDescription(id, text)` / `setTag(id, tag)` | A card's own verbs; a null tag hides it. | Extension packages add verbs of their own: the Rich Text extension adds `setMark`, `setHeading`, `setList` and related story verbs (see [rich text](/agent-docs/api/rich-text.md)), the Table extension adds `insertRow`, `mergeCells`, `setCellText` and related table part verbs (see [tables](/agent-docs/api/tables.md)), and the shapes extension adds `showSecondarySection` for entities. ### Connectors and paths | Verb | Behavior | | --- | --- | | `connect(from, to, {fromPort, toPort, type, route, select})` | Connects existing elements; `id` is the connector. | | `reconnect(id, {required atStart, required endpoint})` | Moves one end, admitted by the `canConnect` rule. | | `setConnectorStyle(id, {color, strokeWidth, strokeStyle})` / `setStartArrowhead(id, {kind, width, height})` / `setEndArrowhead(...)` | Line appearance, and each end's arrowhead; see [connectors](/agent-docs/api/connectors.md). | | `setConnectorRoute(id, {route, portSpacing, options})` / `setRouteGeometry(id, {route, bend, controlPoints, routedPoints, preserveRoute})` / `reroute({ids})` | Route kind, edited route geometry and obstacle-avoiding reroutes; `reroute` defaults to every connector. | | `addConnectorLabel(id, {text, story, fraction, offset, size})` / `setConnectorLabel(id, labelId, {...})` / `removeConnectorLabel(id, labelId)` / `arrangeLabels({ids, spacing})` | Connector labels; `addConnectorLabel`'s `id` is the label, and `arrangeLabels` defaults to every connector. | | `setPathClosed`, `addPathPoint(id, {required after, t, id})`, `removePathNodes`, `setPathHandleMode`, `setPathSegmentKind`, `movePathControl` | Edit authored path nodes and handles. `addPathPoint` splits the segment after a node; its `id` is the new node. | ### History, persistence and output | Member | Behavior | | --- | --- | | `undo()` / `redo()` | This controller's own latest edit. Not available inside a batch. Undo is history, not a reverse verb. | | `save(format)` | Encodes `document` in `format`, such as `DiagramJsonCodec.new`. | | `load(data, {format, expectedRevision, label})` | Replaces the document as one undoable edit. With `format`, decodes `data` first; without it, `data` is a `DiagramDocument`. Invalid input leaves the document unchanged; a stale `expectedRevision` is denied with `conflict`. See [persistence](/agent-docs/api/persistence.md). | | `exportSvg(options, {imageProvider})` / `exportPng(options, {imageProvider})` | Captures the committed snapshot and exports asynchronously; see [output](/agent-docs/api/output.md). | ## Selection, camera and tool Selection, camera, active tool, creation styles and options are not part of the document or its history, so they are not verbs. They change through plain controller methods that are not undoable and are not admitted by the diagram's rules. | Member | Behavior | | --- | --- | | `select(ids)` / `selectAll({ownerId})` / `clearSelection()` / `setSelection(selection)` | Change this actor's selection. Missing and non-selectable elements are filtered. | | `setSelection(ConnectorLabelSelection(connectorId: c, labelId: l))` / `setSelection(PathPointSelection(elementId: e, nodeIds: {...}))` | Select one connector label, or path nodes. | | `setTool(tool)` | Activates a registered tool. Rejected during an interaction. | | `setCamera(camera)` | Moves this actor's viewport. | | `setShapeCreationStyle(type, style)` | Appearance for future shapes of a type; read it with `controller.shapeCreationStyle(type)`. | | `setConnectorCreationRoute(route)` | Route kind for connectors drawn next. | | `setBounds(bounds)` | Replaces the canvas bounds for every controller on the diagram and re-clamps every camera. See [canvas bounds](/agent-docs/api/canvas.md#canvas-bounds). | | `setFonts(fonts)` / `setDefaultFontFamily(family)` | Replace the font choices or the default family for every controller on the diagram; a new default family lays text out again. See [fonts](/agent-docs/api/configuration.md#fonts). | | `setOptions(value)` | Replaces the options of the installed extension that owns `value.runtimeType`, such as `GridOptions`, for every controller on the diagram. Denied when no installed extension owns them. See [extensions and options](/agent-docs/api/configuration.md). | ```dart controller.select([id]); controller.edits.setOptions( controller.options().copyWith(visible: true), ); ``` ## Batch `batch(label, build)` runs `build`, whose verbs publish as one undo step. It returns the batch's `EditResult`. ```dart final result = controller.edits.batch('Add pair', () { final a = controller.edits.createShape(Shapes.rectangle, at: DiagramPoint.zero); final b = controller.edits.createShape( Shapes.rectangle, at: const DiagramPoint(200, 0), ); controller.edits.connect(a.id!, b.id!); }); ``` When admission denies a verb (a rule, a lock or another controller's lease), later verbs are skipped, earlier changes are withdrawn and that denial is returned. A verb refused before it submits anything, such as one naming a missing element, only returns its denial; call `requireAllowed()` on it to abandon the batch. Other exceptions withdraw the batch and propagate. A nested batch joins the outer one. ## Interactions `beginInteraction(label, {cumulative})` starts a continuous edit, such as a drag or a slider, and returns a `DiagramInteractionLease`: | Member | Behavior | | --- | --- | | `perform(ids, verb, [args])` | Previews a verb as `controller.perform` would apply it. | | `performAll(invocations, {selection})` | Previews several `DiagramVerbInvocation`s together, optionally showing a selection. | | `commit()` | Records one undo entry from the start to the last preview. | | `cancel()` | Restores the start without a history entry. | | `isActive` | Whether the lease can still preview or finish. | A gesture lease, the default, starts every preview over from the interaction's starting document, so previews never accumulate. A cumulative lease, such as a text composition, applies each preview on top of the last and yields: an unrelated edit, an undo or a new interaction commits it first. ```dart final lease = controller.beginInteraction('Drag'); lease.perform([id], 'move', {'delta': const DiagramPoint(20, 0)}); lease.perform([id], 'move', {'delta': const DiagramPoint(50, 0)}); lease.commit().requireAllowed(); // one entry: moved 50 ``` `controller.cancelInteraction()` cancels whichever interaction the controller holds, such as one a canvas gesture started; it does nothing when idle. Only this controller sees the preview through `document` and `scene`; other controllers and `diagram.document` see committed content. Other controllers cannot edit the elements the preview changes until it ends. Disposing a controller cancels its interaction. ## Discovery Code and agents can discover what an element accepts and edit whatever the inspector can. | Member | Returns | Behavior | | --- | --- | --- | | `verbs([ids])` | `List` | The verbs on `ids`, with parameter schemas and availability; see [verbs](/agent-docs/api/verbs.md#discovery). | | `describe(id)` | `DiagramElementAnatomy?` | Kind, type, text `slots` (id, text definition, `maxLines`, `isOptional`, `hasText`), value schema, ports, structured `contents`, connector `labels` and `acceptsChildren`. Null for a missing id. | | `properties({ids})` | `DiagramPropertyFields` | Properties shared by the affected selection, or explicit `ids`. Typed keys retain each value's type; `set` is one revision-checked undoable edit. | | `resolvedElementById(id)` | `ResolvedElement?` | Observe live geometry for one identity, including previews, without subscribing to unrelated scene changes. | | `checkDiagnostics({rules})` | `DiagramDiagnostics` | Installed domain checks and optional additional checks, captured at one document snapshot. | | `fixDiagnostic(report, fix)` | `EditResult` | Apply a report's proposed verbs atomically; stale reports and partial failures cannot overwrite the document. | | `setProperty(ids, key, value)` | `EditResult` | Sets one property by key on every target as one undoable edit. Unknown keys are denied. | ```dart final anatomy = controller.describe(card)!; final optional = anatomy.slots.where((slot) => slot.isOptional); final names = controller.verbs([card]).map((verb) => verb.name); controller.setProperty([card], 'element-opacity', 50); final fill = controller.properties(ids: [card]).require(ShapeProperties.fill); fill.set(const DiagramColor(0xff2457ff)).requireAllowed(); ``` Omit `ids` to use the current selection. A multi-selection offers only fields declared by every selected kind. `valueState` distinguishes `shared`, `mixed` and `unavailable`; `choices` and `bounds` intersect all selected declarations. Kind-owned properties can read different underlying values and still edit together through their own verb arguments. Resolve fields again after an edit: the snapshot revision is checked by default, including at gesture start. `DiagramPropertyField` and `DiagramPropertyGesture` belong to the application import. Declare properties in `ShapeDefinition(properties: [...])` through `extension_api.dart`; custom Flutter property editors receive `DiagramPropertyField` with their declared value type. To continue a connection with a registry-default shape and one undo entry: ```dart final next = controller.createConnectedShape( Shapes.card, source: BoundEndpoint(elementId: card, portId: 'right'), toPort: 'left', at: const DiagramPoint(400, 0), ); ``` Connection rules, shape grammar and revision guards apply to both new elements as one transaction. `id` first requires an allowed result and then a created identity, so callers do not need `result.id!`. ## Extension verbs Extensions contribute verbs through `DiagramExtension(verbs: [...])` and shapes through `ShapeDefinition(verbs: [...])`; see [writing verbs](/agent-docs/api/verbs.md#writing-verbs). A verb's `perform` receives a `DiagramVerbCall` and submits its edit with `call.submit(transaction)`, which goes through the same admission and history as every other edit and joins an enclosing batch or lease. `DiagramTransaction` and its steps come from the engine integration library, `package:vyuh_diagram_core/adapter.dart`. ```dart import 'package:vyuh_diagram_core/adapter.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final setApproved = DiagramVerb( id: 'setApproved', label: 'Approved', symmetry: DiagramVerbSymmetry.setter, target: DiagramVerbTarget.element, parameters: [DiagramVerbParameter.boolean('approved')], perform: (call) { final shape = call.document.shapeById(call.id)!; return call.submit( DiagramTransaction( label: 'Approve', steps: [ ReplaceElementStep( before: shape, after: shape.copyWith( values: {...shape.values, 'approved': call.arg('approved')}, ), ), ], ), ); }, ); ``` A setter that only replaces its targets is shorter as `DiagramVerb.update`. Text verbs build on `call.updateText(label: ..., transform: ...)`. `controller.edits.dispatch(transaction, {expectedRevision})` is the low-level hook under `call.submit`; application code performs verbs instead, and the repository's boundary check rejects raw transactions outside verb implementations. ## Observing changes Diagram state is observed two ways: widgets read the controller's observable getters inside an `Observer`, and document-change events arrive on `diagram.changes`. | Member | Behavior | | --- | --- | | `document`, `scene`, `selection`, `activeTool`, `camera`, `canUndo`, `canRedo`, `isInteracting`, `isAttached` | Observable. An `Observer` that reads them rebuilds when they change. | | `elementById(id)` | Observable per identity: an `Observer` that reads `elementById('a')` rebuilds only when `a` changes, including removal and restoration. | | `configuration`, `bounds` | Observable configuration and canvas bounds. | | `options()`, `effects.playing` | Observable options and playing effects. | | `diagram.changes` | A `ValueListenable` notified once per committed change from any controller, including undo and redo. | ```dart Observer( builder: (_) => IconButton( onPressed: controller.canUndo ? () => controller.edits.undo() : null, icon: const Icon(Icons.undo), ), ); final changes = controller.diagram.changes; changes.addListener(() { final change = changes.value!; final author = controller.diagram.participantById(change.participantId); save(change.after, author: author?.name ?? change.participantId); }); ``` `Observer` comes from `package:flutter_mobx`. Outside Flutter, `reaction` and `autorun` from `package:mobx` observe the same getters. A `DiagramDocumentChange` carries `before` and `after` documents, the matching `scene`, the `participantId` of the participant that made it (resolve it with `diagram.participantById`), `origin`, `label` and the changed identities. A gesture emits once, when it commits. Previews, cancellation, selection, camera and options changes and denied edits emit nothing. Listeners cannot edit synchronously during notification; queue a follow-up verb instead. ## Navigation and motion These Flutter members require a mounted canvas. See [navigation and motion](/agent-docs/api/navigation-and-motion.md) for targets, motion and effect options. | Member | Returns | Behavior | | --- | --- | --- | | `screenToWorld(point)` | `DiagramPoint` | Converts canvas-local screen coordinates to world coordinates. | | `globalToWorld(offset)` | `DiagramPoint` | Converts a Flutter global position through the laid-out canvas. | | `view.show(target, {motion})` | `Future` | Jumps to a `ViewTarget`, or travels with `motion`. `false` for missing content or an interrupted move. | | `view.stop()` | `void` | Interrupts the current move. | | `effects.play(effect, {required on})` | `EffectHandle` | Plays an effect along a connector, or inside or around a shape. | | `effects.stopAll({on})`, `effects.playing`, `effects.playingOn(id)` | | Stop or list playing effects. | ## Lifetime and errors Calls through `controller.edits` return an `EditResult`: inspect `allowed` or call `requireAllowed()`, which throws `DiagramChangeDenied` carrying the `result`. A denial has a stable `DiagramDenialCode` (`policy`, `locked`, `unavailableTarget`, `invalidSelection`, `unsupportedOperation`, `conflict`) and an optional `reason`. Host rules returning `EditResult.denied(reason: ...)` default to `policy`. | Condition | Result | | --- | --- | | Unknown verb, missing argument, or an argument of the wrong type, non-finite or outside its parameter's range | Denial with `unsupportedOperation`. | | Unknown target element | Denial with `unavailableTarget`. | | Locked target, or a target inside a locked owner | Denial with `locked`, from admission. | | Stale `expectedRevision` on any verb, `load`, `dispatch` or a property write | Denial with `conflict`; nothing is evaluated. | | Edit touches an element another controller is previewing | Denial with `conflict`, naming the holder. | | Creation denied by a rule or admission | Denied result without an `id`. | | Invalid input that is not a verb argument, such as `createPolyline` with fewer than two points | `ArgumentError`. | | `diagram` with `document` or `configuration`, or a participant with an empty `id` | `ArgumentError`. | | `setOptions` for a type no installed extension owns | Denial with `unsupportedOperation`. | | A participant `id` already attached to the diagram | `StateError`. | | `undo()` or `redo()` inside a batch | `StateError`. | | Any verb after disposal | `StateError`. Listener removal and repeated `dispose()` are safe. | | Viewport member while no canvas is mounted | `StateError`. | | `dispose()` while its canvas is mounted | `StateError`; unmount first. | `dispose()` cancels the controller's interaction and releases its subscriptions without notifying them; other controllers still observe the release. Disposing again, even from another controller's listener, does nothing. A controller that created its diagram disposes the diagram and every controller on it; a controller that joined one only leaves it. Capture `diagram.snapshot` before disposal to retain the document and its geometry. ```dart final controller = DiagramController( document: DiagramDocument.empty('my-drawing'), ); void onChange() { // Persist controller.diagram.changes.value!.after or update host UI. } controller.diagram.changes.addListener(onChange); // Return this widget inside a bounded layout: final canvas = DiagramCanvas(controller: controller); // After the canvas is mounted and laid out: await controller.view.show(const ViewTarget.selection(), motion: Motion.smooth); // After removing the canvas from the widget tree: controller.diagram.changes.removeListener(onChange); controller.dispose(); ``` --- # Domain diagnostics `DiagramDiagnostics.check` runs explicit checks against an immutable document. `DiagramDiagnostics` and `DiagramDiagnostic` are engine types in `package:vyuh_diagram_core/adapter.dart`. Use it to review drafts without preventing incomplete edits. Keep hard admission rules in a [`beforeChange` rule](/agent-docs/api/hooks.md#fixed-domain-validation). ```dart import 'package:vyuh_diagram_core/adapter.dart'; import 'package:vyuh_diagram_core/vyuh_diagram_core.dart'; final report = DiagramDiagnostics.check(controller.document, rules: [ (document) => [ for (final shape in document.elements.whereType()) if (shape.type == Shapes.rectangle && shape.parentId == null) DiagramDiagnostic( id: 'department:${shape.id}', message: 'Assign this task to a department.', elementIds: [shape.id], ), ], ]); if (report.isCurrent(controller.document) && report.items.isNotEmpty) { controller.select(report.items.first.elementIds); } ``` Each finding has a unique ID, message, severity and optional element targets. Targets must exist in the checked document. `hasErrors` ignores informational findings and warnings. Check `isCurrent` before using a result; rerun checks after content changes. Rules must be pure. Checks run only when called, not on pointer movement or camera updates. The engine provides reports; presenting them is up to the host. The examples below mount a small review panel that owns a **Run checks** button and a list of findings. Selecting a finding selects its target elements. For targets hidden inside collapsed frames, it selects the nearest visible containing frame without expanding it or changing undo history: hidden bundle members select their visible representative, and hidden internal connectors use their endpoint frames even without a parent. Edits mark the report stale (`isCurrent` turns false) and disable its selection actions until checks run again. Try [network review](/agent-docs/examples/dense-network.md) for a missing backbone binding or [department ownership](/agent-docs/examples/swimlanes.md) for an unassigned review task. Both demonstrate repair, rechecking, and undo using host-owned rules. --- # Animation & effects A diagram moves in three ways, and none of them is a document edit: | Animation | API | What moves | | --- | --- | --- | | **Effects** (this page) | `controller.effects.play(effect, on: id)` | A transient emphasis on one shape or connector: particles, pulses, halos, scaling and fading. | | **Camera motion** | `controller.view.show(target, motion: ...)` | The viewport travels to a target. See [Navigation and motion](/agent-docs/api/navigation-and-motion.md#motion). | | **Element motion** | `move`, `resize`, `setElementBounds` and `layout` with `motion:` | Elements travel to the geometry an edit gave them. See [Animated geometry](/agent-docs/api/navigation-and-motion.md#animated-geometry) and [Live data](/agent-docs/guide/live-data.md#animated-bounds). | Effects play on a mounted editing canvas. Playing, changing or stopping one never edits the document, adds undo entries, changes hit testing, or appears in exports. ```dart // Particles flowing along a connector. final flow = controller.effects.play( const Effect.flow(particle: EffectParticle.dash(), count: 6), on: 'order-to-invoice', ); // Blink a shape three times in the brand color, then stop. final blink = controller.effects.play( const Effect.pulse( color: DiagramColor(0xFF4F46E5), waveform: Waveform.step, period: Duration(milliseconds: 500), repeat: 3, ), on: 'invoice', ); await blink.done; flow.stop(); ``` [Open runnable example](/examples-app/#/motion/shape-effects) ## On this page | Category | What you can do | | --- | --- | | [The five kinds](#the-five-kinds) | Choose flow, pulse, halo, scale or fade. | | [Play, update and stop](#play-update-and-stop) | Control effects with their handles. | | [Shared values](#shared-values) | Timing, color, sizes and particles every kind reads. | | [Blink and pulse](#blink-and-pulse) | Oscillate smoothly or switch on and off. | | [Repeat and hold](#repeat-and-hold) | Play a number of cycles, or hold a fade. | | [Branding recipes](#branding-recipes) | Effects in your brand colors. | | [Reduced motion](#reduced-motion) | What plays when the platform asks for less motion. | | [Custom effects](#custom-effects) | Register your own kinds. | ## The five kinds | Kind | Plays on | Behavior | | --- | --- | --- | | `Effect.flow()` | Connectors | Particles or marching dashes travel along the route. The connector's own stroke dims to `baseOpacity` while it plays. | | `Effect.pulse()` | Shapes and connectors | Oscillates between rest and emphasis. `target` picks what changes: `EffectTarget.fill` (a tint over a shape's fill), `.stroke` (a bright outline or route), `.opacity` (the element's opacity, between 1 and `dim`) or `.all`. `Waveform.step` makes it blink. | | `Effect.halo()` | Shapes | A ring around the outline. `HaloMode.ripple` grows it `spread` outward and fades it each cycle; `HaloMode.steady` glows in place. | | `Effect.scale()` | Shapes | Grows the shape to `amount` times its size about its center and back, such as `1.08` to breathe or `1.2` to pop. | | `Effect.fade()` | Shapes and connectors | Changes opacity once over `period`: `FadeDirection.fadeOut` to `dim`, or `FadeDirection.fadeIn` from `dim`. It holds the result until stopped. | Scale and fade present the element itself: its fill, border, text, ports, connector markers, labels and widget slots scale and fade together. Selection handles stay on the element's real bounds, and clicks land where the element really is, not where it appears while scaled. Playing an effect on an element it does not suit throws an `ArgumentError`, such as a flow on a shape or a scale on a connector. Several effects may play on one element; their scales and opacities multiply. ## Play, update and stop ```dart EffectHandle play(Effect effect, {required String on}) void stopAll({String? on}) List get playing List playingOn(String id) EffectRegistry get registry ``` | Member | Contract | | --- | --- | | `play` | Starts `effect` on the element with id `on`. Throws `ArgumentError` naming the first invalid value, for an unregistered kind, or for an element the kind does not suit. When the element does not exist, the returned handle is already stopped. Throws `StateError` while no editing canvas is mounted. | | `stopAll` | Stops every effect, or only those on the element with id `on`. | | `playing`, `playingOn` | Handles of the playing effects, observable in an `Observer`. | | `registry` | The kinds the canvas can play, including custom ones. | | `EffectHandle` member | Contract | | --- | --- | | `elementId` | The element the effect plays on. | | `effect` | Current values, or `null` once stopped. | | `isPlaying` | Whether the effect still plays. | | `update(effect)` | Replaces the values and keeps the timeline, so a color change does not restart a cycle. Returns `false` once stopped. | | `stop()` | Stops the effect; stopping a fade restores the element's opacity. Safe to call more than once. | | `done` | Completes when the effect stops: stopped, finished its `repeat` cycles, lost its element, or its canvas unmounted. | Effects follow their element as it moves, resizes or reroutes, including while [element motion](/agent-docs/api/navigation-and-motion.md#animated-geometry) animates it. Removing the element stops its effects, and undoing the removal does not restart them. ## Shared values Every value has a default; each named constructor offers the values its kind reads. `copyWith(...)` changes any value (`clearEndColor: true` removes a gradient, `clearRepeat: true` repeats forever again). | Value | Type | Default | Contract | | --- | --- | --- | --- | | `period` | `Duration` | `1600 ms` (fade `600 ms`) | One cycle, or the whole change of a fade. Positive. | | `delay` | `Duration` | `zero` | Time before the effect starts, for staggering. A fade shows its start during the delay; other kinds show nothing. | | `repeat` | `int?` | `null` | Cycles before the effect stops itself; `null` repeats until stopped. At least 1. | | `phase` | `double` | `0` | Offset into the cycle, from 0 to 1, for staggering. | | `reverse` | `bool` | `false` | Runs each cycle backward, such as particles flowing from end to start. | | `waveform` | `Waveform` | `.smooth` | `smooth`, `step` or `easeInOut`; see [blink and pulse](#blink-and-pulse). | | `color` | `DiagramColor?` | `null` | The effect color; `null` uses the connector color or shape stroke. | | `endColor` | `DiagramColor?` | `null` | Second color of a gradient across the effect. | | `opacity` | `double` | `0.9` | Peak opacity of what the effect draws. | | `dim` | `double` | `0.6` pulse, `0` fade | The element's opacity at rest for a pulse, and the faded end of a fade. | | `baseOpacity` | `double` | `0.2` | The connector's own stroke opacity while a flow or pulse plays along it. | | `target` | `EffectTarget` | `.all` | What a pulse changes. | | `mode` | `HaloMode` | `.ripple` | How a halo moves. | | `direction` | `FadeDirection` | `.fadeOut` | Which way a fade goes. | | `amount` | `double` | `1.08` | The size factor a scale reaches. Above 0, at most 10. | | `width` | `double` | `2` | Dash, pulse or halo stroke width. | | `spread` | `double` | `8` | How far a halo reaches beyond the outline. | | `particle` | `EffectParticle` | `.circle()` | The flow particle, below. | | `count` | `int` | `5` | Evenly spaced flow particles. | | `size` | `double` | `3` | Particle radius, half a character's font size, or an eighth of a dash. | | `scale` | `EffectScale` | `.world` | `world` sizes follow zoom; `screen` keeps `size`, `width` and `spread` in logical pixels. | Values are checked when an effect plays or updates, in release builds too: `controller.effects.play(const Effect.pulse(repeat: 0), on: id)` throws an `ArgumentError` whose `name` is `repeat`. `isValid` and `validate()` run the same check. ### Particles | Constructor | Shape | Size | | --- | --- | --- | | `EffectParticle.circle()` | A filled circle. | Radius = `size`. | | `EffectParticle.dash()` | A stroke that follows the route: marching dashes. | Length = `size × 8`; thickness = `width`. | | `EffectParticle.arrow()` | A chevron that points the way it travels. | Half-length = `size`. | | `EffectParticle.path(points)` | A filled outline through `points`, in particle units with x pointing the way it travels. | Units × `size`. | | `EffectParticle.polygon({sides = 4, rotation})` | A regular polygon, 3 to 20 sides. | Circumradius = `size`. | | `EffectParticle.character(character)` | One grapheme, such as an emoji. | Font size = `size × 2`. | Arrows and path particles turn with the route. `count` changes spacing, not size; dense particles may overlap. ## Blink and pulse A pulse moves between rest (its element at `dim` opacity, nothing drawn) and emphasis (full opacity, tinted fill and bright stroke) once per `period`. The `waveform` decides how: | Waveform | Over one cycle | | --- | --- | | `Waveform.smooth` | Eases from rest to emphasis at mid-cycle and back, like a sine. | | `Waveform.step` | Emphasis for the first half of the cycle, rest for the second: a blink. | | `Waveform.easeInOut` | Rises and falls along `MotionCurve.easeInOut`, holding briefly at each end. | ```dart // A calm pulse on a connector's route. controller.effects.play( const Effect.pulse(target: EffectTarget.stroke, width: 4), on: 'feed', ); // An urgent blink of a shape's fill, twice a second. controller.effects.play( const Effect.pulse( target: EffectTarget.fill, waveform: Waveform.step, period: Duration(milliseconds: 500), color: DiagramColor(0xFFE11D48), ), on: 'alarm', ); ``` The same waveforms shape scale and a steady halo: `Effect.scale(waveform: Waveform.step)` switches between sizes. A fade uses the waveform as its easing. ## Repeat and hold `repeat: n` plays `n` cycles, then the effect stops itself, its handle stops playing and `done` completes: ```dart final attention = controller.effects.play( const Effect.scale( amount: 1.2, period: Duration(milliseconds: 360), waveform: Waveform.easeInOut, repeat: 1, ), on: 'new-order', ); await attention.done; // After one pop. ``` A fade plays once and holds its end state for as long as it plays, without redrawing. Stop it to restore the element: ```dart // Dim everything except the path under review. final dims = [ for (final id in unrelatedIds) controller.effects.play(const Effect.fade(dim: 0.25), on: id), ]; // Later: for (final dim in dims) { dim.stop(); } ``` Stagger several effects with `delay` or `phase`: ```dart for (final (index, id) in steps.indexed) { controller.effects.play( Effect.halo(delay: Duration(milliseconds: 200 * index), repeat: 1), on: id, ); } ``` ## Branding recipes Every drawing kind takes `color` and `endColor`, so effects can carry a brand palette: ```dart const brand = DiagramColor(0xFF4F46E5); const accent = DiagramColor(0xFFF97316); // A gradient flow from the brand color to the accent. controller.effects.play( const Effect.flow(color: brand, endColor: accent, count: 8), on: 'pipeline', ); // A steady brand halo on the selected step. controller.effects.play( const Effect.halo(mode: HaloMode.steady, color: brand, spread: 10), on: 'current-step', ); // Fixed-size arrows that read at every zoom. controller.effects.play( const Effect.flow( particle: EffectParticle.arrow(), color: brand, size: 6, scale: EffectScale.screen, ), on: 'handoff', ); ``` Colors adapt to the canvas theme like authored colors do. The [connector effects](/agent-docs/examples/connector-effects.md) and [shape effects](/agent-docs/examples/shape-effects.md) examples offer a brand color picker for every kind. ## Reduced motion When the platform asks to reduce motion (`MediaQuery.disableAnimations`), effects do not move. Each holds a static emphasis instead: a pulse or scale at its peak, a rippling halo half spread, flow particles still, and a fade at its end. Effects with a `repeat` count still stop after their cycles, so `done` completes as it would otherwise. ## Custom effects Register an `EffectDefinition` through a Flutter extension's `effects`. The definition is in `package:vyuh_diagram_flutter/extension_api.dart`; `Effect`, `EffectKind` and `EffectPlacement` are in the main library. ```dart import 'dart:math' as math; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; const orbit = EffectKind('app.orbit'); final orbitEffects = DiagramFlutterExtension( id: 'app.orbit', effects: [ EffectDefinition( kind: orbit, label: 'Orbit', placement: EffectPlacement.around, properties: const {EffectProperty.color, EffectProperty.speed}, paint: (canvas, context) { final bounds = context.shape.bounds; final radius = math.max(bounds.width, bounds.height) / 2 + 8; canvas.drawArc( Rect.fromCircle( center: Offset(bounds.center.x, bounds.center.y), radius: radius, ), context.progress * math.pi * 2, math.pi / 2, false, context.createPaint()..style = PaintingStyle.stroke, ); }, ), ], ); final controller = DiagramController( configuration: DiagramConfiguration(extensions: [orbitEffects]), ); DiagramCanvas(controller: controller); controller.effects.play(const Effect(orbit), on: 'gateway'); ``` See the [custom effect](/agent-docs/examples/custom-effect.md) example for a complete dashed ring that the inspector edits. | Placement | Plays on | Painting | | --- | --- | --- | | `EffectPlacement.along` | Connectors | Along the route; badge labels stay readable above it. | | `EffectPlacement.inside` | Shapes | Clipped to the shape's outline. | | `EffectPlacement.around` | Shapes | Over the shape and beyond its outline, for halos, rings and badges. | | `EffectPlacement.any` | Shapes and connectors | Unclipped; read `context.element` to tell them apart. | ### `EffectDefinition` | Argument | Type | Default | | --- | --- | --- | | `kind` | `EffectKind` | Required, unique. | | `label` | `String` | Required inspector label. | | `placement` | `EffectPlacement` | Required. | | `paint` | `void Function(Canvas, EffectContext)?` | Draws over the canvas each frame, in world coordinates. Paint only; change content through controller verbs. | | `present` | `EffectPresentation Function(EffectContext)?` | Scales and fades the element's own rendering, as scale and fade do. A definition paints, presents, or both. | | `animated` | `bool` | `true`. `false` for effects that change only when updated, so the canvas does not redraw them each frame. | | `holds` | `bool` | `false`. `true` plays once over the period and holds the end, like a fade. | | `properties` | `Set` | Empty. Values an inspector offers. | | `editing` | `EffectEditing` | Inspector ranges, below. | `EffectPresentation(scale:, opacity:)` scales about the element's center and multiplies its opacity. Connectors ignore scale. ### `EffectContext` | Member | Type | Purpose | | --- | --- | --- | | `element` | `ResolvedElement` | The connector or shape. | | `connector`, `shape` | `ResolvedConnector`, `ResolvedShape` | The element as its kind; the other throws `StateError`. | | `effect` | `Effect` | Current values. | | `progress` | `double` | Position in the cycle, from 0 to 1, after `phase` and `reverse`; for a holding effect, how far its change has come. | | `level` | `double` | Emphasis from 0 (rest) to 1 (peak): `progress` shaped by the waveform. Held at 1 with reduced motion. | | `elapsed` | `Duration` | Time since the effect started, after its delay. | | `path` | Flutter `Path` | Copy of the connector route or the shape outline, in world coordinates. | | `metric` | Flutter `PathMetric` | Length and segments of a connector route. | | `pathGeometry` | `ResolvedPathGeometry` | Route sampling with tangents, for connector effects. | | `inverseZoom`, `sizeToWorld` | `double` | Inverse camera zoom; `sizeToWorld` is 1 for world scale and the inverse zoom for screen scale. | | `createPaint([intensity = 1])` | Flutter `Paint` | The effect color, gradient and opacity, adapted to the canvas theme; `intensity` from 0 to 1. | | `adapt` | `ColorAdaptation` | How the canvas theme adapts authored colors. Apply it to any other color the effect draws. | ### Registry and inspector ranges | API | Contract | | --- | --- | | `EffectRegistry.standard` | Flow, pulse, halo, scale and fade. | | `EffectRegistry(definitions)` | Exactly the supplied effects; include the built-ins with `[...EffectRegistry.standard.definitions, ...custom]`. Rejects empty kinds or labels, duplicate kinds, and definitions that neither paint nor present, with `ArgumentError`. | | `definitions`, `forConnectors`, `forShapes` | All definitions, or those that play on connectors or on shapes. | | `contains(kind)`, `registry[kind]`, `require(kind)` | Lookup; `require` throws `StateError` when missing. | The inspector offers the advertised `EffectProperty` values of the effect on the selected shape or connector: `particle`, `color`, `gradient`, `speed`, `baseOpacity`, `opacity`, `size`, `width`, `count`, `direction`, `scale`, `waveform`, `repeat`, `delay`, `target`, `mode`, `amount`, `spread`, `dim` and `fade`. `EffectEditing` groups their `EffectRange(minimum, maximum, step)` bounds; ranges do not clamp authored values. | Property | Default range | Units | | --- | --- | --- | | `speed` | `(0.1, 5, 0.1)` | Cycles per second | | `delay` | `(0, 10, 0.1)` | Seconds | | `baseOpacity`, `opacity`, `dim` | `(0, 100, 5)` | Percent | | `size`, `width` | `(1, 24, 1)` | Pixels | | `spread` | `(1, 48, 1)` | Pixels | | `amount` | `(0.5, 2, 0.02)` | Scale factor | | `count` | `(1, 30, 1)` | Particles; whole numbers | | `repeat` | `(1, 20, 1)` | Cycles; whole numbers | ## Examples | Example | Shows | | --- | --- | | [Connector effects](/agent-docs/examples/connector-effects.md) | Dots, dashes, arrows and gradient flows; pulse and blink along connectors. | | [Shape effects](/agent-docs/examples/shape-effects.md) | Pulse, blink, ripple and steady halos, breathe and pop, fades and dimming, in brand colors. | | [Element motion](/agent-docs/examples/element-motion.md) | Animated move, resize and layout. | | [Custom effect](/agent-docs/examples/custom-effect.md) | A registered effect kind the inspector edits. | | [Navigation and animation](/agent-docs/examples/navigation.md) | Camera motion. | | [Live energy flow](/agent-docs/examples/path-effects.md) | Live data with flows, a beacon and animated load bars. | --- # Arrowheads Package: `vyuh_diagram_extension_connectors`. Optional commercial extension; import it alongside `vyuh_diagram_flutter` in a Flutter application, or alongside core in Dart. ## Install `ConnectorsExtension()` installs the full arrowhead set together with the elbow and curved routes; `ConnectorsExtension(arrowheads: false)` leaves the arrowheads out. Core draws `ArrowheadKind.none` and `ArrowheadKind.angle` without it. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), ConnectorsExtension()], ), ); controller.edits.setEndArrowhead(connectorId, kind: ArrowheadKind.filledDiamond); ``` ## Arrowhead set `connectorArrowheads` lists the `DiagramArrowheadDefinition`s the extension installs: | Kind | Label | | --- | --- | | `ArrowheadKind.triangle` | Triangle | | `ArrowheadKind.filledTriangle` | Filled triangle | | `ArrowheadKind.square` | Square | | `ArrowheadKind.dot` | Circle | | `ArrowheadKind.diamond` | Diamond | | `ArrowheadKind.invertedTriangle` | Inverted triangle | | `ArrowheadKind.bar` | Bar | | `ArrowheadKind.filledDiamond` | Filled diamond | | `ArrowheadKind.cross` | Cross | | `ArrowheadKind.capsule` | Capsule | | `ArrowheadKind.halfCapsule` | Half capsule | Each definition supplies headless geometry; shared rendering consumes it. See [connectors API](/agent-docs/api/connectors.md) for the shared verbs and configuration. --- # Connector routing Package: `vyuh_diagram_extension_connectors`. Optional commercial extension; import it alongside `vyuh_diagram_flutter` in a Flutter application, or alongside core in Dart. ## Public entry points `ConnectorsExtension({routes = ConnectorRoutes.all, arrowheads = true})`, id `vyuh.connectors`: the elbow and curved routes and the full [arrowhead set](/agent-docs/api/extension-arrowheads.md), in one extension. Limit `routes` to the ones your application offers, or turn `arrowheads` off. Install it once in the configuration's `extensions`; it supplies headless providers, and shared rendering consumes their output. The extension owns its route identities: `ConnectorRoutes.orthogonal`, `ConnectorRoutes.quadratic` and `ConnectorRoutes.bezier`. The library exports only `ConnectorsExtension` and `ConnectorRoutes`; the route providers behind those names are private to the package. Core keeps only `ConnectorRoute.straight`. Each provider declares its options schema and capabilities: an installed route places its own bend handle, and a route whose control editor moves free points draws arms from its terminals to its controls on the canvas. ```dart import 'package:vyuh_diagram_extension_connectors/vyuh_diagram_extension_connectors.dart'; import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), ConnectorsExtension()], ), ); controller.edits.connect('a', 'b', route: ConnectorRoutes.orthogonal); ``` Routes are a separate contribution from connector definitions: any connector type may select any installed route, as the inspector's route choice does. See [connectors API](/agent-docs/api/connectors.md) for the shared commands and configuration. --- # Graph layout Package: `vyuh_diagram_extension_layout`. Optional commercial extension; import it alongside `vyuh_diagram_flutter` in a Flutter application, or alongside core in Dart. ## Public entry points `const LayoutExtension()`, id `vyuh.layout`, performs every `Layout`: layered, tree (including radial), force, circular and grid. Install it in the configuration's `extensions`; its algorithms are headless, and shared rendering consumes their output. ```dart final controller = DiagramController( configuration: DiagramConfiguration(extensions: [const LayoutExtension()]), ); await controller.edits.layout(Layout.tree(direction: TreeDirection.right)); ``` `layoutGraph(GraphLayoutRequest request, Layout layout)` runs a layout synchronously on the calling isolate, for importers that place nodes before any controller exists. Without pinned nodes, its result's top-left corner is the origin. See [layout API](/agent-docs/api/layout.md) for the layouts, their options and the shared verbs. --- # Shapes library Package: `vyuh_diagram_extension_shapes`, library `package:vyuh_diagram_extension_shapes/vyuh_diagram_extension_shapes.dart`. Optional commercial extension; import it alongside `vyuh_diagram_flutter` in a Flutter application, or alongside core in Dart. ## Public entry points - `ShapesExtension({only, tools = true})`, id `vyuh.shapes`: installs every shape with one palette tool each. `only` limits it to the listed shape types; `tools: false` installs the shapes without palette tools. It installs `TableExtension()` for entity sections and `RichTextExtension(tool: false)` for their rich rows, unless the application installs its own. - `ShapesExtension.library`: the `ShapeLibrary` (id `shapes`, name `Shapes`). - `DiagramShapes`: the shape type constants, plus the `DiagramShapes.entitySecondary` value key. ## Register the library ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_shapes/vyuh_diagram_extension_shapes.dart'; import 'package:vyuh_diagram_extension_table/vyuh_diagram_extension_table.dart'; import 'package:vyuh_diagram_extension_table_flutter/vyuh_diagram_extension_table_flutter.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), TableFlutterExtension(), ShapesExtension(only: [DiagramShapes.decision, DiagramShapes.entity]), ], ), ); ``` The entity's sections are table content. Add `TableFlutterExtension()`, which installs `TableExtension()`, for the table's interactive row controls. Use `ShapesExtension.library.shape(type)` to reuse one definition in your own extension. ## Shapes | Shape | Type | Notes | | --- | --- | --- | | Start | `DiagramShapes.start` | Circle with a play icon. | | End | `DiagramShapes.end` | Circle with an X. | | Decision | `DiagramShapes.decision` | Diamond with a centered label. | | Subprocess | `DiagramShapes.subprocess` | Rectangle with inner side bars. | | Preparation | `DiagramShapes.preparation` | Hexagon with a centered label. | | Extract | `DiagramShapes.extract` | Triangle with a centered label. | | Junction | `DiagramShapes.junction` | Small circle with a one-letter label. | | Parallelogram | `DiagramShapes.parallelogram` | Slanted sides, for data in and out. | | Trapezoid | `DiagramShapes.trapezoid` | Wide at the top, for a manual operation. | | Cylinder | `DiagramShapes.cylinder` | A drum with a curved rim, for stored data. | | Document | `DiagramShapes.document` | A page with its top-right corner folded. | | Entity | `DiagramShapes.entity` | Tag and title over a primary section and an optional secondary section. | | Arrow | `DiagramShapes.arrow` | Block arrow with `direction` (`right`, `left`, `up`, `down`), `doubleHeaded`, `shaft`, `head` and `headWidth` values. | | Star | `DiagramShapes.star` | `points` (integer 3 to 20) and `innerRadius` values. | | Arc / Pie | `DiagramShapes.arc` | `startAngle` and `sweepAngle` values; `closeToCenter` makes a pie. | | Callout | `DiagramShapes.callout` | Speech callout with `pointer` and `depth` values. | Decision, preparation and extract are regular polygons whose side count is their `sides` value (4, 6 and 3 by default), so their sides and corner radius are editable like the core polygon's. `createShape` fills in the default; an authored `ShapeElement` supplies `values: {'sides': n}` itself. Rectangles, ellipses, polygons, cards and frames are core shapes and need no extension. A flowchart process is a core rectangle or card; a card carries an optional tag, a title and a plain-text description, with ports on each side. Arrows, stars, arcs and callouts are adjustable: their outline is derived from their values, and each value has an on-canvas [adjustment](/agent-docs/api/shapes.md) control with magnetic snap stops (Shift constrains to the stops). See the [adjustable shapes example](/agent-docs/examples/adjustable.md). ## Entity sections An entity models a class, a record or an ER entity. Its header holds an optional `tag` (shown only while it has text, for example a class annotation) and a single-line `title`. Below it, the `primary` section lists rows such as attributes. The `secondary` section, for example methods, shows only while the entity's `DiagramShapes.entitySecondary` value is on. Rows are single-line; adding rows grows the shape. Only the whole shape resizes: sections have no row or column resize handles, and columns cannot be added. Relationships attach anywhere on the outline (`ShapeConnectionDefinition.outline()`), as class and ER edges do. ## Entity verbs An entity's own [verbs](/agent-docs/api/verbs.md) are declared on its `ShapeDefinition(verbs: [...])`, and `DiagramEntityVerbs` adds typed wrappers for them to the controller: the card verbs `setTitle` and `setTag` (`setTag(id, null)` hides the tag), and `showSecondarySection(id, shown)`, which sets the `DiagramShapes.entitySecondary` value. Each section's rows are its table part's verbs, addressed as `primary.insertRow` or `secondary.insertRow`; the typed table wrappers take `part: 'primary'`. See [tables](/agent-docs/api/tables.md#verbs). ```dart controller.edits.setTitle(entityId, 'Order'); controller.edits.showSecondarySection(entityId, true); controller.edits.insertRow(entityId, at: 1, part: 'primary'); ``` ## Shape affordances The entity declares its on-canvas controls in `ShapeDefinition.affordances`: `diagramTagAffordance` (the core card's optional tag) and a `ShapeValueToggleAffordance` for `showSecondarySection`. When an entity is selected, the editor shows an add or remove tag button beside its title, performing `addSlot` or `removeSlot`, and an add or remove secondary section button, performing `showSecondarySection` with the opposite of the current value. Each performs a verb, so it supports undo, and shows only while that verb is available. `EditorExtension()` draws affordances. See [shape affordances](/agent-docs/api/canvas.md#shape-affordances). Create instances with `controller.edits.createShape(..., at: ...)`, which reports the new ID in `id`. Definitions own their anatomy: outline, body, values, ports and behavior. Register a new type to customize a definition; do not overwrite installed IDs. Shared Flutter rendering and codecs consume the ordinary resolved primitives, so no separate library-specific painter is needed. See [shapes API](/agent-docs/api/shapes.md) for the shared verbs and configuration. --- # Extension reference The foundation includes basic shapes and port markers, Plain Text, the default `connector` type with straight routes, base arrowheads, interaction tools and the core verbs through `diagramCoreExtensions`, which every `DiagramExtensionRegistry` installs first. Optional extensions are installed explicitly; `vyuh_diagram_flutter` does not depend on them. - [Table extension](/agent-docs/api/tables.md) - [Rich-text extension](/agent-docs/api/rich-text.md) - [Connectors: routes and arrowheads](/agent-docs/api/extension-connectors.md) - [Arrowheads](/agent-docs/api/extension-arrowheads.md) - [Graph layout](/agent-docs/api/extension-layout.md) - [Shapes library](/agent-docs/api/extension-shapes.md) An extension is an `id`, the extensions it depends on, its options and typed contribution lists, each keyed by type: `shapes` (by shape type), `textTypes` (by text type), `connectors` (by connector type), `routes` (by route name), `arrowheads` (by kind), `portShapes` (by port shape), `contents` (by content type), `verbs`, `tools` and `graphLayouts`. Shapes compose these parts by type reference. A Flutter extension adds presentation and interaction only when needed. Ordinary shape libraries render through the shared primitives. Install concrete types such as `RichTextExtension()`, `TableFlutterExtension()` and `EditorExtension()` in the configuration's one `extensions` list; each brings its configuration as constructor arguments and its runtime options as a typed value (see [extensions and options](/agent-docs/api/configuration.md)). A custom portable extension constructs `DiagramExtension(...)` inline or subclasses it when it carries members of its own; a custom Flutter extension constructs or subclasses `DiagramFlutterExtension`. ## Libraries Extension authoring types live in a second library, so application code sees only the application surface. An extension file imports both: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ``` | Library | Holds | | --- | --- | | `vyuh_diagram_flutter.dart` (or `vyuh_diagram_core.dart` in pure Dart) | The application surface: `DiagramExtension`, `DiagramController` and its verbs, typed property fields, gestures and keys, diagnostics and repairs, the document model, `DiagramTool`, options such as `GridOptions`, and in Flutter `DiagramCanvas` and `DiagramTheme`. | | `extension_api.dart` | Everything an extension contributes or reads: `ShapeDefinition` and its parts, `ShapeLibrary`, `ShapeRegistry`, value fields, `DiagramTextDefinition`, `DiagramToolDefinition`, `DiagramShortcut`, `DiagramVerb` and `DiagramVerbTarget`, `DiagramConnectorDefinition`, route providers, arrowhead and port-shape definitions, `DiagramContentDefinition`, `DiagramProperty` and its schema, `DiagramMoveAdjuster`, `GraphLayoutAlgorithm`, `DiagramExtensionRegistry`, `DiagramOutput` and the resolved scene. The Flutter `extension_api.dart` adds `DiagramFlutterExtension`, `DiagramCanvasExtensionHost`, `DiagramCanvasBehavior`, `ShapeWidgetBuilder`, `DiagramKeyBinding`, `DiagramPropertyEditor`, `EffectDefinition` and `FlutterDiagramTextLayoutEngine`, and re-exports `package:vyuh_diagram_core/extension_api.dart`. | | `adapter.dart` | Engine internals for tooling: transactions and steps, editor state, the resolver, render plan, painters, `RenderingExtension` and `TextElementDefinition`. | | `testing.dart` | Test helpers: `editingExtension()`, canvas surface keys and `testRegistry(...)`. | A package that extends another extension imports that package's `extension_api.dart` for its model: `package:vyuh_diagram_extension_table/extension_api.dart` (table cells, rows, codec, layout) and `package:vyuh_diagram_extension_rich_text/extension_api.dart` (rich paragraph and run attributes, `richParagraph`, `RichTextFormatting`). Inspector building blocks are in `package:vyuh_diagram_extension_editor/controls.dart`. ## Related foundation APIs [Shapes](/agent-docs/api/shapes.md), [Plain Text](/agent-docs/api/text.md), [canvas](/agent-docs/api/canvas.md), [extensions and options](/agent-docs/api/configuration.md), [persistence](/agent-docs/api/persistence.md), [output](/agent-docs/api/output.md), [widgets](/agent-docs/api/widgets.md), [navigation and motion](/agent-docs/api/navigation-and-motion.md), [diagnostics](/agent-docs/api/diagnostics.md) and [history](/agent-docs/api/history.md). ## Define an extension ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final card = ShapeDefinition( type: 'app.card', body: const ShapeText('body', text: 'A custom card'), behavior: const ShapeBehavior(rotatable: false), ); final controller = DiagramController( configuration: DiagramConfiguration(extensions: [cardsExtension()]), ); DiagramExtension cardsExtension() => DiagramExtension( id: 'app.cards', shapes: [card], tools: DiagramToolDefinition.forShapes([card], group: 'app.cards'), ); ``` Use the Flutter imports in a Flutter host; model-only packages import `package:vyuh_diagram_core/vyuh_diagram_core.dart` and `package:vyuh_diagram_core/extension_api.dart`. Stable, unique type IDs identify saved instances. Install all required definitions before opening a document. An `id` is namespaced lowercase segments, such as `app.cards` or `vyuh.table`. Duplicate conflicting ids and unresolved type references are rejected. `DiagramToolDefinition.forShapes(shapes, group: ...)` returns one palette creation tool per shape; add them to `tools` beside the shapes. A contributed tool, property, option or group carries its own `DiagramIcon`: a name plus an optional portable `svg` glyph. The editor shows its own icons for core tools (`defaultDiagramToolIcons`) and otherwise draws the declared glyph (`diagramToolIcon`); both are in `package:vyuh_diagram_extension_editor/controls.dart`. An extension's icons travel with it, as the table tool's icon and rich text's `RichTextIcons` do. ```dart const DiagramExtension({ required String id, List dependencies = const [], List shapes = const [], List textTypes = const [], List connectors = const [], List routes = const [], List arrowheads = const [], List portShapes = const [], List contents = const [], List verbs = const [], List tools = const [], List graphLayouts = const [], List? palette, Object? options, DiagramTextLayoutEngine? textLayout, DiagramOutput? output, }) ``` | Contribution | Keyed by | | --- | --- | | `ShapeDefinition` | Shape type; carries its own `verbs` | | `DiagramTextDefinition` | Text type (`type`, such as `richText`); each is also a type of the core standalone text element | | `DiagramConnectorDefinition` | Connector type (`'connector'` by default) | | `DiagramConnectorRouteProvider` | Route name | | `DiagramArrowheadDefinition` | `ArrowheadKind` | | `DiagramPortShapeDefinition` | `PortShape` | | `DiagramContentDefinition` | Content type; a matching layout provider and versioned codec | | `DiagramToolDefinition` | Tool id | | `GraphLayoutAlgorithm` | `Layout` type, such as `TreeLayout` | Beside its contributions, an extension may declare: | Field | Meaning | | --- | --- | | `dependencies` | Extension instances installed with it, with those defaults, unless the application installs an extension with the same `id`. | | `options` | Its typed options value, keyed by Dart type with exactly one owner; see [options](/agent-docs/api/configuration.md#options). | | `palette` | The tools offered, in order. At most one installed extension declares a palette (the editor's `tools:`); without one, every installed tool the grammar supports is offered. | | `textLayout`, `output` | Text shaping and SVG/PNG output for hosts without a mounted canvas; at most one installed extension supplies each. | Override `propertiesFor(scope)` to contribute property-panel entries, such as controls for the extension's own options. ## Assemble the grammar `DiagramExtensionRegistry(extensions: [...])` is the one place installed extensions are assembled into a grammar; a diagram builds it from the configuration's extensions and exposes it as `controller.diagram.registry`. 1. The application's extensions are installed. 2. Each one's `dependencies` are installed, with their defaults, unless an extension with the same `id` already is. Dependencies must be acyclic. 3. `diagramCoreExtensions` fill in as defaults. An installed extension with a core id, such as `GridExtension` (`vyuh.core.grid`), replaces that core extension. A contribution with the same key as a core one replaces it, so an extension can supply its own `rectangle`, `text` type, `connector` type or `select` tool. Two non-core extensions contributing the same key conflict, as do two distinct extensions with one `id` and two extensions declaring the same options type; assembly rejects each with an `ArgumentError` naming both. The registry exposes the assembled maps (`shapes`, `textElements` (the core's standalone text element definition for each installed text type), `connectors`, `arrowheads`, `portShapes`, `tools`, `contents`, `contentLayouts`, `graphLayouts`, `routes`, `verbs`), the `codecs` (`DiagramModelCodecs`) that persist installed content and text attributes, and the validated `ShapeRegistry` the resolver and controller read through the `shapeRegistry` getter: ```dart import 'package:vyuh_diagram_extension_table/vyuh_diagram_extension_table.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; final shapes = DiagramExtensionRegistry( extensions: [cardsExtension(), TableExtension()], ).shapeRegistry; ``` Text elements are keyed by type: the core extensions register `text` (plain) and `RichTextExtension()` registers `richText`. These keys name standalone text elements. Shape slots, table cells and connector labels choose their text with a `textType` definition, which is plain unless rich text is given. ## Add Flutter behavior when needed `DiagramFlutterExtension` extends `DiagramExtension`: it takes every portable argument above plus its Flutter contributions. Construct one, or subclass it and pass the same arguments to `super(...)`: ```dart const DiagramFlutterExtension({ required String id, // ...every DiagramExtension argument... bool editable = false, DiagramCanvasContainerBuilder? container, List shortcuts = const [], Map widgets = const {}, List effects = const [], List propertyEditors = const [], DiagramPasteHandler? paste, }) ``` Install it in the configuration's `extensions` like any other; the mounted canvas uses the installed Flutter extensions. A Flutter extension that needs a portable one declares it in `dependencies`, so applications list one class per feature: `TableFlutterExtension` installs `TableExtension`. | Member | Contributes | | --- | --- | | `editable` | Whether it makes the canvas edit. The editor is editable; without an editable extension the canvas navigates and selects only. | | `container` | A widget around the canvas; the first installed container is innermost. | | `shortcuts`, `widgets`, `effects` | Key bindings, shape widget builders and effects. | | `propertyEditors` | Inspector controls for its custom properties. | | `paste` | Handles external text pasted on the canvas, such as Mermaid source: `(controller, text) async => handled`. | | `createBehavior(host)` | Canvas input behavior while the canvas edits. | | `createMoveAdjuster(controller)` | A selection-move adjuster, such as snapping. | | `build(context, host)` | A viewport overlay, such as a minimap. | A Flutter extension that adjusts selection moves overrides `createMoveAdjuster(controller)` to return a portable `DiagramMoveAdjuster`. The canvas applies installed adjusters in installation order and shows the guides they report as the host's `moveGuides`; the snap-guides extension contributes its alignment snapping this way. Inspector properties come from the [property grammar](/agent-docs/guide/properties.md): an installed route provider, content provider or text formatting contributes properties by implementing `DiagramPropertySource`, an extension contributes its own through `propertiesFor(scope)`, and a Flutter extension renders its custom properties through `propertyEditors`. Ordinary composed shapes use shared rendering and need no Flutter extension. Use UI contributions for custom interaction and controls; perform controller verbs for edits so selection, validation and undo remain consistent. See [verbs and keyboard bindings](/agent-docs/guide/verbs.md), [widgets](/agent-docs/api/widgets.md) and [tables](/agent-docs/api/tables.md) for concrete integrations. Portable extensions own `verbs` and `tools`. A shape's own verbs belong on `ShapeDefinition(verbs: [...])`; element and diagram verbs belong on the extension. Flutter key bindings, `DiagramKeyBinding`, name an installed verb; they do not define a separate mutation path, and assembly rejects a binding whose verb is not installed. An application can install its own extension alongside packaged extensions. `EditorExtension()` is the editable Flutter extension: it makes the canvas edit with every installed tool the grammar supports, or `EditorExtension(tools: [...])` to restrict and order them, and composes a palette, inspector and toolbar around the canvas. Its `container` callback receives `(context, controller, canvas)` for a custom layout. Without an editable extension the canvas renders and navigates but does not edit through user input. See [editor composition](/agent-docs/api/canvas.md#compose-an-editor). To change a core part, contribute a part with the same key: a text definition whose `type` is `text` replaces plain text, and a `DiagramConnectorDefinition(...)` without a `type` replaces the default `connector`. A Flutter extension that draws chrome keeps its colors in its own options and picks a light or dark default by `DiagramTheme.brightness`; see [theming](/agent-docs/guide/theming.md#extension-themes). Any extension can be built without subclassing. To install a `ShapeLibrary`, pass its `shapes` and `DiagramToolDefinition.forShapes(library.shapes, group: library.id)` to a `DiagramExtension`. `DiagramFlutterExtension(...)` does the same for the Flutter half. A Flutter extension that draws an overlay or joins the canvas input pipeline subclasses `DiagramFlutterExtension` and overrides `build(context, host)` or `createBehavior(host)`. The `DiagramCanvasExtensionHost` exposes the `controller`, a `camera` (`zoomBy`, `setZoom`, `setCenter`, `fitBounds`, `fitWidth`, `worldToScreen`, `screenToWorld`, `state`), the `selectedIds`, the `hoverScreenPoint`, `moveGuides` and the shared demand-driven `frameClock`. Read these inside an `Observer` so the overlay rebuilds when they change: ```dart import 'package:flutter/widgets.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; final class ZoomBadge extends DiagramFlutterExtension { const ZoomBadge() : super(id: 'app.zoom_badge'); @override Widget build(BuildContext context, DiagramCanvasExtensionHost host) => Observer( builder: (_) => Text('${(host.controller.camera.zoom * 100).round()}%'), ); } ``` Route edits through `host.controller`, for example `canPerform` and `perform`; canonical document and resolved geometry remain owned by the diagram. `build` renders on both edit and view surfaces; `createBehavior` runs only while the canvas edits. ## Persist custom content Standard shape geometry, properties and text use the shared document codec. Structured content contributes `DiagramContentDefinition(layout: ..., codec: ...)`; the provider and codec must report the same content type. A text definition persists the paragraph and run attributes it admits through its `codec` (`DiagramTextCodec`). The registry collects both into `codecs`, and `controller.save(DiagramJsonCodec.new)`, `controller.edits.load(..., format: DiagramJsonCodec.new, ...)` and `DiagramController.open(..., format: DiagramJsonCodec.new, configuration: DiagramConfiguration(extensions: [...]))` build the codec over them, so hosts never wire extension codecs by hand. The [JSON format](/agent-docs/api/json-format.md) page shows where values, attributes and content appear. See [persistence](/agent-docs/api/persistence.md) and [output](/agent-docs/api/output.md) for host-facing contracts. --- # Grids and snapping `GridExtension` owns the grid: its `GridOptions` set the base interval, visibility, snapping and pattern. With the grid visible, direct manipulation snaps to the displayed spacing, including density reduction when zooming out. It never snaps to hidden subdivisions. With the grid hidden, snapping uses the configured base interval. Visibility does not enable snapping by itself. ## On this page | Category | What you can do | | --- | --- | | [Grid options](#grid-options) | Set visibility, spacing and snapping. | | [Patterns](#diagramgridpattern) | Choose or compose a visual pattern. | | [Layers](#grid-layers) | Describe each pattern layer. | ## Grid options Core always installs `GridExtension()` (id `vyuh.core.grid`); installing your own replaces it with the values you give. Read the current options with `controller.options()` and change them at runtime with `controller.edits.setOptions(...)`, for every controller on the diagram. See [extensions and options](/agent-docs/api/configuration.md) for how options work. ```dart GridExtension({ bool visible = false, bool snap = false, double size = 20, DiagramGridPattern pattern = DiagramGridPattern.layered, Iterable patterns = DiagramGridPattern.presets, }) ``` | `GridOptions` field | Type | Default | Contract | | --- | --- | --- | --- | | `visible` | `bool` | `false` | Paint the grid. Does not enable snapping. | | `snap` | `bool` | `false` | Enable grid snapping. Does not require a visible grid. | | `size` | `double` | `20` | World-space interval, normalized by `GridExtension` and `copyWith`. | | `pattern` | `DiagramGridPattern` | `DiagramGridPattern.layered` | Immutable composition of paint layers. | `patterns` is the list the property panel offers; `GridExtension` contributes Show grid, Grid type, Snap to grid and Grid size to the inspector's canvas group. `copyWith` returns new options; omitted arguments preserve existing values. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [GridExtension(visible: true, snap: true)], ), ); final grid = controller.options(); controller.edits.setOptions(grid.copyWith(size: 40)); ``` ### Size normalization `copyWith(size: value)` normalizes the interval, and `effectiveSize` reports the normalized interval of any options value. Painting and snapping always use the normalized interval. ```dart final grid = const GridOptions().copyWith(size: 23); assert(grid.size == 24); ``` | Constraint | Value | | --- | --- | | Minimum interval | `GridOptions.minimumSize`, `4` | | Maximum interval | `GridOptions.maximumSize`, `128` | | Interval increment | `GridOptions.sizeStep`, `4` | Finite inputs are divided by `4`, rounded with Dart's `round()`, multiplied by `4`, and clamped to `[4, 128]`. Non-finite inputs become `20`. Normalization does not throw for those values. ## `DiagramGridPattern` ```dart factory DiagramGridPattern({ required String id, required String label, required Iterable layers, }) ``` | Property | Type | Requirement | | --- | --- | --- | | `id` | `String` | Nonempty after trimming and no leading/trailing whitespace. | | `label` | `String` | Nonempty after trimming. | | `layers` | `List` | Unmodifiable copy containing 1–16 layers. | Patterns compare by `id`, `label`, and ordered layer values, with a matching `hashCode`. | Static value | ID / label | Layers | | --- | --- | --- | | `DiagramGridPattern.dots` | `dots` / `Dots` | One default `DiagramDotGridLayer`. | | `DiagramGridPattern.lines` | `lines` / `Lines` | One default `DiagramLineGridLayer`. | | `DiagramGridPattern.layered` | `layered` / `Layered` | Lines at interval `1`, color `0xB8E5E5E5`; lines at interval `5`, color `0x9ED4D4D4`. | | `DiagramGridPattern.presets` | — | Constant list `[dots, lines, layered]`. | ## Grid layers `DiagramGridLayer` is sealed. Its concrete productions are dots, lines, and crosses: ```dart const DiagramDotGridLayer({ int spacingMultiple = 1, DiagramColor color = const DiagramColor(0xFFCDD5E4), double size = 2, }) const DiagramLineGridLayer({ int spacingMultiple = 1, DiagramColor color = const DiagramColor(0xFFCDD5E4), double size = 1, }) const DiagramCrossGridLayer({ int spacingMultiple = 1, DiagramColor color = const DiagramColor(0xFFCDD5E4), double size = 3, }) ``` | Property | Type | Default | Meaning / accepted range in a pattern | | --- | --- | --- | --- | | `spacingMultiple` | `int` | `1` | Multiplies the shared world interval; `1`–`1024`. | | `color` | `DiagramColor` | `DiagramColor(0xFFCDD5E4)` | ARGB integer from `0` through `0xFFFFFFFF`. | | `size` | `double` | Dot: `2`; line: `1`; cross: `3` | Screen-space dot diameter, line stroke width, or cross arm length. Must be finite, `> 0`, and `<= 32`. | Layer values compare by concrete type and all three properties. Validation occurs when constructing `DiagramGridPattern`, which throws `ArgumentError` for invalid identity, label, layer count, spacing, size, or color. Layer constructors themselves do not perform this pattern validation. ## Example ```dart final pattern = DiagramGridPattern( id: 'cross-and-major-lines', label: 'Crosses and major lines', layers: const [ DiagramCrossGridLayer(size: 3), DiagramLineGridLayer(spacingMultiple: 5, color: DiagramColor(0x99CDD5E4)), ], ); controller.edits.setOptions( controller.options().copyWith( visible: true, snap: true, size: 20, pattern: pattern, ), ); ``` To offer the pattern in the inspector, install `GridExtension(patterns: [...DiagramGridPattern.presets, pattern])`; the list is `GridOptions.patterns`, and duplicate pattern ids throw an `ArgumentError`. See [custom grid patterns](/agent-docs/guide/canvas.md#compose-your-own-pattern) for a canvas example. Rotation snapping uses `EditorOptions.rotationSnap`, owned by `EditorExtension(rotationSnap: ...)`, independent of the grid. `EditorOptions` implements the core `DiagramSnapSettings` interface the engine reads; without the editor the engine snaps rotation to 15° (`DiagramSnapSettings.standard`). ## Neighbor snap guides Grid snapping and neighbor alignment are independent. Install the optional `vyuh_diagram_extension_snap_guides` package to align moved selections to nearby resolved bounds: ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_snap_guides/vyuh_diagram_extension_snap_guides.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), SnapGuidesExtension( policy: const DiagramSnapGuidePolicy( sides: true, centers: true, maxCandidates: 24, ), tolerance: 6, ), ], ), ); ``` `SnapGuidesExtension` (id `vyuh.snap_guides`) owns `SnapGuidesOptions` (`enabled`, `policy`, `tolerance`, `theme`, `copyWith`). Toggle guides at runtime: ```dart controller.edits.setOptions( controller.options().copyWith(enabled: false), ); ``` Guide lines use `SnapGuidesOptions.theme`, set with `SnapGuidesExtension(theme: SnapGuideTheme(color: color))`. Without one they use `SnapGuideTheme.light` (`Color(0xFF5260FF)`) or `SnapGuideTheme.dark` by the canvas [diagram theme](/agent-docs/guide/theming.md)'s brightness. The color does not change snapping behavior. The snap tolerance is in screen pixels. Candidate shapes must intersect the current viewport. Candidate limits range from 1 to 256 and apply after the spatial query and distance ranking. Guides use resolved bounds, including borders. Selected elements and their containing ancestors are excluded. Neighbor alignment takes priority over the grid on aligned axes; other axes keep grid behavior. Guides appear only during selection moves and clear on completion or cancellation. Try [snap guides](/agent-docs/examples/snap-guides.md) and [policy options](/agent-docs/examples/snap-policy.md). ## Headless snapping The same rules are plain Dart values, so controllers without a canvas snap exactly as the canvas does. `DiagramGridSnapping.point` in `package:vyuh_diagram_core/adapter.dart` snaps to the visible grid for a viewport. Neighbor alignment belongs to the snap guides package: `SnapGuidesOptions` is also a pure-Dart `DiagramMoveAdjuster` carrying the policy and tolerance that `SnapGuidesExtension` installs. Its `adjust(DiagramMoveRequest)` returns a `DiagramMoveAdjustment` with the settled delta and the `DiagramMoveGuide`s that explain it. Core offers only the generic hook. A Flutter extension contributes an adjuster by overriding `DiagramFlutterExtension.createMoveAdjuster(controller)`; the canvas applies installed adjusters in order and exposes their guides as `DiagramCanvasExtensionHost.moveGuides`. The snap-guides extension paints those guides. ```dart import 'package:vyuh_diagram_flutter/adapter.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final snapped = DiagramGridSnapping.point( point, controller.options(), visibleBounds: viewportWorldBounds, zoom: zoom, ); ``` --- # Headless text and SVG A pure Dart `DiagramController` can create and edit documents without Flutter. Approximate text metrics are the default headless fallback. Supply a DiagramTextLayoutEngine for font-aware geometry before exporting. The SVG codec consumes resolved text geometry. A mounted Flutter canvas supplies `FlutterDiagramTextLayoutEngine`. For unmounted Flutter export, install an extension carrying it: `DiagramExtension(id: 'app.backends', textLayout: FlutterDiagramTextLayoutEngine(), output: FlutterDiagramOutput())`; both backends are in `package:vyuh_diagram_flutter/extension_api.dart`. In pure Dart, `PangoTextLayoutExtension(fontFiles: ..., defaultFontFamily: ...)` from `package:vyuh_diagram_core/vyuh_diagram_pango.dart` supplies font-aware metrics, and `SvgExtension()` from `package:vyuh_diagram_codec_svg/vyuh_diagram_codec_svg.dart` supplies SVG output. Load the intended fonts before creating or refreshing the controller. Native text shaping requires the platform dependencies described in the core package's native text documentation. See [output](/agent-docs/api/output.md) for export APIs and [controller](/agent-docs/api/controller.md) for ownership. --- # Undo and redo Use `controller.edits.undo()` and `controller.edits.redo()` for document history. The diagram has one history; text editing, shape manipulation, connector changes and host commands do not maintain separate undo stacks. Each entry records the controller that made it, and `undo()` and `redo()` replay only that controller's own entries: an agent's edits stay when the user undoes, and the reverse. History retains at most **50 committed commands** across undo and redo together. Recording a new command evicts the oldest retained command when the budget is full. Undo and redo transfer entries without increasing this budget. A committed gesture or interaction lease counts as one command; pointer samples do not consume separate entries. The limit applies across participant branches, not separately to each branch. ## On this page | Category | What you can do | | --- | --- | | [Undo and redo](#controller-api) | Read availability and undo or redo an edit. | | [Atomic edits](#atomic-editing) | Combine related changes into one operation. | | [Live data](#edits-without-history) | Apply edits that mirror live data without undo entries. | | [Restored content](#what-undo-restores) | Understand what an undo action changes. | | [Edit grouping](#editing-granularity) | Keep each user action as one history entry. | | [Permissions and events](#permissions-and-events) | Apply admission rules and observe completed history actions. | ## Controller API | Member | Type / signature | Behavior | | --- | --- | --- | | `canUndo` | `bool get canUndo` | Whether this controller has an undo entry. Observable. This is availability, not a permission check. | | `canRedo` | `bool get canRedo` | Whether this controller has a redo entry. Observable. This is availability, not a permission check. | | `undo()` | `EditResult undo()` | Restore the changed elements of this controller's latest entry, and its selection, after admission. | | `redo()` | `EditResult redo()` | Reapply this controller's latest undone entry after admission. | `undo()` and `redo()` take no arguments. With an empty corresponding stack they return an allowed result without restoring anything. Commit or cancel this controller's active interaction before calling either method; neither may be called inside `batch`. ### Return value | `EditResult` member | Meaning | | --- | --- | | `bool allowed` | The operation passed admission. An allowed no-op does not mean content changed. | | `DiagramDenialCode? code` | Category when denied, such as `conflict` when another controller is editing a restored element. | | `String? reason` | Optional explanation when denied. | | `void requireAllowed()` | Throws `DiagramChangeDenied` if denied; otherwise returns normally. | A denied restoration leaves its history cursor and current publication unchanged. Undo restores only the elements its entry changed, so later edits by other controllers to other elements remain. If another controller has since changed those same elements, undo returns a `conflict` denial instead of overwriting them. ```dart final result = controller.edits.undo(); if (!result.allowed) { // Present result.reason in the host application's UI. } ``` ### Keeping toolbar state current ```dart Observer( builder: (_) => Row( children: [ IconButton( onPressed: controller.canUndo ? () => controller.edits.undo() : null, icon: const Icon(Icons.undo), ), IconButton( onPressed: controller.canRedo ? () => controller.edits.redo() : null, icon: const Icon(Icons.redo), ), ], ), ); ``` `canUndo` and `canRedo` are observable: the `Observer` (from `package:flutter_mobx`) rebuilds when either changes. Schedule follow-up edits outside the builder. ## Atomic editing Each [verb](/agent-docs/api/verbs.md) is one validated operation. Verbs such as `move` and `setStyle` update multiple elements as one undo action. Use `batch` to combine several verbs into one undo step: ```dart final result = controller.edits.batch('Add pair', () { final a = controller.createShape(Shapes.rectangle, at: DiagramPoint.zero); final b = controller.createShape(Shapes.rectangle, at: const DiagramPoint(200, 0)); controller.edits.connect(a, b); }); ``` `batch` runs on a cumulative interaction lease: each verb applies on top of the last, and the batch commits one entry. The first admission denial withdraws every earlier change and is returned. See [batch](/agent-docs/api/controller.md#batch). For an edit that spans several calls, such as a panel that applies changes over time, open the cumulative lease yourself: ```dart final lease = controller.beginInteraction('Restyle', cumulative: true); lease.perform([id], 'setOpacity', {'opacity': .5}); lease.perform([id], 'setStyle', {'strokeWidth': 2.0}); lease.commit(); // one undo entry; lease.cancel() restores the start ``` A cumulative lease yields: an unrelated edit, an undo or a new interaction commits it first. `lease.isActive` reports whether it is still open. There are no separate history groups. A nested `batch` joins the outermost one and takes its `history` setting. ## Edits without history Edits that mirror live data, such as a telemetry feed updating a charger's kW, are not the user's intent and do not belong in undo. Pass `history: false`: ```dart controller.edits.batch('Telemetry', () { controller.edits.setText('charger', '42 kW', slot: 'body'); controller.edits.setStyle(ids: ['charger'], fill: const DiagramColor(0xFFFFE9C7)); controller.edits.setElementBounds( 'charger-load', const DiagramRect.fromLTWH(0, 100, 126, 8), motion: Motion.smooth, ); }, history: false); ``` | Aspect | Behavior | | --- | --- | | Pipeline | The same as any batch: locks, rules, resolution, one publication and one `diagram.changes` event. A denial withdraws the whole batch. | | Undo and redo | No entry for any controller; the redo stack is kept. | | Change event | `DiagramDocumentChange.history` is `false`: skip autosave or dirty-marking for it. | | Selection | Unchanged. | | During an interaction | Runs while this or another controller drags or types. It applies to the committed document; the interaction keeps the fields it is changing, such as a dragged frame, and shows the live values of the others. Another controller's preview does not deny it. | | Any controller | A person's or an agent's controller can apply live data. | Earlier entries stay correct. When a live edit changes an element, every history entry that changed the same element, of every controller, is rebased field by field: undo restores the fields that entry changed and keeps the live values of the others. Fields are an element's placement and flags, each style property, each shape value, each connector route option and each paragraph of a text story; ports, connector labels and point lists are single fields. **A later live write to the same field wins.** If the user changes a fill, a live update changes the text and the user presses Undo, the fill is restored and the live text stays. If both changed the text, undo leaves the live text. A live edit that deletes an element, or reorders elements, makes an older entry depending on it a `conflict`, as another controller's edit would. See [Live data](/agent-docs/guide/live-data.md) for connecting a feed. ## What undo restores | State | History behavior | | --- | --- | | Document elements, stories, bindings and order | Restored from the entry's before/after snapshot. | | Selection | Restored with the document and mapped to valid resolved targets. | | Camera, zoom and viewport animation | Current navigation is retained. See [navigation and motion](/agent-docs/api/navigation-and-motion.md). | | Options, such as grids and snapping, canvas bounds and fonts | Current values are retained. | | Active tool and default connector route | Current choices are retained. | | Environmental layout refresh | No document history entry. | Restoration resolves geometry before publishing it with the document and selection. Revisions remain monotonic: undo restores prior content, not an old revision number. An edit with unchanged content creates no history entry or completed-change event and preserves redo. This includes same-content replacements and a lease or batch that returns to its starting content. Selection-only changes are transient. An unchanged verb retains the document revision and scene; already-published previews can have advanced the revision even when the final net edit is empty. A new content-changing transaction after undo clears the redo branch. Cancelling a lease restores the redo branch that existed before it. ## Editing granularity | Operation | Undo unit | | --- | --- | | One verb, on one or more elements | One entry. | | Continuous move, resize or other editor gesture | A gesture lease: live previews followed by one committed entry. Cancellation restores the baseline. | | `beginInteraction(label)` lease | Each `perform`, `performAll` or `preview` starts over from the baseline; `commit()` records one entry, `cancel()` restores the start. While active, the previewed elements are leased to this controller. | | `beginInteraction(label, cumulative: true)` lease | Each preview applies on top of the last; `commit()` records one entry. | | IME composition | A cumulative lease, committed as one entry when composition finishes. | | Ordinary text edits outside composition | Each text verb. No general time-based typing coalescing is exposed. | | `batch(label, build)` | Every verb in `build`, committed as one entry. | | `batch(label, build, history: false)` | No entry. Existing entries are rebased onto it. | ## Permissions and events The `beforeChange` rule evaluates verbs, lease previews and history restoration. Undo and redo use `DiagramChangePhase.commit` and origins `undo` / `redo`; they receive new operation IDs. Their restoration of previously admitted snapshots bypasses ordinary element-lock checks, but **does not bypass the `beforeChange` rule**. `diagram.changes` receives one completed nonempty edit from any controller, including undo/redo and edits without history, whose `history` is `false`. It excludes previews, cancellation, camera movement and selection-only changes. Read the controller's observable `document` inside an `Observer` when the host needs provisional state. See [rules and changes](/agent-docs/api/hooks.md) for proposal and event property tables. ## Keyboard shortcuts With the canvas or paragraph editor focused: | Action | Shortcut | | --- | --- | | Undo | Command/Ctrl + Z | | Redo | Command/Ctrl + Shift + Z, or Command/Ctrl + Y | The paragraph editor closes composition before invoking command-based undo/redo and resynchronizes its editing buffer from canonical state. ## Current scope History stays in the diagram’s memory and is excluded from document JSON. Use `canUndo` and `canRedo` for toolbar state. Stack inspection, limits, clearing and persistence are not exposed. Disposing a controller that joined a diagram preserves the shared history. --- # Rules and changes Admit edits with the controller's `DiagramRules`, and observe committed document changes on `diagram.changes`. The diagram applies its rules consistently, so a canvas, headless controller, custom tool and [verb](/agent-docs/api/verbs.md) use the same boundary, whichever controller submits the edit. ## On this page | Category | What you can do | | --- | --- | | [Rules](#diagramrules) | Admit changes, creations and connections. | | [Domain invariants](#fixed-domain-validation) | Validate all changed documents consistently. | | [Proposed changes](#diagramchangeproposal) | Inspect an edit before accepting it. | | [Results](#editresult) | Allow or reject an operation with a reason. | | [Committed changes](#diagramdocumentchange) | Observe accepted content updates. | | [Interactions](#interactions-on-a-canvas) | Shape regions, connections and paste on a mounted canvas. | ## `DiagramRules` ```dart const DiagramRules({ DiagramChangeRule? beforeChange, DiagramCreationRule? canCreate, DiagramConnectionRule? canConnect, }) ``` | Rule | Signature | Decides | | --- | --- | --- | | `beforeChange` | `EditResult Function(DiagramChangeProposal)` | Whether a proposed document change may be published: every verb, gesture, load, undo and redo, from any controller. | | `canCreate` | `EditResult Function(FramedElement)` | Whether a prepared shape or text element may be created. The element carries its identity and materialized defaults. | | `canConnect` | `EditResult Function(DiagramConnectionIntent)` | Whether a connection may be made, from hovering a port to committing the connector. | Each rule returns `const EditResult.allow()` or `EditResult.denied(reason: ...)`; a denied edit publishes nothing and the verb returns the denial. Pass the rules as `DiagramController(configuration: DiagramConfiguration(rules: ...))`, read them from `controller.diagram.configuration.rules` and replace them for every later edit with `controller.diagram.setRules(DiagramRules(...))`. ## Example ```dart final controller = DiagramController( document: document, configuration: DiagramConfiguration( rules: DiagramRules( beforeChange: (proposal) { if (readOnly) { return const EditResult.denied( reason: 'This drawing is read-only.', ); } return const EditResult.allow(); }, canConnect: (intent) => intent.source?.elementId == intent.target.elementId ? const EditResult.denied(reason: 'No loops') : const EditResult.allow(), ), ), ); final changes = controller.diagram.changes; void onChange() => saveQueue.add(changes.value!.after); changes.addListener(onChange); // On host disposal: // changes.removeListener(onChange); ``` ## Fixed domain validation A document validator is a `beforeChange` rule over the proposed document: ```dart DiagramController( document: document, configuration: DiagramConfiguration( rules: DiagramRules(beforeChange: (proposal) => validate(proposal.after)), ), ); ``` `beforeChange` checks changed candidates, including previews, imports and undo/redo. It does not run on the initial document; validate content before constructing the controller. Lock checks run before layout, so an edit denied by a lock is never resolved. Return `allow()` for `DiagramChangePhase.preview` to check only commits; history, imports and verbs performed outside a lease always commit. Rules must not edit the drawing. Asynchronous validation requires a separate preparation contract; returning a `Future` from a rule is unsupported. ## `DiagramChangeProposal` The argument to `beforeChange`. Read this immutable event in your callback; `elements` is calculated only when requested. | Property | Type | Meaning | | --- | --- | --- | | `before` | `DiagramDocument` | Operation baseline, not the previous pointer or IME preview. | | `after` | `DiagramDocument` | Proposed content after the edit. | | `scene` | `ResolvedScene` | Geometry matching the proposed document. | | `currentDocument` | `DiagramDocument` | Current content, including the previous preview when applicable. | | `currentScene` | `ResolvedScene` | Geometry matching the current document. | | `phase` | `DiagramChangePhase` | `preview` or `commit`. | | `origin` | `DiagramDocumentChangeOrigin` | Entry path listed below. | | `operationId` | `int` | Diagram-local identity retained across previews and final commit. | | `historyOperationId` | `int?` | Original accepted operation being undone or redone; null for other edits. | | `participant` | `DiagramParticipant` | Initiating participant captured with the operation: the submitting controller's `participant`, defaulting to `DiagramParticipant.local`. Attribution, not authentication. | | `label` | `String` | Operation label. | | `elements` | `DiagramChangeSet` | Baseline-to-candidate delta carried from the transaction. | ## `EditResult` | Member | Arguments | Result | | --- | --- | --- | | `const EditResult.allow()` | None | `allowed == true`, `reason == null`. | | `const EditResult.created(String id)` | Created identity | `allowed == true`; `id` names the created element or part. | | `const EditResult.denied({DiagramDenialCode code = DiagramDenialCode.policy, String? reason})` | Optional category and explanation | `allowed == false`; a categorized denial for host handling. The code defaults to `policy`. | | `bool allowed` | Read-only property | Whether admission succeeded. | | `String? reason` | Read-only property | Optional denial explanation. | | `DiagramDenialCode? code` | Read-only property | Null for success; stable category for denial. | | `String? id` | Read-only property | The identity a creating verb reported; null otherwise. | | `void requireAllowed()` | None | Returns normally when allowed; otherwise throws `DiagramChangeDenied`. | The denial categories are `policy`, `locked`, `unavailableTarget`, `invalidSelection`, `unsupportedOperation`, and `conflict`. Branch on `code`, not the human-readable reason. `DiagramChangeDenied.result` contains the rejected `EditResult`. Its string representation uses the reason when supplied. ## `DiagramDocumentChange` The value of `diagram.changes`. Read this immutable event in your listener; `elements` is calculated only when requested. | Property | Type | Meaning | | --- | --- | --- | | `before` | `DiagramDocument` | Baseline before the completed edit. | | `after` | `DiagramDocument` | Accepted content after the edit. | | `scene` | `ResolvedScene` | Geometry matching the accepted document. | | `label` | `String` | Completed operation label. | | `origin` | `DiagramDocumentChangeOrigin` | `transaction` (a verb), `import`, `interaction` (a gesture lease), `batch` (a cumulative lease or `batch`), `undo`, or `redo`. | | `operationId` | `int` | Matches the admission proposal for this operation. | | `historyOperationId` | `int?` | Original accepted operation being undone or redone; null for other edits. | | `participantId` | `String` | The `id` of the participant captured by the admission proposal; resolve it with `diagram.participantById`. | | `history` | `bool` | Whether the edit recorded a history entry; `false` for `batch(history: false)`. Hosts can skip autosave or dirty-marking for these. | | `elements` | `DiagramChangeSet` | Baseline-to-final delta carried from the transaction. | ### `DiagramChangeSet` | Property | Type | Meaning | | --- | --- | --- | | `insertedIds` | `Set` | Identities added to the document. | | `removedIds` | `Set` | Identities removed from the document. | | `updatedIds` | `Set` | Existing identities whose elements changed. | | `reorderedIds` | `Set` | Surviving identities whose canonical order changed. | | `reparentedIds` | `Set` | Updated identities whose owner changed. | | `orderChanged` | `bool` | Element order changed, including insertion or removal. | Sets are unmodifiable. `DiagramElementChangeSet` remains an alias. The diagram derives the delta once from the transaction's proven edits, visiting only changed elements; `DiagramChangeSet(before, after)` compares independent snapshots completely. Replacing the document identity treats all old elements as removed and all new elements as inserted, even when local element IDs match. ## Document admission `beforeChange` receives a `DiagramChangeProposal` containing the operation's `before` document, validated candidate publication, currently published snapshot, label, origin, phase and operation ID. Its `after` document and lazy `elements` delta describe the actual candidate, including indirectly removed elements. Return `EditResult.allow()` or `EditResult.denied(reason: reason)`. The rule cannot rewrite the candidate or synchronously mutate the diagram. Transformations belong in explicit transactions. An exception aborts admission and propagates to the caller; it never becomes an implicit allow. | Entry path | Admission behavior | | --- | --- | | `perform` and typed verbs | Checks locks and `expectedRevision`, then the proposed edit, before history or publication changes. Invalid arguments are denied with `unsupportedOperation` before admission. | | `setValues` | Ordinary verb admission. Invalid value fields/types/ranges reject before publication. | | `beginInteraction` / shape widget `beginValueEdit` | Returns a lease; each preview and the final `commit` use the gesture rules below. | | Gesture preview | Checks baseline-to-candidate with `preview` phase. Denial restores the baseline while retaining gesture ownership for recovery. | | Gesture commit | Rechecks with `commit` phase. Denial restores the baseline and closes the gesture without a history entry. | | Cumulative lease (text composition, `batch`) | Checks provisional changes, then checks the complete operation when the lease commits. Final denial restores the lease baseline and prior redo branch. | | `load` | Checks the complete replacement and expected revision through the same pipeline. | | Undo and redo | Checks the actual restoration before advancing history. | | Another controller's preview | An edit touching an element another controller is previewing is denied with `DiagramDenialCode.conflict` before rules run. An edit without history is admitted and the preview is rebased onto it. | | Cancellation | Always restores the baseline, without consulting admission. | | Camera, selection, options and layout refresh | Plain controller methods such as `setCamera`, `select` and `setOptions`; not undoable, not admitted, and available without document permission. | Admission owns lock and revision checks: a locked target is denied with `DiagramDenialCode.locked`, and a stale `expectedRevision`, which every verb accepts, is denied with `DiagramDenialCode.conflict`. Direct methods throw `DiagramChangeDenied` on denial; calls through `controller.edits` report it in the result. The result-oriented methods on `controller.edits`, including `batch`, `setProperty`, `undo` and `redo`, return an `EditResult`; a creation verb reports the new identity in `id` only when the content was inserted. `dispatch` is the low-level hook that verb implementations submit through; applications perform verbs. Operation IDs are local to the diagram. A lease, such as a gesture or composition, retains its ID across previews and final admission. The element delta is the one the operation produced; reading it does not scan the document. ## Completed changes and live state Read the controller's observable getters, such as `document` and `scene`, inside an `Observer` for that controller's live state, including its interaction previews and provisional text composition. Use `diagram.changes` for completed verbs, committed leases, undo and redo. Cancellation does not emit a completed change. `diagram.changes` is a `ValueListenable` notified once per completed change from every controller on the diagram. Any number of independently owned consumers can add and remove listeners; it excludes camera and selection updates, and its listeners are released when the diagram is disposed. `change.participantId` names the participant that made the edit (`diagram.participantById` resolves it). Changing rules, options or the canvas bounds does not replace these subscriptions. `change.operationId` matches the admission proposal for that operation. Lease previews keep the same ID through their final commit. Undo and redo each receive a new ID. IDs are local to the diagram's lifetime, not persistent document IDs or globally unique audit identifiers; a denied proposal has no corresponding completed change. A cumulative lease commits when composition finishes or when an unrelated edit, undo or new interaction takes over. Its event contains the complete baseline-to-final delta. If final admission is denied, the unrelated operation is also left unapplied; submit a fresh intent against the restored state. Observers cannot synchronously edit the drawing. Queue later work as a separate verb. All observers receive the publication before callback failures are forwarded to the current error zone. ## Embedded control edits Widget controls use the same rules as headless verbs. There is no separate widget persistence or authorization callback. | Control action | Live state | Completed `diagram.changes` | | --- | --- | --- | | `shape.setValues(patch)` | Performs `setValues` as one admitted edit. | One event for a nonempty accepted edit. | | `shape.beginValueEdit().preview(patch)` | Previews `setValues` on a lease, relative to the gesture baseline. | None until commit. | | `edit.commit()` | Rechecks commit admission. | One baseline-to-final event if accepted and changed. | | `edit.cancel()` or denied commit | Restores the baseline. | None. | Here `shape` is the `ShapeWidgetContext` supplied to the native control builder. The corresponding controller verb is `controller.edits.setValues(elementId, patch)`; for a continuous value edit outside a shape widget, perform `setValues` on a `beginInteraction` lease. A continuous slider should use a value edit so persistence sees one completed operation instead of every pointer sample. Observe the controller's live `document` in an `Observer` when a host preview needs to follow each sample. Compare `ShapeElement.values` in `before` and `after` for IDs in `elements.updatedIds`; this is not a field-level diff. Check permissions in admission, not the widget’s `enabled` flag. A denied commit restores the gesture baseline without adding history. ## Interactions on a canvas Canvas input goes through verbs and rules; the canvas has no separate callbacks. - **Shape regions.** A `ShapeSurface` whose `onInteract` names a verb of its shape performs that verb, without arguments, when a tap ends inside the region. See [shape regions](/agent-docs/api/canvas.md#shape-regions). - **Connections.** Dragging a connector asks `canConnect` from port hover to commit. Observe the result through the controller's observable `document`, `selection` and `isInteracting`, or `diagram.changes` for the committed connector. - **Paste.** A `DiagramFlutterExtension` with a `paste` handler receives text pasted when no copied diagram content is available, such as Mermaid source. Browser gestures supply their clipboard text; native keyboard requests pass `null` so the handler reads the clipboard. Return `true` when handled. ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), DiagramFlutterExtension( id: 'app.paste', paste: (controller, text) async => importText(controller, text), ), ], ), ); ``` `canCreate` and `canConnect` filter their respective intents. They are not universal permission gates: edits that are not creation or connection intents skip them but always pass through `beforeChange`. Put application-wide mutation rules in `beforeChange`. Rules are read-only. Nested verbs, ID allocation, disposal and rule evaluation throw `StateError`; perform later verbs after the rule returns. Failure leaves the controller usable. Verbs reject disposed controllers. External host side effects cannot be rolled back. ## Ownership and lifetime Replace rules with `diagram.setRules`. Add listeners to `diagram.changes` and remove them when their host is disposed. For persistence, use `diagram.changes` so document edits made without a mounted surface, or by another controller, are also observed. Never mutate during admission or observer delivery. Advanced ownership adapters are documented in [API reference](/agent-docs/api/index.md). Initial document loading does not run rules or replay creation events. Authorizing access to a snapshot belongs to the host. Rules are synchronous client-side controls; asynchronous approval and server authorization remain host responsibilities. See [persistence and imports](/agent-docs/api/persistence.md) for revision-checked replacement. ## Verbs versus rules Use a [verb](/agent-docs/api/verbs.md) for an edit initiated by a button, key or painted region. Use `beforeChange` to admit or deny the resulting edit and `diagram.changes` to observe publication. A verb cannot bypass the rules. --- # API reference For day-to-day integration, start with the [common tasks map](/agent-docs/guide/common-tasks.md). It covers verb outcomes, extensions and options, and platform capabilities. See [all packages](/packages) for the package list and registry version badges. Choose a reference by the object or operation you are working with. [Hello world](/agent-docs/guide/hello-world.md) shows the six core concepts in one program, and the [getting started guide](/agent-docs/guide/getting-started.md) covers your first canvas. [Libraries](#libraries) says which import holds each type. ## Vocabulary The API uses one word per concept. A **diagram** holds a **document** of **elements**: **shapes**, standalone **text** and **connectors**, plus one shared history. Each actor edits it through its own **controller**. A **definition** describes a shape type, a **library** groups definitions, and an **extension** installs them. Every edit is a named **verb**, performed through the controller: `createShape`, `add`, `connect`, `move`, `resize`, `rotate`, `delete`, and `set…` for single properties; `batch` makes several verbs one undo step. Selection, camera and tool change through plain controller methods such as `select` and `setTool`, which are not undoable. See the full [vocabulary](/agent-docs/guide/vocabulary.md). ## Start here [Diagram and controller](/agent-docs/api/controller.md), [everything the controller can do](/agent-docs/api/controller-reference.md), [extensions and options](/agent-docs/api/configuration.md), [writing extensions](/agent-docs/api/extensions.md), and [ownership and lifetimes](/agent-docs/api/ownership.md). ## Shapes and content - [Shape definitions](/agent-docs/api/shapes.md) - [Plain Text](/agent-docs/api/text.md) - [Rich Text](/agent-docs/api/rich-text.md) - [Tables](/agent-docs/api/tables.md) - [Widgets inside shapes](/agent-docs/api/widgets.md) - [Shape behavior](/agent-docs/guide/shape-capabilities.md) - [Shapes library](/agent-docs/api/extension-shapes.md) ## Connections and layout - [Connectors](/agent-docs/api/connectors.md) - [Routing extensions](/agent-docs/api/extension-connectors.md) - [Arrowheads](/agent-docs/api/extension-arrowheads.md) - [Graph layout](/agent-docs/api/layout.md) - [Layout algorithms](/agent-docs/api/extension-layout.md) ## Viewport and canvas - [Canvas and editor](/agent-docs/api/canvas.md) - [Navigation and motion](/agent-docs/api/navigation-and-motion.md) - [Grids and snapping](/agent-docs/api/grids.md) ## Editing and integration - [Verbs](/agent-docs/api/verbs.md) - [Undo and redo](/agent-docs/api/history.md) - [Verbs and shortcuts](/agent-docs/guide/verbs.md) - [Rules and changes](/agent-docs/api/hooks.md) - [Controllers and collaboration](/agent-docs/api/collaboration.md) - [Domain diagnostics](/agent-docs/api/diagnostics.md) ## Data and output - [Persistence and imports](/agent-docs/api/persistence.md) - [Export](/agent-docs/api/output.md) - [Headless text](/agent-docs/api/headless-text.md) ## The object model | Object | Responsibility | | --- | --- | | `DiagramDocument` | Immutable authored shapes, standalone text, connectors, parent relationships, text stories and styles. | | `FramedElement` | Shared placement and transform contract for shapes and standalone text. | | `TextElement` | Standalone text, plain or rich according to its registered type, with a required story and no shape appearance fields. | | `TextElementDefinition` | The core's standalone text geometry (bounds, layers, sizes and interaction capabilities) for one installed text type; an extension contributes the text type through `textTypes`, and `registry.requireText(type)` reads the definition. Engine-level: in `adapter.dart`. | | `ShapeDefinition` | One shape type's anatomy: outline, body parts, values, ports, container, collapse and behavior. In `extension_api.dart`. | | `ShapeRegistry` | Immutable, validated collection of definitions, plus connector capabilities. In `extension_api.dart`. | | `ShapeElement` / `ConnectorElement` | Authored instances with stable IDs. A shape's `type` selects its definition. | | `Diagram` | The shared committed document and resolved scene, one history, installed extensions and their options, rules, participants, document changes and lifetime. | | `DiagramController` | One actor (`DiagramParticipant`) on a diagram: its selection, active tool, camera, in-progress edit, verbs, per-controller undo/redo and subscriptions. | | `DiagramExtension` | Installs shapes, tools, verbs, codecs and options, in the configuration's one `extensions` list; `DiagramFlutterExtension` (in `extension_api.dart`) adds canvas behavior. | | `DiagramRules` | The application's `beforeChange`, `canCreate` and `canConnect` admission rules. | | `DiagramConfiguration` | What a diagram is and allows, immutable and shared per document: installed extensions, canvas bounds (`CanvasBounds`), fonts, rules and license. | | Options | Typed values, such as `GridOptions`, each owned by one installed extension and holding all of its settings; read with `controller.options()`, changed with `controller.edits.setOptions(...)`. | | `DiagramCanvas` | The bounded Flutter widget that displays one controller; it edits when an editable extension such as `EditorExtension()` is installed. | A controller supports one mounted canvas at a time. Content operations also work without mounting it; camera and visual animation commands need a mounted canvas. Several controllers can share one diagram, for example a user and an agent: each has its own selection and undo, and an element one controller is previewing is leased from the others. Synchronization across processes is not provided; see [collaboration](/agent-docs/api/collaboration.md). ## Use the toolkit Start with one import in a Flutter application: ```dart import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ``` | Task | API | | --- | --- | | Start editing | Create a `DiagramController` and display it with `DiagramCanvas`. | | Create content | `controller.createShape`, `createText`, `connect`, `add`. | | Change appearance | `controller.setStyle`, `controller.setOpacity` and text formatting verbs. | | Edit objects | Movement, resize, grouping, clipboard and deletion verbs, or any verb by name with `controller.perform`; `batch` for one undo step. Selection through `controller.select` and `controller.setSelection`. | | Undo or redo | `controller.edits.undo()`, `controller.edits.redo()`. | | Save or load | `controller.save(DiagramJsonCodec.new)`, `controller.edits.load(json, format: DiagramJsonCodec.new, ...)`. | | Export | `controller.exportSvg(...)`, `controller.exportPng(...)`. | | Move the view or play effects | `controller.view.show(ViewTarget.element(...), motion: Motion.smooth)` and `controller.effects.play(...)`. | | Add domain concepts | Register shape definitions, values, ports, verbs and widget builders; use the same verbs. | A domain extension adds its own meanings and validation to these building blocks. It does not need a second selection, connection, history or export system. For plain Dart agents, see the [agent guide](/agent-docs/agents/index.md). ## Libraries Every package's main library is the application surface: what you need to build, edit, save and display diagrams. Authoring an extension, or reaching into the engine, takes an explicit second import, so an application's autocomplete shows only application types. | Library | Import it when you | Contains | | --- | --- | --- | | `package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart` | build a Flutter application | `Diagram`, `DiagramController` and its verbs, `DiagramExtension`, rules, the document model, geometry, selection, text model, tools, layout, output and codec types (everything in `package:vyuh_diagram_core/vyuh_diagram_core.dart`), plus `DiagramCanvas`, `controller.view` and `controller.effects`, `DiagramTheme`, `Motion`, `NavigationExtension`, `ImagesExtension` and `DiagramJsonCodec`. | | `package:vyuh_diagram_core/vyuh_diagram_core.dart` | work in pure Dart (servers, agents, CLIs) | The same application surface without Flutter. | | `package:vyuh_diagram_flutter/extension_api.dart` | write shapes, text types, tools, verbs, connectors, properties or Flutter extensions | `ShapeDefinition` and its parts, `ShapeLibrary`, value fields, `DiagramTextDefinition`, `DiagramToolDefinition`, `DiagramVerb`, `DiagramConnectorDefinition`, route providers, `DiagramProperty`, `DiagramExtensionRegistry`, the resolved scene, plus `DiagramFlutterExtension`, shape widget builders, `DiagramKeyBinding`, property editors and `EffectDefinition`. It re-exports `package:vyuh_diagram_core/extension_api.dart`, the pure-Dart half. | | `package:vyuh_diagram_flutter/adapter.dart`, `package:vyuh_diagram_core/adapter.dart` | build engine tooling or low-level integrations | Transactions and steps, editor state, the resolver and render plan, diagnostics, painters, `RenderingExtension`, `TextElementDefinition` and other internals. Not needed by applications or ordinary extensions. | | `package:vyuh_diagram_flutter/testing.dart`, `package:vyuh_diagram_core/testing.dart` | write tests | Canvas surface keys, `editingExtension()` and `testRegistry(...)`. | Extension packages follow the same split: `vyuh_diagram_extension_editor.dart` for the editor chrome and `controls.dart` for inspector building blocks; `vyuh_diagram_extension_table.dart` and `vyuh_diagram_extension_rich_text.dart` for the extension and its typed verbs, and each package's `extension_api.dart` for its model, codec and layout. SVG export is its own import: `package:vyuh_diagram_codec_svg/vyuh_diagram_codec_svg.dart`. The [hello world](/agent-docs/guide/hello-world.md) needs only the Flutter main library and the editor. - [Verbs and keyboard bindings](/agent-docs/guide/verbs.md) - [Complete custom-library recipe](/agent-docs/guide/build-a-library.md) --- # Property inspector `DiagramInspector(controller: controller)` displays the properties supported by the current selection. Import it from `package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart`. The canvas and inspector share the same controller and registry. Everything the inspector shows is a property of the [property grammar](/agent-docs/guide/properties.md): built-in element, shape, connector, text and canvas properties, shape value fields, properties contributed by installed extensions and the host's own. An element property names the [verb](/agent-docs/api/verbs.md) that sets it, and each change performs that verb as one undoable edit. Canvas options, such as the grid, are not part of the document: the extension that owns them contributes their properties, they change through `controller.setOptions` and are not undoable. ## Shared properties | Section | Controls | | --- | --- | | Transform | Paired X/Y fields; Width, Height and Rotation in one row; aspect-ratio lock. | | Alignment | Left, horizontal center, right, top, vertical center and bottom; available for eligible multi-selections. | | Appearance | Whole-element opacity, independently of fill and stroke alpha. | | Shape properties | Fill, stroke, corner radius, geometry, declared values, image, text and extension sections such as tables. | | Connector properties | Registered route choices, port spacing and route options, independent start/end arrowhead sizes, and stroke. | | Text | Direction, font, color and size; marks, headings and lists when rich text is installed; paragraph alignment. | | Canvas | Finite canvas, grid visibility and type, snapping, grid resolution and rotation snapping. | Movement, resizing and rotation fields follow the element's behavior; fill, stroke, corner radius, text and value fields follow its anatomy. Locked elements expose their lock state instead of editing controls. Multi-selection exposes alignment, opacity and compatible kind-owned style, value and connector properties. Each selected kind must declare the field. Ranges and choices intersect; disjoint constraints show a reason and differing values display **Mixed**, without marking the first choice as selected. Opacity slider drags preview continuously and commit one undo entry. Cancelling or unmounting an unfinished control restores its baseline. Numeric inputs allow exact values without dragging. ## Customize the inspector | Parameter | Effect | | --- | --- | | `properties` | A `DiagramProperties` whose `sources` contribute your own properties. | | `editors` | `DiagramPropertyEditor.of` editors that render custom properties of value type `T`, ahead of the built-in ones. | | `icons` | Resolves the `DiagramIcon` names of your properties and options; declarations without a match draw their `svg` glyph. | | `searchable` | Offers a filter by property label. | Every field shows the denial of its last change under its control. See [properties and the inspector](/agent-docs/guide/properties.md) for a worked example. ## Whole-element opacity ```dart controller.setOpacity(0.6, ids: ['warehouse', 'delivery-route']); ``` `setOpacity(double opacity, {Iterable? ids})` accepts finite values from `0` to `1`. It applies one atomic, undoable edit; a missing or locked target rejects the selection edit. Fill and stroke colors retain their own alpha values. All canonical elements have an `opacity` property, including shapes, Plain Text, Rich Text, tables and connectors. It survives copying, duplication and JSON serialization; JSON requires it on every element. Flutter and SVG apply it to the element's rendered content. Transparent elements retain their hit geometry; selection handles and the text caret remain visible. On a focused editor canvas with selected elements, `1`–`9` set 10–90% and `0` sets 100%. Focused text fields and active text editing keep their normal typing behavior. Set 0% using the inspector or API. Opacity targets element IDs. Composed text/image slots and table cells do not have independent element opacity. Child elements owned by a frame retain their own opacity; changing the frame does not rewrite them. This is a durable appearance setting, not a playback or blinking API. ## Standard controls for editors Custom editors can use the same controls as the built-in ones. They, the `DiagramPropertyInspector` panel and the other `DiagramInspector*` building blocks are in the editor's controls library: ```dart import 'package:vyuh_diagram_extension_editor/controls.dart'; ``` A custom editor itself, `DiagramPropertyEditor`, is in `package:vyuh_diagram_flutter/extension_api.dart`. | Control | Purpose | | --- | --- | | `DiagramNumericProperty` | Compact labeled number with bounds, step and unit. | | `DiagramPropertyStepper` | Horizontal label/value numeric control. | | `DiagramPercentageProperty` | Slider and exact percentage input; nullable value displays Mixed. | | `DiagramVisualChoiceField` | Visual alternatives supplied by the caller. | | `DiagramInspectorControl` | Shared theme-derived control height. | | `DiagramInspectorSectionLabel` / `DiagramInspectorGap` | Consistent section hierarchy and spacing. | The percentage control separates drag preview (`onChanged`), drag completion (`onChangeEnd`) and exact-value submission (`onSubmitted`). Connect preview and completion to `field.begin()`, whose gesture previews the property's verb on an interaction lease so a drag remains one undo entry, and submission to `field.set`, which performs the verb once. The inspector reads connector routes and arrowheads from the installed registry; it does not maintain a second list of supported types. --- # Diagram JSON format A saved diagram is one JSON document, written and read by `DiagramJsonCodec` from `vyuh_diagram_codec_json`. The format has one version, `1`. The codec writes version 1 and reads only version 1. Save with `controller.save(DiagramJsonCodec.new)` and load with `controller.edits.load(json, format: DiagramJsonCodec.new, expectedRevision: ...)`. Both build the codec over the installed registry's codecs, so every extension's text attributes and content persist without extra wiring. Install the same extensions when loading. ## Rules The decoder is strict. Each of these throws `FormatException`: - `schema` is not `"vyuh.diagram"`, or `version` is not exactly `1`. - A key the encoder always writes is missing, or any key has the wrong JSON type. - An enum name is unknown, a coordinate is not finite, or a width or height is negative. - A record has a key this page does not list for it. This applies to the document, every element record (a `kind: text` record has no `type`, `values`, `style`, `ports`, `clipContent`, `isCollapsed` or `aspectLocked`) and every nested record, including attribute and content envelopes (`type`, `version`, `data`). The error names the key and its path, such as `Unknown key "extra" at elements[2].labels[0].` - Two contents of one story share an `id` or `slotId`. - A text element owns a child, or a connector binds to a named port on a text element. - An attribute or content envelope names a codec type that is not installed, or a version that codec does not read. Three maps are open: shape `values` and connector `routeOptions`, whose keys the installed definitions check on import, and an envelope's `data`, which its codec reads. Sparse keys may be omitted. The encoder omits them at their default, and the decoder restores that default: `parentId`, `isCollapsed`, `aspectLocked`, `textStory` on shapes, `textType`, `inkPreset`, `preserveRoute`, `routedPoints`, `routeOptions`, `bundleKey`, `portId`, `anchorMode`, `targetLayerId`, `connectedFill`, `slotId`, `attributes`, `contents`, `fontFamily`, `fontSize` and run `color`. Decoding checks the format only. `load` then admits the document against the installed registry and rejects it, leaving the current document in place, when an element ID is empty or repeated, a shape, text or connector type or a route is not installed, or shape values or route options do not match their declared fields. ## Document | Key | Type | Meaning | | --- | --- | --- | | `schema` | string | Always `"vyuh.diagram"`. | | `version` | integer | Always `1`. | | `id` | string | Document identity. | | `revision` | integer | Revision the document was saved at. | | `elements` | array | Shape, text and connector records. | A rectangle, a text element and a connector between them: ```json { "schema": "vyuh.diagram", "version": 1, "id": "doc-1", "revision": 3, "elements": [ { "kind": "shape", "id": "box", "type": "rectangle", "values": {}, "zIndex": 0, "isLocked": false, "isVisible": true, "opacity": 1, "frame": { "x": 0, "y": 0, "width": 160, "height": 100 }, "rotation": 0, "clipContent": false, "style": { "fill": 4294967295, "stroke": 4279308561, "strokeWidth": 2, "cornerRadius": 10, "strokeStyle": "solid" }, "textSizingMode": "fixedWidth", "ports": [] }, { "kind": "text", "id": "note", "zIndex": 1, "isLocked": false, "isVisible": true, "opacity": 1, "frame": { "x": 260, "y": 30, "width": 120, "height": 40 }, "rotation": 0, "textStory": { "id": "note-story", "blocks": [ { "id": "p1", "alignment": "start", "direction": "ltr", "role": "body", "runs": [{ "text": "Hello" }] } ] }, "textSizingMode": "fixedWidth" }, { "kind": "connector", "type": "connector", "id": "link", "zIndex": -1, "isLocked": false, "isVisible": true, "opacity": 1, "start": { "kind": "bound", "elementId": "box", "anchor": { "x": 0.5, "y": 0.5 } }, "end": { "kind": "bound", "elementId": "note", "anchor": { "x": 0.5, "y": 0.5 } }, "router": "straight", "controlPoints": [], "bend": 0, "terminalGap": 0, "color": 4279308561, "strokeWidth": 2, "strokeStyle": "solid", "startArrowhead": { "kind": "none", "width": 12, "height": 10 }, "endArrowhead": { "kind": "angle", "width": 12, "height": 10 }, "labels": [] } ] } ``` ## Elements Every record has `kind` (`shape`, `text` or `connector`), `id` (string), `zIndex` (integer), `isLocked` and `isVisible` (booleans), `opacity` (0 to 1) and an optional `parentId`. Shared values: | Value | JSON | | --- | --- | | Color | Unsigned 32-bit ARGB integer. | | Point | `{x, y}` finite numbers. | | Frame | `{x, y, width, height}`; width and height not negative. | | Fill | A color, or `{kind: "none"}`, `{kind: "linear", begin, end, stops}` or `{kind: "radial", center, radius, stops}`; each stop is `{offset, color}`. | | Text story | `{id, blocks, contents?}`. A block is `{id, alignment, direction, role, slotId?, attributes?, runs}`; a run is `{text, attributes?, fontFamily?, fontSize?, color?}`. | **Shape** (`kind: shape`). Required: `type` (installed shape type), `values` (object, see below), `frame`, `rotation`, `clipContent`, `style`, `textSizingMode` (`fixedWidth` or `autoWidth`) and `ports`. Optional: `isCollapsed`, `aspectLocked` and `textStory`. `style` is `{fill, stroke, strokeWidth, cornerRadius, strokeStyle, inkPreset?}`; `strokeStyle` is `solid`, `dashed`, `dotted` or `handDrawn`; `inkPreset` is `pen`, `brush` or `marker`. A port is `{id, side, offsetKind, offset, shape, width, height, fill, stroke, strokeWidth, targetLayerId?, connectedFill?}`, where `side` is `top`, `right`, `bottom` or `left` and `offsetKind` is `fraction`, `distanceFromStart` or `distanceFromEnd`. **Text** (`kind: text`). Required: `frame`, `rotation`, `textStory` and `textSizingMode`. Optional: `textType`, the installed text element type when it is not `text`. **Connector** (`kind: connector`). Required: `type` (installed connector type), `start`, `end`, `router` (installed route), `controlPoints`, `bend`, `terminalGap`, `color`, `strokeWidth`, `strokeStyle`, `startArrowhead`, `endArrowhead` and `labels`. Optional: `preserveRoute`, `routedPoints`, `routeOptions` and `bundleKey`. An endpoint is `{kind: "free", point}` or `{kind: "bound", elementId, anchor, portId?, anchorMode?}` with `anchorMode` `outline` or `point`. An arrowhead is `{kind, width, height}`. A label is `{id, story, fraction, offset, width, height, presentation}`; `presentation` is `{kind: "plain"}` or `{kind: "badge", fill, cornerRadius, padding, stroke, strokeWidth, strokeStyle}`. ## Extending the format Extensions add data in four places. The registry applies their codecs automatically; element records keep the same shape. **Shape values.** A shape's `values` holds exactly the fields its definition declares, each validated by its `ValueField`: | Field | JSON | | --- | --- | | `NumberValueField` | Finite number within its bounds; integral when declared integer. | | `TextValueField` | String, from its allowed values when declared. | | `ChoiceValueField` | String from its values. | | `BooleanValueField` | `true` or `false`. | | `ColorValueField` | ARGB integer. | | `ObjectValueField` | Object of finite JSON values. | | `PathValueField` | `{closed, nodes}`; a node is `{id, position, incoming, outgoing, mode, segment}` with `[x, y]` points, `mode` `corner`, `smooth` or `symmetric`, and `segment` `line` or `cubic`. | | `InkValueField` | `{points, widths?}`; `points` is a flat `[x0, y0, x1, y1, ...]` list in unit coordinates, `widths` one factor in (0, 2] per point. | | `ImageValueField` | `null` or `{uri, fit, fileName?}` with `fit` `contain`, `cover` or `fill`. | ```json { "type": "polygon", "values": { "sides": 5 } } ``` **Route options.** A connector's `routeOptions` maps option keys its route declares to values accepted by the option's `ValueField`. Omitted options use their default. ```json { "router": "orthogonal", "routeOptions": { "cornerRadius": 12 } } ``` **Text attributes.** A block's or run's `attributes` is an envelope written by the `DiagramTextCodec` of the text definition that owns them: `{type, version, data}`. ```json { "type": "richText", "version": 1, "data": { "kind": "orderedListItem", "nestingLevel": 1 } } ``` **Content.** A story's `contents` holds envelopes written by the `DiagramContentCodec` of each content type: `{type, version, data}`. Every codec in this SDK is version 1 and reads only version 1. ```json { "type": "vyuh.content.table", "version": 1, "data": { "id": "t1", "slotId": "table", "columns": [], "rows": [] } } ``` ## What each package contributes | Package | Contributes | | --- | --- | | `vyuh_diagram_core` | Shapes `rectangle`, `ellipse`, `card`, `group`, `frame`, `comment`; `path` and `line` with `path` (`PathValueField`); `polygon` with `sides` (`NumberValueField`, integer 3 to 20); `freehand` with `ink` (`InkValueField`); `image` with `image` (`ImageValueField`). Text element `text` (no attributes). Connector type `connector`, route `straight`. Arrowheads `none`, `angle`. Port shapes `circle`, `square`, `diamond`, `halfCapsule`. | | `vyuh_diagram_extension_shapes` | Shapes `shapes.start`, `shapes.end`, `shapes.subprocess`, `shapes.junction`, `shapes.parallelogram`, `shapes.trapezoid`, `shapes.cylinder`, `shapes.document`; `shapes.decision`, `shapes.preparation`, `shapes.extract` with `sides`; `shapes.entity` with `secondaryEnabled` (`BooleanValueField`). `shapes.arrow`: `direction` (`TextValueField`: `right`, `left`, `up`, `down`), `doubleHeaded`, `shaft`, `head`, `headWidth`. `shapes.star`: `points` (integer), `innerRadius`. `shapes.arc`: `closeToCenter`, `startAngle`, `sweepAngle`. `shapes.callout`: `pointer`, `depth`. Numbers are `NumberValueField`, flags `BooleanValueField`. | | `vyuh_diagram_extension_table` | Shape `table`. Content `vyuh.content.table`: `{id, slotId, cellPadding, outerBorder, rowBorder, columnBorder, merges, columns, rows}`; a border is `{color, width, style}`, a merge `{anchorCellId, rowSpan, columnSpan}`, a column `{id, width, borderAfter?}`, a row `{id, height, borderAfter?, cells}`, a cell exactly `{id, blocks}`. | | `vyuh_diagram_extension_rich_text` | Text element `richText`. Text codec `richText`: paragraph `data` is `{kind?, heading?, nestingLevel?, checked?, markerStyle?}`, omitting defaults, with `kind` `unorderedListItem`, `orderedListItem` or `checklistItem`, `heading` `h1` to `h6`, and `markerStyle` `disc`, `circle`, `square`, `decimal`, `lowerAlpha`, `upperAlpha`, `lowerRoman` or `upperRoman`; run `data` is `{marks}`, a nonempty list of `bold`, `italic`, `underline`, `strikethrough`, `superscript`, `subscript`. | | `vyuh_diagram_extension_connectors` | Routes `orthogonal` (options `terminalExtension` and `cornerRadius`, `NumberValueField` at least 0), `quadratic`, `bezier`. Arrowheads `triangle`, `filledTriangle`, `square`, `dot`, `diamond`, `invertedTriangle`, `bar`, `filledDiamond`, `cross`, `capsule`, `halfCapsule`. | Mermaid import, layout, editor, minimap and snap guides add nothing to the format: they produce or edit the records above. --- # Graph layout `controller.edits.layout(layout)` arranges root-level nodes with one of five layouts, as one undoable edit. A `Layout` names the layout and carries its options; the installed [`LayoutExtension()`](/agent-docs/api/extension-layout.md) performs all five. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), const LayoutExtension()], ), ); (await controller.edits.layout( Layout.layered(direction: LayoutDirection.right, gap: 60, layerGap: 100), )).requireAllowed(); ``` | Layout | Options | Places nodes | | --- | --- | --- | | `Layout.layered()` | `direction` (`down`, `up`, `left`, `right`), `gap`, `layerGap` | On layers along the direction with few edge crossings (ELK's layered algorithm). Connected components sit side by side. | | `Layout.tree()` | `direction` (`down`, `up`, `left`, `right`, `radial`), `gap`, `levelGap` | As a tidy tree: each parent centred over its children, subtrees packed without overlap, each level as deep as its largest node. `radial` puts the levels on rings, each subtree in a wedge of its parent's in proportion to its leaves. | | `Layout.force()` | `iterations`, `gap` | By Fruchterman–Reingold forces between node centres, with gravity that keeps disconnected parts close, then removes overlaps. | | `Layout.circular()` | `radius`, `gap` | On one circle in input order. A null `radius` is the smallest that keeps `gap` between neighbours. | | `Layout.grid()` | `columns`, `rows`, `flow`, `gap`, `rowGap`, `columnGap`, `cells` | In grid cells. Row and column sizes follow their largest node. | Every layout keeps `gap` between nodes (and `layerGap` or `levelGap` between layers or levels), is deterministic, and places nothing on top of another node. Options are validated when the layout is created: a negative or non-finite gap, a non-positive count or radius, or an empty or negative cell throws an `ArgumentError`. ## Trees from any graph A tree layout lays out a breadth-first spanning tree. Its roots are the nodes without incoming edges, in input order; a cycle that no root reaches starts at its first node. Each node sits one level below the node that first reached it, so every tree edge points in the layout's direction, and each tree sits beside the previous one. ## Grids `flow: GridFlow.rows` (the default) fills across each row and wraps after `columns` cells; `flow: GridFlow.columns` fills down each column and wraps after `rows` cells. When the wrapping count is null it is the node count divided by the other count, or the square root of the node count when both are null. Nodes beyond `rows × columns` add rows (row flow) or columns (column flow). `cells` places nodes by id, like CSS grid placement: `GridCell(row: 1)` puts a node in the first free cell of row 1, `GridCell(column: 3)` in the first free cell of column 3, and `GridCell(row: 1, column: 3)` in that cell. The other nodes fill the free cells in flow order. A lane is a row, a stage on a timeline is a column, and `gap: 0` packs the cells tightly. ```dart await controller.edits.layout( Layout.grid( gap: 32, cells: { 'plan': const GridCell(row: 0, column: 0), 'build': const GridCell(row: 1, column: 1), 'ship': const GridCell(row: 2, column: 2), }, ), ); ``` ## Locked nodes Locked nodes stay where they are and the other nodes are placed around them. The layout moves as a whole so that the first locked node keeps its position; other locked nodes become fixed obstacles that the remaining nodes move past. A force layout treats every locked node as a fixed obstacle in the simulation. Without locked nodes, the laid-out nodes keep the top-left corner of their bounds. ## Applying a layout `layout` applies all positions through one revision-checked `applyLayout` verb. Undo restores the previous arrangement. Pass `motion` for a mounted canvas to animate the nodes and their connectors to their new places; the document has the final positions at once: ```dart await controller.edits.layout(Layout.tree(), motion: Motion.smooth); ``` A document change, active edit, newer layout request, or `controller.cancelLayout()` prevents a pending result from being applied. Cancellation invalidates the result; it does not interrupt computation. Invalid or incomplete output cannot partially move the graph. The layout is denied with `unsupportedOperation` when no installed extension performs it. Layout uses resolved node sizes. Without `ownerId`, it arranges root nodes; `ownerId` arranges the direct children of a container in that owner's axes. Explicit `nodeIds` must be siblings. Moving a child-owning node translates its descendants together and preserves their offsets. Locked nodes remain pinned; internal edges inform placement and boundary bindings remain intact. ```dart await controller.edits.layout(Layout.grid(columns: 3), ownerId: 'swimlane'); ``` The layered layout uses the published pure-Dart [elk package](https://pub.dev/packages/elk). No JavaScript engine, worker script, npm dependency or network service is required. On native Dart platforms, layouts run in an isolate to keep computation off the UI thread. Flutter web executes the same Dart code in its compiled runtime; it yields before starting, but the calculation itself is synchronous, so measure representative graphs before laying out large ones interactively. ## Custom algorithms `GraphLayoutAlgorithm` performs one layout type, such as `TreeLayout`, and is part of `extension_api.dart` (`package:vyuh_diagram_core/extension_api.dart`, re-exported by `package:vyuh_diagram_flutter/extension_api.dart`). Extend it and implement `layout(GraphLayoutRequest request, L layout)` to return a `GraphLayoutResult` with one finite top-left position per requested node, keeping pinned nodes where they are. The request holds the node sizes, current positions, pins and directed edges. Install it with `DiagramExtension(id: 'app.layout', graphLayouts: [...])`; a diagram installs at most one algorithm per layout type. Synchronous and isolate-backed implementations use the same API. Try the [topology graph](/agent-docs/examples/topology.md) and the [layout gallery](/agent-docs/extensions/layouts.md). --- # License Attribution is built into the bottom-right of every drawing canvas, including viewers. There is no canvas option to hide or reposition it; a valid license removes it. ```dart final controller = DiagramController( configuration: DiagramConfiguration(license: licenseToken), ); DiagramCanvas(controller: controller); ``` `license` is a signed runtime license, not a private package-registry credential, and belongs to the diagram (`controller.diagram.configuration.license`), so every canvas on it honors it. Verification is offline. Invalid, missing, expired, or untrusted tokens leave attribution visible. ## Service contract and provisioning Runtime tokens use compact JWT with `alg: EdDSA`, `typ: JWT`, and a `kid` matching an SDK-pinned Ed25519 public key. Required claims are `iss` equal to `https://diagram.vyuh.tech`, `aud` equal to `vyuh_diagram`, a nonempty `sub`, integer Unix-second `iat` and `exp`, and an `entitlements` array containing `attribution.remove`. Optional `nbf` must not be in the future. **Production activation is pending key provisioning.** The SDK currently trusts no runtime signing keys. The licensing service must adopt this contract and its public key must be pinned before licensed removal can work. Test keys are never trusted by the shipped canvas. The private signing key stays on the server. Payloads are readable and must not contain secrets. Offline verification cannot detect immediate revocation or prevent a modified application from bypassing enforcement. --- # Navigation and motion Move the viewport with `controller.view` and play transient effects with `controller.effects`. Both act on the mounted canvas. Neither moves elements, changes the document, nor adds undo entries. Geometry verbs take the same [`Motion`](#motion) to [animate elements](#animated-geometry) to their new places. ```dart // Jump to the selection. controller.view.show(const ViewTarget.selection()); // Travel to an element. await controller.view.show(ViewTarget.element('review'), motion: Motion.smooth); // Particles flowing along a connector. final flow = controller.effects.play(const Effect.flow(), on: 'review-to-approval'); flow.stop(); ``` ## On this page | Category | What you can do | | --- | --- | | [Show a target](#show-a-target) | Jump or travel to a point, rectangle, element, region, the selection or everything. | | [Motion](#motion) | Choose how the viewport travels, and interrupt it. | | [Animated geometry](#animated-geometry) | Animate moved and resized elements. | | [Pointer and keyboard](#pointer-and-keyboard-navigation) | Configure edge auto-pan and Arrow-key movement. | | [Coordinates](#coordinates) | Convert pointer positions into drawing coordinates. | | [Read the view](#camera) | Observe camera position, zoom and viewport. | | [Observe changes](#presentation-listeners) | React to view and effect changes without tracking document edits. | | [Effects](#effects) | Play effects on shapes and connectors; see [Animation & effects](/agent-docs/api/effects.md). | ## Show a target ```dart Future show(ViewTarget target, {Motion? motion}) void stop() ``` `controller.view.show` moves the viewport to one target. Without `motion` it jumps; with `motion` it travels. The future completes with `true` once the target is shown, and with `false` when the target names missing content or the move is interrupted. | Target | Shows | | --- | --- | | `ViewTarget.point(point, {zoom})` | Centers a world point. Keeps the current zoom unless `zoom` is given. | | `ViewTarget.rectangle(rectangle, {padding = 48})` | Fits a world rectangle. | | `ViewTarget.element(id, {padding = 48})` | Fits an element's bounds. | | `ViewTarget.region(id, regionId, {padding = 48})` | Fits a named region of a shape or text element. | | `ViewTarget.selection({padding = 48})` | Fits the current selection. | | `ViewTarget.all({padding = 48})` | Fits every element in the diagram. | | Quantity | Meaning | | --- | --- | | `point`, `rectangle` | World coordinates in the document. | | `padding` | Logical screen pixels kept free on each side of the viewport. | | `zoom` | Scale factor: `1` means 100%; clamped to the camera's zoom limits. | `regionId` is a shape-layer definition ID or a text slot ID, such as a card's `title`. Rotated regions fit their axis-aligned world bounds. Fitting preserves aspect ratio and chooses the smaller of the horizontal and vertical scales within zoom limits. Finite canvas bounds may constrain the requested center. A target that names a missing element, region or an empty selection returns `false` and leaves the viewport where it is. Mount `DiagramCanvas(controller: controller)`, editable or view-only, before calling `show`; a detached or disposed controller throws `StateError`. For initial placement, wait until the canvas has completed its first layout, for example in a post-frame callback. The target is captured when the move starts; it does not follow an element that moves later. ## Motion ```dart const Motion({ Duration duration = const Duration(milliseconds: 450), MotionCurve curve = MotionCurve.easeInOutCubic, }) ``` `Motion` is a plain description in the core library, shared by the camera and the geometry verbs. A zero or negative duration presents the change at once. | Preset | Duration | Curve | | --- | --- | --- | | `Motion.none` | 0 ms | — | | `Motion.quick` | 200 ms | `MotionCurve.easeOut` | | `Motion.smooth` | 450 ms | `MotionCurve.easeInOutCubic` | | `Motion.slow` | 900 ms | `MotionCurve.easeInOutCubic` | `MotionCurve.cubic(x1, y1, x2, y2)` is an easing curve as CSS `cubic-bezier` describes it: from (0, 0) to (1, 1) through two control points whose x lies within 0 and 1; y may overshoot. The named curves are `linear`, `ease`, `easeIn`, `easeOut`, `easeInOut` and `easeInOutCubic`. ```dart final shown = await controller.view.show( const ViewTarget.region('approval', 'title', padding: 64), motion: const Motion( duration: Duration(milliseconds: 600), curve: MotionCurve.cubic(0.215, 0.61, 0.355, 1), ), ); if (!shown) { // The region is missing, or another move interrupted this one. } ``` Only one move runs at a time. Starting another move, a jump, `controller.view.stop()`, a user pan or zoom, or any other camera change such as `controller.setCamera` interrupts the current move, which then completes with `false`. `stop` leaves the camera where it is and is safe to call when nothing is moving. Unmounting the canvas also interrupts a move. A zero duration, or a device with animations turned off, shows the target immediately. Overshooting curves may overshoot position, but zoom stays within camera limits. Targets must have finite coordinates and zoom, and curves finite control points; an invalid target or curve completes with `ArgumentError` without changing the camera. ## Animated geometry `move`, `resize`, `setElementBounds` and `layout` accept a `motion`. The document takes the final geometry at once: undo, persistence, rules, agents and hit testing see the target. The mounted canvas then animates the rendered geometry from where it showed the elements to their committed place: ```dart controller.edits.setElementBounds( 'charger-load', const DiagramRect.fromLTWH(0, 100, 126, 8), motion: Motion.smooth, ); await controller.edits.layout(Layout.layered(), motion: Motion.slow); ``` | Aspect | Behavior | | --- | --- | | What moves | Every element the verb moved or resized, with its contents; text and ports follow. Many elements animate at once. | | Connectors | Attached connectors re-route every frame. Only the moving elements and their connectors are resolved again. | | Selection | Selection chrome follows the animated geometry. | | Pointer input | Hits the committed geometry, even mid-animation. | | A new change | Retargets smoothly from the shown frame. A change without motion jumps. | | Batches | Verbs inside a `batch`, including `batch(history: false)`, animate when the batch commits. | | Reduced motion | With the platform's reduce-motion setting (`MediaQuery.disableAnimations`), elements jump. | | No canvas | A headless controller ignores motion. | Verbs performed by name take a `Motion` or a preset name: `controller.edits.perform([id], 'move', {'delta': delta, 'motion': 'smooth'})`. ## Pointer and keyboard navigation While dragging an element, handle, marquee or connection, entering the padding inside a canvas edge starts auto-pan. Speed increases toward the edge and continues while the pointer stays there. Corners pan on both axes. Leaving the edge area, releasing or cancelling the drag stops auto-pan. Hover alone does not move the canvas. The active edit follows the camera and remains one undo step. Escape cancels the active gesture, including modifier combinations such as Space-drag panning, Shift rotation and Shift+Alt resizing. Document previews roll back without an undo entry; marquee selection returns to its starting selection. Panning stops at the current camera position. Remaining pointer movement and release cannot resume or commit the canceled gesture. With canvas focus, Arrow keys move selected elements by one world unit in the pressed direction. Shift+Arrow moves them by ten world units; holding a key repeats movement. With no selection, neither shortcut moves the canvas. Text editing and focused widget controls retain their own arrow-key behavior. Selection movement supports undo and respects locks and host admission. ```dart final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), NavigationExtension( edgePanEnabled: true, edgePadding: 48, maximumPanSpeed: 600, keyboardStep: 1, shiftMultiplier: 10, fitOnAttach: true, ), ], ), ); ``` `NavigationExtension` (id `vyuh.navigation`) owns `NavigationOptions`, with the same fields; without it the canvas uses these defaults, except `fitOnAttach`, which defaults to `false`. `fitOnAttach` fits the content when the canvas first has a viewport. Change the values at runtime with `controller.edits.setOptions(controller.options().copyWith(...))`. Distances use logical screen pixels; `maximumPanSpeed` uses pixels per second. Numeric values must be finite and positive. Set `edgePanEnabled: false` to disable pointer auto-pan. Fit canvas bounds still constrain navigation. Only move and resize drags auto-pan by default. Shape manipulators, custom controls, and other gestures leave the camera stationary. Custom tools can explicitly opt in with `DiagramToolGesture(autoPan: true, ...)`; `edgePanEnabled` remains the global gate. For touch pan and pinch, see [DiagramCanvas](/agent-docs/api/canvas.md#touch-navigation). ## Coordinates ```dart DiagramPoint screenToWorld(DiagramPoint screenPoint) DiagramPoint globalToWorld(Offset globalPosition) ``` | Method | Argument | Return | | --- | --- | --- | | `screenToWorld` | Point relative to the canvas's top-left, in logical pixels. | World point under that canvas position. | | `globalToWorld` | Flutter global pointer position, such as `details.globalPosition`. | World point under that pointer. | Both require a mounted canvas; `globalToWorld` also throws `StateError` before the canvas has been laid out. Do not pass a global pointer coordinate to `screenToWorld` when the canvas is embedded below a header or beside a panel. ## `camera` ```dart DiagramCameraState get camera ``` Returns this controller's camera snapshot. It is never `null`; until a canvas is mounted and laid out, `viewportSize` is zero. Check `isAttached` to know whether a canvas is mounted. The immutable snapshot exposes: | Property | Type | Meaning | | --- | --- | --- | | `center` | `DiagramPoint` | World point at the viewport center. | | `zoom` | `double` | Current projection scale. | | `viewportSize` | `DiagramSize` | Laid-out canvas size in logical pixels. | | `minZoom` | `double` | Lower zoom limit; camera-state constructor default `0.25`. | | `maxZoom` | `double` | Upper zoom limit; camera-state constructor default `4`. | `DiagramCameraState.copyWith(...)` creates a snapshot; it does not update a controller. Use `controller.view.show` to change the mounted camera. ## Observing the camera and effects `controller.camera` and `controller.effects.playing` are observable. Read them inside an `Observer` to rebuild when they change. The camera changes after each new camera state, including layout, user navigation and motion; identical camera geometry does not notify. Effects change when they start, change or stop, not on every frame. These observations are separate from document events and undo/redo. ```dart Observer( builder: (_) => Text('${(controller.camera.zoom * 100).round()}%'), ); ``` ## Effects `controller.effects` plays transient effects on the mounted canvas: flows and pulses along connectors, and pulses, halos, scaling and fades on shapes. See [Animation & effects](/agent-docs/api/effects.md) for the five kinds, their values, repeat counts, reduced motion and custom effects. ```dart final flow = controller.effects.play(const Effect.flow(), on: connectorId); controller.effects.play(const Effect.halo(), on: shapeId); flow.stop(); ``` ## Selecting inside groups Click an element in a group to select its group. Double-click it without modifiers to enter the group and select that child; subsequent clicks select children within that group. Press Escape to return to the containing group. **Cmd-click** (macOS) or **Ctrl-click** selects a child without entering its group; **Shift-click** adds or removes selection. Then drag, delete or edit the child normally without affecting siblings. Select a child before clicking its text to edit. On connection labels, Shift-click toggles the connector selection and Command/Ctrl-click selects the connector directly. These modified clicks do not start label editing. Use an unmodified double-click to edit the label. Outside text editing, modifier-clicking a checklist marker selects its text owner without checking or unchecking the item. An ordinary click still toggles it. --- # Output Both Flutter and pure Dart hosts use `controller.exportSvg(options)` and `controller.exportPng(options)`. Flutter supplies image loading and raster rendering. Pure Dart supplies SVG output with prepared resources; PNG requires a host `DiagramOutput` raster adapter and otherwise throws `UnsupportedError`. The playground includes an **Export diagram** menu for SVG and PNG downloads. Both are generated locally in the app. Exports contain the diagram bounds with padding, without selection handles, the minimap or other editor controls. Embedded widgets use their declared portable fallback. ## On this page | Category | What you can do | | --- | --- | | [Export PNG](#controller-exportpng) | Capture the drawing as an image. | | [PNG options](#pngoptions) | Choose bounds, scale and background. | | [Export SVG](#controller-exportsvg) | Export vector geometry and text. | | [Resources](#images-and-fonts) | Provide images and fonts for output. | | [Failures](#failures) | Handle unavailable or invalid resources. | ## SVG import `DiagramSvgInput` from `package:vyuh_diagram_codec_svg/input.dart` imports a supported subset into editable paths. Decode first, then add the returned `elements` in one `batch`, so the import is one undo step. Each import needs a unique `idPrefix`. ```dart import 'package:vyuh_diagram_codec_svg/input.dart'; final result = const DiagramSvgInput().decode(svg, idPrefix: 'logo'); controller.edits.batch('Import SVG', () { for (final element in result.elements) { controller.edits.add(element, select: false); } }); ``` The result also includes `warnings`: unsupported text, images, references and effects are omitted; groups are flattened and compound-path holes may differ. No scripts execute and no resources are fetched. Rectangles, ellipses, circles, lines, polylines, polygons, curve paths and basic transforms are supported. Export subsequently writes the imported diagram's supported geometry. The playground header offers **Import JSON** from a file and **Export JSON** in the same compact menu as SVG and PNG. JSON import replaces the canvas as one undoable edit. ## `controller.exportPng` ```dart Future exportPng( PngOptions options, { Object Function(DiagramImageSource)? imageProvider, }) ``` | Argument | Contract | | --- | --- | | `options` | Required positional crop, raster scale, background, and image-loading timeout. | | `imageProvider` | Optional resolver for authenticated or application-owned images. In Flutter, return an `ImageProvider`. | The committed drawing snapshot (`controller.diagram.snapshot`) is captured when called, before asynchronous image loading. Both exports validate finite, positive crop dimensions and positive resource limits before invoking the output backend. PNG also requires a finite, positive scale and finite, positive scaled dimensions. Invalid options fail the returned future with an `ArgumentError`, without loading resources or changing the drawing. Custom backends receive the same validation; backend-specific allocation limits still apply. ## `PngOptions` ```dart const PngOptions({ required DiagramRect bounds, double pixelRatio = 1, DiagramColor? background, Duration resourceTimeout = const Duration(seconds: 30), int resourceConcurrency = 4, int maximumDecodedImageBytes = 256 * 1024 * 1024, int maximumOutputPixels = 64 * 1024 * 1024, }) ``` | Property | Default | Contract | | --- | --- | --- | | `bounds` | Required | Finite world-space crop with positive width and height. Negative world positions are allowed. | | `pixelRatio` | `1` | Finite, positive raster scale; does not reflow text. | | `maximumOutputPixels` | 64 × 1024 × 1024 | Positive limit on rounded output width × height. Oversized requests fail with `ArgumentError` before invoking the output backend. Hosts may configure this limit. Flutter additionally caps output at 8192 pixels per side and 16 × 1024 × 1024 pixels overall; raising this option does not raise those limits. | | `background` | `null` | Transparent when omitted. | | `resourceTimeout` | 30 seconds | Positive image-loading timeout, not a deadline for the complete render. | | `resourceConcurrency` | `4` | Positive maximum number of simultaneous image loads. Failure or timeout stops queued loads. | | `maximumDecodedImageBytes` | 256 MiB | Positive budget for decoded source-image RGBA bytes retained during PNG output, deduplicated by URI. Exceeding it rejects export with `StateError`; images are never silently downsampled or omitted. | Options are immutable. Validation occurs during export, not in the const constructor. ## `PngSnapshot` | Property | Type | Contract | | --- | --- | --- | | `bytes` | `Uint8List` | Copied, unmodifiable PNG bytes. | | `documentId` | `String` | Captured document identity. | | `revision` | `int` | Captured document revision. | | `textLayoutRevision` | `int` | Captured scene's text-layout revision. | | `bounds` | `DiagramRect` | Requested world crop. | | `width` | `int` | `ceil(bounds.width * pixelRatio)` pixels. | | `height` | `int` | `ceil(bounds.height * pixelRatio)` pixels. | ## Example Export a captured document without mounting a canvas: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( document: document, configuration: DiagramConfiguration( extensions: [ DiagramExtension( id: 'app.backends', textLayout: FlutterDiagramTextLayoutEngine(), output: FlutterDiagramOutput(), ), ], ), ); final snapshot = await controller.exportPng( const PngOptions( bounds: DiagramRect.fromLTWH(0, 0, 1200, 800), pixelRatio: 2, background: DiagramColor(0xffffffff), ), ); // Hand these bytes to your application's save/share/download integration. final pngBytes = snapshot.bytes; ``` Bounds define a world-space crop; pixel ratio changes raster resolution without reflowing text. Background defaults to transparent. Empty documents use the requested background. Flutter limits output to 8192 pixels per side and 16 × 1024 × 1024 pixels overall, alongside the configured budget. Invalid or oversized requests fail before allocation. Headless adapters may impose different limits. The result contains immutable PNG bytes, pixel dimensions, world bounds, document ID, document revision and text-layout revision. Malformed PNG bytes from a custom output adapter throw `ArgumentError`; dimensions that disagree with the requested crop and scale throw `StateError`. Export captures the committed drawing snapshot when called, excluding uncommitted interaction previews from any controller. Later edits, navigation or controller disposal do not retarget an in-flight export. Calling it after disposal fails. Export draws shapes, connectors, labels, ports and clipping exactly as the canvas does, at full detail. Grid, selection, hover, text-entry placeholders and editor overlays are excluded. Runtime animation effects and arbitrary Flutter widget overlays are not canonical document content and are not included. ## Images and fonts Images load the same way they do on the canvas. Export waits for them and rejects the first failed load immediately (even while other images remain pending), or a resource timeout (30 seconds by default), rather than painting a loading placeholder. A host can pass `imageProvider` to supply an authenticated or application-owned Flutter `ImageProvider` for each `DiagramImageSource`. Text must already have Flutter-shaped line and marker geometry in the captured scene. Normal `DiagramController` instances provide this. Custom integrations must supply compatible text layout; see [API reference](/agent-docs/api/index.md). Load application fonts before constructing the controller or calling `controller.diagram.refreshLayout()`; export preserves the captured shaping, including any font fallback already present, and does not silently reshape it after an asynchronous font load. ## Failures | Condition | Result | | --- | --- | | Call after controller disposal | Synchronous `StateError`. | | Invalid crop, scale, timeout, or excessive pixel allocation | Future fails with `ArgumentError`. | | Mismatched document and geometry or missing Flutter text geometry | Future fails with `StateError`. | | Image loading fails | Future propagates the loading failure. | | Image loading exceeds the timeout | Future fails with `TimeoutException`. | | PNG encoder returns no bytes | Future fails with `StateError`. | Rendering failures propagate. Temporary render resources are released on success or failure. For custom renderers that already own a resolved document, see [API reference](/agent-docs/api/index.md). ## Output limits Exports capture a static drawing. Runtime animation and arbitrary native widget pixels are excluded; widgets use their portable content. The host owns file names, saving and sharing. PNG output is limited to the dimensions described above and does not tile oversized images. ## `controller.exportSvg` ```dart Future exportSvg( SvgOptions options, { Object Function(DiagramImageSource)? imageProvider, }) ``` Captures the committed drawing snapshot before asynchronous image loading. Later edits, navigation, and controller disposal do not change the export. Calling after disposal throws `StateError`. Images load the same way they do on the canvas and in PNG export. | Argument | Contract | | --- | --- | | `options` | Required positional `SvgOptions`. | | `imageProvider` | Optional resolver for authenticated or application-owned images; in Flutter, return an `ImageProvider`. Decoded images are embedded as PNGs. | ### `SvgOptions` | Property | Type / default | Contract | | --- | --- | --- | | `bounds` | Required `DiagramRect` | Finite, positive world-space crop. Does not reflow content. | | `resourceTimeout` | `Duration(seconds: 30)` | Positive deadline for image loading and encoding into embedded PNG resources; excludes final SVG serialization. | | `resourceConcurrency` | `4` | Positive maximum number of simultaneous image loads. Failure or timeout stops queued loads. | | `maximumDecodedImageBytes` | `256 * 1024 * 1024` | Positive budget for decoded source images during export. Exceeding it fails export with `StateError`; images are not replaced with placeholders. | | `maximumResourceBytes` | `64 * 1024 * 1024` | Positive combined byte budget for all supplied font faces and embedded images, before base64 expansion. Images are counted once per URI. Exceeding it fails export with `StateError`. | | `fonts` | Empty `Iterable` | Host-prepared faces, copied into an immutable list. The codec embeds referenced weight/style faces. If an exact face is unavailable, supplied family variants remain available for viewer fallback. | ### `SvgSnapshot` | Property | Type | Contract | | --- | --- | --- | | `svg` | `String` | Self-contained SVG source. The host owns saving/downloading. | | `documentId` | `String` | Captured document identity. | | `revision` | `int` | Captured document revision. | | `textLayoutRevision` | `int` | Captured scene text-layout revision. | | `bounds` | `DiagramRect` | Requested crop. | ```dart final snapshot = await controller.exportSvg( SvgOptions(bounds: DiagramRect.fromLTWH(0, 0, 1200, 800)), ); final svgSource = snapshot.svg; ``` Invalid XML text rejects before image loading begins. Resource errors propagate immediately, even if another image is still pending; a loading deadline fails with `TimeoutException`. Temporary images are released on success or failure. No document commands or camera changes occur. Widget slots export their declared portable fallback, not a screenshot of the mounted widget. Native text inside those fallbacks is included. For a publication already captured by the host, `package:vyuh_diagram_flutter/adapter.dart` exposes `exportDiagramSvg(publication, options: options, imageProvider: provider)` and `exportDiagramPng` with the same result and lifetime contract. ## Pure Dart SVG export Import `package:vyuh_diagram_core/vyuh_diagram_core.dart` and `package:vyuh_diagram_codec_svg/vyuh_diagram_codec_svg.dart`, install `SvgExtension()`, and use the same controller export verb: ```dart final result = await controller.exportSvg( SvgOptions( bounds: DiagramRect.fromLTWH(0, 0, 1200, 800), ), ); // result.svg contains the SVG document. ``` For image content, install `SvgExtension(resources: preparedResources)` in the configuration's `extensions`. `DiagramSvgResources` contains prepared PNG images and font bytes. This adapter does not fetch or decode resources. Missing required images and unsupported content reject the export, including outside the crop. Resource preparation remains the host's responsibility. The result captures the committed document and text-layout revision before asynchronous export begins. Custom `DiagramOutput` adapters must return that captured document identity, document revision, text-layout revision and requested crop. The controller rejects mismatched metadata with `StateError`, including when an adapter completes after the diagram changes or is disposed. Supported content includes shape outlines, fills and styled borders, pressure ink, region fills, dividers, ports, connector bodies, terminal markers, shadows and embedded PNG image layers. Owner transforms, intersecting ancestor clips and the canvas's separate border/port/marker passes are preserved. Native ``/`` output includes standalone text, shape stories, list markers and connector labels. It preserves captured line breaks, alphabetic baselines, text-region and ancestor clips, foreground colors, font sizes/families and run marks. Label badges retain fill, border and corner geometry in the final label pass. Runtime animations, grids, hover and selection are excluded. Unknown resolved element/outline implementations and XML-incompatible characters reject export. The SVG viewer shapes the native characters. Glyphs, font fallback, ligatures and spacing can differ from Flutter; this is **not** an outline-level or pixel-identical text snapshot. Export does not ask SVG to wrap paragraphs again. Justified lines use the captured line width with SVG `textLength`/spacing adjustment; the viewer's gap distribution may differ. Superscript/subscript retain the same OpenType `sups`/`subs` features used by the canvas, so support depends on the font. Pure-Dart bootstrap measurements remain approximate; provide a font-aware layout backend when exact host line breaks are required. PDF output is not implemented. ### Image resources `DiagramSvgScene.imageSources(scene)` validates supported scene content and returns an immutable, URI-deduplicated list of `DiagramImageSource` values to prepare. It performs no I/O and rejects unsupported content even outside the crop. ```dart import 'package:vyuh_diagram_codec_svg/vyuh_diagram_codec_svg.dart'; final resources = DiagramSvgResources(images: { imageSource.uri: DiagramSvgImage(decodedPngBytes), }); final svg = DiagramSvgScene.encode(scene, bounds: crop, resources: resources); ``` | Object / property | Contract | | --- | --- | | `DiagramSvgImage(pngBytes)` | Snapshots static PNG bytes; rejects malformed containers, invalid dimensions, CRC errors, APNG and unknown critical chunks with `ArgumentError`. | | `image.width`, `image.height` | Intrinsic PNG pixel dimensions. | | `image.pngBytes`, `image.dataUri` | Immutable bytes and self-contained `data:image/png;base64,...` content. | | `DiagramSvgResources(images: ...)` | Immutable URI-to-image map. The codec does not fetch URLs or load files. | The producer must supply decodable PNG pixels; container validation does not inflate or validate the IDAT pixel stream. Decode/transcode other image formats before constructing a resource. The original URI is only an identity key and is never emitted as a remote SVG image reference. Declared contain, cover and fill behavior uses the same resolved layer rectangle and clipping. An image slot without an authored source retains the canvas's portable placeholder. Shadows use the declared color, local offset and Gaussian sigma before the shape fill, under the same owner and ancestor transforms. Independent SVG rendering has been checked for image fitting and shadows; exhaustive renderer and font parity across viewers remain open. ## Embedded font resources ```dart final face = SvgFont( family: 'IBM Plex Sans', bytes: fontBytes, format: SvgFontFormat.ttf, weight: 400, ); final snapshot = await controller.exportSvg( SvgOptions(bounds: crop, fonts: [face]), ); ``` | Member | Contract | | --- | --- | | `SvgFont(family:, bytes:, format:, weight: 400, style: SvgFontStyle.normal)` | Immutable font bytes. Malformed or mismatched font containers are rejected. | | `format` | `ttf`, `otf`, `woff`, or `woff2`; must match the supplied container. | | `family` | Nonempty name matching the authored `TextRun.fontFamily`. | | `weight` / `style` | Weight from 1 to 1000; style `normal` or `italic`. Supply separate faces as needed. | | `bytes` / `dataUri` / `cssRule` | Immutable bytes, embedded data URI and safely escaped `@font-face` declaration. | | `DiagramSvgResources(fonts: [...])` | Pure codec resource collection. Family matching and duplicate detection ignore casing; duplicate family/weight/style faces reject. | The host supplies valid font bytes it can embed; neither codec nor controller fetches fonts. Without a supplied face, the viewer resolves the named family; runs without a family use `sans-serif`. Embedded font support varies by SVG consumer. The encoder escapes family names as literal CSS strings and never accepts raw CSS or remote font URLs. Image loading uses `imageProvider`; it does not resolve fonts. Applications export through `controller.exportSvg` or `controller.exportPng`. --- # Controller ownership and lifetime Create one DiagramController per editor. `DiagramController(document:, configuration: DiagramConfiguration(extensions:))` creates and owns a Diagram; other actors, such as an agent or a second canvas, join it with `DiagramController(diagram: controller.diagram, participant: DiagramParticipant.agent(id: ..., name: ...))`. Mount a DiagramCanvas with a controller; it edits when an editable extension such as EditorExtension is installed; only one canvas may own a controller at a time. Unmounting the canvas preserves the document. Dispose each controller when its host is disposed. Disposing a controller that joined a diagram releases only its selection, previews and listeners. Disposing the controller that created the diagram disposes the diagram and every controller on it, so dispose the joined controllers and unmount their canvases first. Content verbs work without a mounted canvas. Camera, coordinate conversion and animation operations require a mounted presentation. Capture `controller.diagram.snapshot` before disposal when retaining the committed document and resolved geometry. Core owns headless editing; Flutter supplies the public canvas and platform input. Optional UI supplies DiagramInspector and ready-made controls. Portable and Flutter extensions are installed in the configuration's one `extensions` list. See [controller](/agent-docs/api/controller.md), [extensions and options](/agent-docs/api/configuration.md) and [writing extensions](/agent-docs/api/extensions.md). ## Extensions own their elements end to end An extension that introduces an element owns all of it in its own package: the model and its persistence codec, layout and paint contributions, verbs and properties, on-canvas affordances, icons and any Flutter UI. Rich text owns its paragraph and run attributes and `RichTextCodec`; connectors own the orthogonal, quadratic and bezier route identities (`ConnectorRoutes`); snap guides own alignment snapping. A package is split only by platform: `x` holds the pure Dart extension and `x_flutter` its widgets, as with `vyuh_diagram_extension_table` and `vyuh_diagram_extension_table_flutter`. Behaviour that the core extension points can express stays pure Dart, so most extensions need no Flutter package. Core, Flutter, the codecs and the editor only define extension points, such as `TextParagraphAttributes`, `DiagramTextCodec`, `DiagramConnectorRouteProvider`, `DiagramMoveAdjuster`, `ShapeDefinition.affordances` and `DiagramIcon`. They never depend on an extension, not even for tests. Test an extension in its own package with `package:vyuh_diagram_core/testing.dart`, whose `testRegistry(...)` assembles a grammar from test contributions. See [extensions](/agent-docs/api/extensions.md). --- # Persistence and imports JSON persistence lives in `vyuh_diagram_codec_json`; SVG export lives in `vyuh_diagram_codec_svg`. Shared adapter contracts and output values belong to `vyuh_diagram_types`. Headless controllers depend on neither codec implementation. A document format is a `DiagramDocumentFormat`: a function that builds a `DiagramDocumentCodec` over the installed extensions' model codecs. The JSON format is `DiagramJsonCodec.new`, from `vyuh_diagram_codec_json.dart`. Pass it to `controller.save(...)`, `controller.edits.load(...)`, or `DiagramController.open(...)`; the diagram supplies its registry's codecs, so the content and text attributes each extension owns persist without wiring. For another format, pass its own format function the same way. Headless SVG export requires installing `SvgExtension()` from `package:vyuh_diagram_codec_svg/vyuh_diagram_codec_svg.dart` in the configuration's `extensions`; `vyuh_diagram_flutter` does not re-export it. JSON preserves authored content for reopening; SVG exports a resolved scene and does not provide a lossless document round trip. Save with `controller.save(DiagramJsonCodec.new)` and restore with `controller.edits.load(json, format: DiagramJsonCodec.new)` or `DiagramController.open(json, format: DiagramJsonCodec.new)`. Install the same extensions when restoring, so their shapes, content and text attributes decode. The [JSON format](/agent-docs/api/json-format.md) page specifies the document. Connectors may carry an optional `bundleKey`, an explicit key for collapsed-frame connection presentation. The key does not merge or replace the underlying connectors. A frame's `isCollapsed` state is persisted while its expanded geometry, descendants, and original connector bindings are retained. Paths from explicit elbow rerouting, editable path nodes, multi-stop linear/radial fills and point-anchor bindings are also persisted. Point anchors store normalized frame coordinates, so they remain attached through owner transforms. ```dart final json = controller.save(DiagramJsonCodec.new); ``` `save` encodes `controller.document`, which includes that controller's own in-progress preview. Save outside an interaction, or encode the committed content every controller shares: ```dart final json = DiagramJsonCodec(controller.diagram.registry.codecs) .encode(controller.diagram.document); ``` Camera state, options such as the grid, rules and runtime path animations are controller or diagram state, not saved document content. ## On this page | Category | What you can do | | --- | --- | | [Load a document](#open-or-load-a-document) | Open JSON as a new controller, or load it into a live one. | | [Handle rejection](#rejection-and-recovery) | Keep the existing document when an import fails. | | [Format version](#format-version) | Understand which persisted version is read. | | [JSON format](/agent-docs/api/json-format.md) | Read the document keys and extension data. | ## Open or load a document To open saved JSON as a new controller in Flutter or plain Dart, pass the format and the extensions that own the document's content: ```dart final controller = DiagramController.open( json, format: DiagramJsonCodec.new, configuration: DiagramConfiguration( extensions: [EditorExtension(), TableFlutterExtension()], ), ); ``` The controller validates initial content against the registry and starts with empty history; opening adds no history entry. Malformed JSON throws `FormatException`. Install the extensions that register the document's custom shapes. To load into a live controller, call `controller.load`. `expectedRevision` is optional: omit it to replace without a conflict check, or capture the revision **before** waiting for a file or server response so a document that changed meanwhile is denied with `DiagramDenialCode.conflict`: ```dart final expectedRevision = controller.document.revision; final json = await loadFile(); // Supplied by your application. final result = controller.edits.load( json, format: DiagramJsonCodec.new, expectedRevision: expectedRevision, ); if (!result.allowed) { showMessage(result.reason ?? 'Import was not allowed.'); } ``` Without `format`, `data` must already be a `DiagramDocument`: `controller.edits.load(document, expectedRevision: ...)`. Replacement is one verb, performed like any other edit. It validates the imported content against the diagram's registry, consults the `beforeChange` rule, clears the current selection and emits one completed change with `import` origin. Undo restores the previous document and selection; redo restores the imported document. Current camera and options remain in place. Imported revision numbers are normalized to the diagram's monotonic revision sequence. An import replaces the whole document, so it is denied with `DiagramDenialCode.conflict` while another controller is previewing an edit. A different document ID represents a different identity scope. Even if both documents contain a shape named `shape-1`, the change delta reports removal from the old document and insertion into the new one. ## Rejection and recovery | Stage / condition | Result | Recovery | | --- | --- | --- | | `load` or `open` with `DiagramJsonCodec.new`: malformed JSON, missing fields, invalid enum/value, or a `version` other than the current one | `FormatException` | Correct the input or use a reader supporting that format. The diagram has not been changed. | | `load`: stale `expectedRevision` | `EditResult` with `code == DiagramDenialCode.conflict` | Resolve the conflict or reload. Do not blindly retry with the newest revision. Publication and existing redo remain unchanged. | | Candidate fails registry or geometry validation | Validation exception | Correct the candidate or use its intended registry. The existing publication and history remain unchanged. | | The `beforeChange` rule denies import | `EditResult` with `allowed == false` | Display `reason` if provided. No replacement, completed-change event or history entry is added. | | Replacement during this controller's own interaction | `StateError` | Commit or cancel the interaction first; import cannot take over its lease. | | Another controller is previewing an edit | `EditResult` with `code == DiagramDenialCode.conflict` | Retry after that controller commits or cancels. | | Controller already disposed | `StateError` | Use a live controller. | `load` with a `format` decodes before attempting replacement, so a malformed file reports a format error even if its captured revision is also stale. The controller decodes, then validates and replaces the candidate once. Successful replacement during text editing closes the old editor. A stale text client cannot mutate reused IDs in the imported document. Opening data as a new `DiagramController` validates its snapshot but does not emit an import operation, run rules or replay creation events. Authorizing access to the initial snapshot belongs to the host. ## Current boundaries This API replaces a complete snapshot. It does not merge two documents, remap pasted IDs or synchronize concurrent agents. Clipboard verbs (`copy`, `paste`) retain their separate merge semantics while using the same admission. [PNG output and SVG scene output](/agent-docs/api/output.md) are available; full-content SVG and PDF output remain incomplete. Runtime animation bindings are not imported or reset by snapshot replacement; hosts that bind presentation to document identity should update those bindings from the import change event. ## Format version The JSON format is version 1: `DiagramJsonCodec.currentVersion` is 1, the codec writes version 1, and a document with any other `version` throws `FormatException`. The [JSON format](/agent-docs/api/json-format.md) page specifies every key, what the decoder rejects and what each extension adds. ## Standalone text `TextElement` is written as `kind: text`, with frame, rotation, parent, stacking order, required story and sizing mode. Run colors persist directly. Paragraph and run attributes an extension owns, such as rich text's list kinds and marks, are written by that text's `DiagramTextCodec` inside a `{type, version, data}` envelope; decoding them requires the owning extension to be installed. Shape-only fields are absent; the codec rejects shape-specific fields on `kind: text` records. ## Object lock persistence Every shape, text element, and connector carries a required boolean `isLocked`. Copies preserve the flag unless explicitly changed; malformed flags are rejected. The diagram enforces locks for new changes and inherited ownership. The inspector exposes a lock toggle and hides editing fields while locked. Undo/redo replays admitted history and still consults host admission. ## Label borders Badge labels carry required, validated `stroke`, `strokeWidth`, and `strokeStyle` fields. Plain labels cannot carry decoration. ## Shape values Every shape requires a `values` object, empty when unused. It persists with history and copies. A shape's per-kind data lives here too: a path's `path`, a drawing's `ink`, an image's `image` and a polygon's `sides`, each written by its value type's `toValue()`. Values support null, booleans, strings, finite numbers, lists and string-keyed maps. Nested data is copied and frozen; widgets and callbacks cannot be serialized. Files with missing, null or non-object `values` are rejected, as are non-finite numeric values. The codec preserves custom keys without interpreting them; the restoring registry and diagram admission own their semantic validation. Text elements do not carry shape values. --- # Rich Text extension Every text slot is filled by exactly one **text definition**: a shape's `ShapeText` part, a table's cells, a connector's labels and a standalone text element. There are two: - `PlainTextDefinition` (type `text`, in core): runs and paragraph breaks, with inline font, size and color. No lists, headings or marks. - `RichTextDefinition` (type `richText`, from the optional Rich Text extension): marks, headings, lists, checklists and font sizing, as its `RichTextGrammar` allows. Both take `maxLines`: `1` is a single line (Enter finishes editing), `N` allows at most N typed paragraphs (soft wrapping does not count), and `0`, the default, is unlimited. Both share the engine's selection, transforms, history and persistence. ## Install Rich Text explicitly ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), RichTextExtension()], ), ); final id = controller.createRichText( at: const DiagramPoint(200, 120), text: 'Edit this Rich Text', ); // Mount DiagramCanvas(controller: controller). // Dispose the controller when its owner is disposed. ``` The Flutter foundation defaults to Plain Text. The Rich Text package is an optional commercial extension; it is not a runtime dependency of Flutter or core. `RichTextExtension({grammar = const RichTextGrammar(), tool = true})`, id `vyuh.rich_text`, contributes the rich text type allowing `grammar` through `textTypes`, and its creation tool unless `tool` is false. Because text elements are a core concept, installing the rich text type is what makes standalone `richText` elements: their element `type` is the text type's name. The core card, standard shapes, connector labels and the default `text` element stay plain until an application reconfigures them, as [Rich text in shapes](#rich-text-in-shapes) shows. ## Compose Rich Text inside a shape ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final note = ShapeDefinition( type: 'app.note', body: ShapeColumn([ const ShapeText( 'title', text: 'Plain title', textType: PlainTextDefinition(maxLines: 1), ), const ShapeText( 'body', text: 'Formatted body', textType: RichTextDefinition(grammar: RichTextGrammar(headings: false)), ), ]), ); final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), RichTextExtension(), DiagramExtension(id: 'app.notes', shapes: [note]), ], ), ); ``` Each slot selects its own text and editing behavior; a slot without `textType` holds plain text. A table chooses the text of all its cells with `ShapeTable(..., textType: ...)`, and a connector its labels with `ConnectorLabelingCapability(textType: ...)`. Admission rejects paragraphs a slot's text does not admit, such as a list item in a plain slot or a second paragraph in a single-line slot. ## Rich text in shapes A shape declares its text parts; which text fills them is configuration. `ShapeDefinition.withText(text, {slot})` returns a copy of a shape whose text parts hold `text`: every text part, or only the one filling `slot`. The shape never checks what is installed and never changes by itself. The copy keeps its type, so an application that installs it in its own extension replaces the definition it was made from, a core shape's included: ```dart const rich = RichTextDefinition(); final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ EditorExtension(), RichTextExtension(), DiagramExtension( id: 'app.rich_shapes', shapes: [ ShapeLibraries.standard.shape(Shapes.comment).withText(rich), ShapeLibraries.standard.shape(Shapes.rectangle).withText(rich), // Only the card's description; its title stays one plain line. ShapeLibraries.standard .shape(Shapes.card) .withText(rich, slot: 'body'), ], ), ], ), ); ``` Comments, rectangles and cards then take headings, marks, lists and checklists through the same shortcuts, input rules and inspector controls as standalone rich text, and the Comment tool creates rich comments. An application's own comment-like shape works the same way, either declaring `ShapeText('body', textType: const RichTextDefinition())` or configuring a plain declaration with `withText`: ```dart final note = ShapeDefinition( type: 'app.note', name: 'Note', body: const ShapeText( 'body', verticalAlignment: DiagramTextVerticalAlignment.top, placeholder: 'Write a note…', ), ); DiagramExtension( id: 'app.notes', shapes: [note.withText(const RichTextDefinition())], ); ``` The rules: - **Replacing a core shape.** An application extension's definition for a core shape type replaces the core default. Two application extensions defining the same type still fail assembly. - **Rich text must be installed.** Every text type a shape, table, connector label or text element holds must be installed; `RichTextExtension()` installs rich text, with its codec, verbs and tool. A shape configured for rich text without it fails assembly with an `ArgumentError` naming the shape and slot. - **Saved documents.** A rich shape persists paragraph and run attributes in the rich text envelope, `{"type": "richText", "version": 1, "data": …}`. Plain text is rich text without attributes, so documents saved with plain comments load unchanged into rich comments and save back byte for byte. The reverse is strict, as JSON loading is everywhere: rich attributes in a shape configured for plain text are rejected, never silently dropped. Without `RichTextExtension()` decoding throws a `FormatException` (no codec for `richText`); with it, admitting the document throws a `StateError` because the plain slot does not admit the attributes. ## What the Rich Text definition contributes `RichTextDefinition` owns everything rich about the slots it fills: - `RichTextGrammar`: which marks, headings, lists, checklists and font sizes the slot allows. - Keyboard shortcuts for marks, sizes, headings and lists, and Tab to nest list items. - Input rules that turn a typed `- `, `* `, `1. ` or `[] ` into a list item. - Paragraph editing: Enter continues or exits a list, Backspace unlists an empty item. - List and checklist markers, heading presentation and accessible descriptions. - Inspector controls for marks, headings and lists. - Story verbs: `setMark`, `setHeading`, `setList`, `changeIndent`, `adjustFontSize`, `clearFormatting` and `setChecked`, declared by `RichTextDefinition.storyVerbs`. Every element holding rich text offers them, including shapes whose table cells are rich, without registering anything on an extension. Standalone text elements share the core's standard placeholder, sizes and behavior. For text with its own sizes or behavior, such as `ShapeBehavior(rotatable: false, resizable: false)` to remove rotation and resize handles, place a rich `ShapeText` in a shape instead. See [shape behavior](/agent-docs/guide/shape-capabilities.md). ## Why there is no separate Rich Text Flutter package Formatting changes portable text runs and paragraphs; it is not a Flutter widget. The text definition decides what a key chord means. The shared Flutter adapter paints the resulting text, manages selection and IME, translates physical keys, and offers each chord to the text filling the edited slot. Plain text handles no formatting chords. The Rich Text extension needs no custom painter or overlay, so it has no separate Flutter extension. A future floating formatting toolbar, custom popup, or Flutter-specific overlay would contribute a `DiagramFlutterExtension`. That UI belongs in an optional Flutter/UI package; model formatting rules remain in the pure Dart Rich Text extension. Not every extension requires a second package. JSON persists authored text data. SVG consumes the shared resolved text output. Neither format requires a Flutter widget to interpret the Rich Text definition. ## Editing verbs Perform range and paragraph formatting [verbs](/agent-docs/api/verbs.md) on the controller, by name or through the typed `RichTextVerbs` extension on `DiagramController`, available once the Rich Text package is imported. See the [text reference](/agent-docs/api/text.md) for exact signatures, scope and denial handling. A rich verb is denied unless every touched paragraph is in a rich text slot whose grammar admits the result. Installing Rich Text does not turn any plain slot into Rich Text. | Verb | Arguments | Symmetry | | --- | --- | --- | | `setMark` | `mark: TextMark`, `on: bool` | setter | | `setHeading` | `heading: HeadingLevel` | setter | | `setList` | `kind: ParagraphKind`; `ParagraphKind.paragraph` removes the list | setter | | `changeIndent` | `delta: int` | setter | | `adjustFontSize` | `delta: double` | setter | | `clearFormatting` | none | derived, reversed by `replaceText` | | `setChecked` | `blockId`, `checked: bool` | setter | Every verb except `setChecked` also accepts `storyId`, `start` and `end`. There are no toggle verbs: a toggle control performs the setter with the opposite of the current value, such as `setMark(..., on: !isBold)`. ```dart controller.edits.setMark(elementId: id, mark: TextMark.bold, on: true); controller.edits.perform([id], 'setHeading', {'heading': HeadingLevel.h2}); ``` ## Text inside any shape Named `ShapeText` slots let a card have separate title and body regions while keeping one canonical story. A slot whose text has `maxLines: 1` holds one paragraph and exits editing on Enter; a rich single-line slot accepts inline formatting only. A multiline rich slot supports paragraphs, nested ordered/unordered lists and checklists. Default line height is 1.2. Wrapped visual lines share that line height; successive authored blocks have a separate 6-unit after-gap. The final block adds no trailing gap to the text box. Empty paragraphs retain the same line and caret geometry as populated paragraphs. The platform keyboard follows the active region: single-line slots request a text keyboard with a Done action; multiline slots request a multiline keyboard with a Newline action. Done exits a single-line slot without inserting a paragraph. Moving between slots updates the existing IME connection; ordinary caret movement does not reconfigure it. These platform-contract checks do not certify real-device mobile selection, keyboard viewport handling or IME behavior. Inside an active text region, touch-and-hold selects a word; dragging after the hold extends selection by whole words using the same resolved geometry as mouse selection. A finger move before the hold threshold does not perform mouse-style drag selection. A second finger transfers control to canvas navigation and exits text editing through the shared lifecycle. Selection handles, a mobile clipboard menu and keyboard occlusion remain open; touch navigation and text selection still need real-device validation. Text reflows in each declared region. The definition's text sizing policy decides whether the owner grows or retains its bounds. Display, selection and editing consume the same resolved lines rather than measuring a separate text widget. ## The rich text model The text model in `vyuh_diagram_types` is generic. A `TextParagraph` holds runs, alignment, direction, role and slot, plus optional extension-owned `TextParagraphAttributes`. A `TextRun` holds text, font family, size and color, plus optional `TextRunAttributes`, which contribute to the portable `TextRunAppearance` (weight, italic, underline, strikethrough and script) that shaping, painting and export read. Rich text owns its structure and marks. `ParagraphKind`, `HeadingLevel`, `TextMark` and `DiagramListMarkerStyle` come from the Rich Text package's main library, stored as `RichParagraphAttributes` and `RichRunAttributes`. Code that builds or reads rich paragraphs directly imports `package:vyuh_diagram_extension_rich_text/extension_api.dart`, which holds the attributes, the builders below, `RichTextFormatting`, `RichTextMarkers`, `RichTextCodec`, `richTextVerbs`, `richTextProperties` and `RichTextIcons`: | API | Purpose | | --- | --- | | `richParagraph(id:, runs:, kind:, heading:, nestingLevel:, checked:, markerStyle:, ...)` | A paragraph with rich structure; all-default structure carries no attributes. | | `richRun(text, marks: {...}, fontFamily:, fontSize:, color:)` | A run with marks; no marks carries no attributes. | | `RichTextParagraph` on `TextParagraph` | `kind`, `heading`, `nestingLevel`, `checked`, `markerStyle` and `copyWithRich(...)`. | | `RichTextRun` on `TextRun` | `marks` and `withMarks(...)`. | | `RichTextCodec` | Persists the attributes; `RichTextDefinition.codec` returns it. | ```dart import 'package:vyuh_diagram_extension_rich_text/extension_api.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; final item = richParagraph( id: 'item', kind: ParagraphKind.checklistItem, runs: [richRun('Pack lunch', marks: {TextMark.bold})], ); final checked = item.copyWithRich(checked: true); ``` Plain text admits no attributes. Every installed text definition's `codec` joins `DiagramExtensionRegistry.codecs`, so saving through `controller.save(DiagramJsonCodec.new)` writes rich attributes in a `{type, version, data}` envelope and reopening requires Rich Text to be installed. ## `TextRun` ```dart TextRun( String text, { TextRunAttributes? attributes, String? fontFamily, double? fontSize, DiagramColor? color, }) ``` | Property | Default | Meaning | | --- | --- | --- | | `text` | Required | Inline text, with UTF-16 offsets used by editing verbs. | | `attributes` | `null` | Extension-owned inline presentation, such as rich text's marks. | | `fontFamily` | `null` | Inherits the renderer's font family. | | `fontSize` | `null` | Uses the standard diagram font size. | | `color` | `null` | Inherits the text region foreground; an explicit color paints the glyphs, not the owner rectangle. | `copyWith` preserves omitted properties. Explicit `null` clears `fontFamily`, `fontSize`, or `color` back to inheritance. Colors persist through JSON, text splitting, merging, and paragraph editing. Clear formatting also clears the explicit color. Inspector formatting follows the current selection across all text owners: | Selection | Inline properties (font, size, color, marks) | Paragraph properties | | --- | --- | --- | | Text range | Only selected characters, including ranges across blocks | Blocks touched by the range | | Caret while editing | Next typed characters; existing content is unchanged | The caret's block | | Element or connector label | The whole story | All applicable blocks; titles retain their single-line contract | Formatting is stored in canonical runs and blocks and survives JSON export/import. Caret-only typing preferences belong to the mounted text editor until text is inserted; they are not serialized as document content. ## Paragraph verbs For inline formatting in rich text, use `controller.edits.setMark(elementId: id, mark: TextMark.bold, on: true)` or `controller.edits.clearFormatting(elementId: id)`. Both accept optional `storyId`, `start = 0`, and `end` arguments. Omit the range to affect the story's text, or supply UTF-16 offsets to format selected characters only. Range endpoints may be supplied in either order and are clamped to the story. Unselected runs and paragraph structure are preserved. Clear formatting removes explicit marks, font, size, and color from the selected text. A collapsed range does not change document formatting or configure future typing. Format paragraphs through controller verbs without building replacement stories. These verbs work for shape text, text boxes, and connector labels. | Verb | Formatting argument | Purpose | | --- | --- | --- | | `setTextAlignment` | positional `ParagraphAlignment` | Align ordinary paragraphs. | | `setTextDirection` | positional `ParagraphDirection` | Set reading direction. | | `setList` | `kind: ParagraphKind` | Make ordered, unordered, or checklist items, or ordinary paragraphs with `ParagraphKind.paragraph` (rich text). | | `changeIndent` | `delta: int` | Adjust list nesting (rich text). | Each requires the element ID (positional for the core verbs, `elementId:` for the rich verbs) and accepts an optional `storyId`, `start = 0`, and optional `end` UTF-16 offsets. Omitted `end` reaches the story's end. A range ending at the next paragraph's start excludes that paragraph. Lists retain fixed alignment. ```dart controller.setList( elementId: textId, kind: ParagraphKind.checklistItem, ); ``` For shapes, text boxes, and connectors with one label, the story is inferred. Supply `storyId` for a connector with multiple labels; omitting it denies the edit without changing any label. The same inference applies to `setChecked`, which still requires `blockId`. Verbs return an admission result and record a changed operation as one undo entry. Locked or unavailable targets are denied, and invalid arguments are denied with `DiagramDenialCode.unsupportedOperation`. A list control performs `setList` with `ParagraphKind.paragraph` when the paragraphs are already of that kind, restoring ordinary paragraphs. ## The `replaceText` verb Publishes one replacement story through the same admission and history pipeline for shape text, standalone text and connector labels. Build `after` with the pure `DiagramTextCommands` helpers, then perform the verb by name with the current `before` story. It has no typed wrapper; `setText` is the typed text setter. ```dart controller.edits.perform([id], 'replaceText', { 'before': before, 'after': after, 'label': 'Edit text', // Optional. 'selectionAfter': selection, // Optional StorySelection. }); ``` | Argument | Contract | | --- | --- | | `id` | Owning element ID. For a connector label, this is the connector ID; `before.id` identifies its label story. | | `before` | Current canonical story. A stale story is denied with `conflict` without publishing or adding history. | | `after` | Replacement with the same story ID. The target's paragraph/region grammar is validated before publication. | | `label` | Description of the history operation. | | `selectionAfter` | Optional text selection referring to this element and story. A different identity is denied with `unsupportedOperation`. Anchor and focus offsets are independently clamped to the resulting story's UTF-16 length, preserving range direction. | The result is an `EditResult`: missing, locked or noneditable targets are denied, as are edits rejected by host admission. `requireAllowed()` converts a denied result into `DiagramChangeDenied`. Calls through a disposed controller throw `StateError`. To combine it with other edits in one undo step, call it inside `controller.batch`. Rich text verbs such as `clearFormatting` build on it, so `replaceText` expresses their reverse. The published document, resolved scene and mapped selection agree before observers receive the update. Undo/redo restores the admitted story and selection; offset correction does not create another history entry. This verb does not mount an editor, request keyboard focus or establish an IME connection. See the [range-formatting example](/agent-docs/examples/formatting.md) for a complete call. ## Lists and checklists The paragraph inspector offers bullets, numbers and checklists. While editing, it changes the selected paragraphs; with an element selected, it changes the applicable story blocks. Single-line regions do not accept lists. | Input at the start of a paragraph | Result | | --- | --- | | `- ` or `* ` | Bulleted item | | `1. ` | Numbered item | | `[] ` or `[ ] ` | Unchecked checklist item | | Enter after an item | Next item of the same kind and nesting level; new checkboxes start unchecked | | Tab / Shift+Tab | Nest beneath the preceding item / outdent | | Enter on an empty item | Outdent one level, or leave the list at the root | | Click a checkbox | Toggle its checked state, with undo/redo | Prefixes also work before existing text: move to the start, type the marker and its trailing space, and the paragraph becomes a list item while retaining its text and formatting. The caret stays before that text. Immediate Backspace restores the literal marker. Typing elsewhere in an existing line does not automatically convert it. These shortcuts are shared by all multiline paragraph regions. Each slot's `RichTextGrammar` controls allowed list kinds; shortcut spellings are fixed. List kinds can be mixed at nested levels. Kind, nesting depth, checked state, and formatted text runs persist through document JSON export/import. ## Grammar configuration Inline appearance is validated at the same story-admission boundary for every text owner. A run's `fontSize` may be `null` (inherit) or finite and strictly positive. Its `color` may be `null` or an unsigned 32-bit ARGB value, including transparent. These validity rules do not clamp authored text to inspector font size limits. Invalid edits and imports throw `StateError` before publication. Direct paragraph-layout calls also validate their placement inputs before shaping: region slot IDs must be nonempty and unique, bounds must be finite with nonnegative dimensions, and block spacing and list indentation must be finite and nonnegative. Region foreground and default font size must be valid. Invalid layout arguments throw `ArgumentError`; duplicate slots are never silently merged. | Rule | Configuration | | --- | --- | | Plain versus rich text of a shape slot | `ShapeText.textType` | | Plain versus rich text of table cells | `ShapeTable.textType` | | Plain versus rich text of connector labels | `ConnectorLabelingCapability.textType` | | Single-line, limited or unlimited paragraphs | `maxLines` on `PlainTextDefinition` or `RichTextDefinition` | | Allowed marks, font sizes, headings, bulleted, numbered and checklist blocks | `RichTextDefinition.grammar` (`RichTextGrammar`) | | Maximum list nesting depth | No host-configurable limit yet | | Input shortcut spellings | Shared built-in mapping; not configurable yet | Each slot chooses its text; there is no registry-wide text grammar. A note with a plain title and a rich body that allows bullets and numbers but not checklists: ```dart import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; final note = ShapeDefinition( type: 'app.note', body: ShapeColumn([ const ShapeText('title', textType: PlainTextDefinition(maxLines: 1)), const ShapeText( 'body', textType: RichTextDefinition( grammar: RichTextGrammar(checklists: false), ), ), ]), ); ``` `RichTextGrammar` permissions (`bullets`, `numberedLists`, `checklists`, `headings`, `marks` and `fontSizing`) default to `true`. Ordinary paragraphs are always allowed. A single-line slot restricts rich content to one ordinary paragraph with inline formatting: no headings or list structure. `fontSizing: false` requires inherited run sizes, and `marks: false` requires unmarked runs. Plain text admits no marks, headings or lists. These restrictions apply to imports and verbs too. Disabled list shortcuts remain literal text and their inspector actions are hidden. Canonical admission rejects forbidden blocks from API edits or imports; it does not silently discard or flatten content. Maximum nesting depth and custom shortcut spellings are not yet configurable. ## Standalone text ### Per-slot grammar and headings A single-line rich label can permit marks but require a fixed inherited font size: ```dart import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; const label = ShapeText( 'label', textType: RichTextDefinition( maxLines: 1, grammar: RichTextGrammar(fontSizing: false), ), ); ``` Semantic headings use the `heading` of `RichTextParagraph` (`HeadingLevel.none`, `h1`–`h6`), independently of the shape's title/body slot. They are ordinary body paragraphs with an outline level, not list items. `controller.setHeading` applies a level to the selected range, or the whole story when the range is omitted. Inline marks and authored font sizes are retained; heading typography is derived during layout. Enter at a heading's end creates a body paragraph; splitting within a heading preserves its level. JSON, clipboard, and undo/redo retain heading levels. While editing multiline text, use Cmd/Ctrl + Alt/Option + 1–6 for headings and 0 for body text. Cmd/Ctrl + Shift + 7/8/9 toggles numbers/bullets/checklists. Alignment uses Cmd/Ctrl + Alt/Option + Shift + L/E/R/J (start/center/end/justify) to leave browser location, search, reload, and hard reload shortcuts available. The demo header's keyboard icon lists marks, font-size, alignment, navigation, and canvas shortcuts. Unavailable formatting is hidden by the inspector and rejected by canonical admission. `TextElement` owns text without a shape surface; its `type` is the name of an installed text type, `text` (plain) or `richText`. It extends `FramedElement`, sharing rectangle-based placement and transformation mechanics with shapes. It has no `style`, ports, path, image, or child-clipping properties. Text inside a card remains a story in that card's declared regions; both owners use the same paragraph verbs, resolved lines, selection, and IME pipeline. ```dart final caption = controller.createText( id: 'caption', at: const DiagramPoint(150, 100), size: const DiagramSize(220, 80), text: 'A little room for ideas', ); ``` `controller.edits.createText` returns an `EditResult` whose `id` is the element ID, and creates one undoable edit. Supply `textStory` instead of `text` when you need rich formatting. Read the resulting `TextElement` with `controller.document.textById(caption)`; its stored fields are listed below. | Constructor field | Default | Meaning | | --- | --- | --- | | `id` | Required | Stable element identity. | | `frame` | Required | Rectangle in the owner's coordinate system. | | `textStory` | Required | Canonical paragraphs, lists, runs, and formatting. | | `rotation` | `0` | Rotation in radians. | | `parentId` | `null` | Optional containing element; text cannot own children itself. | | `zIndex` | `0` | Stacking order. | | `textSizingMode` | `DiagramTextSizingMode.fixedWidth` | Wrapped fixed width or intrinsic `autoWidth`. | `type` defaults to `Shapes.text` and is fixed after creation. `copyWith` preserves identity and omitted fields; explicit `parentId: null` removes its parent. `DiagramDocument.textById` retrieves standalone text, while `framedElementById` retrieves either text or a shape. The text tool starts a clicked box in auto-width mode; dragging creates a wrapping box. Auto-width does not limit paragraph count. Both modes support Enter-created paragraphs and use the configured sizing policy for height. Standalone text uses the core's standard geometry for every installed text type; see [text elements](/agent-docs/api/shapes.md#text-elements-and-rectangular-mechanics). ## Text verbs ### Plain-text replacement `controller.edits.setText(String id, String text, {String? slot, String? storyId})` returns `EditResult`. Every text part offers `setText`; `slot` names the part, so `setText(id, 'Orders', slot: 'title')` performs `title.setText`. Table cells are not text parts: set their text with the table verb [`setCellText`](/agent-docs/api/tables.md#verbs). The verb retains the story ID and existing paragraph IDs where possible, allocates IDs for additional paragraphs, and resets marks, lists, direction and alignment to plain-paragraph defaults. Role and slot bindings are retained. CRLF, CR and LF split paragraphs; a trailing newline creates an empty paragraph. An empty string leaves one empty paragraph. Omit `storyId` for a shape, standalone text or a connector with exactly one label. Specify it for a connector with multiple labels. Omit `slot` only when the selected story has one slot; otherwise supply an existing effective slot ID. Missing or ambiguous targets return `unavailableTarget` without publication. Other slots retain their original content. Registry-invalid content, such as a newline in a single-line slot, is rejected by admission. Undo restores the whole previous story in one step. Use `replaceText` when preserving rich formatting. ::: warning Bidirectional editing boundary With a collapsed caret, plain Left/Right traverses shaped visual caret positions. Shift+Left/Right extends the range through those positions. Canonical selections retain anchor and focus affinity through platform input, selection clamping and history. Shaped caret geometry, canvas caret painting and IME placement consume it at soft wraps. Pointer caret placement and dragging, vertical navigation, and Home/End preserve wrap affinity. Plain range collapse chooses visual endpoints, and Home/End uses shaped visual edges. Alt/Ctrl+Left/Right follows shaped word intervals; adding Shift preserves the selection anchor. Word deletion remains a logical content operation. Paragraphs support explicit left-to-right and right-to-left base direction. Automatic direction detection is not provided. ::: ### Paragraph direction Set `TextParagraph.direction` to `ParagraphDirection.ltr` (the default) or `ParagraphDirection.rtl`. `TextStory.paragraph` accepts the same `direction` argument. Direction is saved with the paragraph and inherited when Enter splits it. Start/end alignment and list gutters follow that direction. ```dart controller.setTextDirection( 'notes', ParagraphDirection.rtl, ); ``` | Argument | Meaning | | --- | --- | | `id` | Required text owner ID (positional). | | `direction` | Positional. Explicit paragraph base direction. Inline mixed-direction runs still use normal text shaping. | | `storyId` | Optional story ID. Inferred when the owner has one story; required to choose among multiple connector labels. | | `start`, `end` | Optional UTF-16 range; all touched paragraphs are formatted. Omit to format the whole story. | The verb uses normal validation and undo/redo. The inspector's **Direction** control formats selected paragraphs while editing, or the entire story otherwise. The text verbs are ordinary controller verbs: they report every outcome as an `EditResult`, and throw `StateError` only after the controller is disposed. Pure Dart hosts call the same verbs. They edit the existing story in a shape, standalone text element, or connector label. The canvas paragraph editor and checklist interaction use these same verbs. Text layout comes from the diagram’s configured text backend; no canvas is required. ```dart import 'package:vyuh_diagram_core/adapter.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; final before = DiagramTextTarget.resolve( controller.document.elementById(elementId), storyId, )!.story; final after = DiagramTextCommands.replaceText(story: before, blockIndex: 0, start: 0, end: before.blocks.first.plainText.length, text: 'Updated by the host'); final result = controller.edits.perform([elementId], 'replaceText', {'before': before, 'after': after}); ``` ### `replaceText` arguments Perform it by name with the owning element as the single target; it returns an `EditResult`. | Argument | Type | Required / default | Meaning | | --- | --- | --- | --- | | `before` | `TextStory` | Required | Expected current story. A stale value is denied with `conflict` before publication. | | `after` | `TextStory` | Required | Replacement with the same story ID; registry and document validation still apply. | | `label` | `String` | `'Edit text'` | History and change-event description. | | `selectionAfter` | `StorySelection?` | `null` | Optional selection in this same owner/story; otherwise preserve current selection. | Missing or non-editable targets return a denied result. Locks and host admission remain effective. A changed story ID or a selection targeting a different story is denied with `unsupportedOperation`. Successful edits publish state and resolved geometry atomically and participate in undo/redo. Calls after the controller is disposed throw `StateError`. ### Several stories in one undo step Wrap several `replaceText` calls in `controller.batch` to publish them as one undo entry. A failed edit leaves the entire batch unpublished. ```dart controller.batch('Update invitation', () { controller.perform([titleOwner], 'replaceText', {'before': oldTitle, 'after': newTitle}); controller.perform([bodyOwner], 'replaceText', {'before': oldBody, 'after': newBody}); }); ``` Stories may belong to shapes, text elements or connector labels. A changed story identity or a stale expected story is denied; call `requireAllowed()` on each edit to withdraw the whole batch. Missing/noneditable targets and permission denials reject the whole batch. Registry grammar and fixed domain validation still apply to the complete result. ### `setChecked(...) → EditResult` | Argument | Type | Meaning | | --- | --- | --- | | `elementId` | `String` | Required text owner ID. | | `storyId` | `String?` | Inferred when the owner has one story; supply it for multiple connector labels. | | `blockId` | `String` | Required checklist-item ID, independent of line wrapping or block index. | | `checked` | `bool` | Required checked state. | Sets the item's checked state as one undoable edit; clicking a checkbox performs it with the opposite of the current state. Missing, non-editable, non-checklist or plain targets return a denied result. This verb does not convert paragraphs into lists; use `controller.setList` for that. Use `replaceText` for custom structural or run-formatting edits that need an explicit replacement story. Text measurement and baseline contracts are covered in [API reference](/agent-docs/api/index.md). ## Font-size editing bounds `ShapeDefinition.fontSizeRange` and `ConnectorLabelingCapability.fontSizeRange` declare one `DiagramTextFontSizeRange`; standalone text uses the core's standard range (`DiagramTextFontSizeRange()`). The resolved text target carries it to the inspector, selected-object shortcuts, selected-text formatting, and pending caret formatting. | Member | Type | Contract | | --- | --- | --- | | `minimum` | `double` | Defaults to `8`; finite and positive. | | `maximum` | `double` | Defaults to `96`; finite and at least `minimum`. | | `constrain(size)` | `double → double` | Clamps a finite positive requested size to the range. | | `adjust(size, delta)` | `(double, double) → double` | Adds a finite delta and clamps the result; the original size must be finite and positive. | Invalid declarations fail registry admission with `ArgumentError`. These are editing bounds: importing or resolving an already-authored size does not silently rewrite it. Run sizes still require finite positive values under document admission. ```dart import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; ShapeDefinition( type: 'app.note', body: const ShapeText('body', textType: RichTextDefinition()), fontSizeRange: const DiagramTextFontSizeRange(minimum: 12, maximum: 48), ) ``` ## Whole-story paragraph formatting When `end` is omitted, paragraph verbs include the final empty paragraph, including one created by a trailing newline. An explicit `end` remains exclusive: a range ending at the next paragraph's start does not format that paragraph. This applies equally to Flutter and headless controllers. ## Adjust font size Use the same controller verb in Flutter or headless Dart: ```dart controller.adjustFontSize( elementId: textId, delta: 2, start: 0, end: 5, ); ``` The verb adjusts existing runs within the character range as one undo step. Omit the range to adjust all existing text. Runs without an explicit size start from the resolved target’s font size, and results are bounded by the target’s registered `DiagramTextFontSizeRange`. Connector labels normally use 14. Reversed ranges are normalized. A collapsed range does not set future typing style. Invalid numeric arguments are denied without publishing content or clearing redo. --- # Shapes, elements and registries Shape elements, `Shapes` type ids, styles, ports and the rest of the document model are in the main library. Definitions and their parts (`ShapeDefinition`, `ShapeOutline`, `ShapeText`, `ShapeColumn`, value fields, `PortDefinition`, `ShapeLibrary`, `ShapeRegistry`) are extension authoring types in `package:vyuh_diagram_flutter/extension_api.dart` (`package:vyuh_diagram_core/extension_api.dart` in pure Dart). Describe a shape through these related concepts: | Concept | What it describes | | --- | --- | | **Outline** | The shape's own surface: the contour it paints, hit-tests and clips connectors to. | | **Body** | Title, body and footer regions, arranged using rows, columns, stacks, sizing and padding. | | **Values** | Typed instance data, such as a path's points, an image or a domain field. | | **Appearance** | Fills, stroke styles, widths and colors; text has its own formatting properties. | | **Connections** | Explicit named ports or virtual anchors, attachment rules and connection snapping. | | **Behavior** | What a person may do on the canvas: select, move, resize, rotate and delete. | | **Alignment snapping** | Geometric features that help align a moving shape with nearby shapes. | Connection snapping chooses where a connector attaches. Explicit ports provide named anchors; portless shapes offer virtual anchor candidates and allow other attachment positions according to their connection policy. The saved binding keeps the connector attached as the shape changes. See [connection anchors](/agent-docs/api/connectors.md). Alignment guides serve a different purpose: they align shapes while moving them. Currently they use the sides and centers of nearby resolved element bounds, subject to the snap-guide policy and candidate limit. Internal title/body/footer regions and ports do **not** currently contribute separate alignment candidates. Selectable children contribute as document elements; body parts do not. A future declaration of snappable internal regions should reference their shared resolved geometry, rather than introduce independently calculated guide positions. This is an extension point to develop, not an available per-part snapping API. See [shape anatomy](/agent-docs/guide/shape-composition.md) for the parts a body is made of and [widgets inside shapes](/agent-docs/api/widgets.md) for live Flutter content. ## On this page | Category | What you can do | | --- | --- | | [Create elements](#controller-createshape) | Create registered shapes, standalone text or connected elements. | | [Appearance](#shape-appearance) | Set fills, strokes and other supported styles. | | [Custom definitions](#shapedefinition) | Declare a shape's anatomy: outline, body, values, connection and behavior. | | [Register definitions](#shaperegistry) | Make custom shape types available to the drawing. | | [Edit and lock](#mutation-and-locking) | Update elements while respecting each definition's behavior. | | [Images](#image-content) | Set or clear image content. | | [Custom values](#custom-values) | Declare and edit fields for controls and domain extensions. | ## Standard collection See the [illustrated element catalog](/agent-docs/elements/standard.md) and [capability matrix](/agent-docs/elements/index.md) for the built-in elements and their editing support. The core extensions contribute rectangle, ellipse, polygon, path, card, group, frame, comment, freehand and image. Tables are supplied by the table extension. Standalone text and connectors have their own element definitions. Entities (for example classes) belong to the optional [Shapes library](/agent-docs/api/extension-shapes.md) (`DiagramShapes.entity`); comments have a folded top-right corner with fixed yellow fill and outline. The Connector tool uses `L`; Path uses `P`, and Comment uses `N`. Path covers straight strokes and curves. Click an anchor to select it (Shift-click adds anchors), then Delete removes the selected points. Removing an endpoint from a two-point path removes the path. Double-click an anchor to cycle Corner, Smooth, and Symmetric. All edits support undo/redo. Use `DiagramTools.connector` for connections and `DiagramTools.path` for editable paths. ## Shape appearance ### Frame and group transforms Standard frames own children and can clip them. Moving a frame moves its subtree; resizing it changes only its boundary, preserving child geometry. Standard frames disable rotation. Hosts can explicitly enable rotation in their registered frame definition; enabled rotation carries the subtree with it. Logical groups resize their contents together. A container declares `ShapeContainer(resizesChildren: ...)` (default `true`); the standard frame sets it to `false`. This policy is shared by controller resize verbs and pointer handles. A group selected around a frame still scales its complete contents as one group transformation. Try [frames and ownership](/agent-docs/examples/containment.md). For rotatable shapes, `ShapeBehavior(rotationHandle: true)` adds a visible rotation handle. It defaults to `false`; corner rotation remains available. `ShapeBehavior(rotatable: false)` disables both. See [custom shapes](/agent-docs/guide/custom-shapes.md) for registration examples. `controller.edits.setStyle({ids, fill, stroke, strokeWidth, cornerRadius, strokeStyle, inkPreset})` performs the `setStyle` [verb](/agent-docs/api/verbs.md), which changes a shape's editable appearance. Only the parts you pass change; the others keep their values. Flutter and pure Dart hosts use this same verb, and the inspector's appearance properties perform it. | Argument / result | Contract | | --- | --- | | `ids` | Existing shape identities; missing IDs and standalone text are denied. | | Named parts | `fill` (`DiagramFill`), `stroke` (`DiagramColor`), `strokeWidth`, `cornerRadius`, `strokeStyle`, `inkPreset`; each optional. | | Editable fields | Fill and stroke parts require a shape with an outline; `cornerRadius` requires an outline that rounds its corners. Other changes are denied. | | Return | `EditResult`; locks and host admission can deny the edit. Invalid numeric or color values are denied with `DiagramDenialCode.unsupportedOperation`. | | History | One admitted change is one undo unit. Selection, content and geometry remain unchanged. | ```dart controller.setStyle( ids: [id], fill: const DiagramColor(0xFFE4E4E7), ); ``` Text formatting uses the [text verbs](/agent-docs/api/rich-text.md#editing-verbs); connector appearance has its own model. Pass several IDs for atomic multi-shape styling in Flutter or Dart. All targets must pass validation and permissions; otherwise none change. A change is one event and one undo step. ```dart controller.setStyle( ids: [for (final shape in selectedShapes) shape.id], strokeStyle: StrokeStyle.dashed, ); ``` Initial authored styles and imports retain their separate document-validation contract; the anatomy-derived editable fields govern this verb and the inspector. ## Connection declarations | Constructor | Port ownership | | --- | --- | | `ShapeConnectionDefinition.none()` | No connections. | | `ShapeConnectionDefinition.outline()` | Connections bind to the shape outline. | | `ShapeConnectionDefinition.fixedPorts(ports)` | The definition owns the named ports. | | `ShapeConnectionDefinition.instancePorts(...)` | Instance ports replace the definition's defaults when present. | For `instancePorts`, `defaultPorts` supplies an immutable list of named fallback ports. When nonempty it takes precedence over generated `defaultSides`. An empty instance port list uses these defaults; it does not disable connections. The `fixedPorts` field is reserved for fixed-port definitions. Both kinds of declared ports are checked for unique IDs, valid placement, and valid appearance during registry admission. `defaultSides` must contain unique sides, in the desired port order. Repeating a side is rejected at registration because generated ports use the side name as their identity. To place several ports on the same side, declare named `fixedPorts` or `defaultPorts` with distinct IDs instead. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ShapeConnectionDefinition.instancePorts( defaultPorts: [ PortDefinition.onSide(id: 'input', side: PortSide.left), PortDefinition.onSide(id: 'output', side: PortSide.right), ], ) ``` ## Appearance before drawing Select Draw to configure fill, stroke color, stroke style and stroke width before pressing on the canvas. These per-controller choices do not modify selected objects or create undo entries. Live ink and the finished drawing use the same appearance. A visible fill colors the area enclosed by the path and its closing edge. Existing drawings remain editable through their properties. | Controller API | Arguments | Result | | --- | --- | --- | | `shapeCreationStyle(type)` | Registered shape type ID | Current `ShapeStyle`, falling back to the definition's default | | `setShapeCreationStyle(type, style)` | Registered type ID and valid `ShapeStyle` | Updates subsequent creations of that type; an explicit creation style takes precedence | Custom tools opt into the same inspector through `DiagramToolBehavior.creationShapeType`. Standard shape and drawing tools use this contract. Creation choices are not serialized into the document; each created shape stores its final appearance normally. Choosing a creation tool clears the old selection so these defaults are visible. Once a drawing is selected, its own properties take priority—even if Draw remains active. Stroke style changes on that selection participate in undo/redo. New ink uses restrained pressure variation (80–120% of the chosen width). Pressure is carried through each local smoothed segment; appending points does not rescale the earlier stroke's pressure coordinates. Solid ink has no repeated sample-based oscillation or whole-stroke taper. ## Definitions and elements A **definition** describes a reusable shape type. An **element** is one immutable record in the document. The **registry** connects its `type` to the definition. The **controller** inserts and changes records through the canonical engine. | Type | Package | Role | | --- | --- | --- | | `DiagramElement` | `vyuh_diagram_types` | Base authored record with identity, stacking and lock state. | | `ShapeElement` | `vyuh_diagram_types` | A shape instance: `type`, frame, appearance, values and text. | | `TextElement` | `vyuh_diagram_types` | Standalone text; shared rectangular mechanics without shape appearance. | | `ConnectorElement` | `vyuh_diagram_types` | Connection endpoints, route, markers and labels. | | `ShapeDefinition` | `vyuh_diagram_core` | A shape's anatomy: outline, body parts, values, connection and behavior. | | `ShapeRegistry` | `vyuh_diagram_core` | Definition lookup and validation. | | `DiagramController` | `vyuh_diagram_core` | One actor's verbs, selection and camera; its `diagram` holds installed extensions, rules, history and lifetime. | Import `package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart` in a Flutter host; it exports these types. Pure Dart hosts import `package:vyuh_diagram_core/vyuh_diagram_core.dart` and use the same controller verbs. ## `controller.add` Use an element directly when you already know its identity, frame and content: ```dart EditResult add( DiagramElement element, { bool select = true, }) final result = controller.edits.add(ShapeElement( id: 'review-card', type: Shapes.card, frame: const DiagramRect.fromLTWH(200, 160, 240, 160), )); ``` | Argument / result | Contract | | --- | --- | | `element` | Required immutable record. Shapes, text and connectors use this same method. | | `select` | Defaults to `true`; selects the inserted record. `false` preserves selection. | | Result | `EditResult`; denied changes return a reason. Call `requireAllowed()` to throw on denial. | | Defaults | Preserves the supplied record; does not invent an ID, story, style, size or parent. | | Validation | Registry, identity, ownership, bindings and the diagram's `beforeChange` admission still apply. Invalid records throw; no partial insertion occurs. | | History | One admitted edit and undo entry. Works before mounting a canvas. | The `canCreate` rule is not called by raw insertion; a connector inserted this way is still admitted by the `canConnect` rule. Put permissions that must cover **every** mutation in [the `beforeChange` rule](/agent-docs/api/hooks.md), which also covers transactions, imports and history. ## `controller.createShape` Use named arguments when the registry should supply defaults. ```dart final cardId = controller.createShape( Shapes.card, at: const DiagramPoint(320, 240), size: const DiagramSize(240, 160), ); ``` Returns an `EditResult`; when allowed, `id` is the created element ID. The type is positional; the rest are named: | Argument | Type | Default / behavior | | --- | --- | --- | | `type` | `String` | Positional registered shape type. Standalone text uses `createText`. | | `at` | `DiagramPoint` | Required center in world coordinates. | | `id` | `String?` | Allocated when omitted; explicit IDs must be unique. | | `size` | `DiagramSize?` | Definition's `size`; requested dimensions are clamped up to its minimum. | | `style` | `ShapeStyle?` | Definition's `style`. | | `values` | `Map?` | Overrides for the definition's declared `values`; the remaining defaults are filled in. A path, drawing or image shape receives its path, ink or image here. See [custom values](#custom-values). | | `text` | `String?` | Plain Text with generated story and paragraph IDs; line breaks preserve blank and trailing paragraphs. Supply either `text` or `textStory`. The registered type must host text; otherwise creation fails without changing content or history. | | `textStory` | `TextStory?` | Materialized from the definition's declared text slots when omitted. | | `textSizingMode` | `DiagramTextSizingMode?` | Omit to use the definition’s `textCreation.sizingMode`; explicit `autoWidth` opts into intrinsic text width. | | `ports` | `List?` | Empty; admitted by the registered connection grammar. | | `parent` | `DiagramShapeParentPlacement` | `const AutoDiagramShapeParent()`: deepest accepting owner beneath the center. | | `select` | `bool` | `true`: select the new shape. | | `zIndex` | `int` | `0`. | Use `const RootDiagramShapeParent()` for explicit root placement, or `OwnedDiagramShapeParent(ownerId)` for an explicit child-owning shape. Missing or unsuitable explicit owners throw. Registry admission, the `canCreate` rule and `beforeChange` run before successful publication. A denial returns a denied result without an `id`. The operation creates one undo entry and requires no mounted canvas. ## `controller.createText` ::: tip Creation rules The `canCreate` rule receives the actual immutable shape or text element that would be created, including its allocated ID, frame and default content. It runs before insertion, including drawing previews. Use the element's properties to allow or deny creation. For rules covering imports and authored insertions too, use the diagram's `beforeChange` rule. ::: ```dart final textId = controller.createText( at: const DiagramPoint(320, 240), text: 'Your notes', ); ``` Returns an `EditResult` whose `id` is the new ID. Named arguments are `at` (required), `id`, `size`, `text`, `textStory`, `textSizingMode`, `parent`, `select`, and `zIndex`, with the same types/defaults as above. Omitted size and story come from the registered `text` element, `registry.requireText(Shapes.text)`. There are no fill, border, port, image or path arguments. Use `text:` for Plain Text; the controller assigns its story and paragraph IDs. Line breaks (LF, CRLF, or CR) create separate paragraphs, including blank and trailing lines. An empty string creates one empty paragraph. Use `textStory:` for formatted paragraphs and lists. Supplying both throws `ArgumentError` before changing the drawing. Omitting both keeps the registered default story. ## `controller.createConnected` Pass the element you want to insert. The controller adds it and its incoming connection atomically. The element keeps the ID you gave it; the result's `id` is the connector ID: ```dart final connectorId = controller.createConnected( source: BoundEndpoint(elementId: existingShapeId), element: ShapeElement( id: 'review-card', type: Shapes.rectangle, frame: const DiagramRect.fromLTWH(420, 190, 200, 100), ), ); ``` | Argument | Meaning | | --- | --- | | `source` | Required source endpoint: bound to an existing element or a free world point. | | `element` | Required `ShapeElement` or `TextElement`. Its identity, geometry, content, appearance and parent are preserved. | | `toPort` | Required for port-only targets; otherwise omit. Must name a declared target port. | | `connectorId` | Optional explicit ID; allocated when omitted. | | `route` | Defaults to `ConnectorRoute.straight`. | | `connectorZIndex` | Defaults to -1. The connector shares the target's parent. | | `select` | Defaults to true; selects the new element. False preserves selection. | | Return | `EditResult`; `id` is the connector ID. | One Undo removes both records; Redo restores their identities and binding. Invalid identities, unsupported targets, missing ports, a `canConnect` denial or document admission failure insert neither record. No mounted canvas is needed. ::: tip Authored elements and defaults This method preserves an authored element, like `add`; it does not materialize registry defaults or call the `canCreate` rule. Use `beforeChange` for permissions that must cover every insertion. The `canConnect` rule and canonical document validation still apply. `createShape` and `createText` supply registry defaults when you want the controller to construct an element. ::: ## `ShapeElement` | Constructor property | Type | Default / contract | | --- | --- | --- | | `id`, `type` | `String` | Required identity and registry type. | | `frame` | `DiagramRect` | Required authored frame. | | `rotation` | `double` | `0`, radians around the frame center. | | `style` | `ShapeStyle` | `const ShapeStyle()`; raw records do not acquire definition defaults. | | `values` | `Map` | Empty immutable value map by default; raw insertion must supply exactly the declared fields. Paths, ink, images and polygon sides live here. | | `textStory` | `TextStory?` | `null`. | | `textSizingMode` | `DiagramTextSizingMode` | `fixedWidth`. | | `ports` | `List` | Empty immutable snapshot; subject to the definition's connection grammar. | | `parentId` | `String?` | `null`; explicit owner identity when present. | | `clipContent` | `bool` | `false`; requires a clipping container (`ShapeContainer(clips: true)`). | | `isCollapsed` | `bool` | `false`; collapsed presentation of a collapsible container. | | `aspectLocked` | `bool` | `false`; resizing keeps the width-to-height ratio. | | `isLocked` | `bool` | `false`; per-instance editing lock. | | `zIndex` | `int` | `0`; stacking order. | Records are immutable. Change them by performing [verbs](/agent-docs/api/verbs.md) such as `setStyle`, `setValues` or `move`. Geometry and story data are validated on admission. Structured values have typed readers. Decode them with the value's own type rather than reading map keys: ```dart final path = DiagramVectorPath.fromValue(shape.values['path']); final ink = DiagramInk.fromValue(shape.values['ink']); final image = DiagramImageSource.fromValue(shape.values['image']); ``` Each type writes itself back with `toValue()`, for example `{'path': DiagramVectorPath.polyline(points).toValue()}`. ## `ShapeDefinition` A shape definition is the shape's **anatomy**: an `outline` that is its own surface, a `body` of parts laid out inside or beside it, typed instance `values`, a `connection` declaration, optional `container` and `collapse` policies, and the `behavior` a person may exercise on the canvas. Painting, hit testing, text editing, handles and the inspector all follow from these declarations; a definition adds no painter or editor code of its own. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final service = ShapeDefinition( type: 'acme.service', name: 'Service', size: const DiagramSize(200, 120), outline: const ShapeOutline.rect(), style: const ShapeStyle(cornerRadius: 10), body: ShapeColumn([ ShapeSized( extent: 36, child: ShapeStack([ const ShapeText( 'title', text: 'Service', textType: PlainTextDefinition(maxLines: 1), role: TextRole.title, ), const ShapeDivider(edge: ShapeEdge.bottom), ]), ), const ShapeText( 'body', verticalAlignment: DiagramTextVerticalAlignment.top, placeholder: 'Describe the service…', ), ]), values: { 'replicas': const NumberValueField(defaultValue: 1, minimum: 1, integer: true), }, behavior: const ShapeBehavior(textSizing: ShapeTextSizing.growHeight), ); ``` Registry admission rejects invalid default appearance, surface fills, shadow colors, and port styles with `ArgumentError`. Colors must be unsigned 32-bit ARGB values; shape border width and corner radius must be finite and nonnegative. Port size must be finite and positive; port border width may be zero. Transparent colors remain valid. These are value-validity rules, independent of which appearance controls a definition exposes. Authored shapes and ports follow the same rules at document admission. Invalid transactions or imports throw `StateError` before publication and preserve the previous document, scene and history; values are not silently clamped. | Constructor property | Type | Default / contract | | --- | --- | --- | | `type` | `String` | Required open registry key. | | `name` | `String?` | Optional nonblank human-readable kind name for inspector titles and accessibility. Defaults to the type ID; supply a localized name when constructing the registry. Does not change serialized identity. | | `outline` | `ShapeOutline?` | `const ShapeOutline.rect()`. The shape's surface, hit area and connection boundary; `null` for a shape that paints no surface of its own. | | `body` | `ShapePart?` | `ShapeParts.body`: one editable `body` text slot inset by 12. `null` for a shape with no text and no parts. | | `values` | `Map` | Empty. Typed declarations of each instance's durable `ShapeElement.values`. | | `previewValues` | `Map` | Empty. Values a palette thumbnail shows instead of the defaults. | | `adjustments` | `Iterable` | Empty. On-canvas handles bound to numeric values. | | `connection` | `ShapeConnectionDefinition` | `const ShapeConnectionDefinition.outline()`. | | `container` | `ShapeContainer?` | `null`. Present when the shape owns child elements. | | `collapse` | `ShapeCollapseDefinition?` | `null`. A container's compact presentation. | | `behavior` | `ShapeBehavior` | `const ShapeBehavior()`: selectable, deletable, movable, resizable and rotatable, fixed text sizing. See [shape behavior](/agent-docs/guide/shape-capabilities.md). | | `minimumSize` | `DiagramSize` | `24 × 24`, raised to fit a composed body. | | `size` | `DiagramSize` | `160 × 100`; the size of a new shape. | | `style` | `ShapeStyle` | `const ShapeStyle()`; the appearance of a new shape. | | `shadow` | `ShapeShadowDefinition?` | `null`. Painted only for a shape with an outline. | | `fontSizeRange`, `textCreation` | | Text sizing limits and creation defaults. | | `properties` | `Iterable` | Additional inspector properties. See [properties](/agent-docs/guide/properties.md). | | `verbs` | `List` | The shape's own [verbs](/agent-docs/api/verbs.md), such as a card's `setTitle`, offered beside element verbs and its parts' verbs. | | `affordances` | `Iterable` | On-canvas controls beside the selected shape, such as a card's optional tag. | ### Outline `ShapeOutline` is a closed set of contours. Each resolves at the shape's frame from its style and values: | Outline | Contour | Corner radius | | --- | --- | --- | | `ShapeOutline.rect()` | Rectangle filling the frame; `rect(cornerRadius: false)` keeps square corners. | Editable | | `ShapeOutline.ellipse()` | Ellipse filling the frame. | None | | `ShapeOutline.polygon(points)` | Fixed closed polygon through unit-coordinate points. | None | | `ShapeOutline.normalized(path)` | Fixed `DiagramVectorPath` in unit coordinates, scaled to the frame. | Opt in with `cornerRadius: true` | | `ShapeOutline.path(builder)` | Contour computed by `(DiagramSize size, Map values) => DiagramVectorPath` in shape-local units, so caps and insets keep their size as the frame grows. | Opt in with `cornerRadius: true` | | `ShapeOutline.regularPolygon()` | Regular polygon whose side count is the integer value `sides`, declared with `ShapeOutline.sidesField(n)`. | Editable | | `ShapeOutline.editablePath()` | The path each instance stores in its `path` [`PathValueField`](#custom-values), edited point by point. | Editable | | `ShapeOutline.ink()` | A freehand stroke stored in the instance's `ink` `InkValueField`. | None | | `null` | No surface: nothing painted, picked by its frame rectangle. | None | A closed, straight-edged path resolves as a precise polygon for hit testing and connector clipping. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final hexagon = ShapeDefinition( type: 'acme.hexagon', outline: ShapeOutline.regularPolygon(), values: {'sides': ShapeOutline.sidesField(6)}, ); ``` ### What is editable Editing follows from the anatomy rather than from separate flags: | Anatomy | Derived editing | Read it as | | --- | --- | --- | | An outline | Fill and stroke | `definition.paintsSurface` | | An outline that rounds its corners | Corner radius | `definition.cornerRadiusEditable` | | An editable `ShapeText`, or a content part such as a table | Text | `definition.textEditable` (false while collapsed) | | Any `ShapeText` or content part | A text story | `definition.hostsText` | | A `PathValueField`, sides value or `ImageValueField` | Points, sides or image editors | `definition.propertyEditors` | | Any other value | One control per value | `definition.customValues` | `definition.layers` lists what the body compiles to, in paint order. Layers are compiled output that renderers, picking and editing read; author shapes with parts, not layers. A surface or image region's `onInteract` can name one of the shape's verbs: on the canvas, a tap inside that region performs it with no arguments. Any other `onInteract` ID goes to the host's region interaction callback. ### Shorthand constructors Two shorthand constructors cover the most common definitions: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ShapeDefinition.labeled( 'acme.task', name: 'Task', outline: const ShapeOutline.rect(), connection: const ShapeConnectionDefinition.outline(), size: const DiagramSize(180, 100), ); ShapeDefinition.symbol('acme.start', name: 'Start'); ``` `labeled` fills the shape with one padded, editable `label` text slot that starts with the name (or `text:`). `symbol` is a small, text-free marker with an ellipse outline by default and an optional `glyph` part drawn inside it. `TextStory? createTextStory(String elementId)` materializes the declared text slots and initial content. It returns `null` when the shape hosts no text. It does not reset an existing element's story. ### Minimum size `minimumSize` sets the creation and resize floor in world units. `size` sets the initial size and must meet that floor. Both require positive finite dimensions. Explicit creation sizes below the minimum are clamped. A composed body raises the floor to fit its fixed extents and padding; a body that is a single text part scales with the shape. | Definition | Minimum width × height | | --- | --- | | Rectangle, ellipse, polygon, frame | `24 × 24` | | Path | `1 × 1` | | Line, freehand drawing | `4 × 4` | | Card | `140 × 88` | | Comment | `100 × 80` | | Image | `80 × 60` | | Group | `1 × 1`, additionally constrained by its children | | Playground controls example | `280 × 260`, to accommodate the native controls | For your own type, declare the minimum with its anatomy: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ShapeDefinition( type: 'small-marker', outline: const ShapeOutline.ellipse(), body: null, minimumSize: const DiagramSize(8, 8), size: const DiagramSize(32, 32), ) ``` Both dimensions must be finite and positive. A group or multiple selection also respects the minimum of each selected child. Text that grows to fit its content can require more height than the declared floor. The minimum is not a substitute for choosing enough room for a native widget's controls. ## `ShapeRegistry` A `ShapeRegistry` is the validated grammar that extensions assemble; it is not constructed directly. Obtain it from the extension assembly: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final registry = DiagramExtensionRegistry( extensions: [myShapesExtension()], ).shapeRegistry; // or, from a diagram: final installed = controller.diagram.registry.shapeRegistry; ``` The core extensions always supply the built-in shapes. An extension's `ShapeDefinition` with a built-in type, such as `Shapes.rectangle`, replaces the built-in one; two non-core extensions contributing the same type are rejected. Definitions are immutable. Register required types before opening a document; live replacement of registered definitions is not supported. An already registered type can be instantiated at any time. Shape registration does not install a toolbar button. Add creation tools to the same extension's `tools`, for example with `DiagramToolDefinition.forShapes(shapes, group: ...)`. See [custom shapes](/agent-docs/guide/custom-shapes.md) for a complete example. ## Mutation and locking | Operation | API | Behavior | | --- | --- | --- | | Lock / unlock | `controller.edits.setLocked(locked, ids: ids)` | Returns `EditResult`; one admitted reversible change. | | Delete | `controller.edits.delete(ids: ids)` | Removes the ownership/dependency closure; locks, `behavior.deletable` and admission apply. | | Move | `controller.edits.move(delta, ids: ids)` | Translate the specified elements together. | | Resize | `controller.edits.resize(size, ids: ids, fromCenter: false, preserveAspectRatio: false)` | Resize the specified elements with optional centered and proportional sizing. | | Rotate | `controller.edits.rotate(ids: ids, pivot: pivot, radians: radians)` | Rotate the specified elements around a pivot. | | Replace text | `controller.edits.perform([id], 'replaceText', {'before': story, 'after': editedStory})` | Replace a story after validating its expected content. | Each verb publishes and undoes as one operation. For custom atomic edits, see [`controller.batch`](/agent-docs/api/controller.md#batch). Use `beforeChange` for permissions; definition behavior and instance locks are not an authorization boundary. ## Image content ```dart EditResult setImage(String id, DiagramImageSource? image) ``` Call `controller.edits.setImage(id, image)` in Flutter or pure Dart; it performs the `setImage` [verb](/agent-docs/api/verbs.md). The verb requires no mounted canvas. This sets the authored source; image fetching and decoding belong to rendering or export. A shape shows an image by declaring an `ImageValueField` and placing a `ShapeImage(valueKey)` part where the image belongs. The built-in image shape is ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; ShapeDefinition( type: 'app.photo', outline: null, values: const {'image': ImageValueField()}, body: const ShapeSurface( outline: null, onInteract: 'choose-image', child: ShapeImage('image'), ), ) ``` The stored value is `DiagramImageSource.toValue()`; read it back with `DiagramImageSource.fromValue(shape.values['image'])`. The `choose-image` interaction asks the host's image picker for a source. | Argument / outcome | Contract | | --- | --- | | `id` | Existing shape whose definition declares an `ImageValueField`. | | `image` | Image source to store in that value; `null` removes it. | | Missing shape or no image value | Returns a denied `EditResult`. | | Invalid source URI | Returns a result denied with `DiagramDenialCode.unsupportedOperation`; only HTTP(S) URLs and image data URIs are accepted. | | Locked shape or rejected host permission | Returns a denied result without publishing the edit. | | Changed content | One admitted edit and undo entry. | | Identical content | Allowed no-op; no content-change event or undo entry. | When the image is chosen after awaiting a file picker or network response, pass `expectedRevision` to `perform` so a document that changed meanwhile is denied as a conflict. As with other verbs, edits after disposal are rejected. ## Text elements and rectangular mechanics `TextElement` is a distinct sibling of `ShapeElement`. Both extend `FramedElement`, so movement, resize, rotation, parent placement, selection, and history share the same mechanics. Text owns a required Rich Text story; it has no shape style, fill, border, ports, image, path, or child-clipping fields. Standalone text is a core element. Extensions contribute text *types* through `textTypes`, and every installed text type is also a type of the standalone text element: the element's `type` is the text type's name, `text` for the core plain text and `richText` for `RichTextExtension()`. The core gives every standalone text element the same standard geometry (placeholder, sizes, font size range, connection and behavior); read it with `registry.requireText(type)`, which returns the `TextElementDefinition` (an engine type in `adapter.dart`) the core built for that text type. Do not register a `ShapeDefinition` with a text type's name or construct `ShapeElement(type: Shapes.text)`. ```dart final controller = DiagramController( configuration: DiagramConfiguration(extensions: [RichTextExtension()]), ); controller.createText( type: RichTextDefinition.textType, at: DiagramPoint.zero, text: 'Notes', ); ``` A custom element type name needs a text definition whose `type` is that name: subclass `DiagramTextDefinition` and contribute it in `textTypes`. For text with other geometry, such as a larger box or ports, use a shape with a text slot instead. `ShapeDefinition.textCreation` and `TextElementDefinition.textCreation` use a `ShapeTextCreation` declaration: | Property | Type | Contract | | --- | --- | --- | | `sizingMode` | `DiagramTextSizingMode` | Default for controller creation verbs and drag-created frames; defaults to `fixedWidth`. | | `clickSizingMode` | `DiagramTextSizingMode` | Default for click creation; inherits `sizingMode` unless specified. The standard text definition specifies `autoWidth`. | Explicit `textSizingMode` arguments override these creation defaults. Existing records retain their authored sizing mode. Auto-width defaults require a growing `behavior.textSizing` and are rejected during registry admission otherwise. Custom shape tools may explicitly request auto-width on click; the built-in text tool consumes the definition without imposing an additional sizing default. The core's `TextElementDefinition` for each text type has that `textType`, an editor-only `placeholder` (`Type something…`), standard minimum/default sizes and a `behavior`. Its frame is filled by one `body` text slot that is always editable; there is no shape surface, body composition or child ownership. Its default `ShapeBehavior(textSizing: ShapeTextSizing.growHeight)` grows text height. It does not introduce a second paragraph editor. Its `connection` is `ShapeConnectionDefinition.outline()`. Standalone text accepts center and edge anchors and shares contour clipping with shapes for every route. Text does not declare named ports; use a shape with a text slot when you need ports or no bindings. Its rectangular geometry remains independent of shape fill and border presentation. Built-in images have no outline, so they expose their pixels across the full frame without fill, border, corner rounding or the corresponding inspector controls. A custom image shape with an outline gains those controls. Authored drawings use **Stroke color**, **Stroke style** and **Stroke width** in the inspector. Choose Solid, Dashed or Dotted. Solid preserves captured pressure and smooth caps through the shared ink geometry used for painting and SVG. The former Hand-drawn option is no longer offered; its serialized value remains readable for existing documents. Text color belongs to `TextRun.color`. A null run color inherits the text region foreground. See [standalone text](/agent-docs/api/text.md#standalone-text) for the record and [persistence](/agent-docs/api/persistence.md#standalone-text) for its saved form. ## Transform geometry for custom verbs The pure Dart engine exposes geometry operations for custom verbs and tools. They return immutable elements; they do not bypass publication, permissions, ownership closure, or history. Return results from a `DiagramVerb.update` setter, or submit them from a verb implementation. | API | Arguments | Result | | --- | --- | --- | | `DiagramElementTransform.translate` | `DiagramElement element`, `DiagramPoint delta` | Translates a shape/text frame or connector free points. | | `DiagramElementTransform.rotate` | `DiagramElement element`, required `DiagramPoint pivot`, required `double radians` | Rotates placement about a world-space pivot; framed element dimensions remain unchanged. | | `DiagramResizeTransform` | Required `DiagramRect fromBounds`, `DiagramRect toBounds`; `double rotation = 0` | Creates one immutable mapping for all elements in a resize selection. Bounds are expressed in its unrotated coordinate frame. | | `resize.mapPoint` | `DiagramPoint point` | Maps a world point through the resize coordinate frame. | | `resize.apply` | `DiagramElement element`; optional `DiagramRect resolvedFrame`, `bool fixTextWidth = false` | Maps frame or free connector geometry. A horizontal text resize can set fixed wrapping width. | Use the resolved frame captured at the beginning of the gesture for auto-grown text. Use bounds from that same scene revision, and enforce registry minima when choosing `toBounds`. The mapping preserves text, styles, local paths, and bound endpoint identity; bound connectors follow their endpoints automatically. Non-finite inputs and non-positive resize bounds are rejected. Hold **Shift** to preserve aspect ratio, **Alt/Option** to resize around the center, or both. These work on side and corner handles, including multi-selections, and can change during a drag. Minimum sizes remain enforced. Side-handle aspect resizing expands the perpendicular dimension equally. ## Rounded outline geometry Rounded rectangle radii fit to half the smaller frame dimension. The resolved outline uses those fitted arcs for containment and connector boundary anchors, as well as painting. A child clipped by a rounded parent cannot be hit through the parent's cut-off corners. Rotation is applied through the shared local/world transform; it does not change the local corner radius. See [the visual anatomy guide](/agent-docs/api/widgets.md#compose-a-shape-visually) for how title, body and footer regions, content layout, and widget slots fit inside one shape. ### Body containment Surfaces, dividers and images in a body are clipped to their owning shape's resolved outline, including rounded corners and rotated outlines. Interactive surfaces use the same containment: clipped-away corners cannot activate a region. This is a rule of the body, independent of child-frame clipping. Text is never clipped to the outline; it clips to its own text region, so a slanted or curved edge does not cut through letters. Keep text inside a curved outline with padding, such as `ShapePadding.proportional(.18, child: ...)`. Ports and shadows are separate from the body and can extend beyond the outline. On-screen drawing and PNG output share the scene painter and therefore the same content clip. ## Custom values A registered shape declares its durable instance data as typed `values`. The document owns them; Flutter widget state must not become a second source of truth. Mount controls through the [widget slot and builder APIs](/agent-docs/api/widgets.md). ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final definition = ShapeDefinition( type: 'control-card', values: { 'progress': const NumberValueField( defaultValue: 25, minimum: 0, maximum: 100, ), 'status': ChoiceValueField( defaultValue: 'draft', values: ['draft', 'ready'], ), 'enabled': const BooleanValueField(defaultValue: true), }, ); // Install the definition in the configuration's extensions first. final id = controller.createShape( 'control-card', at: const DiagramPoint(200, 150), values: {'progress': 50}, ); final result = controller.edits.setValues(id, {'status': 'ready'}); ``` The inspector shows one control per value. Paths, ink, images and a regular polygon's sides have their own editors instead. | API | Arguments | Behavior | | --- | --- | --- | | `ShapeDefinition.values` | `Map` | Immutable declarations; unknown fields are rejected. | | `BooleanValueField` | Required `bool defaultValue` | Accepts only booleans. A boolean can show or hide a part with `ShapeVisibility.value(key)`. | | `NumberValueField` | Required `num defaultValue`; optional `minimum`, `maximum`; `integer = false` | Finite numbers within inclusive bounds; integer fields require an integral value. [Adjustment handles](#adjustment-handles) set number values. | | `ColorValueField` | Required `int defaultValue` | Unsigned 32-bit ARGB color, such as `0xFF3355FF`; uses a color picker. Can be specialized for domain constraints. | | `ChoiceValueField` | Required `String defaultValue` and `List values` | Restricts a value to named choices. | | `TextValueField` | Required `String defaultValue`; optional `List allowedValues` | Strings, optionally restricted to the declared choices. | | `ObjectValueField` | Required `Map defaultValue` | Structured JSON for domain payloads; hosts supply schema-based forms. | | `PathValueField` | Required `DiagramVectorPath defaultValue` | An editable path in unit coordinates, read by `ShapeOutline.editablePath()` and edited point by point. | | `InkValueField` | None | A freehand stroke (`DiagramInk`), read by `ShapeOutline.ink()`. Every instance supplies its own ink; there is no default. | | `ImageValueField` | None | An optional image (`DiagramImageSource`), shown by `ShapeImage(valueKey)`; `null` until chosen. | | `definition.createValues(overrides)` | Optional value map | Materializes defaults and validates overrides, useful when constructing a `ShapeElement` directly. | | `controller.edits.createShape(values: ...)` | Partial value map | Supplies remaining defaults once during creation. | | `controller.edits.setValues(id, patch)` | Shape ID and partial value map | Performs the `setValues` [verb](/agent-docs/api/verbs.md); returns `EditResult`; one admitted update is one undo unit. | | `ShapeElement.values` | Read-only value map | Preserved by copy, duplication, history and JSON. | Direct element insertion must contain every declared field; admission does not silently change supplied records. `setValues` denies unknown keys and values its field does not accept (`unsupportedOperation`) without publishing, as it denies host permission and lock rejections. An unchanged patch creates no history entry. Text elements do not accept custom shape values. Use the scalar fields for ordinary editable properties and `ObjectValueField` only for structured domain payloads. Custom field validation must be read-only and free of external side effects. During shape creation, grouping, and document admission, attempts to perform nested edits from a validator throw `StateError` before the candidate is published. Return whether the value is valid; submit any follow-up edit separately. `ShapeStyle.fields` describes the standard fill, stroke, stroke width, corner radius and stroke style using these same field types. A style remains one typed value; this metadata does not create a second property store. Custom color fields store ARGB integers in `ShapeElement.values`, while typed appearance properties use `DiagramColor`. ### Continuous control edits In a shape widget, call `shape.beginValueEdit()` on its [widget context](/agent-docs/api/widgets.md#shapewidgetcontext), call `preview(patch)` during a drag, then `commit()` or `cancel()`. The returned `ShapeValueEdit` holds an interaction lease on which each preview performs `setValues`. Previews start from the original values; commit adds one undo step. Cancellation, denial or owner disposal restores the original values. While the edit is active, other controllers' edits to that shape are denied, and closed edits reject later callbacks. ```dart final edit = shape.beginValueEdit(); edit.preview({'progress': 40}); edit.preview({'progress': 70}); final result = edit.commit(); ``` ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; ShapeValueEdit beginValueEdit() // on ShapeWidgetContext // Methods and property on the returned edit: bool get isActive EditResult preview(Map patch) EditResult commit() void cancel() ``` | Member | Contract | | --- | --- | | `beginValueEdit()` | Requires an enabled context for an existing unlocked shape and an idle controller. Throws `StateError` when read-only, for a missing or locked shape, or while the controller holds another interaction. | | `isActive` | Whether this edit still owns the interaction. Becomes `false` after completion, cancellation or controller disposal. | | `preview(patch)` | Performs `setValues` with the patch on the lease, starting from the **starting** value map. Include all fields intended for the current preview; successive calls do not accumulate patches. Returns the admission result. | | `commit()` | Requests a committed edit through admission. An inactive edit returns denial and cannot commit another interaction. | | `cancel()` | Restores the starting state while active; safely does nothing after the edit closes. | Unknown fields and invalid values are denied like rejected admitted operations, so host controls handle one outcome: the result. Cancel an active edit when its control is unmounted or its gesture is abandoned. The [widget context](/agent-docs/api/widgets.md) adds mounted slot ownership checks. Pure Dart hosts use `controller.edits.setValues(id, patch)` for discrete edits and [`controller.beginInteraction(label)`](/agent-docs/api/controller.md#interactions) for continuous ones, performing `setValues` on the lease: ```dart final lease = controller.beginInteraction('Edit shape values'); lease.perform([id], 'setValues', {'values': {'progress': 40}}); lease.commit(); ``` ### Appearance editing limits The inspector bounds shape border width to 32 and corner radius to 200 world units. These limits govern editing controls; they do not normalize imported or programmatically authored appearance values. Connector-label badges declare their own limits through `ConnectorLabelingCapability.appearanceEditing`. A clipping container always shows its border so its extent stays visible: when its stroke is fully transparent, the canvas and SVG draw a dark hairline of at least 1.5 units instead. Dividers and image placeholders inside a body use at least a 1-unit stroke. These fallbacks affect the rendered projection only; they do not change the stored `ShapeStyle`. ## Adjustment handles An adjustment is an on-canvas handle bound to a numeric value, such as an arrow's head length. Dragging it sets the value within the field's `minimum`, `maximum` and `integer` bounds, and the outline recomputes from the new value. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final arrow = ShapeDefinition( type: 'acme.arrow', outline: ShapeOutline.path((size, values) { final head = (values['head']! as num).toDouble() * size.width; return DiagramVectorPath.polyline([ DiagramPoint(0, size.height * .3), DiagramPoint(size.width - head, size.height * .3), DiagramPoint(size.width - head, 0), DiagramPoint(size.width, size.height / 2), DiagramPoint(size.width - head, size.height), DiagramPoint(size.width - head, size.height * .7), DiagramPoint(0, size.height * .7), ], closed: true); }), values: { 'head': const NumberValueField(defaultValue: .3, minimum: .1, maximum: .6), }, adjustments: [ ShapeAdjustment( field: 'head', label: 'Arrowhead length', position: (values) => DiagramPoint(1 - (values['head']! as num).toDouble(), 0), direction: (_) => const DiagramPoint(-1, 0), ), ], ); ``` | `ShapeAdjustment` argument | Contract | | --- | --- | | `field`, `label` | Required. The `NumberValueField` the handle sets, and its accessible name. | | `step`, `pixelsPerStep` | `.01` per `4` pixels of scrubbing by default. | | `handle` | `ShapeAdjustmentHandle.diamond` or `circle`. | | `position` | The handle's unit-coordinate position for the current values; null places it on the frame's top edge. | | `direction` | The shape-local direction that increases the value; null scrubs right/up. | | `drag` | Maps a unit-coordinate pointer delta to a value, or returns null to scrub. | | `snapStops` | Meaningful values for magnetic snapping, or strict snapping with Shift. | The [adjustable shapes](/agent-docs/examples/adjustable.md) use adjustments for arrows, stars, arcs and callouts. ## Plain line `Shapes.line` is a standard shape: an open editable path that starts as a horizontal stroke through its frame center. Drag its endpoints to change its length and direction, or rotate it. It has no text, ports, arrowheads, or connector endpoint bindings. `DiagramTools.connector` remains the existing connector tool. ```dart controller.edits.createShape( Shapes.line, at: const DiagramPoint(160, 120), size: const DiagramSize(200, 8), ); ``` ## Editable paths A line or polyline is an editable path with straight segments and corner nodes. The same `DiagramVectorPath` can mix straight and cubic Bézier segments, and can be open or closed. Closed paths require at least three nodes; open paths require two. Only closed paths paint their fill. A path shape stores its geometry in its `path` value, a `PathValueField` that its `ShapeOutline.editablePath()` outline reads. Read it with `DiagramVectorPath.fromValue(shape.values['path'])`; the path verbs below write it. Declare your own editable path shape the same way: ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final route = ShapeDefinition( type: 'acme.route', outline: ShapeOutline.editablePath(), body: null, values: { 'path': PathValueField( defaultValue: DiagramVectorPath.polyline( const [DiagramPoint(0, 1), DiagramPoint(.5, 0), DiagramPoint(1, 1)], ), ), }, behavior: const ShapeBehavior(resizable: false), ); ``` ```dart final pathId = controller.createPath( at: const DiagramPoint(240, 160), size: const DiagramSize(240, 160), path: DiagramVectorPath.polyline( const [DiagramPoint(0, 0), DiagramPoint(1, 0), DiagramPoint(1, 1)], closed: true, ), ); controller.edits.setPathSegmentKind( pathId, 'node-0', DiagramPathSegmentKind.cubic, ); controller.edits.setPathHandleMode( pathId, 'node-1', DiagramPathHandleMode.symmetric, ); controller.edits.addPathPoint(pathId, after: 'node-0', id: 'extra'); ``` For authored curves, construct `DiagramVectorPath(nodes: [...])` using `DiagramPathNode(id:, position:, incoming:, outgoing:, mode:, segment:)`. Positions and tangent offsets use frame-local unit coordinates. `segment` describes the segment leaving that node, including the closing segment. Node IDs are unique within their path and survive edits and persistence. The path verbs are `setPathClosed`, `setPathHandleMode`, `setPathSegmentKind`, `addPathPoint`, `removePathNodes`, and `movePathControl`. Each returns an admission result and records one undo entry when allowed. Invalid node counts, IDs or coordinates are rejected without changing the document. `addPathPoint` uses De Casteljau subdivision to preserve cubic geometry. Moving a node recomputes the frame while preserving the other points through rotation and containment. Handle modes: `corner` is independent; `smooth` keeps opposite directions; `symmetric` also keeps equal lengths. Choose **Path** (`P`) and drag to create a path. Drag vertices to edit it or hover and drag a midpoint to insert a point. The inspector controls closure, point type and insertion/removal. Smooth and Symmetric add Bézier handles; Corner collapses them. Edits support commit, cancel and undo. The playground also exposes **Polygon** (`G`) in its toolbar. ## Surface fills and rounded corners `ShapeStyle.fill` accepts the closed `DiagramFill` grammar. Existing `DiagramColor` values remain valid solid fills: ```dart final gradient = DiagramLinearGradient( begin: const DiagramPoint(0, 0), end: const DiagramPoint(1, 1), stops: const [ DiagramGradientStop(0, DiagramColor(0xFF6366F1)), DiagramGradientStop(0.4, DiagramColor(0xFFEC4899)), DiagramGradientStop(1, DiagramColor(0xFFFFC857)), ], ); controller.edits.setStyle(ids: [pathId], fill: gradient, cornerRadius: 12); ``` Use `const DiagramFill.none()` for no fill, or `DiagramRadialGradient(stops:, center:, radius:)` for a radial fill. Gradient coordinates are normalized to the shape frame; radial radius is a fraction of its shorter side. They move and rotate with the shape. Stops are immutable, ordered, and contain at least two finite offsets in `[0, 1]`; duplicate offsets permit hard color transitions. Each stop supports alpha. Linear endpoints must differ, and radial radius must be positive. Invalid paints fail admission. The inspector uses a single gradient bar: click to add a stop, drag its handle to change its position, and select it to edit its color or remove it. Arrow keys adjust the selected stop; Delete removes it while retaining at least two stops. It also supports fill kind, stop positions, linear angle, and radial center/radius. JSON, canvas, minimap and SVG preserve the full fill. SVG uses native linear/radial gradient resources. Sweep gradients are not currently supported. `representativeColor` is available for contrast or simplified host UI; it is not a replacement for rendering the full gradient. `cornerRadius` is measured in world units. Rectangles, regular polygons and editable paths support it; long radii clamp to adjacent segment lengths. Path rounding changes resolved geometry without rewriting the authored nodes or handles. Smooth joins and open endpoints are preserved. Ellipses have no corners. A custom definition offers corner-radius editing whenever its outline rounds corners: `ShapeOutline.rect()`, `regularPolygon()`, `editablePath()`, or a `path`/`normalized` outline declared with `cornerRadius: true`. Body surfaces also accept `DiagramFill`. `ShapeStyle.fill` is a `DiagramFill`: a solid `DiagramColor`, a gradient or no fill. To read a solid color, pattern-match `DiagramColor(:final argb)`; to choose a contrasting color for any fill, use `fill.representativeColor`. ## Simple paths and declarative inspectors Use `controller.edits.createLine(start: ..., end: ...)` for two world-space points, or `controller.edits.createPolyline(points: ..., closed: true)` for a polygon. Open paths require two points; closed paths require three. Both return a result whose `id` is the element ID, and create one undo step. Use `controller.createPath` when you need explicit normalized nodes, tangents and frame geometry. `controller.edits.addPathPoint(id, after: nodeId)` splits a segment without changing its curve; the result's `id` is the new point ID. `setPathHandleMode` converts that point to a corner, smooth or symmetric handle. `ShapeDefinition(type: 'card')` provides a rectangle with inset text. Its inspector's standard editors always follow its anatomy. Inspector visibility does not change permissions. See [common tasks](/agent-docs/guide/common-tasks.md) for examples. The inspector's shape properties follow the anatomy alone: clipping for a clipping container, points for an editable path, fill and stroke for an outline, corner radius for a rounded outline, sides for a polygon, one standard control per declared value, an image and text. Hosts add their own through a `DiagramPropertySource`. See [properties and the inspector](/agent-docs/guide/properties.md). ## Compound shapes and libraries Use `ShapeDefinition.body` to arrange reusable parts with `ShapeRow`, `ShapeColumn`, `ShapeStack`, `ShapeSized`, `ShapePadding` and `ShapeOutside`, around leaves such as `ShapeText`, `ShapeSurface`, `ShapeDivider`, `ShapeImage` and `ShapeWidget`. A body contributes minimum dimensions and compiles into the shape's layers. See [shape anatomy](/agent-docs/guide/shape-composition.md) for layout rules, named text slots, parts, and libraries. ## Tables The table extension contributes a standalone table shape (`TableExtension.shapeType`). Embed the same content in another shape with `ShapeTable('members', rows: 2, columns: 1)` inside its body. The table fills that declared region; wrapped cell content grows its row and the owning shape. Columns start equally spaced and wrap text at their assigned width. A story owns `TextTable` elements with nested `DiagramTableRow` and `DiagramTableCell` elements. Cells accept body paragraphs with inline styling; headings, lists, and nested tables are rejected by the grammar. In the editor, Enter adds a row below the active cell and keeps the same column. Shift+Enter adds a line within the cell. Tab moves across cells and then into the next row; Tab at the final cell appends a row. Shift+Tab moves backward. Drag a vertical divider to resize the column on its left, or a horizontal divider to resize the row above. Other track sizes stay unchanged and the enclosing shape follows the new table size. Minimum sizes come from one measured character plus padding and the cell's text height. The inspector also exposes exact sizes and add/remove row and column controls. At least one row and one column must remain. Use the [table verbs](/agent-docs/api/tables.md#verbs) on the controller for the same structural and sizing edits. Outer borders, inner row borders, and inner column borders have separate color, width, and solid/dashed/dotted/none styles. Row and column separator overrides are supported; cell-level borders and merged cells are not part of this initial grammar. --- # Table extension Tables are optional structured content, installed through the portable extension and, for interactive table chrome, its Flutter extension. | Library | Holds | | --- | --- | | `package:vyuh_diagram_extension_table/vyuh_diagram_extension_table.dart` | `TableExtension` (`TableExtension.shapeType`, `TableExtension.toolId`), `ShapeTable`, `ShapeTableStyle`, `ShapeTableControls`, `ShapeTableCapabilities`, `ShapeTableControlPresentation`, `TableCellSelection`, `DiagramTableDirection` and the typed `DiagramTableVerbs`. | | `package:vyuh_diagram_extension_table/extension_api.dart` | The table model (`TextTable`, `DiagramTableCell`, `DiagramTableRow`, `DiagramTableColumn`, merges, ranges, `DiagramTableNavigation`), `TableStoryContent` (`story.tables`), the `DiagramTables` and `DiagramTableCells` reads and navigation, the codec, layout and geometry, `ShapeTableLayerDefinition`, `tableVerbs` and `tableProperty`. | | `package:vyuh_diagram_extension_table_flutter/vyuh_diagram_extension_table_flutter.dart` | `TableFlutterExtension`, `TableFlutterOptions`, `TableOverlayMode` and `TableTheme`. | ## Install and create ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_extension_table/vyuh_diagram_extension_table.dart'; import 'package:vyuh_diagram_extension_table_flutter/vyuh_diagram_extension_table_flutter.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [EditorExtension(), TableFlutterExtension()], ), ); final ownerId = controller.createShape(TableExtension.shapeType, at: const DiagramPoint(200, 160)); // DiagramCanvas(controller: controller) ``` `TableExtension({tool = true, shortcut})`, id `vyuh.table`, contributes the table shape (`TableExtension.shapeType`), its creation tool (`TableExtension.toolId`, activated by `shortcut`, Shift+T by default) unless `tool` is false, and the table content, which pairs `TableContentLayoutProvider` with `TableContentCodec`. The content type is `vyuh.content.table`. `TableFlutterExtension()` installs `TableExtension()` as a dependency, so a Flutter application lists only `TableFlutterExtension()`; a pure Dart host installs `TableExtension()`. No table implementation is installed by the foundation default. ## Compose a custom table shape ```dart import 'package:vyuh_diagram_extension_table/vyuh_diagram_extension_table.dart'; import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final grid = ShapeDefinition( type: 'app.grid', body: const ShapeTable( 'body', rows: 4, columns: 3, controls: ShapeTableControls( capabilities: ShapeTableCapabilities(mergeCells: false, mergeRows: false), ), ), ); final grids = DiagramExtension( id: 'app.grids', dependencies: [TableExtension()], shapes: [grid], ); ``` | Declaration | Configuration | | --- | --- | | `ShapeTable` | A content part: stable slot ID, initial `rows`/`columns` (default 3), `controls`, `style` and cell `textType`. Nest inside rows, columns, stacks and padding. | | `ShapeTableLayerDefinition` | What a `ShapeTable` compiles to in `definition.layers`; read it, do not author it. | | `ShapeTableControls` | Row/column controls, labels, row renaming and control presentation. | | `ShapeTableCapabilities` | Add/remove/resize rows and columns, merge cells or whole rows, unmerge, resize table. Defaults allow each operation. | | `ShapeBehavior` | Outer shape movement, rotation, selection and resizing. | Presentation is not permission. Hidden controls do not disable verbs; use the capability declaration to deny operations. `resizeTable: false` makes the owning shape not resizable. Initial rows and columns must each be at least one. ## Flutter overlays ```dart final tableUi = TableFlutterExtension( standalone: TableOverlayMode.full, embedded: TableOverlayMode.minimal, theme: const TableTheme(range: Color(0xFF0A7D5A)), ); // Install tableUi in the configuration's extensions. // Later, change the overlays at runtime. controller.edits.setOptions( controller.options().copyWith( embedded: TableOverlayMode.off, ), ); ``` `TableFlutterExtension({standalone, embedded, resolve, theme})` owns `TableFlutterOptions`, which holds all of its settings; the table behavior reads them live. Modes are `full`, `minimal` and `off`; defaults are full for standalone tables and off for embedded tables. `resolve(owner, table)` can override individual instances, and `TableFlutterOptions.modeFor(owner, table)` returns the mode that applies. `theme` is the selected cell-range color, or null for the canvas selection color. A layer's explicit `ShapeTableControlPresentation` overrides automatic standalone/embedded selection. Overlays do not affect exported appearance. `TableFlutterExtension.rangeHighlightKey` keys the painted highlight of a selected cell range, for widget tests. ## Verbs Each table part offers the table [verbs](/agent-docs/api/verbs.md), declared by `ShapeTableLayerDefinition.verbs`. A shape with one table offers them under their plain names, such as `insertRow`; a shape with several addresses each table as `part.verb`, such as `primary.insertRow`, where the part is the table's slot ID. Importing the table model package enables the typed `DiagramTableVerbs` extension on `DiagramController`; its `part:` argument names the table and is omitted for a shape with one table. ```dart controller.edits.insertRow(ownerId, at: 1); controller.edits.setCellText(ownerId, cell: cellId, text: 'Total'); controller.edits.perform([entityId], 'primary.insertRow', {'at': 2}); ``` | Verb | Arguments after the owner ID | | --- | --- | | `insertRow` / `removeRow` | `at`; `insertRow` also takes optional `focusColumn` | | `insertColumn` / `removeColumn` | `at` | | `removeTracks` | `anchor`, `focus` cell IDs; `rows` (true for rows, false for columns) | | `resizeRow`, `resizeColumn` | `index`, new `height`/`width` | | `mergeCells` / `splitCell` | `anchor`, `focus` cell IDs; `cell` | | `setCellText` | `cell`, `text` | | `clearCells` | `anchor`, `focus` cell IDs | | `setBorders` | `outer`, `rows`, `columns` borders | | `setRowBorder`, `setColumnBorder` | `index`, nullable `border` | Calls through `controller.edits` return `EditResult`; inspect `allowed` or call `requireAllowed()`. Capabilities declared in `ShapeTableCapabilities` deny the matching verbs. The `DiagramTables` and `DiagramTableCells` extensions, from `package:vyuh_diagram_extension_table/extension_api.dart`, add reads and navigation, which are not verbs. Owner IDs identify the containing shape; table IDs identify its structured content, not a row index. Read the table from the owner's story contents and retain its stable IDs. | Method | Meaning | | --- | --- | | `tableControls(ownerId, tableId)` | The declared table controls | | `resolvedTable(ownerId, tableId)` | Resolved geometry, or null | | `selectTableCells(ownerId, tableId, anchor, focus)` | Selects a cell range | | `focusTableCell(ownerId, tableId, cellId)` | Places text editing in a cell | | `navigateTableCell(ownerId, cellId, backward: false)` | Moves to the next or previous cell, appending a row past the last; returns a boolean | Shared undo/redo, selection and clipboard use the canonical document. ## Persistence and output Save with `controller.save(DiagramJsonCodec.new)` and open with `controller.edits.load(json, format: DiagramJsonCodec.new)`; both build the codec over the installed extensions' codecs, so the table content codec is included. Table layout lowers to shared resolved primitives for SVG output; the SVG codec does not need a Flutter table widget. See [table examples](/agent-docs/elements/tables.md), [shape anatomy](/agent-docs/guide/shape-composition.md) and [Rich Text](/agent-docs/api/rich-text.md) for related configuration. --- # Plain Text Plain Text is included by the core extensions. It supports text entry, replacement, selection, wrapping and shared undo/redo, without rich-text marks, lists or headings. For formatting and list operations, see [Rich Text](/agent-docs/api/rich-text.md). ## Create standalone text ```dart import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration(extensions: [EditorExtension()]), ); final id = controller.createText(at: const DiagramPoint(100, 100), text: 'Hello diagram'); controller.setText(id, 'Updated text'); // DiagramCanvas(controller: controller) ``` ## Compose text inside a shape ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; final card = ShapeDefinition( type: 'app.card', body: const ShapeText( 'title', text: 'A plain title', textType: PlainTextDefinition(maxLines: 1), ), ); ``` Register it through the `shapes` of a portable `DiagramExtension`. See [Shapes](/agent-docs/api/shapes.md) and [shape anatomy](/agent-docs/guide/shape-composition.md). ## Definitions and layout Standalone text is a core element. The core text extension (`vyuh.core.text`), always installed, contributes the plain text type (`PlainTextDefinition`, named `text`) through `textTypes`. Every installed text type is also a type of the standalone text element, whose element `type` is the text type's name: `text` for plain text, `richText` once `RichTextExtension()` from the [Rich Text extension](/agent-docs/api/rich-text.md) is installed. The core gives each one the same standard bounds, minimum/default size, capabilities and layers, filled by that text type; `registry.requireText(type)` reads it. | ShapeText option | Purpose | | --- | --- | | Positional slot ID | Stable story region identity | | `text` | Initial content | | `textType` | The text filling the slot: `PlainTextDefinition` (default) or `RichTextDefinition`, each with `maxLines` (1 is single-line, completing on Enter; 0 is unlimited) | | `editable` | Whether this slot can be edited | | `alignment`, `verticalAlignment` | Text placement | | `horizontalPadding`, `verticalPadding` | Region inset | | `overflow` | Allow single-line text to extend beyond its region | Text layout, selection and input use the same resolved geometry. Standalone text has a frame and story; it does not need a painted shape background. ## Replacement and selection `controller.edits.setText(id, text)` accepts optional `slot:` and `storyId:` for multiple regions or stories. Other slots are preserved. Replacement removes formatting in the target region and participates in normal admission and history. A denial is available through `allowed`; `requireAllowed()` throws on denial. The shared model uses `TextStory`, `TextParagraph` and `TextRun` even for Plain Text. Supporting styled runs in the schema does not enable a Rich Text editor. Install the [rich-text extension](/agent-docs/api/rich-text.md) explicitly for that behavior. --- # Verbs A verb is a named, typed edit: the one way anything changes a diagram. The property inspector, canvas overlays, toolbars, keyboard shortcuts, context menus, agents and your own code all perform the same verbs through `DiagramController.perform`. Every verb is admitted like any other edit (locks, the diagram's rules, other actors' leases), records one undo entry. Direct calls complete or throw on refusal; calls through `controller.edits` return an `EditResult`. ## On this page | Category | What you can do | | --- | --- | | [Performing verbs](#performing-verbs) | Perform a verb by name, or through a typed extension. | | [Discovery](#discovery) | List the verbs an element offers, with schemas and availability. | | [Who declares verbs](#who-declares-verbs) | Element, shape and part verbs, and how a shape binds its parts. | | [Results](#results) | Denials, created identities and stale revisions. | | [Previews](#previews) | Perform verbs on an interaction lease for slider and handle drags. | | [Symmetry](#symmetry) | Why every verb is two-way. | | [Writing verbs](#writing-verbs) | Declare a verb for your shape, part or extension. | | [Selection, camera and tool](#selection-camera-and-tool) | Selection, camera, tool and options, which are not verbs. | | [Core verbs](#core-verbs) | The verbs every diagram offers. | ## Performing verbs ```dart EditResult perform( Iterable ids, String verb, [ Map args = const {}, ]) ``` `ids` names the elements a verb acts on: one element for a shape's own verbs, one or more for element verbs such as `move`, and none for diagram verbs such as `createShape`. ```dart controller.edits.perform([cardId], 'setTitle', {'title': 'Orders'}); controller.edits.perform([cardId, noteId], 'setOpacity', {'opacity': .5}); controller.edits.perform([entityId], 'primary.insertRow', {'at': 2}); final created = controller.edits.perform(const [], 'createShape', { 'type': Shapes.rectangle, 'at': {'x': 0, 'y': 0}, }); final id = created.id!; ``` Arguments accept Dart values and, for agents, their JSON form: an enum or a route by name, a color as an ARGB integer, a point as `{x, y}`, a size as `{width, height}` and a rectangle as `{left, top, width, height}`. The package that owns a verb also ships a typed extension on `DiagramController`, a thin wrapper over `perform`: ```dart controller.edits.setTitle(cardId, 'Orders'); controller.edits.move(const DiagramPoint(40, 0), ids: [id]); controller.edits.insertRow(entityId, at: 2, part: 'primary'); controller.edits.setMark(elementId: id, mark: TextMark.bold, on: true); ``` ## Discovery | Member | Returns | Meaning | | --- | --- | --- | | `verbs([ids])` | `List` | The verbs on `ids`: with none, the diagram verbs; with one, that element's verbs, including its parts'; with several, the element verbs they share. | | `verb(ids, name)` | `DiagramVerbDescription?` | One verb on `ids`, or null when none by that name applies. | | `canPerform(ids, verb, [args])` | `EditResult` | Whether `perform` would run, and why not. Nothing is published. | | `applyTo(element, verb, [args])` | `DiagramElement?` | What a setter makes of an element outside the document, such as the next shape a tool creates. | A description carries `name`, `label`, `parameters`, `symmetry`, the bound `part` and `availability`, a result that answers for the current state without arguments. Each `DiagramVerbParameter` has a `name`, a `type` such as `number`, `choice`, `point` or `story`, whether it `isRequired`, and for scalars a `schema` that is the same `ValueField` shape values use, such as a `NumberValueField` with its bounds or a `ChoiceValueField` with its options. ```dart for (final verb in controller.verbs([id])) { print('${verb.name}(${verb.parameters.join(', ')}) ' '${verb.isAvailable ? '' : '- ${verb.availability.reason}'}'); } ``` ## Who declares verbs Verbs belong to the definitions that own them: | Declared by | Examples | Where | | --- | --- | --- | | Extensions: element and diagram verbs | `move`, `setStyle`, `setLocked`, `delete`, `createShape`, `connect` | `DiagramExtension(verbs: [...])`; core installs `diagramCoreVerbs`. | | A shape's own verbs | a card's `setTitle`, `setTag`, `setDescription`; an entity's `showSecondarySection` | `ShapeDefinition(verbs: [...])` | | Text parts | `setText` | `DiagramTextDefinition.verbs`, bound to each text part | | Text stories | rich text's `setMark`, `setHeading`, `setList`, `setChecked` | `DiagramTextDefinition.storyVerbs`, offered once by every element holding that text, including table cells (`ShapeContentLayerDefinition.texts`) | | Content parts | a table's `insertRow`, `mergeCells`, `setCellText`, `setBorders` | `ShapeContentLayerDefinition.verbs` | A shape's verb set is the element verbs that apply to it, its own verbs, and each part's verbs bound to that part. A part verb is offered as `part.verb`, such as `title.setText`, and also under its plain name when only one part offers it: a rectangle's body text is `setText`, while a card has `title.setText`, `tag.setText` and `body.setText`, and an entity has `primary.insertRow` and `secondary.insertRow`. Callers never name slots or content records; the binding carries them. ## Results Calls through `controller.edits` return an `EditResult`: | Outcome | Result | | --- | --- | | Performed | `allowed`; a creating verb reports the identity in `id`. | | Unknown verb, missing or invalid argument, such as a non-finite number, an undeclared shape value or a replacement that changes a story's identity | `DiagramDenialCode.unsupportedOperation` with a reason. | | Missing target, label or cell | `DiagramDenialCode.unavailableTarget`. | | Locked target or owner | `DiagramDenialCode.locked`, from admission. | | Stale `expectedRevision`, or a stale `before` story | `DiagramDenialCode.conflict`. | | A rule or another actor's preview | its code and reason. | Calls through `controller.edits` report a denied edit in the result. Direct methods throw `DiagramChangeDenied` for that same denial. Both paths can also throw for misuse of the controller itself, such as calling it after `dispose`, performing a verb while this controller holds a gesture lease, or inserting an authored record (`add`, a raw transaction) that breaks the installed grammar, which is a programming error in the record. Typed wrappers that compute arguments before performing, such as `createPolyline` with fewer than two points, throw `ArgumentError` for input they cannot compute from. Every verb accepts the argument `expectedRevision`: pass the document revision captured before awaiting a file, dialog or network response, and a document that changed meanwhile is denied as a conflict instead of overwritten. ```dart final revision = controller.document.revision; final source = await pickImage(); controller.edits.perform([id], 'setImage', { 'image': source, 'expectedRevision': revision, }); ``` Inside a direct `batch`, a refused edit throws and rolls back all earlier changes. With `controller.edits.batch`, inspect the result; call `requireAllowed()` on a refused nested result when the entire batch must stop. ## Previews A continuous edit, such as a slider drag, performs the same verb on an interaction lease. Each preview starts over from the lease's baseline, so previews never drift; `commit` records one undo entry and `cancel` restores the baseline. ```dart final lease = controller.beginInteraction('Change opacity'); lease.perform([id], 'setOpacity', {'opacity': .8}); lease.perform([id], 'setOpacity', {'opacity': .4}); lease.commit(); ``` `performAll([DiagramVerbInvocation(ids, verb, args), ...], selection: ...)` previews several verbs at once. A cumulative lease (`beginInteraction(label, cumulative: true)`), as text composition uses, adds each preview to the last instead, and yields: an unrelated edit, an undo or a new interaction commits it first. Custom tool gestures return a `DiagramGesturePreview` of verb invocations for each pointer sample. ## Symmetry Every verb is a forward-moving edit, and every verb is two-way, so an agent can always state the reverse edit. Undo is history, never a reverse verb. Each verb declares its `DiagramVerbSymmetry`: | Symmetry | Meaning | Examples | | --- | --- | --- | | `setter` | Performing it with the previous value reverses it. | `setLocked(false)`, `setTag(null)`, `setImage(null)`, `reparent(parent: null)`, `move(-delta)` | | `pair(counterpart)` | Half of a declared pair; the counterpart is itself a pair verb. | `insertRow`/`removeRow`, `group`/`ungroup`, `frame`/`unframe`, `addSlot`/`removeSlot`, `addConnectorLabel`/`removeConnectorLabel`, `createShape`/`delete` | | `derived(reversedBy)` | Derives new values that the named setter expresses. | `align`, `distribute` and `arrangeLanes` (`setElementBounds`), `reorder` (`setZIndex`), `reroute` (`setRouteGeometry`), `clearFormatting` (`replaceText`) | There are no toggles. A control that toggles performs the setter with the opposite of the current value, such as `setMark(mark, on: !isBold)` or `setList(kind: isList ? ParagraphKind.paragraph : kind)`. Building a diagram validates every installed verb, so a one-way verb, whose counterpart or setter is missing, fails assembly. ## Writing verbs Performing verbs needs only the main library. Writing one uses `DiagramVerb`, `DiagramVerbTarget`, `DiagramVerbSymmetry` and `DiagramVerbCall` from `package:vyuh_diagram_flutter/extension_api.dart`; `DiagramVerbParameter` and `DiagramVerbDescription` stay in the main library because discovery returns them. ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final countParameter = DiagramVerbParameter.integer('count', minimum: 0); final setCount = DiagramVerb.update( id: 'setCount', label: 'Count', parameters: [countParameter], update: (shape, call) => shape.copyWith( values: {...shape.values, 'count': call.read(countParameter)}, ), ); final counter = ShapeDefinition( type: 'counter', values: const {'count': NumberValueField(defaultValue: 0, integer: true)}, verbs: [setCount], ); extension CounterVerbs on DiagramController { EditResult setCount(String id, int count) => perform([id], 'setCount', countParameter.withValue(count)); } ``` `DiagramVerb.update` declares a setter that replaces each target element. For anything else, `DiagramVerb(perform: ...)` receives a `DiagramVerbCall` with the controller, the targets `ids`, the decoded `args`, the bound `part` and `submit(transaction)`, the low-level `dispatch` that verb implementations build on. Text extensions build on `call.updateText`. A verb may compose other verbs with `controller.perform` inside `controller.batch`. | `DiagramVerb` argument | Meaning | | --- | --- | | `id`, `label`, `description` | The name callers perform, and how tools show it. | | `parameters` | `DiagramVerbParameter.boolean`, `.number`, `.integer`, `.text`, `.choice`, `.color`, `.point`, `.size`, `.rect`, `.ids`, `.values`, `.motion` or `.value`. | | `symmetry` | See [symmetry](#symmetry). | | `target` | `DiagramVerbTarget.diagram`, `.element` or `.elements`. | | `appliesTo(element, registry)` | Whether an element offers the verb. | | `check(call)` | Why the verb cannot run on its targets, without arguments; null when it can. | | `admitsLockedTargets` | Lets the verb target locked elements, as unlocking does; its edit is still admitted. | Only verb implementations construct transaction steps or call `dispatch`; the repository's boundary check rejects raw transactions anywhere else, including the demo app. ## Selection, camera and tool Selection, camera, active tool, creation styles and options are not part of the document or its history, so they are not verbs. They change through plain controller methods that are not undoable and are not admitted by the diagram's rules: `setSelection`, `select`, `selectAll`, `clearSelection`, `setCamera`, `setTool`, `setShapeCreationStyle`, `setConnectorCreationRoute` and `setOptions`. Select a connector label or path points with `setSelection(ConnectorLabelSelection(...))` or `setSelection(PathPointSelection(...))`. ## Core verbs Element verbs, on one or more elements: | Verb | Arguments | Symmetry | | --- | --- | --- | | `delete` | — | pair `add` | | `setLocked`, `setVisible` | `locked`, `visible` | setter | | `setOpacity` | `opacity` (0–1) | setter | | `setZIndex` | `zIndex` | setter | | `setStyle` | `fill`, `stroke`, `strokeWidth`, `cornerRadius`, `strokeStyle`, `inkPreset` (each optional) | setter | | `setAspectLocked` | `locked`, `square` | setter | | `setPorts`, `setImage`, `setValues`, `setClipContent`, `setPolygonSides`, `setType` | `ports`, `image`, `values`, `clip`, `sides`, `type` | setter | | `addSlot` / `removeSlot` | `slot`, `text` | pair | | `move`, `resize`, `rotate`, `setElementBounds`, `reparent`, `setFrameCollapsed` | `delta`, `motion`; `size`, `fromCenter`, `preserveAspectRatio`, `motion`; `pivot`, `radians`; `bounds`, `motion`; `parent`, `delta`; `collapsed` | setter | | `group` / `ungroup`, `frame` / `unframe` | — | pair | | `align`, `distribute`, `arrangeLanes`, `reorder` | `alignment`; `distribution`; `direction`, `laneSize`, `gap`; `order` | derived | | `duplicate` | `offset` | pair `delete` | | `setText` (text parts), `setTextStory`, `setTextAlignment`, `setTextDirection`, `replaceText` | `text`; `story`; `alignment`/`direction` with `storyId`, `start`, `end`; `before`, `after` | setter | | `setConnectorRoute`, `setConnectorStyle`, `setStartArrowhead`, `setEndArrowhead`, `reconnect`, `setRouteGeometry`, `setConnectorLabel` | route, style, end and label parts | setter | | `addConnectorLabel` / `removeConnectorLabel` | `text`, `story`, `fraction`, `offset`, `size`; `label` | pair | | `setPathClosed`, `setPathHandleMode`, `setPathSegmentKind`, `movePathControl` | `closed`; `node`, `mode`/`kind`/`control`, `position` | setter | | `addPathPoint` / `removePathNodes` | `after`, `t`, `id`; `nodes` | pair | Diagram verbs: `createShape`, `createText`, `add`, `createConnected`, `connect` and `paste` (each paired with `delete` and reporting `id`), `load` and `applyLayout` (`frames`, `label`, `motion`) (setters), `reroute` and `arrangeLabels` (derived). See [tables](/agent-docs/api/tables.md) for table part verbs, [rich text](/agent-docs/api/rich-text.md) for rich text verbs and [shapes](/agent-docs/api/extension-shapes.md) for card and entity verbs. --- # Widgets inside shapes A shape can mount Flutter controls in declared content slots. The shape registry owns slot geometry and portable fallback content; `DiagramFlutterExtension.widgets` owns Flutter builders. Durable control values live in `ShapeElement.values` and use the same validation, admission and history as other document changes. `ShapeWidget`, `ShapeWidgetBuilder`, `ShapeWidgetContext`, `ShapeValueEdit` and `DiagramFlutterExtension` are in `package:vyuh_diagram_flutter/extension_api.dart`. Open [Controls inside a node](/agent-docs/examples/widgets.md) to try the controls card with a slider, dropdown and counter button. ## On this page | Category | What you can do | | --- | --- | | [Define widget content](#declare-a-slot) | Place a widget part, declare values and portable fallback content. | | [Register controls](#register-flutter-builders) | Connect widget keys to Flutter builders. | | [Read and edit values](#shapewidgetcontext) | Read current values and submit validated updates. | | [Continuous editing](#a-slider-with-one-undo-step) | Preview a drag and commit it as one undo action. | | [Lifecycle and export](#focus-lifecycle-and-output) | Handle focus, replacement and exported fallback content. | | [Pointer behavior](#backgrounds-and-pointer-ownership) | Keep controls interactive and other areas draggable. | ## Compose a shape visually Start with the **outline**, divide the interior into **content regions** with layout parts, then choose the content for each region. Use the same terms whether the content is portable diagram text and artwork or live Flutter controls. | Term | Meaning | API | | --- | --- | --- | | Outline | The outer frame and visible contour. | `ShapeElement.frame`, `ShapeDefinition.outline` | | Content region | A meaningful area such as title, body or footer. These are names you choose, not special shape types. | Named text slots and part IDs | | Content layout | How regions and their content share the shape's interior. | `ShapeRow`, `ShapeColumn`, `ShapeStack`, `ShapeSized`, `ShapePadding`, `ShapeOutside` | | Region content | What appears there: text, surfaces, images, artwork or controls. | `ShapeText`, `ShapeSurface`, `ShapeDivider`, `ShapeImage`; `ShapeWidget` for a live widget | | Diagram layout | How whole shapes are positioned on the canvas. | Graph layout, including `LayoutExtension` | A shape's `body` declares its content layout. A column can give the title a fixed height, let the body fill the remaining space, and reserve a footer below it. A row can arrange an icon beside the title; a stack can layer content in the same region. See [shape anatomy](/agent-docs/guide/shape-composition.md) for the complete set of parts and resizing rules. A `ShapeWidget` is an ordinary body part, so a live control is placed with the same rows, columns and padding as text and artwork. There is no grid part; nest rows and columns for a fixed grid-like arrangement, and use Flutter's `Row`, `Column`, `Stack` or a grid inside a widget's own region. The outline controls the visible contour. Surfaces, images and widgets are clipped to it; text clips to its own region. Ports declare connection attachment points separately from content layout. Draw artwork with `ShapeSurface` parts: a surface's `outline` can be a `ShapeOutline.polygon(points)` for closed straight-sided artwork or a `ShapeOutline.normalized(path)` for open lines and Bézier curves, in unit coordinates of its region, with its own fixed `ShapeStyle`. Use `ShapeStack` for multiple pieces. Canvas and SVG output use the same path geometry. The widget builder receives the region's dimensions and arranges its own controls inside that space. The diagram handles moving, resizing and rotating the owning shape. The portable fallback part occupies the same region when no builder is available and in exported output. ## Declare a slot ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controlDefinition = ShapeDefinition( type: 'host.control', outline: const ShapeOutline.rect(), values: { 'progress': const NumberValueField( defaultValue: 35, minimum: 0, maximum: 100, ), }, body: ShapePadding( 12, child: ShapeWidget( 'host.slider', id: 'control', fallback: ShapeSurface( style: const ShapeStyle( fill: DiagramColor(0xFFEAF1FF), strokeWidth: 0, ), child: ShapePadding( 8, child: const ShapeDivider(edge: ShapeEdge.bottom), ), ), ), ), ); ``` The control has no text part, so it hosts no text and the inspector shows no paragraph or font controls. Its outline gives it fill and stroke; its value gives it a **progress** control. | `ShapeWidget` argument | Type | Contract | | --- | --- | --- | | `widgetKey` | `String` | Required positional builder lookup key; nonempty without surrounding whitespace. | | `fallback` | `ShapePart` | Required portable content, laid out inside the widget's region. Any part except another widget; it may contain text slots. | | `id` | `String?` | Optional stable name for the region, such as a port's `targetLayerId`. | Fallback text uses declared story slots and the shared paragraph layout. See [shape values and definitions](/agent-docs/api/shapes.md) for field schemas and shape creation. ## Register Flutter builders ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final controller = DiagramController( configuration: DiagramConfiguration( extensions: [ DiagramFlutterExtension( id: 'host.controls', shapes: [controlDefinition], widgets: { 'host.slider': (context, shape) => ProgressControl(shape: shape), }, ), ], ), ); DiagramCanvas(controller: controller); ``` A Flutter extension carries its portable contributions, here the shape definition, together with its widget builders. A pure Dart host that loads the same documents installs `DiagramExtension(id: 'host.controls', shapes: [controlDefinition])` instead; its shapes then show their fallback. The builder receives tight slot dimensions. Lay out your control locally; the canvas applies camera movement, rotation, clipping and scene stacking. | API | Arguments / result | Contract | | --- | --- | --- | | `ShapeWidgetRegistry(builders)` | `Map` | Copies the map immutably. Keys must be nonempty without surrounding whitespace. | | `const ShapeWidgetRegistry.empty()` | No arguments | Default registry; all widget slots display their portable fallback. | | `builderFor(key)` | `String` → `ShapeWidgetBuilder?` | Returns `null` when the host has no builder. The mounted canvas retains the fallback. | | `require(key)` | `String` → `ShapeWidgetBuilder` | Throws `StateError` for an absent key. | | `ShapeWidgetBuilder` | `Widget Function(BuildContext, ShapeWidgetContext)` | Builds the live presentation of one resolved slot. | Builders are Flutter extension contributions, never document content. A document can be loaded without its widget builders, provided its shape definitions are registered. ## `ShapeWidgetContext` The canvas supplies a fresh immutable context when canonical state changes. Read values from that context instead of keeping a second authoritative copy in widget state. Widget state may retain transient UI resources, such as focus or an active edit handle. | Member | Type / arguments | Contract | | --- | --- | --- | | `owner` | `ResolvedShape` | Resolved shape snapshot and its canonical `source`. | | `slot` | `ResolvedShapeWidgetSlot` | Resolved bounds and slot definition. | | `values` | `Map` | Immutable canonical values from the owner. | | `readOnly` | `bool` | Host read-only state for this projection. | | `enabled` | `bool` | False when read-only or locked. Use it to disable controls. Live callbacks still recheck ownership and admission. | ### Update widget values Use a discrete update for a button or dropdown, and a continuous edit for a drag. Both participate in the drawing’s validation and undo history. | Member | Type / arguments | Contract | | --- | --- | --- | | `setValues(patch)` | `Map` → `EditResult` | Performs the `setValues` [verb](/agent-docs/api/verbs.md) on this owner, merging the supplied fields as one discrete edit. Unknown fields or invalid field values are rejected; a read-only or locked context returns a denied decision. | | `beginValueEdit()` | → `ShapeValueEdit` | Starts a bounded continuous edit for this owner on an interaction lease. Throws `StateError` when read-only or unavailable. | `enabled` is a UI hint, not an authorization boundary. The diagram's rules remain in the canonical verb path; controls should handle denied results when the application needs to explain them. ## A slider with one undo step Use `setValues` for discrete actions such as buttons, dropdown changes and keyboard slider adjustments. A drag owns a `ShapeValueEdit` until it commits or cancels; each preview performs `setValues` on its interaction lease: | Edit member | Arguments / result | Contract | | --- | --- | --- | | `isActive` | `bool` | Whether the owned interaction lease is active. | | `preview(patch)` | `Map` → `EditResult` | Performs `setValues` with the patch as a preview. Each patch starts from the original values, not the previous preview; include every field being changed together. An inactive edit returns a denied decision. | | `commit()` | → `EditResult` | Commits the accepted preview as one history operation. | | `cancel()` | `void` | Cancels the preview without adding an undo entry. | ```dart import 'package:vyuh_diagram_flutter/extension_api.dart'; class ProgressControl extends StatefulWidget { const ProgressControl({super.key, required this.shape}); final ShapeWidgetContext shape; @override State createState() => _ProgressControlState(); } class _ProgressControlState extends State { ShapeValueEdit? _edit; void _cancel() { _edit?.cancel(); _edit = null; } @override void dispose() { _cancel(); super.dispose(); } @override Widget build(BuildContext context) { final shape = widget.shape; return Listener( onPointerCancel: (_) => _cancel(), child: Slider( value: (shape.values['progress'] as num).toDouble(), max: 100, onChangeStart: shape.enabled ? (_) { _cancel(); _edit = shape.beginValueEdit(); } : null, onChanged: shape.enabled ? (value) { final edit = _edit; if (edit != null) { edit.preview({'progress': value}); } else { shape.setValues({'progress': value}); } } : null, onChangeEnd: shape.enabled ? (_) { _edit?.commit(); _edit = null; } : null, ), ); } } ``` This example uses Flutter's `Slider`, `StatefulWidget` and `Listener`; import your Flutter UI library and `package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart`. Provide the usual UI-library ancestors required by your controls. The complete playground example is in [widget_card.dart](https://github.com/vyuh-tech/vyuh_diagram/blob/main/apps/demo/lib/playground/widget_card.dart). ## Focus, lifecycle and output Replacing a mounted slot's builder cancels its active value edit and restores the starting values before the replacement builder receives its context. Late callbacks from the old edit cannot commit or cancel a successor edit. The mounted canvas interleaves controls with ordinary scene paint and clips them to their slot, the owner outline and clipping ancestors. Selection handles, ports and higher scene content retain their input priority. The accessibility tree retains the object selection entry and ordinary story text, while omitting fallback text replaced by a live slot. Native controls supply their own Flutter semantics; when a builder is absent, the fallback text is announced again. This follows the same block filtering used by paint. Mounted fallback text is also excluded from canvas text editing. Enter, clicks, caret movement and selections target the visible text regions; headless verbs can still update the canonical fallback for portable output. The playground controls card is selectable, movable, resizable and rotatable. Its content belongs entirely to the widget, so its body has no text part. The inspector exposes its registered custom values, fill, border and locking, without paragraph or font controls. Because these follow from the anatomy, the inspector and the verbs always agree. Focused native controls own their keyboard input; Escape cancels the active value edit and returns focus to the canvas when it reaches the slot host. Starting a value edit from a pointer-only control gives its slot keyboard focus when no child already has it, so Escape can cancel a slider drag too. The slot does not add a Tab stop, and an already focused child keeps its focus. Use ordinary Flutter controls and preserve their keyboard and input-method behavior. Text controls should keep the composing range intact and apply a diagram value after composition finishes. Idle offscreen slots may unmount. Focused or pointer-active slots remain mounted until their interaction ends, preserving control state during panning. Deletion, unmounting, read-only/locked transitions and pointer cancellation cancel active edits. Release widget resources in `dispose`; do not store Flutter objects in shape values. Fallback parts provide portable geometry and text for export. They are static declarations, with no automatic value binding or Flutter-widget conversion. Export uses these parts, not widget screenshots. See [Output](/agent-docs/api/output.md) for SVG text and resource limits. ## Backgrounds and pointer ownership The shape definition owns the node background and border. Keep the native widget root transparent (for example, `Material(color: Colors.transparent)`). Padding, labels and other space without a control gesture select and drag the owning node. Sliders, buttons, dropdowns and text fields retain their native gestures. Keep decorative overlays inside `IgnorePointer`. A full-slot `GestureDetector` or `AbsorbPointer` can block diagram input. Interactive controls stay outside that wrapper. Use the shape’s fill and border rather than painting a duplicate widget background. --- --- title: Adjustable shapes --- # Adjustable shapes Arrows, stars, arcs/pies and callouts are part of the Shapes library. Add `ShapesExtension()` (it installs `TableExtension` itself) to the configuration's `extensions`; they are also available in the playground's Shapes library. Try the interactive example. Select arrows, stars, arcs/pies or callouts and drag their 8×8 adjustment controls. Arrow controls follow width and length axes, callout controls follow pointer displacement, and arc endpoints follow the pointer angle around the center. Star controls increase right/up and decrease left/down. Normal resize, rotation and undo continue to work. Adjustment drags do not pan the canvas. Controls gently snap near meaningful geometry stops. Hold Shift to constrain them to those stops: arcs and pies use 15° increments (45° magnetic stops otherwise), and callout pointers use the center and quarter points. Arrow proportions and star inner radii snap to common ratios. Release Shift to resume free adjustment. Four parametric families cover arrows (`DiagramShapes.arrow`), stars (`DiagramShapes.star`), arcs/pies (`DiagramShapes.arc`) and callouts (`DiagramShapes.callout`). Change an arrow's direction or double-head setting in the inspector. Toggle an arc's “Close To Center” value to make a pie. Core polygons already cover triangles, diamonds and hexagons by side count. These shapes do not implement the DrawingML document format. --- # Multi-selection and arrangement [Open runnable example](/examples-app/#/basics/arrangement) Start with three differently sized objects selected. **Align top** aligns their upper edges, then **Space evenly** equalizes the horizontal gaps while keeping the outer span. **Overlap** aligns their horizontal centers. **Moon to front** selects the moon and raises it above the other objects. Each content operation is a separate undo unit. Selection changes do not add to history. After selecting only the moon, distribution is denied: select all three again before retrying. Reset restores the original positions and empty history. ## Controller verbs | Call | Behavior | | --- | --- | | `selectAll()` | Select eligible document elements without modifying content or history. | | `align(DiagramAlignment.top)` | Align the current movable selection to its aggregate top edge. Requires at least two objects. | | `distribute(DiagramDistribution.horizontal)` | Equalize gaps between the selected objects. Requires at least three. | | `align(DiagramAlignment.horizontalCenter)` | Align object centers along the horizontal axis; their vertical positions are retained. | | `reorder(DiagramLayerOrder.front)` | Bring selected objects in front of their siblings. | Verbs return `EditResult`; this example uses `requireAllowed()` so the shared shell displays denials. Hosts can use `controller.verb(ids, 'align')?.isAvailable` or `controller.canPerform(ids, 'distribute').allowed` to enable controls, while execution still goes through admission. `align`, `distribute` and `reorder` also accept explicit `ids:`, defaulting to the selection. The example uses no app-specific geometry or ordering algorithm. ```dart controller.select(['moon', 'cloud', 'comet']); controller.align(DiagramAlignment.top); controller.distribute(DiagramDistribution.horizontal); controller.undo(); // Revert distribution; retain alignment. ``` Source: `apps/demo/lib/examples/basics/arrangement.dart`. For ownership and nested selections, see [frames and ownership](/agent-docs/examples/containment.md). This fixture does not qualify large-document gesture performance. --- # Fitted and infinite canvas [Open runnable example](/examples-app/#/canvas/bounds) Choose **Fit to content**, then **Far away**. The canvas is the extent of the cards plus 64 viewport pixels on every side, so the room around the content looks the same at every zoom, and the camera stays within it. Move a card outward and the canvas grows with it; move it back and the canvas shrinks. Switch to **Infinite** and repeat: the camera can leave the drawing behind. **Fit** returns to the cards. A fit canvas constrains camera navigation only; it is not a parent frame and does not rewrite, clip or delete document elements. An empty document gets a viewport-sized canvas around the origin. The bounds are core configuration: start with `DiagramConfiguration(bounds: CanvasBounds.fit(padding: 64))`, read the observable `controller.bounds` and change them with `controller.edits.setBounds(CanvasBounds.infinite)` or `controller.edits.setBounds(CanvasBounds.fit(padding: 32))`. Bounds changes and camera changes do not enter document undo history. Use an owning frame's clipping grammar when the document itself needs clipped content. See [Canvas API](/agent-docs/api/canvas.md) and [Navigation and motion](/agent-docs/api/navigation-and-motion.md). ## Source ```dart actions: { 'Fit to content': (controller) => controller.edits.setBounds( const CanvasBounds.fit(padding: exampleCanvasPadding), ), 'Infinite': (controller) => controller.edits.setBounds(CanvasBounds.infinite), 'Far away': (controller) => controller.view.show( const ViewTarget.point(DiagramPoint(4000, 4000), zoom: 1), ), }, ``` --- # Locks and capabilities [Open runnable example](/examples-app/#/basics/capabilities) The regular rectangle supports standard transforms. Lock it, select it and try **Move regular** or **Delete selection**: the verb reports rejection without changing the document. Unlock it to resume editing; lock changes are undoable. The fixed-size card has no resize handles and does not rotate because its registered definition's `ShapeBehavior` declares those limits. **Resize fixed** demonstrates the same rejection through the API. It remains selectable and movable. Instance unlocking does not override the definition's behavior. Locking is an editing constraint, not authentication. Application permissions belong in the host admission hook; see [events and permissions](/agent-docs/examples/hooks.md). ## Source ```dart DiagramController createCapabilitiesExample() { final hostShapes = DiagramExtension( id: 'example.capabilities', shapes: [ ShapeDefinition( type: 'example.fixed-card', name: 'Fixed-size card', behavior: const ShapeBehavior(resizable: false, rotatable: false), ), ], ); final seed = DiagramController( configuration: DiagramConfiguration( extensions: [...demoModelExtensions, ...demoEditing(), hostShapes], ), document: DiagramDocument.empty('capabilities'), ); try { for (final (id, type, x, caption) in [ ('regular', Shapes.rectangle, -160.0, 'Lock and unlock me'), ('fixed', 'example.fixed-card', 160.0, 'Move me; size stays fixed'), ]) { seed.edits.createShape( type, id: id, at: DiagramPoint(x, 0), size: const DiagramSize(240, 140), select: false, textStory: TextStory.paragraph( id: '$id-story', blockId: '$id-body', text: caption, ), ); } return DiagramController( configuration: DiagramConfiguration( extensions: [...demoModelExtensions, ...demoEditing(), hostShapes], ), document: seed.document, ); } finally { seed.dispose(); } } ``` See [Shapes](/agent-docs/api/shapes.md) for the capability grammar and [Controller](/agent-docs/api/controller.md) for lock, selection and transform method contracts. --- # Copy, paste and duplicate [Open runnable example](/examples-app/#/integration/clipboard) The two cards and their bound, labeled connection belong to one group. **Copy original** captures an immutable subtree without adding history. **Paste** inserts that snapshot below the original, with new element, story and block identities. The copied connection binds to the copied cards. **Duplicate original** combines capture and paste. Each paste or duplicate is one undo unit; Undo removes the complete copy and Redo restores it. Repeated pastes use the same offset, so copies can overlap; drag a group to separate them. This demonstrates the toolcanvas's in-memory clipboard payload. It does not request browser clipboard permissions or demonstrate cross-application clipboard formats. Reset clears the example's captured payload along with its drawing and history. ## Source ```dart actions: { 'Copy original': (controller) { selectOriginal(controller); payloads[controller] = controller.copy(); }, 'Paste': (controller) { final payload = payloads[controller]; if (payload == null) throw StateError('Copy the original group first.'); controller.edits .paste(payload, offset: const DiagramPoint(0, 300)) .requireAllowed(); }, 'Duplicate original': (controller) { selectOriginal(controller); controller.edits .duplicate(offset: const DiagramPoint(0, 300)) .requireAllowed(); }, }, ``` See [Controller](/agent-docs/api/controller.md) for copy, paste and duplication contracts. --- # Connected cards [Open runnable example](/examples-app/#/connections/cards) Move or resize a card and watch its connection follow the bound ports. Switch between straight, orthogonal, quadratic, and Bezier routes. Select the connector and press Enter to edit its label, or use **Select label** to target it directly. Router changes are validated transactions and can be undone. **Animate** starts a transient path effect; **Stop animation** stops it without editing the document. Reset creates a new controller with empty undo history and clears its effects. The fixture uses `createShape`, `add` for authored connectors, and named `BoundEndpoint` ports. Label selection uses `setSelection(ConnectorLabelSelection(...))`; path motion uses `controller.effects.play(const Effect.flow(), on: ...)` and `stopAll`. Route changes use `setConnectorRoute`, sharing the inspector's validation and undo behavior. See [Connectors](/agent-docs/api/connectors.md), [Effects](/agent-docs/api/effects.md), and [Undo/redo](/agent-docs/api/history.md). ## Source ```dart DiagramDocument connectedCardsDocument() { final seed = DiagramController( configuration: DiagramConfiguration( extensions: [...demoModelExtensions, ...demoEditing()], ), document: DiagramDocument.empty('connected-cards'), ); try { for (final (index, title) in ['A bright idea', 'Make it happen'].indexed) { seed.edits.createShape( Shapes.card, id: 'card-$index', at: DiagramPoint(index * 480, index * 80), size: const DiagramSize(280, 180), select: false, textStory: TextStory( id: 'story-$index', blocks: [ TextParagraph( id: 'title-$index', role: TextRole.title, slotId: 'title', runs: [TextRun(title)], ), TextParagraph( id: 'body-$index', slotId: 'body', runs: [ TextRun( index == 0 ? 'Sketch a tiny adventure.' : 'Build it with a friend.', ), ], ), ], ), ); } seed.edits.add( ConnectorElement( id: 'journey', start: const BoundEndpoint(elementId: 'card-0', portId: 'right'), end: const BoundEndpoint(elementId: 'card-1', portId: 'left'), route: ConnectorRoutes.orthogonal, labels: [ ConnectorLabel( id: 'next-step', story: TextStory.paragraph( id: 'label-story', blockId: 'label-block', text: 'Try it together', ), ), ], ), select: false, ); return seed.document; } finally { seed.dispose(); } } ``` --- # Create and connect atomically [Open runnable example](/examples-app/#/connectors/create-connected) `controller.createConnected` inserts the target and incoming connector in one admitted operation. The target can be a registered shape or standalone text. Both use the same connection geometry and history pipeline. Try each creation button, then Undo: the target and connector disappear together. Redo restores both identities and the binding. **Try invalid port** requests a nonexistent port; the example reports the error and leaves the drawing unchanged. Use Fit after adding several targets to bring the expanded drawing into view. The direct method returns the new ID. Its counterpart through `controller.edits` returns an `EditResult` whose `id` is the new connector's ID; the inline element keeps its supplied ID. A denied request, such as an invalid port, returns a denied result. Connection policy and document admission apply. Like `add`, authored insertion preserves supplied values rather than invoking the defaults factory. ## Source ```dart String addConnectedTarget( DiagramController controller, { bool text = false, bool invalidPort = false, }) { final revision = controller.document.revision; final row = (controller.document.elements.length - 1) ~/ 2; final decision = controller.edits.createConnected( source: const BoundEndpoint(elementId: 'source'), element: text ? TextElement( id: 'target-$revision', frame: DiagramRect.fromLTWH(260, row * 140 - 50, 200, 100), textStory: TextStory.paragraph( id: 'target-story-$revision', blockId: 'target-block-$revision', text: 'Text connects too', ), ) : ShapeElement( id: 'target-$revision', type: Shapes.rectangle, frame: DiagramRect.fromLTWH(260, row * 140 - 50, 200, 100), textStory: TextStory.paragraph( id: 'target-story-$revision', blockId: 'target-block-$revision', text: 'A connected idea', ), ), toPort: invalidPort ? 'missing-port' : null, route: ConnectorRoutes.quadratic, )..requireAllowed(); return decision.id!; } ``` See [Shapes](/agent-docs/api/shapes.md) for the complete argument contract. --- # Connection admission [Open runnable example](/examples-app/#/connectors/admission) Connect the sender to the listener using the toolbar or ports. The quiet node rejects connections. Rejected ports turn red; releasing cancels the connection. Denied verbs show a reason and leave history unchanged. Try undo and redo on an accepted connection. First, **Run checks** in the review panel. The missing-route finding selects both nodes when clicked. Create the connection, then run checks again to clear it. Undo restores the incomplete draft; another check finds the missing route again. Draft diagnostics are explicit and do not prevent editing. Admission rules reject invalid connections immediately. See [domain diagnostics](/agent-docs/api/diagnostics.md). The example uses one endpoint rule at two complementary boundaries: | API | Responsibility | | --- | --- | | `DiagramRules(canConnect: ...)` | Evaluate hover, preview, creation and reconnection intent. `targetIsStart` preserves direction when moving the source endpoint. | | `DiagramRules(beforeChange: (p) => validate(p.after))` | Enforce the same invariant on every candidate document, including imports and history. It does not run on the controller's initial document. | A port hover without an opposite endpoint is allowed until a pair can be checked. This example requires bound endpoints, so a rejected target cannot leave a free connection behind. Application permissions belong in the same `beforeChange` rule. The validator scans connections in this small fixture. It demonstrates admission semantics, not a large-document performance policy or remote authorization. See [Controller](/agent-docs/api/controller.md) and [Rules and changes](/agent-docs/api/hooks.md). ## Source ```dart EditResult admitExampleEndpoints( ConnectorEndpoint? start, ConnectorEndpoint? end, ) => start is BoundEndpoint && start.elementId == 'sender' && start.portId == 'right' && end is BoundEndpoint && end.elementId == 'listener' && end.portId == 'left' ? const EditResult.allow() : const EditResult.denied(reason: 'Only sender → listener is allowed.'); ``` --- # Connector effects [Open runnable example](/examples-app/#/motion/connector-effects) Two connectors start selected. Each button plays one effect on every selected connector with `controller.effects.play`, and stops it when pressed again: dots, marching dashes (`EffectParticle.dash()`), arrows that turn with the route (`EffectParticle.arrow()` at `EffectScale.screen`), a gradient flow from the brand color to orange, a stroke pulse, and a blink (`Waveform.step`) that plays three cycles with `repeat: 3` and stops by itself. **Dim** fades a connector to a quarter of its opacity and holds it there. Pick a brand color before playing an effect. **Stop all** calls `controller.effects.stopAll()`. Effects never edit the document or add undo entries. See [Animation & effects](/agent-docs/api/effects.md). ## Source ```dart final connectorEffects = { 'Dots': (brand) => Effect.flow(color: brand, count: 3, size: 3.5), 'Marching dashes': (brand) => Effect.flow( color: brand, particle: const EffectParticle.dash(), count: 6, size: 1.5, width: 3, ), 'Arrows': (brand) => Effect.flow( color: brand, particle: const EffectParticle.arrow(), count: 2, size: 6, scale: EffectScale.screen, ), 'Gradient flow': (brand) => Effect.flow( color: brand, endColor: const DiagramColor(0xFFF97316), count: 4, size: 3.5, ), 'Pulse': (brand) => Effect.pulse(color: brand, target: EffectTarget.stroke, width: 4), 'Blink 3 times': (brand) => Effect.pulse( color: brand, target: EffectTarget.stroke, waveform: Waveform.step, period: const Duration(milliseconds: 500), repeat: 3, width: 4, ), 'Dim': (_) => const Effect.fade(dim: 0.25), }; ``` --- # Connector labels Connector labels are the words attached to a line. In a crowded drawing they can overlap equipment shapes or each other and become unreadable. **Arrange labels** moves the words into nearby free space; it does not reroute the line or move the equipment. It runs only when requested, not during every drag. Choose **Crowd labels** to place two labels together over a shape, then **Arrange labels** to move them into available space. Undo restores their previous positions in one step. Try the same sequence with Plain Text and large badges. ```dart controller.arrangeLabels(); // Or arrange selected connections while respecting all other labels. controller.arrangeLabels(ids: ['journey'], spacing: 12); ``` `requireAllowed()` means "throw an error if this edit is rejected." The example shell catches that error and displays its message. Applications can instead check the returned result's `allowed` and `reason` properties. Arrangement uses measured text and badge bounds, preserving placements that already fit. Positions are saved with the drawing and remain manually editable. This explicit action does not continuously reposition labels while you edit. It avoids leaf shapes and other labels, using a bounded set of nearby positions; it does not guarantee a global optimum or avoid every crossing line. If no placement fits, the operation reports a message and changes nothing. Locked connectors and connectors owned by groups are rejected in this initial version. [Open runnable example](/examples-app/#/connectors/labels) A picnic journey starts with one label. Select the connection and press Enter to edit its first label; double-click a label to edit that label. The framework owns those interactions. Enter adds a new line; Escape finishes editing. Labels support plain paragraphs and inline formatting, without lists. The editing outline stays visible while typing, and an empty label reserves one character's width. Use **Add label** for a second attachment. The default grammar permits two; a third request shows a denial without editing the document. **First label** and **Last label** choose the target for the other actions. With no label selected, actions target the first remaining label. | Action / public API | What changes | | --- | --- | | `addConnectorLabel` | Creates one attachment with its text and path fraction as one undo step; the result's `id` is the label ID. | | `setSelection(ConnectorLabelSelection(...))` | Selects an individual label without changing history. | | `setConnectorLabel(..., fraction: ...)` | Moves the selected label along the path. You can also drag it. | | `setConnectorLabel(..., story: ..., presentation: ...)` | Changes that label's text size/color and badge together; preserves the other label and connector endpoints. | | `removeConnectorLabel` | Removes one label. Undo restores its text, position and style. | **Large badge** applies 20px text and a subtle bordered surface. **Plain Text** returns to 14px text without a backing surface. The example offers fixed choices to demonstrate the API; the playground inspector exposes more styling controls. Try styling the second label, moving it, deleting it, then stepping backward through Undo. Reset restores the initial document with empty history. JSON persistence preserves both labels and their presentation. See [Connectors](/agent-docs/api/connectors.md) and [Text](/agent-docs/api/text.md). With accessibility enabled, each nonempty visible label has its own **Connector label** target. Activating it selects that label; Enter edits it and Delete uses the same protected verb as canvas interaction. The whole connector remains available as an aggregate target. ## Source ```dart void addExampleLabel(DiagramController s) { final suffix = s.document.revision; final added = s.edits.addConnectorLabel( 'journey', fraction: .7, story: TextStory.paragraph( id: 'label-story-$suffix', blockId: 'label-block-$suffix', text: 'Nearly there', ), ); added.requireAllowed(); final id = added.id!; s.setSelection(ConnectorLabelSelection(connectorId: 'journey', labelId: id)); } ``` --- # Construction site coordination [Open runnable example](/examples-app/#/industries/construction) Illustrative site coordination, not CAD/BIM or engineering verification. Move work zones and inspect dependencies; status changes use sample data. Use **Block material delivery** to mark a connection, then **Undo** to restore it. Host applications supply operational data and domain validation. See [Construction & Infrastructure](/industries/construction) and [connectors](/agent-docs/api/connectors.md). ## SVG asset icons This network contains **18 assets and 24 connections**. Facility cards, circular interchanges and hexagonal checkpoints have distinct silhouettes. Each asset includes an SVG icon, an editable name and an operational label. Select one asset, then choose **Import SVG icon** in the canvas toolbar to replace its icon from a local file. Cancel leaves the document unchanged; **Undo** restores the previous icon. The picker also accepts raster images. To supply SVG from application code: ```dart final icon = DiagramImageSource.fromBytes( utf8.encode(svgMarkup), // import dart:convert mimeType: 'image/svg+xml', ); controller.setImage(assetId, icon); ``` The registered shape declares an `ImageValueField` and includes a `ShapeImage()` part in its body, alongside `ShapeText('title')` and `ShapeText('status')`. SVG bytes stay with the document when saved to JSON. The Flutter image renderer handles display; no per-icon Flutter widget or painter is required. Importing SVG creates image content, not separately editable SVG path elements. ## Source ```dart Widget buildExample() => IndustryCanvas( title: 'Construction site coordination', subtitle: '18 site assets · Materials / amber · Work fronts / blue · Services / teal · Coordination / violet · Inspections / red dashed. Select an asset to replace its SVG icon.', createController: createConstructionController, actions: [ IndustryCanvasAction( label: 'Import SVG icon', icon: FluentIcons.image_20_regular, run: importSelectedNetworkIcon, ), IndustryCanvasAction( label: 'Block material delivery', icon: FluentIcons.warning_20_regular, run: (s) { final link = s.document.elements.whereType().first; s.edits .setConnectorStyle( link.id, color: const DiagramColor(0xFFBE4B49), strokeStyle: StrokeStyle.dashed, ) .requireAllowed(); }, ), IndustryCanvasAction( label: 'Undo', icon: FluentIcons.arrow_undo_20_regular, run: (s) => s.edits.undo().requireAllowed(), ), ], ); ``` --- # Frames and ownership [Open runnable example](/examples-app/#/basics/containment) The outer frame owns a nested frame and a rectangle. The nested frame owns an ellipse that extends beyond its right edge and a small sensor rectangle; clipping hides the ellipse's overflow. Both connect to the sibling rectangle. Each frame has a single-line title above its outline. Collapsible frames automatically show a bordered toggle to the left: **+** expands and **−** collapses. Frames without collapse support show only their title. The collapsed frame uses a blue fill; its contents retain their saved geometry. The control also exposes accessible Collapse and Expand actions. Pressing it and releasing outside cancels the action. - **Move outer** moves the complete tree once. - **Receiver → Collapse receiver**, after collapsing Equipment cell, shows the bundle count at both ends. Expand either frame to inspect its original shapes. - **Collapse inner frame** hides both children and bundles their two connections into one, with a **2** badge at the compact frame. **Expand inner frame** restores both connections to their original children. Saved geometry and bindings stay intact. - **Resize inner frame** changes its boundary to reveal or clip more of the ellipse. The ellipse's position and dimensions stay unchanged. - **Group contents** groups the equipment and receiver frames. The ellipse stays owned by the inner frame, and clipping is preserved. **Ungroup selection** removes the selected group while keeping its children in place. - **Remove inner frame** removes the container and transfers its child to the outer frame, preserving its geometry. The ellipse's previously clipped edge becomes visible. - **Delete outer tree** deletes the container and all its descendants. - **Undo** restores each operation, including ownership and clipping. Selection and manual transforms use the same public verbs as the buttons. Reset restores the original document with empty undo history. Grouping requires at least two elements with the same immediate owner: selecting the ellipse and the sibling rectangle cannot group them across their different owners. Standard frames disable rotation. A host can explicitly enable `rotatable` on a registered frame definition; rotation then carries its descendants with it. Resizing a logical group scales its contents. Resizing a selected frame only changes its boundary, using `ShapeContainer(resizesChildren: false)`. ```dart controller.edits.setFrameCollapsed('inner', true); controller.edits.setFrameCollapsed('inner', false); ``` Collapsed frames stay movable. Expand them before resizing or editing their contents. Collapse and expand each form one undo step; save/load retains the collapse state and the expanded geometry. The frame registration uses an external title part (`ShapeOutside`) in both states and a blue fill for the compact presentation. Both read the same saved title. Bundling is opt-in on the frame through `connections: CollapsedConnectionPresentation.bundled`. Connections also need the same explicit `bundleKey`, such as `equipment-telemetry` in this example. Only compatible connections with the same projected endpoints, direction, appearance and routing settings combine. Connections with authored route points remain separate. The count describes original connections; bundling never deletes or rewrites them. When both endpoints attach to collapsed frames, each end shows the count. Canvas rendering, hit testing and SVG export share these badge bounds. Select the bundled connection and open Properties to see its original connection IDs and endpoints. Property controls apply to the selected representative only; changing it can separate it from the bundle. The canvas accessibility label also announces the number of connections. Expand the frame to edit members individually. A collapsed body reuses the ordinary shape parts: rows, columns, stacks, surfaces and text. Text slots must already exist in the expanded definition; collapsing changes which slots are visible, not their content. `ShapeCollapseDefinition(size:, style:, body:, connections:)` customizes the compact frame; its outline stays the frame's own. ## Source ```dart actions: { 'Collapse inner frame': (s) => s.edits.setFrameCollapsed('inner', true).requireAllowed(), 'Expand inner frame': (s) => s.edits.setFrameCollapsed('inner', false).requireAllowed(), 'Select outer': (s) => s.select(['outer']), 'Move outer': (s) => s.edits .move(const DiagramPoint(40, 0), ids: ['outer']) .requireAllowed(), 'Resize inner frame': (s) { final frame = s.document.shapeById('inner')!.frame; s.edits .resize( DiagramSize(frame.width == 240 ? 360 : 240, frame.height), ids: ['inner'], ) .requireAllowed(); }, 'Group contents': (s) { s.select(['inner', 'companion']); s.edits.group().requireAllowed(); }, 'Ungroup selection': (s) => s.edits.ungroup().requireAllowed(), 'Remove inner frame': (s) { s.edits.unframe(ids: ['inner']).requireAllowed(); }, 'Delete outer tree': (s) => s.edits.delete(ids: ['outer']).requireAllowed(), }, ``` See [Controller](/agent-docs/api/controller.md) for removal, selection and transform contracts. --- # Custom effect [Open runnable example](/examples-app/#/motion/custom-effect) A `DiagramFlutterExtension` contributes an `EffectDefinition` for its own `EffectKind`: a dashed ring that turns around a shape, painted from `EffectContext.progress`. **Play orbit** plays it on every shape with `controller.effects.play(const Effect(orbit), on: id)`. The definition advertises its color, opacity, speed, repeat count, spread and width. Select a shape: the inspector lists **Orbit** beside the built-in shape effects and offers exactly those values. See [custom effects](/agent-docs/api/effects.md#custom-effects). ## Source ```dart final orbitEffects = DiagramFlutterExtension( id: 'demo.orbit', effects: [ EffectDefinition( kind: orbit, label: 'Orbit', placement: EffectPlacement.around, properties: const { EffectProperty.color, EffectProperty.opacity, EffectProperty.speed, EffectProperty.repeat, EffectProperty.spread, EffectProperty.width, }, paint: (canvas, context) { final effect = context.effect; final bounds = context.shape.bounds; final ring = Rect.fromCircle( center: Offset(bounds.center.x, bounds.center.y), radius: math.max(bounds.width, bounds.height) / 2 + effect.spread * context.sizeToWorld, ); final paint = context.createPaint() ..style = PaintingStyle.stroke ..strokeWidth = effect.width * context.sizeToWorld ..strokeCap = StrokeCap.round; const sweep = math.pi / 4; final turn = context.progress * math.pi * 2; for (var index = 0; index < 8; index++) { canvas.drawArc(ring, turn + index * sweep, sweep * .55, false, paint); } }, ), ], ); ``` --- # Make a crowded network readable Three links pass through a narrow corridor, where their names overlap on the actual paths. Equipment can also block the direct path between two devices. This example shows the two capabilities that address those problems. [Open runnable example](/examples-app/#/connectors/dense-network) 1. **Arrange labels:** the three overlapping connection names move into separate readable positions. Devices and connections stay in place. 2. **Move equipment:** the orange device moves into the backbone connection. The path stays in place, making the obstruction visible. 3. **Reroute connections:** the elbow now detours around the equipment. Move the equipment away, then reroute again to restore the direct route. 4. **Undo:** label arrangement, equipment movement and rerouting are separate edits. **Reset** restores the original crowded corridor for another comparison. Drag a blue device: its label follows its connector. Labels are anchored to a fraction of the path, with a small nearby offset; they are not fixed canvas text. After rerouting, use **Arrange labels** again if the new paths create overlaps. Label arrangement and obstacle rerouting are explicit verbs. Ordinary dragging keeps connections attached without repeatedly searching for obstacle-free paths. ```dart controller.edits.connect('access', 'core', route: ConnectorRoutes.orthogonal); final result = controller.edits.arrangeLabels(); if (!result.allowed) { // Show result.reason in your application's feedback area. } final rerouting = controller.edits.reroute(); if (!rerouting.allowed) { // Show rerouting.reason; the verb leaves all connections unchanged. } ``` These are diagram editing capabilities. The network is illustrative; it does not discover devices or fetch live telemetry. See [routing and labels](/agent-docs/api/connectors.md) for current limits and result handling. ## Arrange inside a frame Choose **Containment → Frame network**, then use **Arrange labels**, **Move equipment**, and **Reroute connections** as before. The frame owns the devices and links; the planners respect active ancestor clips. **Collapse network** hides internal links; **Expand network** restores their geometry. Each action supports undo. Reset returns to the unframed fixture. ## Review the network design Open **Network review → Disconnect backbone**, then select **Run checks** in the diagnostics panel. The finding asks you to connect Access switch to Core route; selecting it locates the broken connector (or both devices if the connector was deleted). Choose **Connect to wrong device**, then frame and collapse the network and run checks again: selecting the finding selects the visible frame without expanding it. Choose **Reconnect backbone** and run checks again to clear the finding. Undo brings the disconnected draft back. This rule checks an explicit connection requirement using canonical endpoint bindings. A line ending near the route does not count as connected. The host owns the rule; the engine supplies revision-matched findings and undoable edits. It does not simulate network traffic or perform reachability analysis. ## Source ```dart actions: { 'Arrange labels': (s) => s.edits.arrangeLabels().requireAllowed(), 'Reroute connections': (s) => s.edits.reroute().requireAllowed(), 'Move equipment': moveNetworkEquipment, }, ``` --- # Editor composition An `EditorExtension` composes the canvas with optional UI. Toggle the left tool palette, right inspector, toolbar, canvas, minimap, and shape-attached badges. The minimap comes from `vyuh_diagram_extension_minimap`, installed beside the editor. Move the toolbar between the bottom and left edge without replacing the controller. Canvas visibility preserves the mounted canvas, document, selection, and history. [Open runnable example](/examples-app/#/canvas/editor) ## Composition `EditorExtension(container: ...)` receives the existing canvas and controller. Use ordinary Flutter layout widgets to position `DiagramToolPalette`, `DiagramToolbar`, and `DiagramInspector`. Both tool controls support an `Axis` direction. There is no separate editor-extension contract: it extends `DiagramFlutterExtension`. The shape badges are another concrete Flutter extension. They observe the public scene and camera without changing document geometry or intercepting pointer input. --- # Element motion [Open runnable example](/examples-app/#/motion/element-motion) **Move with motion** calls `controller.edits.move(delta, ids: ['hub'], motion: Motion.smooth)`. **Resize with motion** calls `setElementBounds` with `Motion.slow`. **Lay out as a tree** and **Lay out in a circle** call `controller.edits.layout(layout, motion: Motion.slow)`. The document takes each result at once and records one undo step; the canvas animates the elements and their attached connectors to it. Selection and hit testing use the final geometry while the motion plays, and reduced motion presents the change at once. See [animated geometry](/agent-docs/api/navigation-and-motion.md#animated-geometry) and [Live data](/agent-docs/guide/live-data.md). ## Source ```dart actions: { // The hub travels right, or back left, with its connectors. 'Move with motion': (controller) => controller.edits .move( DiagramPoint(_hub(controller).left < 300 ? 160 : -160, 0), ids: ['hub'], motion: Motion.smooth, ) .requireAllowed(), // The hub grows about its center, or shrinks back. 'Resize with motion': (controller) => controller.edits .setElementBounds( 'hub', DiagramRect.fromCenter( center: _hub(controller).center, size: _hub(controller).width < 200 ? const DiagramSize(240, 150) : const DiagramSize(160, 100), ), motion: Motion.slow, ) .requireAllowed(), 'Lay out as a tree': (controller) async => (await controller.edits.layout( Layout.tree(gap: 48, levelGap: 90), motion: Motion.slow, )).requireAllowed(), 'Lay out in a circle': (controller) async => (await controller.edits.layout( Layout.circular(gap: 48), motion: Motion.slow, )).requireAllowed(), }, ``` --- # Embedded tables [Open runnable example](/examples-app/#/tables/embedded) A class shape contains a single-column member table. Edit members, add a row, and resize the containing shape. The table uses the same editing verbs as a standalone table, while the shape owns its placement. --- # SVG and PNG downloads [Open runnable example](/examples-app/#/output/export) Edit the cards or connector label, then download SVG or PNG. Output captures the resolved document with padding, independent of camera zoom and selection. Neither format includes editor handles or toolbar controls. SVG uses native text and embeds the bundled font faces. PNG has a white background and a scale capped at two pixels per world unit, with its longest side limited to 4096 pixels. Resource preparation finishes before capturing the crop and publication. Downloads run locally in the browser. This fixture includes shapes, text regions, a bound connector and label, plus two embedded image resources. The round photo uses a registered elliptical outline to clip its cover image; the rectangular image uses contain. Resize either photo and compare the two exports. The live CDX **Select the cards** button uses its canonical caption as a portable text fallback in both outputs; exports do not include its click action. SVG text appearance depends on the fonts available to the viewer. See [Output](/agent-docs/api/output.md) for resource limits and failure handling. ## Source ```dart Future exportExample( DiagramController controller, { required bool svg, PlaygroundDownload download = downloadPlaygroundFile, }) async { final fonts = svg ? await loadDiagramExportFonts() : []; // Prepare resources first, then capture crop and content synchronously. final bounds = controller.scene.bounds.inflate(32); final Uint8List bytes; if (svg) { final result = await controller.exportSvg( SvgOptions(bounds: bounds, fonts: fonts), ); bytes = Uint8List.fromList(utf8.encode(result.svg)); } else { final result = await controller.exportPng( PngOptions( bounds: bounds, pixelRatio: math.min(2, 4096 / math.max(bounds.width, bounds.height)), background: const DiagramColor(0xFFFFFFFF), ), ); bytes = result.bytes; } await download( bytes, 'connected-cards.${svg ? 'svg' : 'png'}', svg ? 'image/svg+xml' : 'image/png', ); } ``` ### Document and shape definition Source: [fixture.dart](https://github.com/vyuh-tech/vyuh_diagram/blob/main/apps/demo/lib/examples/output/fixture.dart). ### Portable widget content Source: [portable_widget.dart](https://github.com/vyuh-tech/vyuh_diagram/blob/main/apps/demo/lib/examples/output/portable_widget.dart). ### Font resources The playground and this example share the same bundled font loader. Source: [export_fonts.dart](https://github.com/vyuh-tech/vyuh_diagram/blob/main/apps/demo/lib/export_fonts.dart). --- # Your first drawing Create and edit shapes through one `DiagramController`. This focused example uses the same canvas, selection, text editing and undo verbs as the playground. [Open runnable example](/examples-app/#/basics/first-drawing) ## Try it Click **Add shape**, drag the selected rectangle, delete it and undo the deletion. Double-click a shape's text to edit it. **Reset example** disposes this example's controller and starts a fresh fixture. Source: `apps/demo/lib/examples/basics/first_drawing.dart`. See [Controller](/agent-docs/api/controller.md) for exact method signatures. ## Source ```dart actions: { 'Add shape': (s) => s.edits.createShape(Shapes.rectangle, at: const DiagramPoint(230, 170)), 'Select all': (s) => s.selectAll(), 'Delete selection': (s) => s.edits.delete().requireAllowed(), }, ``` --- # Workplace floor planning [Open runnable example](/examples-app/#/custom-shapes/floor-plan) A live workplace layout made from editable room rectangles and registered wall, door and window shapes. Use the vertical tool rail for rooms, walls, doors, windows and dimensions. Drag, resize or rotate a piece, then double-click room names and dimension labels to edit them. Live occupancy values keep changing without adding dashboard chrome around the drawing. The grid has a 4-unit base resolution. When zooming out hides intermediate lines, shape movement, resizing, and free connector endpoints snap to the displayed spacing instead of invisible subdivisions. Bound endpoints stay attached to their shapes. Plain lines use the standard `Shapes.line` registry definition: they are standalone strokes without arrowheads or endpoint bindings. Dimensions use a straight connector with arrowheads at both ends and a label at its midpoint. Labels are manually authored: this example does not calculate real-world measurements or automatically join walls and openings. ```dart ConnectorElement floorDimension( String id, double x1, double x2, double y, String label, ) => ConnectorElement( id: id, start: FreeEndpoint(DiagramPoint(_floorSnap(x1), _floorSnap(y))), end: FreeEndpoint(DiagramPoint(_floorSnap(x2), _floorSnap(y))), startArrowhead: const Arrowhead.angle(), endArrowhead: const Arrowhead.angle(), strokeWidth: 1, color: const DiagramColor(0xFF64748B), labels: [ ConnectorLabel( id: '$id-label', fraction: .5, story: TextStory.paragraph( id: '$id-story', blockId: '$id-block', text: label, ), ), ], ); ``` --- # MES production routing [Open runnable example](/examples-app/#/custom-shapes/flowchart) Follow a live manufacturing order through mixing, in-process quality, rework and pallet release. The vertical tool rail adds process steps, quality decisions and endpoints without placing chrome above the canvas. Drag shapes to reroute their connectors or connect visible ports. ```dart String addFlowchartShape(DiagramController s, String type) { final decision = switch (type) { DiagramShapes.decision => s.edits.createShape( type, at: const DiagramPoint(500, 200), size: const DiagramSize(180, 120), style: flowchartStyle(type), text: 'Decision?', ), DiagramShapes.start || DiagramShapes.end => s.edits.createShape( type, at: const DiagramPoint(500, 200), size: const DiagramSize(56, 56), style: flowchartStyle(type), ), _ => s.edits.createShape( type, at: const DiagramPoint(500, 200), size: const DiagramSize(180, 96), style: flowchartStyle(type), textStory: _stepStory( 'step-${s.document.revision}', 'New step', 'Describe the work', ), ), }; decision.requireAllowed(); return decision.id!; } ``` --- # Fonts and inheritance [Open runnable example](/examples-app/#/text/fonts) Choose a drawing default to compare the four bundled Google Fonts. The card titles, card bodies and connector label inherit the default. The standalone caption explicitly uses IBM Plex Mono, so changing the default preserves it. `DiagramConfiguration(fonts: ..., defaultFontFamily: ...)` supplies one catalog to all text inspectors. `defaultFontFamily` applies to runs without an explicit family. Changing it with `controller.edits.setDefaultFontFamily(...)`, or the catalog with `controller.edits.setFonts(...)`, does not rewrite the document's runs or add a document undo entry. The host must load the fonts; a catalog entry alone does not download a font. This example uses font assets already bundled with the examples app. See [Extensions and options](/agent-docs/api/configuration.md) and [Text](/agent-docs/api/text.md). ## Source ```dart const exampleFonts = [ DiagramFontFamily(family: 'IBM Plex Sans', label: 'Sans serif'), DiagramFontFamily(family: 'IBM Plex Serif', label: 'Serif'), DiagramFontFamily(family: 'IBM Plex Mono', label: 'Monospace'), DiagramFontFamily(family: 'Shantell Sans', label: 'Handwritten'), ]; ``` --- # Range and whole-story formatting [Open runnable example](/examples-app/#/text/formatting) **Bold picnic** toggles bold on the first occurrence of “picnic”, preserving the word's underline and color. **Italic story** toggles italic across both the paragraph and checklist. **Clear picnic** targets the same word and clears marks and explicit appearance only in that first range. These buttons demonstrate explicit API offsets; if you edit the text, the range still refers to offsets 0–6, not a word search. Double-click the text to select a different range and try keyboard formatting. The action buttons do not represent or capture the current caret selection. **Save**, edit, then **Restore** verifies that mixed formatting is document content. Undo and redo operate on each admitted change; Reset restores the original fixture. ## Public API ```dart import 'package:vyuh_diagram_extension_rich_text/extension_api.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; final story = controller.document.textById('invitation')!.textStory; controller.edits.setMark( elementId: 'invitation', mark: TextMark.bold, // The button switches the mark: it sets the opposite of the range's. on: !RichTextFormatting.hasMark(story, TextMark.bold, start: 0, end: 6), start: 0, end: 6, ).requireAllowed(); ``` `setMark` is a setter verb: there is no toggle verb, so a control that switches a mark reads `RichTextFormatting.hasMark` and passes the opposite as `on`. The verb validates the range against the text's grammar and publishes it with history. Locked or noneditable targets return a denied result; `requireAllowed` throws `DiagramChangeDenied`. Omit the range to set a mark across the whole story, and perform `clearFormatting` to clear a range. See [verbs](/agent-docs/api/verbs.md). Source: `apps/demo/lib/examples/text/formatting.dart`. See [text and paragraphs](/agent-docs/api/text.md) for caret, range, region and grammar rules. This example does not qualify browser IME or screen-reader behavior. --- # Drawing and erasing [Open runnable example](/examples-app/#/basics/freehand) Choose **Draw**, pick a stroke style and drag on empty canvas. Draw clears the selection so style choices configure future strokes. Choose **Select**, select one or more completed drawings, then change their style. The stored points and width samples remain unchanged; Undo restores the previous appearance. The Properties inspector provides three drawing presets: | Preset | Stroke behavior | | --- | --- | | Pen | Smoothed contour, pronounced pressure variation, round caps. | | Brush | The same pressure variation as Pen, with tapered ends. | | Marker | Constant width and round caps, independent of pressure. | Presets share the same captured contour and pressure samples. Changing a preset does not discard pressure, so switching from Marker back to Brush restores its variation. Brush tapers use fixed distances relative to stroke width. The inspector exposes color and width alongside the preset, without advanced tuning. New drawings start at 6 pixels. Mouse input simulates pressure by speed: slow movement thickens Pen and Brush, while fast movement thins them. Styluses use their reported pressure. Both presets capture a 30–170% width range; Brush adds tapered ends. Marker ignores those width samples when painting. While Draw is active, editing a selected drawing's appearance also sets the next stroke's appearance. Editing in Select mode changes only the selection. ```dart controller.setShapeCreationStyle( Shapes.freehand, controller.shapeCreationStyle(Shapes.freehand).copyWith( inkPreset: InkPreset.brush, strokeWidth: 8, ), ); ``` Choose **Eraser** and drag across a drawing. Undo restores the erased element and its original geometry. Reset restores the sample and clears history. The tool buttons use the standard registered draw, select and eraser tools. | API | Purpose | | --- | --- | | `setTool(DiagramTools.draw)` | Activate the registered freehand gesture behavior. | | `setTool(DiagramTools.eraser)` | Activate the registered eraser behavior. | | `shapeCreationStyle(Shapes.freehand)` | Read the current defaults for future strokes. | | `setShapeCreationStyle(type, style)` | Change creation defaults without rewriting existing elements or adding document history. | | `setStyle(ids: ids, strokeStyle: ..., inkPreset: ...)` | Restyle one or more completed drawings through admission, with one undo entry. Only the given parts change. | The style buttons apply to the entire selection of drawings. Mixed selections containing other element types report an error; they do not perform partial edits. Solid, dashed and dotted styles are shown. The sample has explicit variable-width geometry; live strokes use the framework's pressure/speed sampling rules. Source: `apps/demo/lib/examples/basics/freehand.dart`. The regression draws and erases with pointer gestures and checks undo restoration; a separate case verifies defaults and completed-stroke style ownership. This does not certify physical stylus pressure, browser latency or every pointer device. --- # Grids and snapping [Open runnable example](/examples-app/#/canvas/grids) Drag a card with **Snap on**, then compare with **Snap off**. **Hide** removes the background without changing snapping. Choose 20 or 40 world units for the shared interval. Dots, lines and the custom cross pattern use that same interval; the custom pattern adds a major line every five intervals. All controls update the diagram's `GridOptions` with `controller.edits.setOptions(...)`. They do not rewrite document elements or enter document history. Moving a card remains an ordinary admitted edit and can be undone. Reset restores the fixture and its initial visible, snapping grid. See [Grids API](/agent-docs/api/grids.md) for normalization, layer limits and rotation snapping. ## Source ```dart void configureGrid( DiagramController controller, { bool? visible, bool? snap, double? size, DiagramGridPattern? pattern, }) => controller.edits.setOptions( controller.options().copyWith( visible: visible, snap: snap, size: size, pattern: pattern, ), ); ``` --- # Transactions and undo Move two connected cards as one operation using the public diagram controller. [Open runnable example](/examples-app/#/integration/history) ## Try it 1. Click **Preview 40**, then **Preview 80**. Both offsets are measured from the original positions; the second preview does not accumulate the first. Each preview performs `move` on an interaction lease. 2. **Commit**, then **Undo** and **Redo**. Both cards restore together, and their connector follows the resolved ports. 3. Undo again, preview a move and **Cancel**. The original positions and existing redo branch remain available. 4. **Move pair 40** performs the `move` verb once, without previews. The controller owns the edit lease and cancels it on disposal, including example reset. The example retains only the lease token, not a second document snapshot. An expired lease rejects further previews and commits. Buttons report denied verbs through the shared example error surface. ## Source ```dart Widget buildExample() { final edits = Expando(); return ExampleCanvas( title: 'One edit, one undo', instructions: 'Preview the pair at 40 or 80 pixels, then commit or cancel. Each preview starts from the original positions. Undo and redo restore both cards together.', createController: createHistoryExample, actionGroups: { 'Move or preview': ['Preview 40', 'Preview 80', 'Move pair 40'], }, actions: { for (final distance in [40.0, 80.0]) 'Preview ${distance.toInt()}': (controller) { var edit = edits[controller]; if (edit == null || !edit.isActive) { edit = controller.beginInteraction('Move pair'); edits[controller] = edit; } edit.perform(pair, 'move', { 'delta': DiagramPoint(distance, 0), }).requireAllowed(); }, 'Commit': (controller) { final edit = edits[controller]; if (edit == null) throw StateError('Preview a move first.'); edit.commit().requireAllowed(); }, 'Cancel': (controller) => edits[controller]?.cancel(), 'Move pair 40': (controller) => controller.edits.batch('Move pair', () { controller.edits.move(const DiagramPoint(40, 0), ids: pair); }).requireAllowed(), }, ); } ``` See [Undo and redo](/agent-docs/api/history.md) for admission, history ownership, selection restoration and revision behavior. --- # Events and permissions [Open runnable example](/examples-app/#/integration/hooks) The first card is protected by a host admission hook. Try deleting it with the button, or moving and editing it on the canvas. The second card and connection remain editable. A rejected verb displays its reason and adds no undo entry. Change the connection, undo it, and redo it to compare an admitted operation. `DiagramRules(beforeChange: ...)` in the diagram's configuration checks the candidate before publication. UI gestures, verbs and document imports share this boundary. The example protects one identity; a real host supplies its own authorization context. This local hook does not replace authorization on a remote server. The change set is derived lazily and scans the documents when read. Avoid using this example as a performance policy for very large documents without profiling. See [Rules and changes](/agent-docs/api/hooks.md) and [LLM documentation](/agent-docs/agents/index.md). ## Source ```dart EditResult protectFirstCard(DiagramChangeProposal proposal) { // This is host policy, not a second mutation path. The shared store applies // it to UI previews, commands, imports, undo and redo before publication. final changes = proposal.elements; if (changes.updatedIds.contains('card-0') || changes.removedIds.contains('card-0')) { return const EditResult.denied(reason: 'The first card is protected.'); } return const EditResult.allow(); } ``` --- # Images Images use the standard selection and transform mechanics with an undecorated image surface. This example embeds two small original monochrome landscapes so it works without an external image server. [Open runnable example](/examples-app/#/basics/images) ## Try it Choose **Day** or **Night**, then try **contain**, **cover** and **fill**. Contain preserves the full image, cover crops to the frame, and fill stretches to the frame. Changing the image preserves the chosen fit. **Clear** removes the source; undo restores it. Use the canvas resize and rotation handles to transform it. This example uses canonical data URIs, not temporary browser blob URLs. File pickers, uploads, remote-resource permissions and large-image memory budgets are host responsibilities and are not demonstrated here. ## Source ```dart void replaceExampleImage( DiagramController controller, String uri, { DiagramImageFit? fit, }) { final current = exampleImage(controller); controller.edits .setImage( 'image', DiagramImageSource( uri: uri, fit: fit ?? current?.fit ?? DiagramImageFit.contain, ), ) .requireAllowed(); } ``` The fixture constants are in `apps/demo/lib/examples/basics/image_samples.dart`. See [image content](/agent-docs/api/shapes.md#image-content) for the verb's admission and history contract, and [output](/agent-docs/api/output.md) for resource preparation during export. --- # Examples Explore the core canvas first, then add extensions for specialized capabilities. Each page includes an interactive example and its source. Example metadata is available immediately; each implementation loads only when its route opens. For a complete editing surface, open the [playground](/playground/). For coding-agent reference files, see [Agents](/agent-docs/agents/index.md). ## Core ### Getting started | Example | Try it / observable result | API | | --- | --- | --- | | [Your first drawing](/agent-docs/examples/first-drawing.md) | Create, select, move and delete a few shapes using one controller and canvas. | [Controller](/agent-docs/api/controller.md), [Canvas](/agent-docs/api/canvas.md) | | [Transform modifiers](/agent-docs/examples/transforms.md) | Resize from edges/corners, rotate, preserve ratio with Shift and resize from the center with Alt. | [Controller](/agent-docs/api/controller.md) | | [Multi-selection and arrangement](/agent-docs/examples/arrangement.md) | Select, align, distribute, change stacking order and undo separate edits. | [Controller](/agent-docs/api/controller.md) | | [Locks and capabilities](/agent-docs/examples/capabilities.md) | Compare instance locking with a definition that disables resizing and rotation. | [Shapes](/agent-docs/api/shapes.md), [Hooks](/agent-docs/api/hooks.md) | ### Elements and structure | Example | Try it / observable result | API | | --- | --- | --- | | [Images](/agent-docs/examples/images.md) | Add/replace image content, transform it, and inspect its default undecorated appearance. | [Shapes](/agent-docs/api/shapes.md) | | [Drawing and erasing](/agent-docs/examples/freehand.md) | Pick stroke defaults before drawing, edit the finished stroke and erase with undo. | [Shapes](/agent-docs/api/shapes.md) | | [Frames and ownership](/agent-docs/examples/containment.md) | Group and ungroup siblings, move nested contents, clip overflow, remove a frame while keeping children, or delete the complete tree. | [Shapes](/agent-docs/api/shapes.md) | | [Departmental swimlanes](/agent-docs/examples/swimlanes.md) | Arrange department frames in rows or columns without scaling tasks; collapse a lane to show its summary. | [Controller](/agent-docs/api/controller.md) | ### Text | Example | Try it / observable result | API | | --- | --- | --- | | [Plain Text](/agent-docs/examples/plain-text.md) | Edit text without optional formatting. | [Plain Text](/agent-docs/api/text.md) | ### Canvas and navigation | Example | Try it / observable result | API | | --- | --- | --- | | [Custom tools](/agent-docs/examples/tools.md) | Register a tool beside built-ins, with cursor/shortcut and shared verb/preview behavior. | [Extensions and options](/agent-docs/api/configuration.md) | | [Grid snapping](/agent-docs/examples/grids.md) | Switch dot/line/custom patterns, spacing and increments; vary visibility independently of snapping. | [Grids](/agent-docs/api/grids.md) | | [Fitted and infinite canvas](/agent-docs/examples/bounds.md) | Switch between an infinite canvas and one that fits the content plus padding. | [Canvas](/agent-docs/api/canvas.md) | | [View-only diagrams](/agent-docs/examples/view-only.md) | Select, pan, scroll and zoom without moving or editing diagram elements. | [Canvas](/agent-docs/api/canvas.md) | ### Animation & effects | Example | Try it / observable result | API | | --- | --- | --- | | [Navigation and animation](/agent-docs/examples/navigation.md) | Jump or animate to cards/bounds, set normal scale and interrupt animation without editing content. | [Navigation and motion](/agent-docs/api/navigation-and-motion.md) | | [Connector effects](/agent-docs/examples/connector-effects.md) | Play dots, dashes, arrows and gradient flows, a pulse or a three-time blink along the selected connectors, in a brand color. | [Animation & effects](/agent-docs/api/effects.md) | | [Shape effects](/agent-docs/examples/shape-effects.md) | Pulse, blink, ripple or glow, breathe or pop, and fade the selected shape; stop each effect or all of them. | [Animation & effects](/agent-docs/api/effects.md) | | [Element motion](/agent-docs/examples/element-motion.md) | Move, resize and lay out elements with motion; each edit commits at once as one undo step. | [Navigation and motion](/agent-docs/api/navigation-and-motion.md#animated-geometry) | | [Custom effect](/agent-docs/examples/custom-effect.md) | Play an extension's own effect kind, a turning dashed ring, and edit it in the inspector. | [Animation & effects](/agent-docs/api/effects.md#custom-effects) | | [Live energy flow](/agent-docs/examples/path-effects.md) | Watch generation, storage, demand and grid exchange update across animated power paths. | [Animation & effects](/agent-docs/api/effects.md), [Live data](/agent-docs/guide/live-data.md) | ### Embedded controls | Example | Try it / observable result | API | | --- | --- | --- | | [Controls inside a node](/agent-docs/examples/widgets.md) | Use a slider, compact dropdown and button; drag non-interactive space and resize/rotate the node. | [Widgets](/agent-docs/api/widgets.md) | | [Portable widget fallback](/agent-docs/examples/widget-fallback.md) | Compare live controls with their declared portable appearance in output. | [Widgets](/agent-docs/api/widgets.md), [Output](/agent-docs/api/output.md) | | [Widget clipping and layering](/agent-docs/examples/widget-layers.md) | Overlap nodes, clip a widget within a frame, and verify input follows visible content after pan/zoom. | [Widgets](/agent-docs/api/widgets.md) | | [Custom properties](/agent-docs/examples/widget-properties.md) | Edit registered values through the inspector and the widget; observe one canonical value and undo history. | [Widgets](/agent-docs/api/widgets.md) | ### Documents and editing | Example | Try it / observable result | API | | --- | --- | --- | | [Events and permissions](/agent-docs/examples/hooks.md) | Inspect semantic changes, deny an edit, and confirm no partial mutation or extra history entry. | [Hooks](/agent-docs/api/hooks.md) | | [Save and load](/agent-docs/examples/persistence.md) | Round-trip JSON with Rich Text and custom values; reject an invalid or stale replacement. | [Persistence](/agent-docs/api/persistence.md) | | [SVG and PNG](/agent-docs/examples/export.md) | Export the same fixture with text, labels, images, clips and widget fallbacks. | [Output](/agent-docs/api/output.md) | | [Transactions and undo](/agent-docs/examples/history.md) | Preview/commit/cancel a multi-element operation; undo and redo one logical edit. | [Undo and redo](/agent-docs/api/history.md) | | [Copy, paste and duplicate](/agent-docs/examples/clipboard.md) | Duplicate owned contents with fresh identities and retained text/connection relationships. | [Controller](/agent-docs/api/controller.md) | | [Controller lifetime](/agent-docs/examples/lifetime.md) | Unmount, dispose a controller that joined a diagram, remount the retained document, and undo an earlier edit. | [Ownership](/agent-docs/api/ownership.md) | ### Use cases | Example | Try it / observable result | API | | --- | --- | --- | | [Connected building topology](/agent-docs/examples/topology.md) | Explore live gateways, building controls, HVAC and EV charging; rearrange or expand the site hierarchy. | [Graph layout](/agent-docs/api/layout.md), [Shapes](/agent-docs/api/shapes.md) | | [Regional transport network](/agent-docs/examples/transportation.md) | Move nodes, mark a connection and undo the change. | [Connectors](/agent-docs/api/connectors.md) | | [Construction site coordination](/agent-docs/examples/construction.md) | Move nodes, mark a connection and undo the change. | [Connectors](/agent-docs/api/connectors.md) | | [Warehouse execution flow](/agent-docs/examples/warehouse.md) | Track receiving, putaway, storage, picking, packing and dispatch with changing operational queues. | [Shapes](/agent-docs/api/shapes.md), [Connectors](/agent-docs/api/connectors.md) | | [Workplace floor planning](/agent-docs/examples/floor-plan.md) | Edit rooms, walls, doors, windows and dimensions while occupancy changes across the plan. | [Shapes](/agent-docs/api/shapes.md), [Grids](/agent-docs/api/grids.md) | | [MES production routing](/agent-docs/examples/flowchart.md) | Follow a batch through mixing, quality, rework and release while production telemetry changes. | [Shapes](/agent-docs/api/shapes.md), [Connectors](/agent-docs/api/connectors.md) | ### Starter kits | Example | Try it / observable result | API | | --- | --- | --- | ## Extensions ### Connectors | Example | Try it / observable result | API | | --- | --- | --- | | [Crowded network](/agent-docs/examples/dense-network.md) | Arrange overlapping labels, move equipment into a connection, then explicitly reroute the elbow around it. | [Connectors](/agent-docs/api/connectors.md) | | [Connected cards](/agent-docs/examples/connected-cards.md) | Switch four routers on bound cards, select a label, and start/stop a path animation. | [Connectors](/agent-docs/api/connectors.md) | | [Connector labels](/agent-docs/examples/connector-labels.md) | Enter/double-click to edit, add a second label, move it along the path and style/delete each label. | [Connectors](/agent-docs/api/connectors.md) | | [Explicit ports](/agent-docs/examples/ports.md) | Connect fixed and instance-defined ports; observe hover/snap feedback and owner transforms. | [Shapes](/agent-docs/api/shapes.md), [Connectors](/agent-docs/api/connectors.md) | | [Connection admission](/agent-docs/examples/connection-admission.md) | Allow/reject source/target combinations through one endpoint rule for interaction, verbs and imported documents. | [Hooks](/agent-docs/api/hooks.md) | | [Anchors and contour routing](/agent-docs/examples/routing.md) | Compare straight, quadratic, cubic and elbow routes at center/edge anchors; inspect contour termination. | [Connectors](/agent-docs/api/connectors.md) | | [Connected creation](/agent-docs/examples/connected-creation.md) | Create a target and incoming connector atomically, including standalone text; undo both together. | [Shapes](/agent-docs/api/shapes.md) | ### Rich text | Example | Try it / observable result | API | | --- | --- | --- | | [Rich Text](/agent-docs/examples/rich-text.md) | Install formatting explicitly and edit styled content. | [Rich Text](/agent-docs/api/rich-text.md) | | [Paragraphs, lists and checklists](/agent-docs/examples/paragraphs.md) | Edit wrapping paragraphs, numbered/bulleted/checklist items and nesting; save and restore their structure. | [Text](/agent-docs/api/text.md) | | [Fonts and inheritance](/agent-docs/examples/fonts.md) | Configure the shared font catalog/default and compare explicit versus inherited font choices. | [Extensions and options](/agent-docs/api/configuration.md) | | [Single-line and multiline regions](/agent-docs/examples/regions.md) | Edit a card title/body and compare admitted body lists with rejected title lists. | [Text](/agent-docs/api/text.md), [Shapes](/agent-docs/api/shapes.md) | | [Range and whole-story formatting](/agent-docs/examples/formatting.md) | Format a range versus whole text; preserve mixed marks through save/load. | [Text](/agent-docs/api/text.md) | ### Tables | Example | Try it / observable result | API | | --- | --- | --- | | [Basic tables](/agent-docs/examples/tables.md) | Edit cells and add rows in a standalone table. | [Tables](/agent-docs/elements/tables.md) | | [Embedded tables](/agent-docs/examples/embedded-tables.md) | Edit a member table inside a class shape. | [Tables](/agent-docs/elements/tables.md) | | [Table styling](/agent-docs/examples/table-styling.md) | Resize tracks and configure borders. | [Tables](/agent-docs/elements/tables.md) | ### Canvas assistance | Example | Try it / observable result | API | | --- | --- | --- | | [Editor composition](/agent-docs/examples/editor-composition.md) | Toggle panels, toolbar, canvas, minimap and shape overlays; reposition the toolbar. | [Canvas](/agent-docs/api/canvas.md) | | [Snap guides](/agent-docs/examples/snap-guides.md) | Align neighboring sides and centers with a toggleable guide overlay. | [Grids](/agent-docs/api/grids.md) | | [Snap guide policy](/agent-docs/examples/snap-policy.md) | Choose sides, centers and nearby candidate limits. | [Grids](/agent-docs/api/grids.md) | | [Minimap policies](/agent-docs/examples/minimap.md) | Compare outlines/fills, optional connections and custom thumbnails, including filled text boxes. | [Canvas](/agent-docs/api/canvas.md) | | [Layout](/agent-docs/extensions/layouts.md) | Compare layout strategies and their options on the same document. | [Extensions](/agent-docs/api/extensions.md) | | [Mermaid import](/agent-docs/examples/mermaid.md) | Paste Mermaid source on the canvas, edit the native shapes, and copy Diagram JSON. | [Extensions](/agent-docs/api/extensions.md) | See [application compositions](/agent-docs/extensions/starters.md) for service-map and storyboard recipes. --- # Controller lifetime [Open runnable example](/examples-app/#/integration/lifetime) Move a card, choose **Unmount**, then **Dispose controller**. **Mount** creates a new canvas controller that joins the same diagram as the same participant. Your content and undo history remain; **Undo** restores the move. **Reset example** disposes the controller and the diagram and creates a fresh drawing. The host waits for the canvas to unmount before disposing its controller. The diagram is owned separately, so disposing a controller that joined it releases its presentation resources and subscriptions without destroying the document. All resources are disposed when this example leaves the widget tree. The host creates its diagram with `FlutterDiagramTextLayoutEngine`, so every controller that joins it shares the same canonical shaped text geometry. This is an ownership example, not independent multi-user collaboration. A controller that rejoins with the same participant id continues that participant's undo history. Ordinary hosts can instead use `DiagramController(document: ...)` and dispose that controller when finished. See [Ownership](/agent-docs/api/ownership.md) and [Collaboration](/agent-docs/api/collaboration.md). ## Application ownership For a normal application, keep one controller in your host state. Unmounting the canvas retains that controller's content and history. Dispose it when the host ends: ```dart final controller = DiagramController( document: DiagramDocument(id: 'drawing', revision: 0, elements: []), ); // Mount and unmount a DiagramCanvas(controller: controller) as needed. // When the host is finished and the canvas has unmounted: controller.dispose(); ``` To retain a drawing beyond any one controller, create a `Diagram` yourself and join it with `DiagramController(diagram: diagram, participant: const DiagramParticipant(id: 'canvas', name: 'Canvas'))`. Disposing that controller leaves the diagram alive; dispose the diagram when the host ends. This uses the same public verbs and canonical drawing in pure Dart and Flutter. --- # Mermaid import [Open runnable example](/examples-app/#/integration/mermaid) Paste raw Mermaid source onto the canvas with Command-V (Control-V on Windows/Linux). A `mermaid` code fence may be surrounded by prose; the first fenced diagram is imported. You can also edit source beside the canvas and select **Import Mermaid**. Imported elements are native Vyuh Diagram elements; **Copy diagram JSON** saves the result. Pie, packet, user journey and other chart families remain excluded; Gantt is supported as a visual import. --- # Minimap policies Rendering, navigation, and zoom controls are owned by `vyuh_diagram_extension_minimap`. The editor extension neither depends on nor re-exports it: import the minimap package and install `MinimapExtension` beside `EditorExtension` in the configuration's `extensions`. `MinimapExtension(visible: false)` starts hidden; toggle it at runtime with `controller.edits.setOptions(controller.options().copyWith(visible: false))`. `MinimapOptions` holds all of its settings, including placement, policy and `theme` (null picks the light or dark default by the canvas theme's brightness). For custom placement, use the unpositioned `DiagramMinimapControl` with the same extension host. [Open runnable example](/examples-app/#/canvas/minimap) Choose **Filled** or **Outlines** to change thumbnails. **Connections** also shows the resolved connector; **Custom cards** installs a painter for the registered card type. The transparent standalone text has a visible thumbnail in both modes. The minimap shows the same content as the canvas. Custom thumbnail paint receives resolved bounds and an outline, with ancestor and shape clipping already applied. It changes minimap presentation, not document geometry or export. Click or drag the minimap to navigate. Policy changes and camera navigation do not add document undo entries. Replace the policy when external thumbnail inputs change so the minimap redraws its thumbnails. Reset restores the filled policy. ## Source The complete minimap and zoom controls default to the bottom-left with 12-pixel edge margins. Configure placement when installing the extension: ```dart MinimapExtension( alignment: Alignment.bottomLeft, margin: const EdgeInsets.only(left: 20, bottom: 24), initiallyExpanded: true, ) ``` Use any `Alignment` to anchor the overlay elsewhere. The same alignment and margins apply when collapsed or expanded. Colors come from `MinimapExtension(theme: MinimapTheme.dark.copyWith(...))`. ```dart void configureMinimap( DiagramController controller, { bool? visible, bool? filled, bool? connections, bool? custom, }) { final options = controller.options(); final p = options.policy; controller.edits.setOptions( options.copyWith( visible: visible, policy: DiagramMinimapPolicy( shapeAppearance: filled == null ? p.shapeAppearance : filled ? DiagramMinimapShapeAppearance.outlinesAndFills : DiagramMinimapShapeAppearance.outlines, showConnections: connections ?? p.showConnections, shapePainterForType: custom == null ? p.shapePainterForType : custom ? (type) => type == Shapes.card ? paintCardThumbnail : null : null, ), ), ); } ``` --- # Navigation and camera animation [Open runnable example](/examples-app/#/navigation/camera) **Jump to idea** calls `controller.view.show(ViewTarget.element(...))` without motion. **Animate to result** and **Animate overview** pass `motion: Motion(duration: Duration(seconds: 2))` for an element and for `ViewTarget.all()`; the long duration makes interruption easy to observe. **Stop camera** calls `controller.view.stop()`; **Normal scale** shows `ViewTarget.point` with `zoom: 1`. Camera operations are presentation state. They require a mounted canvas, do not edit the document, and do not create undo entries. The example awaits the returned futures. Reset disposes its old controller and ignores late action feedback from it. See [Navigation and motion](/agent-docs/api/navigation-and-motion.md) for targets, return values, coordinate spaces and interruption. ## Source ```dart actions: { 'Jump to idea': (controller) { controller.view.show(const ViewTarget.element('card-0')); }, 'Animate to result': (controller) async { await controller.view.show( const ViewTarget.element('card-1'), motion: const Motion(duration: Duration(seconds: 2)), ); }, 'Animate overview': (controller) async { await controller.view.show( const ViewTarget.all(padding: 80), motion: const Motion(duration: Duration(seconds: 2)), ); }, 'Normal scale': (controller) => controller.view.show( ViewTarget.point(controller.scene.bounds.center, zoom: 1), ), 'Stop camera': (controller) => controller.view.stop(), }, ``` --- # Paragraphs, lists and checklists [Open runnable example](/examples-app/#/text/paragraphs) Double-click the text to edit. Enter continues the current list; Tab nests it and Shift+Tab outdents it. Start a paragraph with `[] ` to create a checklist. Use **Save snapshot**, make an edit, then **Restore snapshot**. The snapshot is local to this example and uses the versioned JSON codec. Restore uses the controller's revision-checked import and is undoable. Reset clears the snapshot and returns to the original document with an empty history. The fixture is a canonical `TextElement` containing paragraph, ordered-list, nested bullet, and checked/unchecked checklist blocks. It uses the same text editing pipeline as text inside shapes and cards. See [Text API](/agent-docs/api/text.md) and [Persistence](/agent-docs/api/persistence.md). ## Source ```dart DiagramDocument paragraphExampleDocument() => DiagramDocument( id: 'paragraph-example', revision: 0, elements: [ TextElement( type: RichTextDefinition.textType, id: 'picnic-list', frame: const DiagramRect.fromLTWH(0, 0, 440, 340), textStory: TextStory( id: 'picnic-story', blocks: [ TextParagraph( id: 'intro', runs: [ TextRun( 'A tiny adventure: plan a picnic, pack something delicious, and leave room for a good story.', fontSize: 20, ), ], ), richParagraph( id: 'step', kind: ParagraphKind.orderedListItem, runs: [TextRun('Pick a sunny spot', fontSize: 20)], ), richParagraph( id: 'nested', kind: ParagraphKind.unorderedListItem, nestingLevel: 1, runs: [TextRun('Somewhere under a tree', fontSize: 20)], ), richParagraph( id: 'blanket', kind: ParagraphKind.checklistItem, checked: true, runs: [TextRun('Bring a blanket', fontSize: 20)], ), richParagraph( id: 'sandwiches', kind: ParagraphKind.checklistItem, runs: [TextRun('Pack sandwiches', fontSize: 20)], ), ], ), ), ], ); ``` --- # Live energy flow [Open runnable example](/examples-app/#/motion/path-effects) A simulated telemetry stream stands in for the site's API. It feeds a MobX store, and a `reaction` on the store writes each reading into the diagram with `batch('Telemetry', ..., history: false)`: the kW metrics, the load colours and the load bars, which animate to their new length with `Motion.smooth`. The switch pauses and resumes the feed. Edit, drag or restyle any asset while readings arrive. The readings add no undo entries and never interrupt a drag, and Undo, on the rail or with Command/Ctrl+Z, undoes only your edits, keeping the latest readings. The battery gauge takes the other path: a widget in a shape slot observes the store and rebuilds without editing the document. A flow effect plays along the active connection and a beacon around the active asset. See [Live data](/agent-docs/guide/live-data.md) and [Animation & effects](/agent-docs/api/effects.md). ## Source ```dart EditResult applyEnergyReading( DiagramController controller, EnergyReading reading, ) { final exporting = reading.gridKw >= 0; return controller.edits.batch('Telemetry', () { _metric(controller, 'solar', '${reading.solarKw} kW generating'); _metric(controller, 'site', '${reading.demandKw} kW load'); _metric(controller, 'charger', '${reading.chargerKw} kW charging'); _metric( controller, 'battery', '${reading.batteryPercent}% · ${exporting ? 'charging' : 'supporting'}', ); _metric( controller, 'grid', '${exporting ? 'Exporting' : 'Importing'} ${reading.gridKw.abs()} kW', ); _load(controller, 'solar', reading.solarKw / 180); _load(controller, 'site', reading.demandKw / 150); _load(controller, 'charger', reading.chargerKw / 60); _load(controller, 'grid', reading.gridKw.abs() / 120); }, history: false); } ``` --- # Save, restore and revision conflicts [Open runnable example](/examples-app/#/data/persistence) 1. **Save** captures the canonical JSON and current revision in memory. 2. Edit the text or choose **Remove list**. 3. **Try captured revision** rejects the now-stale update without changing the drawing or its undo/redo history. 4. **Restore saved snapshot** explicitly replaces current content. Undo restores the edits you had before replacement; redo reinstates the saved content. The fixture includes nested lists and checklists. Their structure, formatting and checked state are serialized, rather than flattened into display text. Capture a revision before waiting for asynchronous work. A stale agent response must be reviewed or replanned; do not silently retry with the latest revision. The separate Restore button here expresses a deliberate replacement decision. This example stores its snapshot in memory only. Reset or reload clears it. File storage, transport and server-side authorization belong to the host. See [Persistence and imports](/agent-docs/api/persistence.md) for validation, the format version and failure contracts, and [Agents](/agent-docs/agents/index.md) for integration guidance. ## Source ```dart actions: { 'Save': snapshot.save, 'Remove list': (controller) => controller.edits.delete(ids: ['picnic-list']).requireAllowed(), 'Try captured revision': snapshot.applyCaptured, 'Restore saved snapshot': snapshot.restore, }, ``` --- # Plain Text [Open runnable example](/examples-app/#/text/plain-text) Uses the foundation defaults with no optional extensions. Double-click to edit and press Enter for another paragraph; Rich Text formatting is not installed. See the [Plain Text API](/agent-docs/api/text.md). ## Source ```dart import 'package:flutter/widgets.dart'; import 'package:vyuh_diagram_extension_editor/vyuh_diagram_extension_editor.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; import '../example_canvas.dart'; Widget buildExample() => ExampleCanvas( title: 'Plain Text', instructions: 'Double-click to edit. Enter adds a paragraph. Formatting shortcuts do not enable rich formatting.', createController: () => DiagramController( configuration: DiagramConfiguration(extensions: [EditorExtension()]), )..createText( type: Shapes.text, at: DiagramPoint.zero, text: 'This is Plain Text.\nEdit me without rich formatting.', ), ); ``` --- # Explicit ports [Open runnable example](/examples-app/#/connectors/ports) The sender's ports belong to its shape definition. The receiver's two ports are authored on the element and saved with the document. Both use the same resolved geometry, connection tools and binding model. | API | Role | | --- | --- | | `ShapeConnectionDefinition.fixedPorts(...)` | Declares stable ports for every element of a type. | | `ShapeConnectionDefinition.instancePorts(...)` | Allows each element to supply its own ports. | | `Port` | Stores an ID, side, offset and appearance; geometry is resolved by the framework. | | `BoundEndpoint(elementId: ..., portId: ...)` | Connects to a port by identity. | | `controller.edits.reconnect(...)` | Changes one endpoint as an undoable, validated edit. | | `controller.edits.setConnectorRoute(...)` | Changes routing while preserving bound port identities. | Choose **Receive below**, then Undo. Change routers, move or rotate either node, and hover over a port to start another connection. The example has no custom port painters, hit regions or routing code. Ports remain attachment intent; visible routes stop at the owner contours. Orthogonal routing negotiates the bound shapes; it does not promise arbitrary scene-wide obstacle avoidance. ## Source ```dart void receiveAt(DiagramController s, String portId) => s.edits .reconnect( 'message', atStart: false, endpoint: BoundEndpoint(elementId: 'receiver', portId: portId), ) .requireAllowed(); ``` --- # Single-line and multiline regions [Open runnable example](/examples-app/#/text/regions) A card owns one canonical story with two named slots. The title is single-line; the body accepts paragraphs and lists. Double-click each region to edit it: Enter finishes the title, while Enter creates another block in the body. **Add body checklist** appends a new block in the body with a fresh identity. **Try title checklist** submits an invalid story through the same public verb. The plain title rejects it before publication, preserving document, selection and history. The shell displays the error; Undo remains available only for prior successful edits. Reset starts with the original two blocks and empty history. ## Declare the slots The note declares a plain single-line `title` and a rich `body` with `ShapeText` parts placed in the shape's body: | `ShapeText` argument | Purpose | | --- | --- | | `slotId` | Matches canonical blocks to the named region. | | `textType` | The text filling the slot. `PlainTextDefinition(maxLines: 1)` restricts the title to a line and determines Enter behavior; `RichTextDefinition()` lets the body hold lists. | | Position in the body | Rows, columns and padding around the part place the region within the shape. | The story's title block has `role: TextRole.title` and `slotId: 'title'`. Body blocks use `slotId: 'body'`. All regions share the drawing's font catalog and canonical text verbs; widgets do not maintain separate text. ```dart import 'package:vyuh_diagram_core/adapter.dart'; import 'package:vyuh_diagram_extension_rich_text/extension_api.dart'; import 'package:vyuh_diagram_extension_rich_text/vyuh_diagram_extension_rich_text.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; final before = controller.document.shapeById('card')!.textStory!; final item = richParagraph( id: DiagramTextCommands.nextBlockId(before), kind: ParagraphKind.checklistItem, slotId: 'body', runs: [TextRun('Remember the blanket')], ); controller.perform(['card'], 'replaceText', {'before': before, 'after': before.copyWith(blocks: [...before.blocks, item])}); ``` JSON retains block identities, roles, slots, marks and list kinds. Use Undo to restore an earlier edit or restore a saved JSON snapshot. Source: `apps/demo/lib/examples/text/regions.dart`. See [paragraph grammar](/agent-docs/api/text.md#grammar-configuration). --- # Rich Text [Open runnable example](/examples-app/#/text/rich-text) Installs the Rich Text extension and reconfigures two core shapes for it. The standalone text is a `richText` element. The Comment and the rectangle are the core shapes, installed as copies made with `withText(const RichTextDefinition())` in the example's own extension, which replace the plain core definitions. The Comment holds a heading, a bulleted item with bold text, and a checked checklist item. Select text and use Command/Ctrl+B; list prefixes such as `- ` are interpreted by the extension, and the Comment tool creates rich comments. See [Rich text in shapes](/agent-docs/api/rich-text.md#rich-text-in-shapes). ## Source ```dart Widget buildExample() => ExampleCanvas( title: 'Rich Text', instructions: 'Double-click the text, the comment or the rectangle to edit. Select words and press Command/Ctrl+B for bold. Type a list prefix such as "- " to start a list; Command/Ctrl+Alt+2 makes a heading.', createController: createRichTextController, ); /// The core Comment and rectangle, reconfigured to hold rich text. The /// shapes declare only their text parts; this application chooses rich text /// for them, and installing the copies replaces the core definitions. ``` --- # Anchors and contour routing [Open runnable example](/examples-app/#/connectors/routing) Switch routers and target anchors, then move or rotate either shape. Drag curve handles to adjust bends. Bézier handles snap near quarter intervals of the anchor span, with a tolerance that stays constant on screen as you zoom. An anchor expresses attachment intent. The visible route stops at the occupied shape contour, including when the anchor lies in the center or on a far edge. The example does not draw its own curve, guides, hit regions or arrowheads. | Control / API | Behavior | | --- | --- | | `setConnectorRoute(id, route: kind)` | Changes between straight, orthogonal, quadratic and Bezier; keeps endpoint identities and bend intent. Router-specific control points are cleared. | | `reconnect(id, atStart: false, endpoint: ...)` | Updates the target's normalized anchor as one undoable edit. | | Center / left / right / top / bottom | Selects `(0.5, 0.5)`, `(0, 0.5)`, `(1, 0.5)`, `(0.5, 0)` or `(0.5, 1)` in target-local coordinates. Rotation is resolved by the framework. | | Select connection | Shows the route's standard editing controls. Drag the bend handle for curved routes. | Try the right or bottom target anchor while the source remains above-left. The connection must terminate when it reaches the target contour. Undo restores each anchor or route edit separately. Reset restores the selected quadratic fixture. The source uses a center anchor in this fixture; the target controls demonstrate all five anchors. Orthogonal routing negotiates the bound owners, not arbitrary unrelated obstacles throughout the diagram. Overlapping owners require different handling and are outside this example's fixed layout. See [Connectors](/agent-docs/api/connectors.md) for attachment and route configuration. ## Source ```dart void setRoutingTarget(DiagramController controller, DiagramPoint anchor) => controller.edits .reconnect( 'route', atStart: false, endpoint: BoundEndpoint( elementId: 'target', normalizedAnchor: anchor, ), ) .requireAllowed(); ``` --- # Shape effects [Open runnable example](/examples-app/#/motion/shape-effects) The middle shape starts selected. Each button plays one effect on the selected shapes and stops it when pressed again: - **Pulse** oscillates the fill tint, outline and opacity smoothly. - **Blink 3 times** uses `Waveform.step` with `repeat: 3`, then stops by itself. - **Ripple halo** and **Steady halo** ring the outline; the steady one uses a gradient from the brand color to orange. - **Breathe** scales the shape by 6% and back; **Pop** scales it by 20% once. Its text and ports scale with it, while its selection handles and hit area stay on its real bounds. - **Fade out**, **Fade in** and **Dim** change its opacity once and hold. Pick a brand color before playing an effect. The status line counts the playing effects, and **Stop all** stops them. Effects never edit the document or add undo entries. See [Animation & effects](/agent-docs/api/effects.md). ## Source ```dart final shapeEffects = { 'Pulse': (brand) => Effect.pulse(color: brand), 'Blink 3 times': (brand) => Effect.pulse( color: brand, waveform: Waveform.step, period: const Duration(milliseconds: 500), repeat: 3, ), 'Ripple halo': (brand) => Effect.halo(color: brand, spread: 14, width: 3), 'Steady halo': (brand) => Effect.halo( mode: HaloMode.steady, color: brand, endColor: const DiagramColor(0xFFF97316), spread: 10, ), 'Breathe': (_) => const Effect.scale(amount: 1.06, period: Duration(milliseconds: 2400)), 'Pop': (_) => const Effect.scale( amount: 1.2, period: Duration(milliseconds: 360), waveform: Waveform.easeInOut, repeat: 1, ), 'Fade out': (_) => const Effect.fade(), 'Fade in': (_) => const Effect.fade(direction: FadeDirection.fadeIn), 'Dim': (_) => const Effect.fade(dim: 0.35), }; ``` --- # Snap guides [Open runnable example](/examples-app/#/canvas/snap-guides) Drag either card near the other. A guide appears when their sides or centers align, and the card snaps into place. Toggle **Snap to shapes** to compare free movement. Release to commit; undo restores the previous position. The optional `SnapGuidesExtension` from `vyuh_diagram_extension_snap_guides` owns alignment snapping end to end: it adjusts selection moves using its `SnapGuidesOptions` and paints the reported guides as passive overlays, without intercepting pointer input. Guides disappear when the gesture finishes. Alignment applies to selection moves, not resizing. See [Snap guide policy](/agent-docs/examples/snap-policy.md) for feature and proximity controls, or [Grids API](/agent-docs/api/grids.md) for its options. ## Source ```dart import 'package:vyuh_diagram_extension_snap_guides/vyuh_diagram_extension_snap_guides.dart'; import 'package:vyuh_diagram_flutter/vyuh_diagram_flutter.dart'; import '../../diagram_extensions.dart'; import 'package:material_ui/material_ui.dart'; import '../connections/cards.dart'; import '../example_canvas.dart'; Widget buildExample({bool policyControls = false}) => ExampleCanvas( title: policyControls ? 'Snap guide policy' : 'Snap guides', instructions: 'Drag a card near another card to align their sides or centers. Toggle guides to compare free movement. Change the feature policy and nearby candidate limit to explore alignment.', createController: () => DiagramController( document: connectedCardsDocument(), configuration: DiagramConfiguration( extensions: [ ...demoModelExtensions, ...demoEditing(), SnapGuidesExtension(), ], ), ), actionGroups: { if (policyControls) 'Guide features': ['Sides and centers', 'Sides only', 'Centers only'], }, selectedActions: (controller) { final guides = controller.options(); return { if (guides.policy.sides && guides.policy.centers) 'Sides and centers' else if (guides.policy.sides) 'Sides only' else 'Centers only', '${guides.policy.maxCandidates} candidates', guides.enabled ? 'Guides on' : 'Guides off', }; }, actionToggles: { if (policyControls) 'Guide candidates': (on: '24 candidates', off: '8 candidates'), 'Snap to shapes': (on: 'Guides on', off: 'Guides off'), }, actions: { if (policyControls) 'Sides and centers': (s) => configureGuides( s, policy: (p) => p.copyWith(sides: true, centers: true), ), if (policyControls) 'Sides only': (s) => configureGuides( s, policy: (p) => p.copyWith(sides: true, centers: false), ), if (policyControls) 'Centers only': (s) => configureGuides( s, policy: (p) => p.copyWith(sides: false, centers: true), ), if (policyControls) '8 candidates': (s) => configureGuides(s, policy: (p) => p.copyWith(maxCandidates: 8)), if (policyControls) '24 candidates': (s) => configureGuides(s, policy: (p) => p.copyWith(maxCandidates: 24)), 'Guides on': (s) => configureGuides(s, enabled: true), 'Guides off': (s) => configureGuides(s, enabled: false), }, ); /// Snap guides are diagram options: changing them adds no document history. /// Changing the [policy] turns guides on. void configureGuides( DiagramController controller, { bool? enabled, DiagramSnapGuidePolicy Function(DiagramSnapGuidePolicy policy)? policy, }) { final guides = controller.options(); controller.edits.setOptions( guides.copyWith( enabled: enabled ?? (policy != null || guides.enabled), policy: policy?.call(guides.policy), ), ); } ``` --- # Snap guide policy [Open runnable example](/examples-app/#/canvas/snap-policy) Choose **Sides and centers**, **Sides only**, or **Centers only**, then move a card beside the other. Sides use the left, right, top and bottom of resolved bounds; centers use their horizontal and vertical midpoints. The candidate menu compares limits of **8** and **24** nearby shapes. Only the nearest visible shapes, up to the limit, are considered for alignment. A smaller limit does less work but may skip a useful alignment. The visible viewport defines the candidate pool. Zooming out includes more world space and potentially more candidates; panning changes the pool. The snap tolerance stays at 6 screen pixels as you zoom. The candidate cap defaults to 24; the API accepts 1–256. Policy changes go through `controller.edits.setOptions(options.copyWith(...))`, preserve the other `SnapGuidesOptions` fields and do not enter document undo history. See [Snap guides](/agent-docs/examples/snap-guides.md), [grid snapping](/agent-docs/examples/grids.md), and [snap guide options](/agent-docs/api/grids.md#neighbor-snap-guides). Guide appearance is part of the extension's options: `SnapGuidesExtension(theme: SnapGuideTheme(color: Color(0xFF5260FF)))`. You can supply any Flutter color; without a theme the guides use `SnapGuideTheme.light` or `SnapGuideTheme.dark` by the canvas `DiagramTheme.brightness`. --- # Departmental swimlanes Each department is an ordinary frame. Tasks belong to that frame through their saved `parentId`; connections keep their task bindings when lanes move. Swimlanes use the same parenting, unparenting, movement and optional collapse as frames. Clipping is a separate choice: declare `ShapeContainer(clips: true)` on the definition and `clipContent` on a lane to hide overflow while expanded. This example leaves clipping disabled. `arrangeLanes` arranges the frames, not the tasks inside them. [Open runnable example](/examples-app/#/basics/swimlanes) For domain review, choose **Task ownership → Detach review task**, then **Run checks**. Select the finding to locate the task and Quality department. **Assign review to Quality** repairs the ownership; run checks again to clear the finding. Undo restores the draft. This host-defined rule reports incomplete work without blocking edits or adding domain policy to the engine. - **Arrange columns** places departments side by side. Their frames change size; task sizes stay unchanged. - **Arrange rows** restores horizontal lanes in Production, Quality, Release order. Both arrangements leave a 32-unit gap between departments. - **Collapse Quality** shows the department summary and redirects external links. **Expand Quality** restores its task before arranging the lanes again. - **Undo** restores an entire lane arrangement in one step. - **Command-drag a task** to transfer it between departments, or outside all departments to release it. Use Control on other platforms. Its bounds only need to intersect the destination; the destination outline is highlighted. Ordinary dragging keeps its current parent. Escape cancels movement and ownership changes. ```dart controller.edits.arrangeLanes( ids: ['production', 'quality', 'release'], direction: DiagramLaneDirection.rows, laneSize: const DiagramSize(720, 180), gap: 32, ); ``` The ID order determines lane order. Omit `laneSize` to preserve existing sizes; `gap` defaults to zero. The arrangement starts at the current lanes' upper-left corner. Lanes must be expanded, unrotated sibling frames. Moving a locked or fixed child rejects the whole operation. Resizing a lane does not automatically fit its contents: hosts choose the lane size and clipping behavior explicitly. Transfer ownership with `controller.edits.reparent(ids: ['task'], parentId: 'quality')`. This preserves world positions; it changes membership without silently laying out the task. Pass no parent to return objects to the root. Transfers, lane movement, deletion, save/load and undo use the ordinary document verbs. To move and transfer together, pass a world-coordinate `delta`. The engine carries descendants without resizing them and records the entire operation as one undo: ```dart controller.reparent( ids: ['task'], parentId: 'quality', delta: const DiagramPoint(32, 48), ); ``` A locked descendant rejects the movement without partially changing ownership or positions. Omit `delta` to change membership while preserving world positions. On macOS, **Command+G** groups a selection, **Command+Option+G** frames it, and **Command+Shift+G** removes selected groups or frames while keeping their contents. Use Control instead of Command on other platforms. Removing a collapsed frame releases its children as well; Undo restores the container and membership. ## Source ```dart actions: { 'Arrange rows': (s) => s.edits .arrangeLanes( ids: laneIds, laneSize: const DiagramSize(720, 180), gap: 32, ) .requireAllowed(), 'Arrange columns': (s) => s.edits .arrangeLanes( ids: laneIds, direction: DiagramLaneDirection.columns, laneSize: const DiagramSize(240, 540), gap: 32, ) .requireAllowed(), 'Collapse Quality': (s) => s.edits.setFrameCollapsed('quality', true).requireAllowed(), 'Expand Quality': (s) => s.edits.setFrameCollapsed('quality', false).requireAllowed(), }, ``` --- # Table styling [Open runnable example](/examples-app/#/tables/styling) Explore table borders in the inspector and drag dividers to resize tracks. Hide column dividers and undo to compare the result. --- # Basic tables [Open runnable example](/examples-app/#/basics/tables) Start with one standalone table. Double-click a cell to type, use Tab and Shift+Tab to navigate, and try adding a row and undoing the change. Continue with [embedded tables](/agent-docs/examples/embedded-tables.md) or [table styling](/agent-docs/examples/table-styling.md) for separate focused examples. See [table behavior](/agent-docs/elements/tables.md) and [text regions](/agent-docs/elements/text-regions.md) for the grammar, sizing rules and supported keyboard interactions. --- # Register a custom tool [Open runnable example](/examples-app/#/canvas/tools) Choose **Checkpoint** or press **K** while the canvas has focus, then click or drag to create a checkpoint. Its label, minimum size and appearance come from the shape definition. Creation returns to selection and adds one undo entry. The ordinary rectangle tool remains available alongside it. The example registers a new tool identity and reuses `DiagramShapeTool`, the same behavior as built-in shape tools. There is no editor switch on the custom type and no second drawing or history implementation. Duplicate identities or shortcuts fail registration rather than silently replacing a default. For a different interaction, implement `DiagramToolBehavior` and use its `DiagramToolContext`: `context.perform(ids, verb, args)` for a direct edit, or a `DiagramToolGesture` whose `preview` returns a `DiagramGesturePreview` of verb invocations for each pointer sample. This example focuses on reusing existing shape mechanics; it does not demonstrate every custom gesture. Text editing retains ownership of letter shortcuts. `returnToDefault: true` applies to both direct `context.perform(...)` tools and gesture tools. An admitted direct verb returns after the callback; a gesture returns after its admitted commit. Denied verbs or commits keep the tool active for retry. Retained callback contexts cannot perform verbs after the callback has ended. If the final creation preview is denied, the gesture rolls back and releases the pointer without resetting the active tool or adding an undo entry. See [Extensions and options](/agent-docs/api/configuration.md) and [Shapes](/agent-docs/api/shapes.md). ## Source ```dart actions: { 'Checkpoint — K': (controller) => controller.setTool(checkpointTool), 'Rectangle — R': (controller) => controller.setTool(DiagramTools.rectangle), 'Select — V': (controller) => controller.setTool(DiagramTools.select), }, ``` --- # Connected building topology For a focused before-and-after demonstration of obstacle routing and label arrangement, open [Make a crowded network readable](/agent-docs/examples/dense-network.md). [Open runnable example](/examples-app/#/custom-shapes/topology) A minimal custom shape: an outlined device icon, status dot, title and status line. Straight links bind to the center of each device icon and follow dragging. Hover over an icon for its address and capacity. Both text lines use independent, single-line canonical text regions. Text editing starts disabled. Use the pencil in the vertical rail to enable it; turning it off keeps nodes movable. Two registered definitions share the same anatomy, except that one declares its text parts with `editable: false`, so people cannot edit them on the canvas while the application still updates them. Use the rail to switch between focused and expanded site views. Live data changes the HVAC plant status and status dot even while direct editing is disabled. Manually editing status text does not infer a new health state: applications own that mapping. The minimap starts expanded and includes connections. Click or drag it to navigate larger topologies. The tooltip is a Flutter widget slot. Its portable image fallback preserves the icon and status dot in exports; transient hover details are not exported. ```dart ShapeDefinition topologyDefinition({required bool editable}) => ShapeDefinition( type: editable ? 'example.topology.editable' : 'example.topology', verbs: [setTopologyTextEditableVerb], name: 'Network device', // The device paints only its icon and labels, not a surface of its own. outline: null, minimumSize: const DiagramSize(140, 112), size: const DiagramSize(140, 112), behavior: const ShapeBehavior(resizable: false, rotatable: false), values: const {'image': ImageValueField()}, connection: ShapeConnectionDefinition.fixedPorts([ PortDefinition.normalized( id: 'center', anchor: const DiagramPoint(.5, 36 / 112), outwardNormal: DiagramPoint.zero, style: const PortStyle( width: 6, height: 6, fill: DiagramColor(0x00000000), stroke: DiagramColor(0x00000000), ), ), ], clipToOutline: false), body: ShapeColumn([ ShapeSized( extent: 76, child: const ShapeWidget( 'example.topology.details', id: 'device-icon', fallback: ShapeImage(), ), ), ShapeSized( extent: 18, child: ShapeText( 'title', horizontalPadding: 0, editable: editable, textType: const PlainTextDefinition(maxLines: 1), role: TextRole.title, ), ), ShapeSized( extent: 18, child: ShapeText( 'status', horizontalPadding: 0, editable: editable, textType: const PlainTextDefinition(maxLines: 1), ), ), ]), ); ``` The hierarchy action calls the shared [graph layout API](/agent-docs/api/layout.md), not example-specific positioning code. ## Network flow Network flow begins automatically. Effects follow route and layout changes while remaining outside document history. --- # Transform modifiers Transform gestures and API verbs share the same canonical geometry and history. [Open runnable example](/examples-app/#/basics/transforms) ## Try it The left rectangle enables `ShapeBehavior(rotationHandle: true)`. Select the right rectangle to compare the default corner rotation without a separate handle. Hold **Shift** to preserve aspect ratio while resizing or **Alt** to resize around the center. Rotate either shape, then undo. The buttons transform the current selection using move, rotate and centered resize verbs. Source: `apps/demo/lib/examples/basics/transforms.dart`. See [Controller](/agent-docs/api/controller.md) for transform arguments and minimum-size behavior. ## Source ```dart actions: { 'Select handle example': (s) => s.select(['target']), 'Select corner example': (s) => s.select(['standard']), 'Move 40': (s) => s.edits .move(const DiagramPoint(40, 0), ids: transformSelection(s)) .requireAllowed(), 'Rotate 15°': (s) => s.edits .rotate( ids: transformSelection(s), pivot: DiagramRect.union([ for (final id in transformSelection(s)) DiagramControlHandleResolver.selectionBoundsFor( s.scene.elementById(id)!, ), ]).center, radians: 0.2617993877991494, ) .requireAllowed(), 'Resize from center': (s) => s.edits .resize( const DiagramSize(360, 240), ids: transformSelection(s), fromCenter: true, preserveAspectRatio: true, ) .requireAllowed(), }, ``` --- # Regional transport network [Open runnable example](/examples-app/#/industries/transportation) Schematic sample data. Select a node, drag it, or mark a link disrupted. This canvas does not compute schedules or geographic routes. Use **Disrupt interchange link** to mark a connection, then **Undo** to restore it. Host applications supply operational data and domain validation. See [Transportation & Transit](/industries/transportation) and [connectors](/agent-docs/api/connectors.md). ## SVG asset icons This network contains **18 assets and 24 connections**. Facility cards, circular interchanges and hexagonal checkpoints have distinct silhouettes. Each asset includes an SVG icon, an editable name and an operational label. Select one asset, then choose **Import SVG icon** in the canvas toolbar to replace its icon from a local file. Cancel leaves the document unchanged; **Undo** restores the previous icon. The picker also accepts raster images. To supply SVG from application code: ```dart final icon = DiagramImageSource.fromBytes( utf8.encode(svgMarkup), // import dart:convert mimeType: 'image/svg+xml', ); controller.setImage(assetId, icon); ``` The registered shape declares an `ImageValueField` and includes a `ShapeImage()` part in its body, alongside `ShapeText('title')` and `ShapeText('status')`. SVG bytes stay with the document when saved to JSON. The Flutter image renderer handles display; no per-icon Flutter widget or painter is required. Importing SVG creates image content, not separately editable SVG path elements. ## Source ```dart Widget buildExample() => IndustryCanvas( title: 'Regional transport network', subtitle: '18 terminals and hubs · Sea / teal · Rail / violet · Road / amber · Air / blue. Select an asset to import your own SVG icon.', createController: createTransportationController, actions: [ IndustryCanvasAction( label: 'Import SVG icon', icon: FluentIcons.image_20_regular, run: importSelectedNetworkIcon, ), IndustryCanvasAction( label: 'Disrupt interchange link', icon: FluentIcons.warning_20_regular, run: (s) { final link = s.document.elements.whereType().first; s.edits .setConnectorStyle( link.id, color: const DiagramColor(0xFFBE4B49), strokeStyle: StrokeStyle.dashed, ) .requireAllowed(); }, ), IndustryCanvasAction( label: 'Undo', icon: FluentIcons.arrow_undo_20_regular, run: (s) => s.edits.undo().requireAllowed(), ), ], ); ``` --- # View-only diagrams [Open runnable example](/examples-app/#/navigation/view-only) Select shapes and connections, drag to pan, scroll to navigate, or pinch to zoom. Ctrl/Command-scroll zooms around the pointer. Arrow keys pan; Escape clears the selection. None of these operations modifies diagram content. Mount `DiagramCanvas(controller: controller)` on a controller with no editable extension installed (leave out `EditorExtension`). The canvas then has no editing tools, transform handles, text input or editing shortcuts. It draws the same diagram, so shapes, text and images look exactly as they do in the editor. Attribution is built in. Pass `DiagramController(configuration: DiagramConfiguration(license: token))` to remove it; see [License](/agent-docs/api/license.md). The view follows the controller, so application code can still load or update the diagram through the controller. View-only describes canvas interaction, not a restriction on your application's controller verbs. Custom widget shapes use their portable painted representation in this mode. Without an editable extension there are no editing toolbars or inspectors. ## Source ```dart Widget buildExample() => ExampleCanvas( title: 'View only', instructions: 'Select a card or connection. Drag or scroll to pan; pinch or Ctrl/Command-scroll to zoom. Shapes and text cannot be edited.', createController: () => DiagramController( document: connectedCardsDocument(), configuration: DiagramConfiguration(extensions: demoModelExtensions), ), ); ``` --- # Warehouse execution flow [Open runnable example](/examples-app/#/industries/warehouse) Follow goods from receiving through putaway, reserve storage, wave picking, packing and dispatch. Live queue counts and utilization change across the diagram, while the vertical tool rail lets you add a zone or connect a new operational path. The example is a composition of registered shapes, stable ports, orthogonal connectors and presentation-only path animation. It does not add a warehouse-specific branch to the diagram engine. --- # Portable widget content [Open runnable example](/examples-app/#/widgets/fallback) The live CDX button selects both cards. **Show fallback** removes its widget registration, revealing the ordinary text part declared by the shape definition. **Show live control** restores the interactive button. Both use the same canonical caption; switching presentation does not replace the document or add undo history. | Action | API | Result | | --- | --- | --- | | Show fallback | Create the controller over the same document without the Flutter extension that registers the widget builder. | Displays the declared portable fallback instead of native controls. | | Show live control | Install that Flutter extension again | Restores the button and its selection action. | | Download SVG / PNG | `controller.exportSvg` / `controller.exportPng` | Exports portable content in either presentation mode. | The fallback is required in a `ShapeWidget` part. It is an ordinary body part, so layout, clipping and output can resolve it without executing Flutter controls. This example shares a canonical text story between the button and fallback. Arbitrary widget-local state is not captured in output; durable content must be represented by canonical data and declared portable parts. ## Definition and live control ```dart DiagramController fallbackExampleController() { final extensions = [ ...demoModelExtensions, ...demoEditing(), cardActionExtension(), ]; final seed = DiagramController( configuration: DiagramConfiguration(extensions: extensions), document: connectedCardsDocument(), ); try { seed.edits.createShape( exportWidgetType, id: 'card-action', at: const DiagramPoint(260, 260), size: const DiagramSize(240, 64), select: false, ); return DiagramController( document: seed.document, configuration: DiagramConfiguration( extensions: [...extensions], defaultFontFamily: 'IBM Plex Sans', ), ); } finally { seed.dispose(); } } ``` ## Controller and presentation switch Source: [fallback.dart](https://github.com/vyuh-tech/vyuh_diagram/blob/main/apps/demo/lib/examples/widgets/fallback.dart). See [widgets](/agent-docs/api/widgets.md) and [output](/agent-docs/api/output.md) for the complete contracts. --- # Widget clipping and layering [Open runnable example](/examples-app/#/widgets/layers) The controls card extends beyond its clipping frame. A higher element covers part of the live controls. Hidden and covered controls must not receive pointer input; the visible foreground element owns that space. | Action | Public API | Expected result | | --- | --- | --- | | Move frame | `move(delta, ids: ['frame'])` | Moves the child once with its owner; the independent cover stays in place. | | Remove cover | `delete(ids: ['cover'])` | Reveals controls beneath it. | | Release contents | `unframe(ids: ['frame'])` | Removes the frame, retaining the widget and its world position. | | Undo | `undo()` | Restores the prior ownership, clipping or cover. | Try dragging the cover, clicking the visible slider, and releasing the contents to reveal the bottom of the widget. Pan and zoom through the normal canvas controls. The example supplies canonical ownership and z-order; the framework owns widget mounting, clipping, hit testing and transforms. The bottom Count button is fully outside the frame and is omitted from the accessibility tree. Releasing the contents exposes it again. Partially visible controls retain their accessibility nodes; clipping follows the resolved path's bounding rectangle for native semantics, while pointer clipping uses the path. ## Source ```dart DiagramController widgetLayersController() { final seed = createControlsExample(); try { return DiagramController( configuration: DiagramConfiguration(extensions: seed.diagram.extensions), document: DiagramDocument( id: 'widget-layers', revision: 0, elements: [ ShapeElement( id: 'frame', type: Shapes.frame, frame: const DiagramRect.fromLTWH(0, 0, 340, 180), clipContent: true, ), seed.document .shapeById('controls')! .copyWith( parentId: 'frame', frame: const DiagramRect.fromLTWH(60, 0, 300, 280), zIndex: 1, ), ShapeElement( id: 'cover', type: Shapes.rectangle, zIndex: 2, frame: const DiagramRect.fromLTWH(180, 80, 170, 80), style: const ShapeStyle( fill: DiagramColor(0xFFE4E4E7), cornerRadius: 8, ), textStory: TextStory.paragraph( id: 'cover-story', blockId: 'cover-text', text: 'On top of the controls', ), ), ], ), ); } finally { seed.dispose(); } } ``` --- # Widget properties [Open runnable example](/examples-app/#/widgets/properties) The selected controls card advertises `progress`, `mode`, and `count` through its shape definition. `DiagramInspector` creates the corresponding property controls; the live widget reads the same values. There is no separate form model to synchronize. | Definition / API | Contract | | --- | --- | | `NumberValueField` | Numeric bounds and integer constraints are validated at canonical publication. | | `TextValueField.allowedValues` | Declares the mode choices. | | `ShapeDefinition.values` | Supplies defaults and field grammar for both verbs and inspector. | | `controller.edits.setValues(id, values)` | Merges registered values in one admitted edit. | | `DiagramInspector(controller: controller)` | Edits selected elements through the editors their anatomy and values declare. | Change progress or mode in the inspector, then use the widget. **Set ready** updates both fields together; Undo restores both. Locking the card prevents edits through either surface. Text properties are absent because this node's body has no text part. The inspector moves below the canvas on narrow example embeds. ## Source ```dart actions: { 'Select card': (s) => s.select(['controls']), 'Set ready': (s) => s.edits.setValues('controls', { 'mode': 'Ready', 'progress': 100, }).requireAllowed(), }, ``` The fixture, registry and controls are shared with [Widgets inside shapes](/agent-docs/examples/widgets.md). --- # Widgets inside shapes [Open runnable example](/examples-app/#/widgets/controls) The card contains CDX controls. Drag its non-interactive space to move it, or select it to resize and rotate. The slider, dropdown, and button keep their own interactions. **Set ready** changes two registered values through the controller; Undo restores them together. Slider previews commit as one edit. The example composes a `ShapeDefinition` whose body holds a `ShapeWidget` part, and registers its Flutter builder in `DiagramFlutterExtension.widgets`. The values `progress`, `mode`, and `count` are registered fields in the canonical document. There is no separate widget-owned persisted state, and the node has no text story or paragraph controls. The portable output fallback is a simple region, not a screenshot of interactive controls. Hosts must declare an appropriate fallback for their own widget content. See [Widget API](/agent-docs/api/widgets.md) for hit testing, lifecycle, culling, and output contracts. ## Source ```dart DiagramFlutterExtension controlsExampleExtension() => DiagramFlutterExtension( id: 'example.controls', widgets: playgroundWidgetRegistry().builders, shapes: [ playgroundControlsDefinition( style: const ShapeStyle( fill: DiagramColor(0xFFF4F4F5), stroke: DiagramColor(0xFFD4D4D8), strokeWidth: 1, cornerRadius: 12, ), ), ], ); ``` --- # Domain extensions Domain extensions combine shape definitions, connection rules, custom properties and application adapters into a focused editing experience. They share the canvas, selection, text editing and history APIs. | Page | Use it to | | --- | --- | | [Layout](/agent-docs/extensions/layouts.md) | Arrange the same document with different automatic layouts. | | [Application compositions](/agent-docs/extensions/starters.md) | See how the same diagram API supports different host experiences, such as service maps and storyboards. | The host application supplies data, permissions and services. --- # Layout [Open runnable example](/examples-app/#/extensions/layouts) Install the layout extension to arrange the same document using different layout strategies. Change the selected layout and its options, inspect the result, then undo the arrangement through the diagram's shared history. Layout providers operate on canonical diagram geometry. Their results are applied through controller commands, so selection, connectors, export and history agree. See the [layout API](/agent-docs/api/layout.md) and [layout extension](/agent-docs/api/extension-layout.md) for installation and provider options. --- # Application compositions Two headless fixtures show how the same diagram API supports different host experiences. Their source lives in `apps/demo/lib/examples/kits`. They are not part of the interactive example gallery. For an interactive host composition, see [Editor composition](/agent-docs/examples/editor-composition.md). | | Service map | Storyboard | | --- | --- | --- | | Shapes | A custom service node | A clipping board and owned panels | | Text | Single-line service names | Single-line headings and multiline bodies | | Connections | Named input/output ports with directional policy | No connection affordance on boards or panels | | Tools | Select, Service, Connect | Select, Panel, Text | | Shared behavior | Commands, admission, change events, labels, undo and JSON | Commands, text/list editing, ownership, locks and undo | The examples use public package imports. Shape and tool registries deliberately omit unrelated built-in defaults; custom type and tool IDs use the same grammar and dispatch path as the defaults. ## Run without Flutter From the repository root: ```sh dart --packages=.dart_tool/package_config.json apps/demo/bin/headless.dart services dart --packages=.dart_tool/package_config.json apps/demo/bin/headless.dart storyboard ``` Both produce canonical JSON using the plain Dart VM. Their default text metrics are deterministic bootstrap measurements, not font-accurate server rendering. Restore the JSON on a controller that installs the same extensions for its custom shape types. The headless entry point uses `createServiceMapController()` or `createStoryboardController()`, then the same `controller.save(DiagramJsonCodec.new)` and `controller.dispose()` API as a Flutter host. Each factory's controller owns its diagram's registry and document lifetime. ## Embed the same composition The demo supplies Flutter text layout and mounts a `DiagramCanvas`. For your own Flutter application, create a `DiagramController` with your document and the extensions that declare your shapes, then pass it to `DiagramCanvas(controller: controller)`. Dispose the controller after unmounting its canvas. See [Getting started](/agent-docs/guide/getting-started.md) for a complete host example. ```sh cd apps/demo flutter run -d chrome ``` Open [Editor composition](/agent-docs/examples/editor-composition.md) to explore canvas chrome. The `DiagramRules(canConnect: ...)` rule governs the service map's connection commands and gestures. Use `beforeChange` for authorization that must also cover advanced raw transactions. Neither example supplies workflow execution, arbitrary embedded Flutter widgets, SVG/PDF output or complete accessibility; those capabilities should not be inferred from these examples. --- # Capabilities Vyuh Diagram combines editable elements, shared text, connections and extensible tools in one drawing. Use controller commands for application actions and definitions to describe custom elements. ## Elements and editing | Capability | What you can do | | --- | --- | | [Shapes](/agent-docs/api/shapes.md) | Create standard or custom shapes; declare their anatomy: outline, body regions, values, appearance, properties, ports and behavior. | | [Text](/agent-docs/api/text.md) | Edit standalone text, shape text and connector labels with shared formatting, paragraphs, nested lists and checklists. Use a drawing-wide font catalog. | | [Selection and transforms](/agent-docs/api/controller.md) | Select, move, resize, rotate, group, align, distribute, reorder, copy and delete elements. | | [Locks](/agent-docs/api/controller.md) | Protect elements and their owned contents from edits while retaining selection. | | [Undo and redo](/agent-docs/api/history.md) | Undo or redo document edits, including text changes, connections and grouped operations. | | [Custom tools](/agent-docs/examples/tools.md) | Register tools that use the same editing and preview contracts as standard tools. | | [Commands and drawing search](/agent-docs/guide/editor-getting-started.md#find-connect-and-arrange) | Search installed commands with Cmd/Ctrl+K; find elements and reveal collapsed owners. | | [Shared properties](/agent-docs/guide/properties.md) | Edit compatible properties across selected kinds with typed keys, explicit mixed values and intersected constraints. | | [Graph layout](/agent-docs/api/layout.md) | Arrange sibling nodes or a container's direct children; preserve descendant offsets and pinned nodes. | | [Diagnostics and repairs](/agent-docs/api/controller.md#discovery) | Run installed domain checks and apply suggested fixes atomically with a snapshot guard. | ## Connections and presentation | Capability | What you can do | | --- | --- | | [Connectors](/agent-docs/api/connectors.md) | Connect element anchors or explicit ports with straight, elbow, quadratic or cubic Bézier routes. Apply connection rules and edit route controls. | | [Connected creation](/agent-docs/api/controller.md#discovery) | Drop a port into empty space to create the next shape and connection in one undo step. | | [Connector labels](/agent-docs/examples/connector-labels.md) | Add up to two single-line labels by default; edit, style, move and delete them independently. Enter edits the first label or creates one. | | [Navigation](/agent-docs/api/navigation-and-motion.md) | Pan, zoom, fit content and move the view to points, rectangles, elements, regions or the selection, with or without motion. | | [Animation & effects](/agent-docs/api/effects.md) | Play flows, pulses and blinks along connectors, and pulses, halos, scaling, fades or custom badges on shapes. | | [Canvas and grids](/agent-docs/api/grids.md) | Configure canvas bounds, backgrounds, grid patterns and snapping. Compose dot, line and cross layers. | | [Embedded widgets](/agent-docs/api/widgets.md) | Place Flutter controls inside registered elements. Share element values and history while retaining control interaction, transforms and clipping. Supply portable content for export. | | [Accessibility](/agent-docs/api/canvas.md) | Expose element and connector-label selection, text editing and native controls through semantics that follow visible geometry. | ## Integration and output | Capability | What you can do | | --- | --- | | [Rules and changes](/agent-docs/api/hooks.md) | Observe document changes and enforce application permissions or fixed domain invariants. | | [Persistence](/agent-docs/api/persistence.md) | Save versioned JSON and restore documents through validated imports. | | [PNG](/agent-docs/api/output.md) | Export a static drawing with transparent or explicit background, chosen bounds and raster scale. Requires Flutter. | | [SVG](/agent-docs/api/output.md) | Export vector geometry, native text, images, clipping and portable widget content. Supply fonts for self-contained text resources. | | [Agents](/agent-docs/agents/index.md) | Generate and update diagrams through commands, validate proposed edits and save JSON or SVG. | | [Domain extensions](/agent-docs/extensions/index.md) | Build domain editing experiences such as service maps and storyboards. | ## Integration boundaries Automatic elbow routing avoids its disjoint endpoint owners; it does not continuously route around every obstacle in a scene. Use `controller.edits.reroute()` for explicit obstacle-avoiding elbow rerouting in one undoable edit. Moving an unrelated obstacle does not automatically rerun that search; a rerouted path follows endpoint moves while it stays clear and otherwise reports itself stale. Port labels are not supported. Path effects apply to connectors. PDF export is not available. Widget export uses declared portable content rather than arbitrary native widget pixels. SVG text appearance depends on fonts and the target viewer. Controllers that join one diagram share its committed document; each keeps its own selection, interaction and undo. There is no built-in transport for remote collaborators. See [collaboration](/agent-docs/api/collaboration.md) before attaching multiple users or agents.