Loading document parsing libraries...
# GraffitiProEditor
Module
## About
GraffitiProEditor is a canvas-based WYSIWYG document editor for Xojo Desktop projects. It renders its document directly into a `DesktopCanvas`, provides rich text editing without overlaying a native text control, and supports extensible block-level content through `Node` subclasses.
* Canvas-Native Rendering - Draws the whole document into a `DesktopCanvas` with no native text controls laid over it, drawing only the visible area and caching node layout.
* Rich Text Formatting - Bold, italic, underline, strikethrough, inline code, highlight, keyboard keys, superscript, subscript, text and background colors, fonts, sizes, line height, line spacing, and hyperlinks, applied to selected characters or to whole nodes.
* Markdown Shortcuts - Typing "# ", "- ", "1. ", "[] ", "> ", "```", or "---" at the start of a paragraph turns it into a heading, list, checklist, quote, code block, or divider, and typing **bold**, *italic*, `code`, ~~strikethrough~~, or ==highlight== formats the text, unless `MarkdownShortcuts` is off.
* Document Font and Size - A document-wide font and size, 12 points by default, that text set to Default follows.
* Text Blocks - Paragraphs, six heading levels, quotes with citations, bulleted, numbered, and check lists, and code blocks with a copy button.
* Layout Blocks - Tables, columns, collapsible sections, tables of contents that follow the headings, alerts in info, success, warning, and danger styles, dividers, and page breaks.
* Tables - Insertion at a size picked from a grid, header and footer rows, merging and unmerging cells across rows and columns, cell backgrounds and alignment, cell selection by clicking, dragging, and arrow keys, and Tab and Shift-Tab between cells while editing.
* Media - Images with captions, fill modes, and resizing, plus audio and video from local files or URLs.
* Bookmarks and Embeds - Link cards that show a page's title, description, site, and image, and cards for videos, songs, and code sandboxes from an allowlist of providers, built from metadata fetched only when a user adds the address and stored in the document.
* HTML Forms - Forms, labels, text fields, text areas, dropdowns, checkboxes, radio groups, buttons, and datalists, usable inside or outside a form as in HTML.
* Raw Content - Editable source blocks written unchanged to HTML and Markdown.
* Selection and Arrangement - Single and multiple node selection, character selection inside editable nodes, and dragging, duplicating, deleting, and moving nodes up and down from the keyboard.
* Emoji - Typing a colon and a shortcode, such as `:tada`, offers matching emoji to insert, through the built-in `Suggestions.EmojiProvider`.
* Document Statistics - Word, character, and paragraph counts for the document or the selection, and an estimated reading time, through the editor's `Statistics`.
* Annotations - Discussion threads on a range of text or a whole node, with replies, Open and Resolved status, and undo, marked by comment icons in the document margin and opened in a comment popover or the Inspector's Comments tab. Threads stay on their text as it is edited, are saved beside the document's content, can be exported to HTML, and can be turned off with `AllowAnnotations`, through `Editor.Annotations`.
* Undo and Redo - Typing, formatting, inspector edits, and document changes are recorded in the editor's `History`, which also undoes, redoes, and resets them from code.
* Find and Replace - Search across the document from code or a popover below the toolbar, with case-sensitive, whole-word, and regular-expression matching, and replacing one match or every match, through the editor's `Search`.
* Clipboard and Drops - Cut, copy, and paste; dragging selected text to move it, copy it with Option or Alt, or drop it in another application; and dropping text into text at the pointer, or HTML, pictures, and files into the document as blocks.
* Input Methods - Japanese, Chinese, and Korean input methods on macOS and Windows compose text at the caret, with the platform's candidate window beside it.
* Elastic Scrolling - Wheel and trackpad scrolling stretches past either end of the document and springs back, as native scroll views do.
* Toolbars - A contextual main toolbar that shows the tools for the selection, or a classic toolbar of every section, plus a popover toolbar for the selected node, with panels that preview sizes, colors, spacing, and alignment, and command search for every tool. All of them can be rebuilt while the application runs.
* Toolbar Customization - A customizer sheet, modeled on macOS, for adding, moving, and removing items and choosing icons, text, or both, with the arrangement saved and restored as JSON.
* Insertion Chooser - A searchable list of the registered node types, opened from a hover insertion line or from code.
* Pickers - Popovers for choosing a value from a toolbar button or from code, such as the table size grid, font list, and command search, with `GridPicker` and searchable `ListPicker` base classes for application-defined pickers.
* Inspector - A companion control that edits document and node properties in animated collapsible sections, follows the selection, records undo, and lists, opens, resolves, and deletes discussion threads in a Comments tab.
* Keyboard Shortcuts - Platform shortcuts for bold, italic, underline, strikethrough, inline code, highlight, superscript, subscript, hyperlinks, removing formatting, moving nodes, find, command search, and adding comments.
* Suggestions - Pluggable providers for @mentions, #tags, /commands, and other application syntax, shown in a popup at the caret.
* Spelling and Character Input - Native spell checking and automatic correction on macOS, Windows, and Linux, with misspelled words marked throughout the document, and the system emoji and symbols picker, through replaceable text-service providers.
* Right-to-Left Text - Automatic or fixed text direction for the document and each node, ordered with the Unicode Bidirectional Algorithm, with a mirrored interface.
* Color Theme - Light and dark colors for the document and the editor's interface, set in code or in the IDE.
* Backgrounds and Borders - Background images for the document, nodes, table cells, and columns, and per-side borders and rounded corners on nodes.
* Accessibility - Accessibility labels, hints, and roles on each node.
* Localization - Interface text as `Editor` and `Inspector` properties that can be set in the IDE, plus JSON locale packs.
* Notifications - Info, success, warning, and danger messages shown over the editor, dismissed by a click or after a delay shown by a shrinking bar, which the editor also uses for its own errors.
* Read-Only Mode - Prevents changes and hides the editing toolbars while keeping selection and copying.
* JSON Persistence - Lossless saving and loading with versioned documents, validation, and conversion of older formats, in compact JSON that leaves out default values and keeps images as their original files.
* Change Tracking - `IsChanged` reports whether the document has changed since it was loaded or saved, for prompting to save.
* HTML and Markdown - Import and export, with an export stylesheet built from the node types the document uses, and optionally the document's comments.
* Pictures, Printing, and PDF - Pictures of the whole document or of each page, printing, raster PDFs, and vector PDFs with links, fillable form fields, metadata, headers and footers, and password protection.
* Custom Exporters - Application-defined export formats registered alongside the built-in ones.
* Collaboration - An optional client and server for shared editing, with presence, node locking, shared annotations, and Read, Annotate, and Edit access levels checked by the server.
* Custom Nodes - `Node` subclasses that draw, edit, hold child nodes, add toolbar and inspector items, take part in search, and import and export their content.
* Events - Content, selection, scrolling, pointer, keyboard, hyperlink, link metadata, annotation, node dragging, toolbar, and collaboration events.
The public API is contained in the `GraffitiProEditor` module. Add an `Editor` control to a window, register the node types the application permits, and add initial content from the editor's `Opening` event.
```xojo
Editor.NodeTypes.Add(New GraffitiProEditor.ImageNode)
Editor.NodeTypes.Add(New GraffitiProEditor.TableNode)
Editor.NodeTypes.Add(New GraffitiProEditor.ColumnsNode)
Editor.AddNode(New GraffitiProEditor.HeadingNode("Welcome", GraffitiProEditor.HeadingNode.Levels.Heading1))
Editor.AddNode(New GraffitiProEditor.TextNode("Start writing here."))
```
`TextNode` and `HeadingNode` are available to the editor by default. Other built-in and application-defined node types must be registered explicitly. Registration determines which types can be inserted, imported, and restored from serialized documents.
## License
GraffitiProEditor uses icons from the Tabler Icons collection. The applicable third-party license is reproduced below.
### Tabler Icons
Tabler Icons
Copyright (c) 2020-2026 Paweł Kuna
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Members
- [Document](/document.md)
- [BackgroundImage](/backgroundimage.md)
- [FontOptions](/fontoptions.md)
- [FindResult](/findresult.md)
- [HistoryEntry](/historyentry.md)
- [History](/history.md)
- [Selection](/selection.md)
- [Search](/search.md)
- [NodeTypes](/nodetypes.md)
- [Exporters](/exporters.md)
- [SuggestionProviders](/suggestionproviders.md)
- [ToolbarItems](/toolbaritems.md)
- [Statistics](/statistics.md)
- [Formatting](/formatting.md)
- [Inspector](/inspector.md)
- [InspectorItem](/inspectoritem.md)
- [InspectorSection](/inspectorsection.md)
- [Localization](/localization.md)
- [ImageSnapshot](/imagesnapshot.md)
- [Exporter](/exporter.md)
- [TableSnapshot](/tablesnapshot.md)
- [TableCellLayout](/tablecelllayout.md)
- [TableCellPicture](/tablecellpicture.md)
- [SpellingCacheEntry](/spellingcacheentry.md)
- [TextSnapshot](/textsnapshot.md)
- [TextStyle](/textstyle.md)
- [Toolbar](/toolbar.md)
- [ToolbarItem](/toolbaritem.md)
- [ToolbarSection](/toolbarsection.md)
- [Picker](/picker.md)
- [GridPicker](/gridpicker.md)
- [TableSizePicker](/tablesizepicker.md)
- [ListPicker](/listpicker.md)
- [FontPicker](/fontpicker.md)
- [InsertionPicker](/insertionpicker.md)
- [CommandSearchPicker](/commandsearchpicker.md)
- [ValueListPicker](/valuelistpicker.md)
- [SearchPicker](/searchpicker.md)
- [ColorPalettePicker](/colorpalettepicker.md)
- [AlignmentPicker](/alignmentpicker.md)
- [UnknownNode](/unknownnode.md)
- [ValidationIssue](/validationissue.md)
- [CollaborationAuthentication](/collaborationauthentication.md)
- [TestSuite](/testsuite.md)
- [TextIndexMap](/textindexmap.md)
- [TextRange](/textrange.md)
- [TextServiceProvider](/textserviceprovider.md)
- [TextServiceSession](/textservicesession.md)
- [TextServices](/textservices.md)
- [NativeCharacterInputProvider](/nativecharacterinputprovider.md)
- [NativeSpellCheckingProvider](/nativespellcheckingprovider.md)
- [AudioNode](/audionode.md)
- [AlertNode](/alertnode.md)
- [CodeBlockNode](/codeblocknode.md)
- [DividerNode](/dividernode.md)
- [PageBreakNode](/pagebreaknode.md)
- [QuoteNode](/quotenode.md)
- [ColumnsNode](/columnsnode.md)
- [DetailsNode](/detailsnode.md)
- [TableOfContentsNode](/tableofcontentsnode.md)
- [LinkCardNode](/linkcardnode.md)
- [BookmarkNode](/bookmarknode.md)
- [EmbedNode](/embednode.md)
- [EmbedProvider](/embedprovider.md)
- [Annotation](/annotation.md)
- [Comment](/comment.md)
- [Annotations](/annotations.md)
- [AnnotationPicker](/annotationpicker.md)
- [Editor](/editor.md)
- [HeadingNode](/headingnode.md)
- [RawContentNode](/rawcontentnode.md)
- [ImageNode](/imagenode.md)
- [ListNode](/listnode.md)
- [MediaNode](/medianode.md)
- [Node](/node.md)
- [PDFOptions](/pdfoptions.md)
- [Stylesheet](/stylesheet.md)
- [TableNode](/tablenode.md)
- [TextNode](/textnode.md)
- [VideoNode](/videonode.md)
- [MarkdownSupport](/markdownsupport)
- [HTMLSupport](/htmlsupport)
- [Bidi](/bidi.md)
- [Notification](/notification.md)
- [Suggestions](/suggestions)
- [Network](/network)
- [Forms](/forms)
## Enumerations
| Name | Value | Description |
| --- | :---: | --- |
| Alignments | Automatic = 0 <br > Leading = 1 <br > Middle = 2 <br > Trailing = 3 | (None) |
| CollaborationAccess | None = 0 <br > Read = 1 <br > Annotate = 3 <br > Edit = 2 | (None) |
| Directions | Automatic = 0 <br > LeftToRight = 1 <br > RightToLeft = 2 | (None) |
| ThemeColors | Background <br > Primary <br > Selection <br > TextSelection <br > Information <br > Success <br > Warning <br > Danger <br > Text <br > TextMuted <br > Link <br > Border <br > BorderStrong <br > Surface <br > Dark <br > Light <br > Highlight <br > ChromeBackground <br > ChromePopup <br > ChromeControl <br > ChromeHover <br > ChromeBorder <br > ChromeText <br > ChromeTextMuted <br > ChromeAccent | (None) |
| ToolbarDisplayModes | IconOnly = 0 <br > IconAndText = 1 <br > TextOnly = 2 | (None) |
| ToolbarStyles | Contextual = 0 <br > Classic = 1 | (None) |
## Constants
| Name | Type | Default Value | Description |
| --- | :---: | :---: | --- |
| CurrentCollaborationProtocolVersion | Integer | 1 | (None) |
| CurrentDocumentVersion | Integer | 1 | (None) |
| WindowsDirectEditingRender | Boolean | True | (None) |
| WindowsPaintBuffering | Boolean | True | (None) |
## Methods
| Name | Parameters | Return Type | Description |
| --- | :---: | :---: | --- |
| AudioFileFilter | (None) | String | Returns an open-file dialog filter for the audio formats AudioNode plays: AIFF, M4A, MP3, and WAV. |
| ImageFileFilter | (None) | String | Returns an open-file dialog filter for the image formats Picture.Open reads on Windows, macOS, and Linux: PNG, JPEG, GIF, BMP, and TIFF. |
| VideoFileFilter | (None) | String | Returns an open-file dialog filter for the video formats VideoNode plays: MPEG-4 and QuickTime. |
## Notes
Use these guides for the conceptual behavior shared across the API. Individual classes document details that apply only to that class.
The classes in the `gsProEditor Examples` project folder are intentionally not part of the generated reference. They are supplied as starting points for application-defined nodes, toolbar actions, and text services.
### Built-In Content
Text content is supplied by `TextNode`, `HeadingNode`, `QuoteNode`, `ListNode` (including checklists), and `CodeBlockNode`. Structural content is supplied by `TableNode`, `ColumnsNode`, `DetailsNode` for collapsible sections, `TableOfContentsNode`, `AlertNode`, `DividerNode`, `PageBreakNode`, and `FormNode`. Media content is supplied by `ImageNode`, `AudioNode`, and `VideoNode`. Link cards are supplied by `BookmarkNode` and `EmbedNode`, built on `LinkCardNode`, with the embed allowlist made of `EmbedProvider` objects.
HTML form content is supplied by `LabelNode`, `TextFieldNode`, `TextAreaNode`, `DropdownNode`, `CheckboxNode`, `RadioGroupNode`, `ButtonNode`, and `DatalistNode`. Form controls may be used inside or outside a `FormNode`, matching HTML behavior.
### Collaboration Protocol
The collaboration protocol lets clients send changes to a server and receive changes made by other users. Messages are JSON objects sent as WebSocket text. The connection must deliver messages reliably and in the order in which they were sent.
Every message contains `protocolVersion` and `type`. `protocolVersion` must match `GraffitiProEditor.CurrentCollaborationProtocolVersion`. If it does not match, the receiver rejects the message. `type` identifies what the message does, such as beginning authentication, changing a document, or moving a pointer.
A normal session follows these steps:
1. The client opens a WebSocket connection.
2. The client proves the user's identity without sending the password hash.
3. The client may request an application-defined list of documents.
4. The client asks to open a document by its `documentId`.
5. The server checks that the user may access that document.
6. The server sends the current document, revision number, users, selections, and locks.
7. The client sends document changes, selections, and pointer positions until it disconnects.
One connection can participate in only one document at a time. The server's saved document is the shared source of truth. Document snapshots use the format described in **JSON Document Format**. `documentVersion` identifies that saved format, while `protocolVersion` identifies the collaboration messages. They are checked separately.
The built-in transport supports `ws` and `wss`. Call `Network.Server.SetTLSCertificate` and pass `secure = True` to `Network.Client.Connect` to negotiate TLS before the WebSocket upgrade; otherwise the connection is unencrypted and should be limited to trusted networks or placed behind a TLS-terminating reverse proxy. Xojo's `SSLSocket` documentation does not state whether a client verifies the server's certificate chain and host name, or which certificate file format Windows requires. Confirm both on every target platform before relying on `wss` across untrusted networks; until then, a TLS-terminating reverse proxy with verified certificates remains the conservative choice for internet-facing services. The WebSocket layer supports standard text-message splitting, ping and pong, and the closing handshake. Binary messages are not used.
A normal shutdown sends `collaboration.ended` when the whole service is stopping and completes the WebSocket close handshake. A client treats that cycle as a disconnection, not an error. Losing the underlying socket without a valid close frame is reported as `transport-disconnected`.
#### Annotations
Annotations travel separately from content, so commenting never conflicts with editing and needs no lock. They are stored in the document snapshot's `annotations` array, at its current revision, so a user opening the document receives them.
- **Changes:** a client sends `annotation.put` with `documentId` and the whole `annotation` as JSON when a thread is added, answered, resolved, or reopened, or loses a comment, and `annotation.delete` with `documentId` and `annotationId` when it is removed. Undo and redo send the same messages.
- **Rules:** the server compares the proposed thread with its stored copy. `Read` users may change nothing. `Annotate` users may add threads and replies, resolve or reopen threads they started, delete their own comments, and delete a thread when every comment in it is theirs. `Edit` users may do anything. The anchor is fixed when a thread is created, stored comments are kept as they were, and new comments are credited to the sender's `collaboratorId` and user name, whatever the client sent; an `Edit` user restoring a comment, as undo does, keeps its original author.
- **Results:** the server sends `annotation.updated` with `documentId`, `annotationId`, and either the resulting `annotation` or `deleted`, to everyone in the document, the sender included, whose copy is replaced. A refused change is answered with the stored copy, which puts the sender's thread back, followed by an `access-denied` error.
- **Anchors:** when a local edit moves anchors, the client adds `annotationAnchors` to its `document.operation`: an object of `segment`, `start`, and `length` by annotation ID. The server stores them with the operation's revision, and other clients apply them as received.
#### Authentication
Authentication uses a one-time random value called a nonce. This prevents a captured proof from being reused later. The client begins with `authentication.begin`, which contains `userName`, `documentId`, and optionally `initialSelectedNodeId`. An empty `documentId` asks to authenticate the connection. A non-empty `documentId` asks for permission to open that document after the connection has been authenticated.
The server replies with `authentication.challenge`, containing `challengeId`, `nonce`, and `documentId`. The built-in client combines those values with its password hash into an HMAC-SHA256 proof, which `CollaborationAuthentication.VerifyProof` checks on the server. It then sends `authentication.complete` with `challengeId`, the resulting `clientProof`, and `documentVersion`. Each challenge can be used only once and expires after thirty seconds. The password hash itself is never sent across the network.
The application handles `Network.Server.AuthenticateUser` for both checks. It verifies the proof and returns `CollaborationAccess.None`, `Read`, `Annotate`, or `Edit`. `None` refuses access. `Read` allows the user to see the document and other users without changing content. `Annotate` also allows adding comments, replying, and resolving or deleting the user's own threads and comments, without changing content. `Edit` also permits document changes, node locking, and changing any annotation.
When access is allowed, the server sends `authentication.accepted`. The first response contains `userName`, `access`, and an empty `documentId`. The document response also contains the user's `collaboratorId`, the document's format version and revision, the complete `snapshot`, a `snapshotHash`, any lock granted for the user's initial selection, and lists of current collaborators, locks, and presence information.
`snapshotHash` is a SHA-256 checksum written as hexadecimal text. A client checks it before loading the snapshot so damaged or altered data is not applied. `initialSelectedNodeId` lets the server lock the user's initially selected node as part of opening the document. This closes the brief gap in which another user could otherwise change that node.
#### Documents and Operations
After connection authentication, a client may send `documents.list` with a unique `requestId` and an application-defined JSON value in `request`. The server passes that JSON and the authenticated `Network.User` to the application's `Network.Server.RequestDocuments` event. It replies with `documents.listed`, repeating `requestId` and placing the application's JSON in `response`. The protocol does not define the fields inside either JSON value.
Document listing never reads or exposes the collaboration database automatically. Application code must return only entries the authenticated user may discover. Opening an entry still performs the normal document authentication challenge, so appearing in a list does not grant access to its contents.
The server keeps the shared copy of each document and a revision number. The revision starts at zero and increases by one after every accepted change. A client sends `document.operation` with `documentId`, a unique `operationId`, the `baseRevision` it edited, `documentVersion`, and an `operation` object.
The server accepts the change when `baseRevision` matches its current revision. When `baseRevision` is older, the server still applies the change if, among the changes accepted since that revision, none touched the same top-level nodes, none also changed document settings when this change does, and none also reordered or removed nodes when this change does. Such a change is applied to the current revision and announced like any other. The server also remembers each `operationId`. If the same message is delivered again, the server reports the earlier result instead of applying the change twice.
A document operation is atomic, meaning that the entire change succeeds or none of it is saved. Its `kind` is `document.atomic`, and it may contain:
- `settings`: changed document-wide settings. It contains `alignment`, `backgroundColor`, `hasBackgroundImage`, and `backgroundImage` when an image is present.
- `nodes`: changed or inserted top-level nodes. Each entry contains the node's `index` and its complete JSON in `node`. A node that already exists is replaced in its current position; `index` places a newly inserted node.
- `removed`: the `nodeId` of each top-level node to remove.
- `order`: every top-level `nodeId` in display order. It is included only when that order changed.
The server first applies the change to a temporary copy. It checks the resulting document and its node locks before saving anything. If every check passes, the server saves the complete result, increases the revision once, and sends `document.updated` to everyone in that document, including the sender. That message identifies the document, operation, new revision, document format, and user who made the change.
A change that removes top-level nodes is not rejected because some of those nodes are locked by another user, or contain a node that is. The server removes those nodes from `removed`, places them back in `order` after the node that preceded them, and applies the rest of the change. The resulting `document.updated` carries the operation as applied and `adjusted` set to `true`. The sender applies that operation instead of the one it submitted and restores the kept nodes. Changes to the content of a locked node are still rejected.
If the server has already processed an `operationId`, it sends `document.acknowledged` with the earlier revision instead of repeating the change, even when other changes have been accepted since. This makes it safe to resend a message when a connection failure leaves the client unsure whether it arrived.
If `baseRevision` is out of date and the change cannot be applied over the newer revisions, or the change would modify a node locked by another user, the server rejects the entire change and sends `document.conflict`. The response includes the server's current complete snapshot, its checksum, revision, and document format version. The server does not try to merge both versions. The client may preserve work on a node it owns, apply the server copy, and then submit a new change based on the new revision.
If the saved document uses a newer format than the client supports, the server sends `upgrade.required` with `documentId` and `minimumDocumentVersion`. It removes that client from the document session without changing the saved document.
#### Errors and Compatibility
The server reports a failure with an `error` message containing `code` and `message`. Application code should use `code` when deciding how to respond and show or log the readable `message`. An unfamiliar future code should be treated as a general collaboration failure.
Current error codes are:
- `message-too-large`: the message exceeded the server's size limit.
- `invalid-message`: the message was not valid JSON.
- `protocol-version`: the client and server use different protocol versions.
- `unknown-message`: the message type is not supported.
- `invalid-authentication`: required authentication values were missing or too long.
- `authentication-rate-limited`: too many authentication failures occurred recently.
- `authentication-required`: the connection must be authenticated first.
- `challenge-failed`: the server could not create an authentication challenge.
- `invalid-challenge`: the challenge was missing, expired, or already used.
- `authentication-failed`: the proof was rejected by the application.
- `document-not-found`: the requested document is not registered with the server.
- `invalid-document-list`: a document-list request or response was missing required protocol data or did not contain valid JSON.
- `document-list-too-large`: application-defined document-list JSON exceeded the one MiB limit.
- `document-list-failed`: the server application's document-list event failed.
- `access-denied`: the user does not have edit access for that action.
- `invalid-operation`: the document change was missing or invalid.
- `persistence-failed`: the server could not save the accepted change.
- `invalid-lock`: the lock request contained invalid values.
- `node-not-found`: the requested node is not in the current document.
Messages that change saved content or lock state must be handled in arrival order. Presence is different: a newer pointer or selection message can replace an older one that has not yet been displayed. The built-in client sends only one document change at a time. If more local edits occur while it is waiting for the server, it sends them as a later change.
A compatible server does not need to be written in Xojo and does not need the editor's node classes. It must leave unknown JSON values unchanged, calculate authentication proofs in the same way, enforce size and access limits, apply each accepted operation only once, produce the same result from the same operation, replace an existing node in its current position, enforce locks on the server, and save each accepted document change as an all-or-nothing database action. Applying a non-overlapping change based on an older revision is optional; a compatible server may answer every out-of-date change with `document.conflict`, and clients handle both responses. A compatible server must not reject a removal only because a removed node is locked by another user; it keeps that node, applies the rest, and marks the update `adjusted`.
Protocol version 1 is the first released protocol. It includes annotations, with the `annotation.put`, `annotation.delete`, and `annotation.updated` messages, `annotationAnchors` in document operations, and the `Annotate` access level, value 3. A later protocol version will not interoperate with version 1 unless its notes say so.
#### Locks Presence and Lifecycle
When a user with edit access selects a node, the client asks the server to lock it by sending `node.lock.request` with `documentId` and `nodeId`. The server replies with `node.lock.granted` when the node is available. If another user owns the lock, it replies with `node.lock.denied` and identifies that user. A new lock is announced to the other users as `node.locked`. The owner releases it with `node.lock.release`, after which the server sends `node.unlocked`.
Locks exist only during the live session and are not stored in the database. A lock belongs to one connection and one node in one document. It is released when the user changes selection, leaves the document, or disconnects. The editor disables commands that should not change a locked node, but the server always checks again before accepting a change. This protects the document even when two users act at nearly the same time.
A `presence` message describes activity that other users can see but that is not part of the saved document. It contains the document ID, a sequence number, pointer position, selected node IDs, whether the user is editing, and the current text selection. The server adds the user's ID and name, keeps only that user's latest presence information, and sends it to the other users. Omitting `selectedNodeId` and sending an empty `selectedNodeIds` array means the user has cleared the selection. A client keeps only the newest unprocessed `presence` message from each user, so a busy connection skips stale pointer positions without losing any user's latest one. Clients send presence when the pointer moves or the selection changes; the editor shows each connected user's last reported pointer and selection until that user leaves.
The server sends `collaboration.user.connected` and `collaboration.user.disconnected` when someone joins or leaves the document. Each message contains a `collaborator` object represented in application code by `Network.User`. `collaboration.ended` means the server is shutting down the collaboration service.
The server sends `access.changed` with `documentId` and `access` when the application changes a user's access through `Server.Sessions`. An empty `documentId` refers to the connection itself. When the application ends a session with `Server.DisconnectUser`, the server sends an `error` with the code `session-ended`, then `collaboration.ended`, and closes the connection. When it also revokes the document, an `access.changed` with `access` 0 comes first, and the client clears the document.
### Collaboration
Collaboration is opt-in. Construct a `Network.Client` and attach it to an editor when a window should participate; constructing an `Editor` never starts a server. Construct `Network.Server` separately in a desktop, console, or service application and provide the reliable ordered transport between them. Keep the client and server in properties: an object held only by a local variable is destroyed when the method that created it returns.
To share a document that is open in an editor, give it an ID, store it on the server, and have the hosting window join it through a client of its own like every other user:
```xojo
If Editor.DocumentID = "" Then Editor.DocumentID = NewDocumentID ' any unique string, such as a UUID
mServer = New GraffitiProEditor.Network.Server
AddHandler mServer.AuthenticateUser, AddressOf ServerAuthenticateUser
mServer.PutDocument(Editor.DocumentID, Editor.ToJSON)
mServer.Listen(8765, "/editor")
mClient = New GraffitiProEditor.Network.Client
mClient.AttachEditor(Editor)
AddHandler mClient.Connected, AddressOf ClientConnected ' calls sender.Authenticate
AddHandler mClient.Authenticated, AddressOf ClientAuthenticated ' calls sender.OpenDocument
mClient.Connect("127.0.0.1", 8765, "/editor")
```
Attached clients are retained through internal weak references and receive hidden editor notifications. This does not consume or replace the public `ContentChanged`, `SelectionChanged`, and `PointerMoved` events, which remain available to the containing application.
`CollaborationAccess.None` refuses authentication or document access. `Read` lets a user view the document and other users' activity without changing content. `Annotate` adds discussion: the user can comment and reply, resolve or reopen threads they started, and delete their own comments, but cannot change content or lock nodes; their editor is read-only for content. `Edit` also permits document changes after the selected node is locked. Applications choose these levels in the server's `AuthenticateUser` event.
`CurrentCollaborationProtocolVersion` identifies the format of collaboration messages and must match on the client and server. `CurrentDocumentVersion` identifies the format of saved editor JSON. These versions are checked separately.
### Core Concepts
An `Editor` owns one ordered root-level document. Each block in that document is a `Node`. Container nodes such as `TableNode`, `ColumnsNode`, `DetailsNode`, and `FormNode` can own child nodes while remaining part of the same document.
Registration and insertion are separate. `Editor.NodeTypes.Add` installs a template instance, called a prototype, that tells the editor how to import and insert that node type. It does not add the template to the document. `AddNode` adds a separate node instance as document content.
Node selection and text selection are also separate. A selected node receives node-level commands, inspector properties, and a popover toolbar. Entering edit mode gives editable nodes a caret and character range. Multiple selected nodes can receive compatible formatting and document operations together.
### Extension Points
Subclass `Node` to add an application-defined content block. A custom node can draw itself, respond to clicks, support editing and children, add toolbar and menu commands, describe editable inspector properties, participate in search, import HTML or Markdown, and save itself as JSON.
The editor's `Toolbar` can be rebuilt from `ToolbarSection` and `ToolbarItem` objects while the application is running. A toolbar item, in the main toolbar or a node's popover toolbar, can open an application-defined popover by setting its `Picker` to a `Picker`, `GridPicker`, or `ListPicker` subclass; the chosen value reaches the same handler a native menu choice would. A selected node returns `InspectorSection` and `InspectorItem` objects to describe the properties users may edit. Text entry can be extended separately by installing `TextServiceProvider` objects in `TextServices`.
Application-defined text protocols belong to `Suggestions.Provider` objects, not the editor. Add any number of providers to `Editor.SuggestionProviders`, or assign `Node.SuggestionProvider` when one editable node needs an exclusive override. Providers can recognize `@name`, `#topic`, `.Error`, `/command`, or other application syntax. They control lookup, insertion, portable tag colors, and popup rows without changing the editor.
Custom exporters are `Exporter` objects added to `Editor.Exporters`. This permits application formats to coexist with the built-in JSON, HTML, Markdown, picture, PDF, and print output.
### Installation and Setup
Include the `GraffitiProEditor` module and its project items in a Xojo Desktop project together with the required GraffitiSuite support classes. The editor is a `DesktopCanvas` subclass and should be placed on a desktop window or container in the same way as another desktop control.
Perform application-specific configuration in the editor instance's `Opening` event. This is the appropriate place to register nodes and exporters, customize `FontOptions`, assign a `Suggestions.Provider`, install text-service providers, and modify toolbar sections. Keeping configuration on the editor instance allows different editor controls to expose different capabilities.
### JSON Document Format
`Editor.ToJSON` returns a JSON object. The following example shows its main fields for document format version 1:
```json
{
"version": 1,
"documentId": "b11d8db9-10d4-46e1-af2e-2808a218c1a6",
"fontName": "System",
"fontSize": 12,
"backgroundColor": { "red": 255, "green": 255, "blue": 255, "alpha": 0 },
"nodes": [
{
"nodeId": "43d75c95-a5a3-48dc-ad2f-e6fb248516e8",
"type": "text",
"content": {
"text": "Example",
"styleTable": [ {}, { "bold": true } ],
"styleRuns": [ 3, 0, 4, 1 ]
}
}
]
}
```
Values at their defaults are left out: the node above has no borders, a line height of 1, and Automatic alignment, so none of those is written. A missing value loads as its default. Each class's JSON Format note lists its defaults.
- `version` identifies the JSON document format. Version 1 is the first released format: stable document and node IDs, character styles stored as a table of distinct styles plus runs, and the document `fontSize`, with Default sizes saved as zero so text follows the document size.
- `documentId` is the stable UUID for the document. It is empty until one is assigned to `Editor.DocumentID` or loaded with a document; collaboration requires one.
- `alignment` stores `GraffitiProEditor.Alignments` as an integer: `0` Automatic, `1` Leading, `2` Center, and `3` Trailing. It is left out when it is Leading, the document default. Leading and Trailing follow the text direction, so they are the left and right edges in left-to-right text and the right and left edges in right-to-left text. Documents saved when these values were Left and Right keep their numbers.
- `textAlignment` stores the document's text alignment, `Editor.TextAlignment`, with the same values. It is left out when it is Leading.
- `fontName` and `fontSize` are the document font and size. A document without them leaves the editor's font and size unchanged when loaded.
- `backgroundColor` stores the document color as `red`, `green`, `blue`, and `alpha` channel values. The default is opaque white. It is used beneath any document background image.
- `backgroundImage` is optional and uses the `BackgroundImage` JSON format.
- `nodes` is the required, ordered array of root node objects. Every node requires a stable UUID `nodeId` and a stable string `type` matching the `JSONIdentifier` of a node type registered with the receiving editor.
Node subclasses append their own fields to the common `Node` object. Nested content is stored by its owning container; there is no universal root-level `children` field. Use the owning classes' JSON format notes for exact conversions.
### JSON Versioning
`CurrentDocumentVersion` identifies the saved JSON format, not the application or library release. Increase it only when a document saved in the new format needs different loading rules.
Version 1 is the first released format, and a document without `version` is treated as version 1. `ValidateJSON` rejects a format newer than `CurrentDocumentVersion`. When a later format is introduced, `FromJSON` will convert older documents to it in order, and `ValidateJSON` will report that conversion. `FromJSON` leaves the existing editor unchanged if loading fails. Inspect `Editor.LastValidationIssues` for details.
Applications should store the complete output of `Editor.ToJSON`. Construct or rewrite node JSON only when intentionally implementing the documented format.
### Localization
GraffitiProEditor does not ship translated strings or perform language lookup automatically. User-visible English defaults are exposed as ordinary public String properties: on `Editor` for the editor, its built-in nodes, `BackgroundImage`, and the built-in text-service providers, and on `Inspector` for the inspector. Both can be set in the Xojo Inspector under Localization. Assign translated values during application setup or from a subclass constructor, or use `Localization` to load a JSON locale pack into those same properties. This keeps localization compatible with Xojo dynamic constants, application resources, JSON locale files, or any other source chosen by the application.
Localization properties begin with `Text`, which groups them together in Xojo autocomplete and distinguishes them from document data and behavioral properties. The remainder of each name describes its role, such as `TextRemoveNodeTooltip`, `TextContentInspectorCaption`, or `TextWidthCaptionFormat`. Properties such as `Text`, `Title`, `Name`, `Value`, and `URL` remain unprefixed when they contain document content rather than localizable interface text.
Properties are instance scoped: changing one editor or inspector does not change another. Built-in nodes read their text from the editor they belong to whenever they build a menu, inspector section, dialog, or popover, so set values before that UI is shown. A node that belongs to no editor uses the built-in English text. Text that a node constructor uses immediately, such as a toolbar item's caption or a new node's placeholder content, comes from the built-in text, because the node has no editor yet.
Only text displayed by the control belongs to this surface. Stable identifiers, JSON keys, HTML names and values, CSS tokens, routing tags, and messages returned only as programmatic diagnostics remain fixed implementation strings. `Node.TypeName` is also a fixed implementation value: it identifies the node class for diagnostics and editor state, so it is intentionally hardcoded rather than supplied by a mutable localization property.
#### Format Strings
A property whose name ends in `Format` is a complete localizable phrase containing named replacement tokens. Preserve the token spelling, including both percent signs, but place the token anywhere required by the translated grammar. Do not translate a token itself. Repeating a token is supported; omitting it intentionally omits that dynamic value from the result.
The built-in format properties and required tokens are:
- `Editor.TextHeightCaptionFormat`: `%value%`
- `Editor.TextWidthCaptionFormat`: `%value%`
- `Editor.TextLineHeightTooltipFormat`: `%value%`
- `Editor.TextLineSpacingTooltipFormat`: `%value%`
- `Editor.TextTableSizeCaptionFormat`: `%rows%` and `%columns%`
- `Editor.TextDefaultTableHeadingFormat`: `%number%`
- `Editor.TextOptionNumberFormat`: `%number%`, the one-based position of a radio option, used as the label a reset restores
- `Editor.TextUnsupportedContentFormat`: `%type%`
- `Inspector.TextChooseDialogTitleFormat`: `%caption%`
- `Inspector.TextNumberRangeTooltipFormat`: `%minimum%` and `%maximum%`
- `Editor.TextDatalistLabelFormat`: `%id%`
- `Editor.TextMatchCountFormat`: `%count%`, the number of matches in the search popover
- `Editor.TextMatchPositionFormat`: `%index%`, the one-based position of the current match, and `%count%`
Use a complete phrase rather than separate prefix, infix, and suffix properties. Complete formats allow translations to change word order and punctuation without coordinating multiple values.
#### Locale Packs
`Localization` loads a JSON locale pack once and applies its values to public, writable `Text...` String properties through introspection. Rendering continues to read the properties directly, so locale packs add no dictionary lookup to drawing or interaction.
A pack contains a BCP 47 `language` value and a `strings` object keyed by class name. Apply it to the editor, which covers the built-in nodes and text-service providers, and to the inspector. Applying it to an editor also updates the editor's toolbar and the toolbar items of its registered node types, so a pack can be applied at any time, including from `Opening`. A custom node with its own `Text` properties takes a section of its own; apply the pack to it before adding it. Persistent toolbar items keep their own `Caption` and `Tooltip`, so localize those item properties directly when constructing or customizing a toolbar.
```json
{
"language": "fr-CA",
"strings": {
"Editor": {
"TextBoldCaption": "Gras",
"TextSpellingMenuCaption": "Orthographe"
}
}
}
```
```xojo
Var localePack As New GraffitiProEditor.Localization
If localePack.FromJSON(localeJSON) Then
Call localePack.Apply(Editor)
Call localePack.Apply(Inspector)
Editor.TextServices.Language = localePack.Language
End If
```
#### Nodes Toolbars and Helpers
The built-in nodes, `BackgroundImage`, and the built-in text-service providers have no localization properties of their own. They read the editor's whenever they rebuild inspector sections, menus, prompts, rendered labels, or popover content. Text that several of them show, such as `TextFillCaption` or `TextURLCaption`, is a single property. A custom node can read the editor's text through the protected `Node.Strings` method and can expose `Text`-prefixed properties of its own for text the editor doesn't have.
A persistent `ToolbarItem` owns its visible `Caption` and `Tooltip`, copied from the localization properties when the item is built. Each built-in node type copies its toolbar item's text from an editor in `Node.LocalizeToolbarItem`, which the editor calls when the type is registered. `Editor.RefreshLocalization` copies the current values again into the editor's built-in toolbar items and every registered node type's item; the editor calls it when it opens, so values set in the IDE apply, and `Localization.Apply` calls it for an editor. Call it after changing localization properties in code. A custom node type can override `LocalizeToolbarItem` for its own toolbar item. Toolbar items an application adds are localized by the application.
### Performance and Update Batches
The editor virtualizes drawing to the visible viewport and caches node layout and rendering. A long document does not create a document-height backing picture. On Windows, the editor composes one viewport-sized frame before presenting it; controls whose physical viewport exceeds the safe picture limit fall back to direct drawing.
Content that changes height above the visible area, such as a table whose rows or images finish loading, does not move what is on screen: the editor adjusts the scroll by the same amount, keeping the selected node in place when it is visible and otherwise the first visible node. `ScrollTo` aims at its node's current position until it arrives, so content that resizes during the scroll does not leave it short.
Use matching `BeginUpdate` and `EndUpdate` calls around substantial document construction or replacement. Batches may be nested. The outermost batch temporarily hides the editor and its embedded controls, preventing intermediate toolbar, selection, scrollbar, and node states from becoming visible.
### Persistence and Export
Use JSON for lossless application persistence. `Editor.ToJSON` records the document structure and editor-supported node state; `Editor.FromJSON` validates and restores it without propagating malformed input as an exception.
HTML and Markdown are useful for exchanging content with other software. They preserve only the features their formats can represent. Use JSON when saving and restoring an editor document without losing editor-specific state. Registered node templates determine which imported blocks the editor can rebuild.
Image resources chosen from local files or supplied as `Picture` objects are embedded so the output does not depend on the original file: as data URIs in HTML and Markdown, and as Base64 file data in JSON. URL-backed resources retain their URL.
### Platform Text Services
The editor installs separate native providers for character input and spell checking. Emoji and Symbols uses the operating system picker where available. Native spell checking uses the macOS spelling service, the Microsoft Spell Checking API on Windows, and the system-installed Enchant 2 library and dictionaries on Linux. Missing platform services or dictionaries make the provider unavailable without preventing editing.
Providers are independently replaceable through `Editor.TextServices`. Nodes control whether spell checking and automatic correction apply to their editable content, while provider ordering determines which enabled implementation handles a capability first.
`Editor.TextServices.Language` returns the effective BCP 47 language tag. By default it resolves `Locale.Current.Identifier`, removes ICU keyword or encoding suffixes, and normalizes underscores to hyphens, so native spelling follows the current system locale using a tag accepted by the platform spelling API. Assign another tag to select an installed dictionary, or assign an empty string to resume following the system locale. `LanguageOverride` reports only the explicit override and is empty while the system locale is active.
Misspelled words are marked in every visible node, not only in the text being edited, while `Editor.ShowSpellingWhenNotEditing` is True, the default. Results are cached for each text run, such as a paragraph or a table cell, and reused until its text, the language, the providers, or the learned and ignored words change. Text that has not been checked yet is checked in the background a few milliseconds at a time, so long documents open and scroll without waiting for the spelling service. Read-only editors, including collaboration sessions with Read access, never mark misspelled words. Learn Spelling and Ignore Spelling in the context menu refresh the marks everywhere. A provider's `LearnWord` or `IgnoreWord` called from code does not; the marks it affects update when their text changes.
## Examples
The examples below are intentionally small. Configure only the features required by a particular editor instance.
### Complete Opening Setup
Use one update batch when registration, toolbar customization, and initial content are performed together. `EndUpdate` restores the editor's previous visibility and presents one completed frame.
```xojo
Editor.BeginUpdate
Try
Editor.NodeTypes.Add(New GraffitiProEditor.AlertNode("", GraffitiProEditor.AlertNode.Types.Info))
Editor.NodeTypes.Add(New GraffitiProEditor.ImageNode)
Editor.NodeTypes.Add(New GraffitiProEditor.TableNode)
Editor.AddNode(New GraffitiProEditor.HeadingNode("Welcome", GraffitiProEditor.HeadingNode.Levels.Heading1))
Editor.AddNode(New GraffitiProEditor.TextNode("Start writing here."))
Finally
Editor.EndUpdate
End Try
```
### Localize an Editor
Assign localized UI properties on the editor and inspector; the editor's nodes read theirs from the editor. Xojo dynamic constants can supply the values, while the editor API remains ordinary runtime properties.
```xojo
Editor.TextBoldCaption = kTextBoldCaption
Editor.TextLineHeightTooltipFormat = kTextLineHeightTooltipFormat
Editor.TextWidthCaptionFormat = kTextWidthCaptionFormat
Editor.TextLevelCaption = kTextHeadingLevelCaption
Inspector.TextNumberRangeTooltipFormat = kTextNumberRangeTooltipFormat
Editor.AddNode(New GraffitiProEditor.HeadingNode(kDocumentHeading))
Var textItem As GraffitiProEditor.ToolbarItem = Editor.Toolbar.Item("node:text")
If textItem <> Nil Then
textItem.Caption = kTextCaption
textItem.Tooltip = kAddTextTooltip
End If
```
The example classes supplied with the project demonstrate declaring dynamic localized constants and assigning their resolved values in a constructor. They are intentionally excluded from the generated API reference.
### Minimal Editor
Register optional node types and then insert constructed node instances.
```xojo
Editor.NodeTypes.Add(New GraffitiProEditor.ImageNode)
Editor.NodeTypes.Add(New GraffitiProEditor.TableNode)
Editor.AddNode(New GraffitiProEditor.HeadingNode("Document Title", GraffitiProEditor.HeadingNode.Levels.Heading1))
Editor.AddNode(New GraffitiProEditor.TextNode("Document body"))
```
### Save and Restore
Store the native document as JSON when an exact round trip is required.
```xojo
Var savedDocument As String = Editor.ToJSON
Editor.FromJSON(savedDocument)
For Each issue As GraffitiProEditor.ValidationIssue In Editor.LastValidationIssues
System.DebugLog(issue.Message)
Next
```