Host contributions: your app is an extension
Everything your app plugs into the editor (keys, / and @ palettes, type-to-format rules, actions) is a contribution registered into the editor's ElementRegistry through DocumentExtension.register, exactly as the starter kit registers its own. Your app contributes behavior as an extension. Presentation callbacks customize the resulting surfaces: trigger presenters below and the context-menu presenter.
DocumentHostExtension is an extension that owns no document elements. Give it an id and a register callback, and pass it after the defaults:
dart
import 'package:flutter/services.dart';
import 'package:vyuh_document/engine.dart';
import 'package:vyuh_document/paragraph_extension.dart';
import 'package:vyuh_document_editor/document_editor_extensions.dart';
import 'package:vyuh_document_editor/vyuh_document_editor.dart';
import 'package:vyuh_document_extension_divider/vyuh_document_extension_divider.dart';
// Your app's own action ids, declared like any extension's.
enum MentionId with EditorActionKey implements EditorActionId {
alice('mention-alice'),
bob('mention-bob');
const MentionId(this.key);
@override
final String key;
}
/// Everything this app plugs into the editor, registered the way the
/// starter kit registers its own: a key handler, a trigger, an input rule.
DocumentHostExtension notesHost({required VoidCallback closePanel}) =>
DocumentHostExtension(
id: 'notes-app',
register: (registry) => registry
// Escape closes the app's panel before the editor sees the key.
// Return ignored to let the editor run its own Escape steps.
..registerKeyHandler(
DocumentKeyHandler(
id: 'notes-app.close-panel',
handle: (key) {
if (key.key != LogicalKeyboardKey.escape) {
return DocumentKeyResult.ignored;
}
closePanel();
return DocumentKeyResult.handled;
},
),
)
// `@` after a space opens a people palette; the word typed after it
// is the query. Choosing a person removes `@` and the query.
..registerTrigger(
DocumentTriggerContribution(
id: 'notes-app.mention',
trigger: '@',
position: DocumentTriggerPosition.wordBoundary,
title: 'People',
items: (query, context) => rankDocumentTriggerItems([
for (final (id, name) in [
(MentionId.alice, 'Alice'),
(MentionId.bob, 'Bob'),
])
EditorAction(
id: id,
label: name,
group: ToolbarGroup.insert,
execute: (controller) => controller.insertText('@$name'),
),
], query),
),
)
// A line reading ~~~ becomes a scene break when Enter would split
// it: the rule takes that Enter, as one undo step. (The starter
// kit's own rule does the same for ---, *** and ___.)
..registerInputRule(
InputRule(
id: 'notes-app.scene-break',
// Higher priorities run first; equal priorities keep registration
// order. The default is zero, including the starter rules.
priority: 100,
trigger: InputRuleTrigger.onSplit,
pattern: RegExp(r'^~~~$'),
apply: (controller, match) {
final line = controller.textRange.extent.blockId;
controller.transaction(
(tx) => tx
..deleteText(line, start: match.start, end: match.end)
..insert(
DividerBlock(id: BlockId('break-${line.value}')),
at: BeforeBlockAnchor(line),
),
);
},
),
),
);Both editors install it the same way, from the extension list:
dart
// The runtime editor (package:vyuh_document_editor/vyuh_document_editor.dart).
final controller = DocumentEditorController(
extensions: [
...DocumentEditorElements.defaults,
notesHost(closePanel: panel.close),
],
);
DocumentEditor(controller: controller);
// The typed Document API editor
// (package:vyuh_document_editor/document_editor.dart).
DocumentEditor(
controller: documentController,
extensions: [
...DocumentEditorElements.defaults,
notesHost(closePanel: panel.close),
],
);This is the one way in: there is no configuration-level host list, and the extension list is fixed for a controller's lifetime, so the host's contributions install in the same batch as the starter kit's, after them. Registering a contribution with a starter-kit id replaces it, and each registry has an unregister… call to remove one. A host turns a built-in off by id, never with a global switch.
This page covers keys, triggers and input rules. Actions, the right-click menu, inline interactions and the action catalog are on Configuration.
Composed edits must stop on refusal: runtime deleteRange and replaceRange return whether they committed. See Multiline input and breaks for a refusal-aware input rule and complete boundary examples.
Keys
Every key press reaches one key path: the registered DocumentKeyHandlers, highest priority first, until one returns DocumentKeyResult.handled. A handler that returns ignored lets the key fall through to the next one and, past the last, to the platform (text input, focus traversal).
The editor's own key behaviour is registered on the same path, in bands:
Band (DocumentKeyPriority) | Value | Built-in handlers |
|---|---|---|
host | 1000 | The default for your handlers: before every built-in |
triggerSession | 900 | An open / or @ palette: arrows, Enter, Tab, Escape |
camera | 700 | Zoom chords; view-mode reading keys |
gesture | 600 | Escape cancels an inline drag or pointer gesture |
selection | 500 | Escape out of a frame, rectangle, node, header or note, or the highlighter; Enter into a frame; Enter or Space on a form field; Enter on a one-line surface |
platform | 400 | The web's vertical arrows; Command+Left/Right |
bindings | 300 | Every EditorAction.activators chord |
fallback | 100 | For your handlers that should act only when nothing built in did |
Handlers at or above DocumentKeyPriority.admitted (650) run before the editor admits the current layout, so they must not need document geometry; the rest run as one admitted keyboard interaction. While the platform IME is composing, it owns plain keys: no handler sees them. Built-in handler ids are on DocumentKeyHandlerId; registering one replaces that step.
Override a key with an action
A chord belongs to the last registered action whose activators match. To give a key a new meaning, register an action with that activator. An action that is hidden or disabled declines its key, and the key falls through:
dart
registry.registerAction(
EditorAction(
id: AppActionId.palette,
label: 'Command palette',
group: ToolbarGroup.review,
activators: const [
SingleActivator(LogicalKeyboardKey.keyK, meta: true),
SingleActivator(LogicalKeyboardKey.keyK, control: true),
],
transactionKind: DocumentCanonicalTransactionKind.none,
execute: (_) => openPalette(),
),
);Find is an action too. SearchActionId.find (Command/Control+F) opens the editor's search surface when one is mounted; register your own SearchActionId.find to open your find instead; the key, the Edit menu and the ribbon's Find all run that one action. Without a search surface the action is disabled and the chord falls through to the browser.
To remove a chord but keep its action in menus and toolbars, register the action again without it: registry.requireAction(id).copyWith(activators: []).
Triggers
A DocumentTriggerContribution is a typed trigger: its trigger text at a position (lineStart, wordBoundary or anywhere), followed by word characters up to the caret. Those characters are the query, so a fast typist's @al is one trigger with the query al; a space ends it. Offsets are document text units, where an inline atom is one unit.
The editor detects triggers itself: no host polling. It opens them at a collapsed caret in any editable text story, table cells included, but never in code or other literal source. Its items are EditorActions from items(query, context); rankDocumentTriggerItems ranks them by label. Choosing one replaces the trigger and its query with what the action inserts, as one completion step (see Taking a completion back).
The default presenter is the editor's command palette. While you type it takes no focus; Enter or Tab chooses the first item, an arrow key moves into the list, and Escape dismisses it until you type a new trigger. Pass presenter to build your own list; the editor still places it under the trigger and owns dismissal.
A custom presenter reads presentation.highlightedItem and reports hover or keyboard highlight through presentation.onHighlighted?.call(item). Enter or Tab in the document confirms that item; without a highlight it chooses the first available item. Reporting a highlight keeps typing focus in the document. When results change, the session reconciles the highlight with the available items. Confirmation checks availability again, and callbacks from a closed or replaced trigger session do nothing. onSelected(item) confirms a direct pick.
This adapter connects those callbacks to a host-owned choice control. Keep the control's existing focus, hover and keyboard mechanics:
dart
import 'package:flutter/widgets.dart';
import 'package:vyuh_document_editor/document_editor_extensions.dart';
/// Adapt the host's existing choice control. Its hover/keyboard callbacks
/// report highlight separately from confirmation; it takes focus only when
/// navigating is true. The editor owns trigger anchoring and dismissal.
typedef HostTriggerChoices =
Widget Function(
BuildContext context, {
required List<EditorAction> items,
required EditorAction? highlighted,
required bool navigating,
required ValueChanged<EditorAction> onHighlighted,
required ValueChanged<EditorAction> onSelected,
required VoidCallback onDismiss,
});
DocumentTriggerPresenter hostTriggerPresenter(HostTriggerChoices build) =>
(context, presentation) => build(
context,
items: presentation.items,
highlighted: presentation.highlightedItem,
navigating: presentation.navigating,
onHighlighted: (item) => presentation.onHighlighted?.call(item),
onSelected: presentation.onSelected,
onDismiss: presentation.onDismiss,
);The starter kit registers / at the start of a line as DocumentTriggerId.slash, the insert palette. Replace it by registering a trigger with that id, or remove it with unregisterTrigger.
Input rules
An InputRule matches the text before the caret, in document text units. Its trigger says when it runs:
InputRuleTrigger.afterText(the default) runs after typed text, as the starter kit's#,>,-,1.,[ ],```and URL rules do.triggerCharactersskips the match for other keystrokes.InputRuleTrigger.onSplitruns when Enter would split the block. A matching rule takes that Enter instead of the split, so its edit (onecontroller.transaction, say) is the Enter's one undo step. The starter kit's---,***and___rule turns the line into a horizontal line, the separator between scenes or sections.
blockTypes limits a rule to some text leaves: the horizontal-line rule applies only in paragraphs, so a heading or a code line keeps its text.
Rules run in descending priority; the first matching rule wins. The default priority is 0, and equal priorities retain registration order. Set a host rule's priority above the starter rules when overlapping patterns should prefer the host rule. The starter kit's rule ids are on DocumentInputRuleId: register a rule with one of them to replace it, or unregisterInputRule it. Priority does not change the completion's transaction or Undo behavior.
Taking a completion back
A trigger pick and an input rule are completions: each replaces what the reader typed with something else. The editor commits each as one step after the typing before it, so:
- Backspace straight after it, while the document and caret are still what it left, restores the typed text and caret exactly:
@alcomes back after a picked mention,#after a heading,---after a horizontal line. The next Backspace deletes as usual. A soft keyboard's Backspace does the same. - Undo takes back the completion alone, never the typing before it.
What the completion inserted makes no difference: text, an inline field such as a citation or a mention chip, or a block. Moving the caret or making any other change first ends the chance, and Backspace deletes.
A host action that replaces typed text the same way can run as a completion too: controller.complete(() { ... }) commits what the closure does as one completion step. canRevertCompletion says whether Backspace would take the latest one back, and revertCompletion() does it.
Try them live: host key handler and host triggers and input rules.