Behavior and configuration
For the typed API, start with three choices:
| Choice | API | Owns |
|---|---|---|
| Content | DocumentConfiguration(elements:, marks:) | Allowed elements, attributes and commands |
| Presentation | DocumentSurface.pages() or .pageless(maxWidth:) | Physical pages or a continuous column; .line() and .field() support inputs |
| Controls | EditorChrome.none, .floating, .toolbar(...) or .full | Which controls appear, their order and grouping |
Keep the DocumentController alive when changing the surface or chrome. Each document keeps its own controller and participant history. The widget projects that state when you switch documents; surface changes do not create a new document or Undo stack. Pageless width must be finite and positive.
Pass resources: DocumentEditorResources(...) to the typed DocumentEditor when your host supplies font loading, a prepared exact font lease, or a resource failure handler. Keep the loader alive with the host; dispose it when the host closes. The default resource option retains the existing editor behavior. The following complete source example uses only the public typed API:
dart
import 'package:vyuh_document_editor_elements/vyuh_document_editor_elements.dart';
import 'package:flutter/services.dart';
import 'package:vyuh_document/vyuh_document.dart' as document;
import 'package:vyuh_document_editor/document_editor.dart';
const documentChrome = EditorChrome.toolbar(
Toolbar.grouped([
ToolbarSection('History', [UndoButton(), RedoButton()]),
ToolbarSection('Text', [BoldButton(), ItalicButton(), LinkButton()]),
]),
);
// The host keeps one controller per document and owns the loader's lifetime.
DocumentEditor configuredEditor(
document.DocumentController controller,
DocumentFontLoader fonts,
) => DocumentEditor(
extensions: DocumentEditorElements.defaults,
controller: controller,
surface: const DocumentSurface.pageless(maxWidth: 720),
chrome: documentChrome,
textInput: const DocumentTextInputConfiguration(
capitalization: TextCapitalization.sentences,
smartQuotesType: SmartQuotesType.disabled,
),
resources: DocumentEditorResources(fontLoader: fonts),
);onRefused reports rejected edits and onError reports failed durable controller operations, including history restored under changed permissions.
Exact-font opening is available through DocumentOpenCoordinator in the integration library. Supply its exactFontPreparer and admissionElements; preparation covers both the document's referenced fonts and the installed editable elements' default families. Hand its borrowed resources to the editor before the open operation settles. The admitted scene retains its own lease.
configuration.describe() gives agents the installed schema and command signatures. Host extensions contribute actions, inputs, menus, shortcuts and element properties through their owning registries. Hidden controls do not grant or withdraw permission to mutate content.
Discover grammar and lifecycle
Use configuration.describe(includeRuntime: true).toJson() for the canonical content expressions, accepted/rejected groups, contextual containment rules, property value domains, capability predicates, and sealed protocol transitions. The compact default description stays unchanged. Installed core definitions include substrate: the configured element list remains the authoring policy. Each schema identity has one declaration. Reusing that declaration is allowed; conflicting declarations are rejected when constructing the configuration. For a particular insertion or move, the engine validates the complete proposal, including its story and contextual conditions; a list of possible child types alone cannot establish legality.
Keep a DocumentView(controller) and pass it as view: to the editor. view.describe(includeGrammar: true) combines the mounted input phase, mode, revision, selection kind, live action availability, configured content, and installed grammar. view.inputPhase reads the canonical snapshot directly. The view notifies when interaction state or resolved geometry changes.
Input admission has six explicit phases: preparing, preview, retainedPaintOnly, admitted, suspended, and terminated. The exported DocumentInputPhase.contract is the same table the engine evaluates. Mode, protection, grants, story, and command preconditions narrow admission further. An open operation's generation/progress and an IME composition's phase are separate protocols; they do not replace the current document's input authority. Superseded asynchronous work cannot grant input to a successor session.
The phases form one transition table: each phase lists the phases it may follow (contract.allowedPredecessors, mayFollow, successors), the engine refuses any other change, every live phase can reach admitted, and only terminated has no successor.
A host holds all document input with the runtime controller's suspendInput() and returns it with resumeInput(): for example while a blocking dialog is open, or while another owner works on the document. Typing, commands, selection and camera input are refused meanwhile and the document does not change. Mounting, layout and publication never end a suspension.
dart
if (controller.suspendInput()) {
try {
await showBlockingDialog(context);
} finally {
controller.resumeInput();
}
}Every transaction is validated before it becomes the document, by the same rules as loading, on the part it changed. An edit that would break the grammar, reuse an id or leave an annotation without its block is refused and the document stays as it was.
Compose custom surfaces
viewportBuilder: (context, child) => ... wraps the document viewport below toolbar chrome and inside rulers. Use it for a custom background or a clipped overlay. shellBuilder: (context, child) => ... wraps the entire editor for host panels, status, or surrounding controls. Include the supplied child once. For range overlays, listen to DocumentView and use rectsFor(range); it returns current global rectangles, or an empty list before current geometry is available. Convert global rectangles into the overlay's local coordinates. Reuse the editor's input and camera through these slots.
The shared Properties workspace accepts DocumentInspectorConfiguration: override stable destination/tab/group/property addresses to hide, reorder, rename, make read-only, or replace a control with a presentation builder. defaultPropertyAccess: DocumentInspectorAccess.hidden opts addressable fields in individually. Legacy controls without property addresses still require a destination/group restriction. configuration.describe() on this inspector policy exposes the host overrides; canonical property domains stay in the element grammar. Custom controls dispatch the same registered commands.
Standalone WASM hosts
The current CDX code-editor dependency needs this setting in the host app's pubspec when compiling WASM. Package-level overrides do not propagate:
yaml
dependency_overrides:
isolate_manager: ^6.3.2Without it, the older transitive isolate implementation imports dart:html and WASM compilation fails. The demo already carries this override. Validate an unpublished source candidate outside workspace resolution locally with dart run tool/verify_published_consumer.dart --local --wasm; omit --local after publication to check actual registry archives. These are local builds.
The sections below describe the runtime adapter and its richer workspace configuration, used when composing your own editor shell.
Focus writing
The full workspace offers Focus writing in its view switch and command palette. It hides the toolbar and sidebar while keeping the document mounted and its rulers visible. Escape restores the previous workspace after the active menu, dialog or editor interaction has had its turn. An active IME composition keeps Escape for candidate cancellation. There is no floating exit control.
Custom workspaces opt in by passing their existing DocumentWorkspaceViewState as view: and its update callback as onViewChanged: to DocumentEditorWorkspaceScaffold. Project rulers with view.rulersVisible; focus writing makes that projection visible while view.showRulers retains the author's normal preference. Escape restores that preference. Omit onRulersToggled while focus writing is active to keep the ruler's visibility toggle disabled. The same controller, selection, published reading bookmark and Undo history remain in use. This is a personal presentation choice; it does not alter the document or its export.
Saved layouts in the workspace
The demo's Snapshots panel opens a saved layout inside the current shell. Snapshot uses the canonical Viewing authority and a frozen page source; it does not introduce a second editable document. Mode, search, zoom, rulers, outline, bookmarks and page navigation remain in the shared workspace. Choose Editing or Viewing through the existing mode control to return to live layout. A changed document, session or mode invalidates the frozen source.
Custom shells can compose DocumentSnapshotSession and SnapshotRulerFrame from document_editor_workspace.dart. DocumentSnapshotView remains available from viewer.dart for lightweight, editor-free snapshot readers. The workspace adapter binds selection and camera to the editor snapshot; standalone readers can keep their ordinary independent camera.
A host makes three separate choices: extensions install capabilities, the schema restricts content, and configuration chooses behavior and presentation.
The document configuration gates everything
The elements and marks you configure become a schema policy. Every surface asks it before offering anything.
Hiding a button is presentation only. The schema rejects content it does not admit, and document protection guards protected edits.
Editor configuration
dart
import 'package:vyuh_document_editor/vyuh_document_editor.dart';
final configuration = DocumentEditorConfiguration(
toolbar: DocumentToolbarConfiguration(
rows: DocumentWorkspaceToolbarRows.singleRow,
actionIds: {
HistoryActionId.undo,
HistoryActionId.redo,
MarkActionId.bold,
MarkActionId.italic,
MarkActionId.underline,
TextInsertActionId.link,
},
),
showFormattingMarks: false,
);
// Removing an action is one mechanism: a host extension unregisters it, and
// it leaves the toolbar, shortcuts, menus, palette and catalog together.
// Install it in the controller's extension list, after the starter kit:
// DocumentEditorController(extensions: [...DocumentEditorElements.defaults,
// withoutStrike]).
final withoutStrike = DocumentHostExtension(
id: 'app.without-strike',
register: (registry) => registry.unregisterAction(MarkActionId.strike),
);
// Toolbar filtering is presentation. Use a restricted schema to reject
// content, a host extension to remove registered actions, and engine
// protection for authorization. Direct commands still obey their canonical
// validation.Use DocumentEditorConfiguration.copyWith for product variants. The controller's layoutMode chooses paged or pageless editing; the configuration's optional layoutMode only checks it.
Page/column indicators in pageless flow follow showFormattingMarks; hiding them retains the authored boundaries without extra flow height. See Multiline input and breaks.
Embedded surface
A pageless editor draws a white surface with a 42-pixel inset, room for table controls and element handles. Change it on the theme:
dart
final configuration = DocumentEditorConfiguration.richText(
theme: DocumentEditorTheme.light().copyWith(
continuousCanvasColor: const Color(0xFFF7F8FA),
continuousContentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
),
);Use EdgeInsets.zero when the surrounding widget supplies that space. When two toolbar rows would not fit, a docked toolbar shows one scrollable row instead.
Theming
One DocumentEditorTheme styles the editor in light and dark. See Theming.
Host extensions
Configuration chooses presentation; it takes no host callbacks. Everything your app plugs in (actions, the right-click menu's rows, inline interactions, keys, / and @ palettes, type-to-format rules) is a DocumentHostExtension in the controller's extension list, after the starter kit. Host contributions shows the pattern and covers keys, triggers and input rules; this page covers actions.
dart
import 'package:vyuh_document_editor_elements/vyuh_document_editor_elements.dart';
import 'package:vyuh_document_editor/document_editor_extensions.dart';
import 'package:vyuh_document_editor/document_editor_workspace.dart'
show DocumentSemanticIcons;
import 'package:vyuh_document_editor/vyuh_document_editor.dart';
enum AcmeActionId with EditorActionKey implements EditorActionId {
share('acme-share'),
suggestions('acme-suggestions');
const AcmeActionId(this.key);
@override
final String key;
}
/// One suggestion row, named by the word it inserts.
final class SuggestionActionId extends ParameterizedActionId {
const SuggestionActionId(this.word);
final String word;
@override
String get key => 'acme-suggest-$word';
}
// The host is one more extension: keep this instance for the editor's life.
final acmeHost = DocumentHostExtension(
id: 'acme.host',
register: (registry) => registry
// One action: toolbar, shortcut, menus, palette, right-click menu and
// the action catalog all project it.
..registerAction(
EditorAction.toolbar(
id: AcmeActionId.share,
icon: DocumentSemanticIcons.link,
group: ToolbarGroup.review,
tooltip: 'Share selection',
transactionKind: DocumentCanonicalTransactionKind.none,
isEnabled: (controller) => !controller.textRange.isCollapsed,
execute: (controller) => shareSelection(controller.textRange),
contextMenu: const DocumentContextMenuPlacement(group: 50),
),
)
// Removing a starter action removes it from every surface.
..unregisterAction(ImageActionId.insertFromUrl)
// Rows derived from what is under the pointer: spelling suggestions.
..registerActionProvider(AcmeActionId.suggestions, (context) sync* {
if (context.surface != EditorActionSurface.contextMenu) return;
for (final word in suggestionsFor(context.controller)) {
yield EditorAction(
id: SuggestionActionId(word),
label: word,
group: ToolbarGroup.review,
execute: (controller) => replaceSelectionWith(controller, word),
contextMenu: const DocumentContextMenuPlacement(group: 1),
);
}
}),
);
// Installed in the controller's extension list, after the starter kit.
final controller = DocumentEditorController(
extensions: [...DocumentEditorElements.defaults, acmeHost],
);
final configuration = DocumentEditorConfiguration(
review: DocumentReviewConfiguration(
// The one comment prompt: requestComment() returns the new comment.
commentComposer: (controller, selection) async => 'Please check.',
),
);
// Your app's own services.
void shareSelection(DocumentSelection selection) {}
List<String> suggestionsFor(DocumentController controller) => const [];
void replaceSelectionWith(DocumentController controller, String word) {}One EditorAction is the whole vocabulary. An action registered once reaches the toolbar, its shortcut and shortcut help, the menus and command palette, the slash palette and the Insert menu (see Insertions), the right-click menu (when it declares contextMenu) and the action catalog. A later registration with the same ID replaces the earlier one in place.
- Remove an action with
registry.unregisterAction(id). It leaves every surface at once; there is no second disable list. - Remove only its key chord by registering
registry.requireAction(id).copyWith(activators: []): the action stays in menus and toolbars, and the key falls through to text input. - Derive actions from live state with
registerActionProvider: one provider serves every surface and readscontext.surfacewhen a surface needs a different set. Each provided action places itself like a registered one, with apresentation.menuPathfor a submenu. - The extension list is fixed for a controller's lifetime; create the host extension once with the controller.
Insertions
The / palette, the Insert menu and the action catalog list the same registered actions. Every insertion the starter kit offers (paragraphs, headings, lists, tables, shapes, fields, bookmarks, notes, the table of contents, breaks) is an action its owning extension registers, so an insertion you register sits beside them with the same enablement:
dart
const notesGroup = InsertMenuGroup(id: 'notes', label: 'Notes', order: 45);
registry.registerAction(
EditorAction(
id: InsertionId.callout,
label: 'Callout',
description: 'A highlighted note in its own block',
icon: DocumentSemanticIcons.quote,
group: ToolbarGroup.insert, // insertKind: content
showInToolbar: false,
insertMenuGroup: notesGroup,
insertedBlockSchemaType: BlockQuoteBlock.schemaTypeValue,
execute: (controller) => controller.insertBlockQuote(),
),
);The One list of insertions example shows it in all three places.
insertKindsays what the action does from an insertion surface:contentinserts something (the default for aToolbarGroup.insertaction),turnIntoturns the caret's block into another family, andnonekeeps it off the slash palette. The palette liststurnIntorows first, thencontent.descriptionis the line under the label in the palette.insertMenuGroupplaces the action in the Insert menu. A group without aparentis a section between dividers, ordered byorder; asubmenugroup is one row that opens its own items. The starter kit's groups are onInsertMenuGroup(text,textBlocks,fields,visualObjects,shapes,images,references,pageRegions,separators,tables,breaks); an undeclared insertion lands inInsertMenuGroup.other.- An action with
insertKind: noneand a group is Insert-menu only. The menu's "new paragraph below" rows are like that, because typed at the start of a line "Heading 1" means turn this line into a heading. insertedBlockSchemaTypehides the row where the selection's grammar has no room for the block (a table in a table cell, a quote in a text box).insertMenuEntryreplaces the plain row with a richer one, as the table's size grid does.
documentInsertActions(registry:, controller:) returns the actions the Insert menu lists, and DocumentActionState carries description and insertKind, so a host list over controller.actionCatalog matches the editor's own.
The right-click menu
The right-click menu lists the registered actions that declare a DocumentContextMenuPlacement, plus the actions every provider derives for the menu's target (context.contextMenuTarget: the pointer, the block and offset, and the atom under it). A row shows while its action applies to the interaction mode and is visible and enabled; rows sharing a group sit between dividers. Cut, copy, paste, select all, link, add comment and block protection are ordinary registered actions with placements, so a host removes one with unregisterAction and adds spelling-suggestion rows with a provider. DocumentContextMenuConfiguration.disabled() turns the menu off.
Set DocumentContextMenuConfiguration(presenter: ...) to supply a host menu. The callback receives the same hit target and filtered, ordered rows as the default menu. Each row carries its action, label, icon and group. Present those rows with the host's existing document controls and call presentation.invoke(row) when the reader chooses one. Returning from the presenter does not invoke anything. A null presenter retains the built-in menu.
The row list is immutable. invoke returns false if the editor, document session, content revision, selection or configuration changed, current input publication is unavailable, or the action is no longer available. Keep this guarded invocation when a picker is asynchronous; retaining row.action and executing it directly skips the presentation's stale-target check.
dart
import 'package:vyuh_document_editor_elements/vyuh_document_editor_elements.dart';
import 'package:flutter/widgets.dart';
import 'package:vyuh_document/vyuh_document.dart' as document;
import 'package:vyuh_document_editor/document_editor.dart';
/// The host's existing menu surface returns one of the supplied rows, or null
/// on dismissal. Use row.label, row.icon and row.group to build that surface.
typedef ChooseDocumentAction =
Future<DocumentContextMenuRow?> Function(
BuildContext context,
DocumentContextMenuPresentation menu,
);
DocumentEditor editorWithHostMenu(
document.DocumentController controller, {
required ChooseDocumentAction choose,
}) => DocumentEditor(
extensions: DocumentEditorElements.defaults,
controller: controller,
contextMenu: DocumentContextMenuConfiguration(
presenter: (context, menu) async {
final row = await choose(context, menu);
// A delayed choice may outlive its target. The editor rechecks the
// session, revision, selection and current command availability here.
if (row != null) menu.invoke(row);
},
),
);The typed editor takes this as DocumentEditor(contextMenu: ...). The runtime editor takes it as DocumentEditorConfiguration(contextMenu: ...). documentContextMenuRows(registry:, controller:, target:) is also available to hosts projecting an explicit target; the presentation callback is the path that includes the mounted editor's guarded invocation.
Native keyboard preferences
Pass DocumentTextInputConfiguration as the typed editor's textInput, or as DocumentEditorConfiguration.textInput on the runtime editor. It configures capitalization, keyboard appearance, autocorrect, suggestions, smart dashes, smart quotes and IME personalized learning. Defaults preserve the previous keyboard behavior. Native platforms may ignore unsupported preferences.
Updating preferences refreshes the existing platform connection. It preserves the input client, composition, selection and history. Multiline input, newline routing and the delta/full-value protocol remain editor-owned; keyboard preferences do not change document grammar or grant editing permission. The configuration source above shows sentence capitalization and disabled smart quotes.
Named style queries
Use DocumentParagraphStyleIds.normal, .caption and headingStyleIdFor(1..6) as portable IDs when authoring styles. Imported IDs remain intact. The runtime controller's effectiveStyleIdOf(block) delegates to DocumentStyleCascade.effectiveStyleIdOf: it returns the actual named style, falls back to document defaults, or returns null when no named style applies. Direct formatting and semantic heading typography do not invent an authored style identity. Defining heading-1 alone does not assign it to existing unstyled headings; assign styleId explicitly to preserve predictable content.
Search diagnostics
For a runtime search surface, keep a DocumentSearchNavigator for the runtime controller and pass it to DocumentEditor(searchNavigator: ...). Listen to patternError, isPreparing and matchCount for status. Invalid regular expressions clear stale matches and report the engine compiler's diagnostic; the next valid query resumes search. Literal queries do not report regex errors. Do not add a second regex compiler in the UI. The synchronous engine DocumentSearchIndex.search API still throws FormatException for an invalid regular expression.
dart
import 'package:flutter/widgets.dart';
import 'package:vyuh_document/engine.dart';
import 'package:vyuh_document_editor/vyuh_document_editor.dart';
/// Keep one navigator for the runtime controller, pass it to the runtime
/// DocumentEditor(searchNavigator:), and dispose it before the controller.
void searchPattern(DocumentSearchNavigator navigator, String query) {
navigator.updateQuery(
query,
options: const DocumentSearchOptions(regularExpression: true),
selectFirst: false,
);
}
/// The engine's diagnostic is authoritative; do not compile a second RegExp
/// in the UI. A corrected query clears the error and resumes preparation.
Widget searchStatus(DocumentSearchNavigator navigator) => ListenableBuilder(
listenable: navigator,
builder: (context, _) => Text(
navigator.patternError ??
(navigator.isPreparing
? 'Searching…'
: '${navigator.matchCount} matches'),
textDirection: TextDirection.ltr,
),
);Comments
DocumentReviewConfiguration.commentComposer is the one comment prompt. The Add comment action and its shortcut, the right-click menu, a double tap in commenting mode and the review timeline all run controller.requestComment(), which asks your composer for the text, adds the comment and returns the new DocumentComment (with its CommentId). The change feed reports the same comment in change.comments.added. Without a composer, Add comment is not offered.
Inline interactions
registerInlineInteraction gives any inline type (fields, inline assets, mentions and other extension atoms) a tap and a hover. Each is either a surface (a hover card, or a popover on tap) or a registered action invoked with an InlineInteractionContext payload: the atom, its block and offset, and its global anchor rectangle. A tap on a contributed atom runs before the ordinary atom selection; without a contribution the tap selects the atom as before.
The action catalog
controller.actionCatalog lists the mounted editor's actions with their state (label, icon, visible, enabled, active, disabled reason, shortcut), invokes one by ID and notifies when any state changes. Build your own toolbar or palette over it instead of re-deriving state: see Your own controls. The registry belongs to the mounted editor, so the catalog is empty, and invoke runs nothing, until an editor mounts the controller. The typed DocumentEditor takes a host-owned catalog as actions: and a host part as ActionButton(id).
For field-level inspector settings, see Properties inspector.