How the editor (web/src/editor/) is built: its modules, its classes and how they interact.
Each section links to the API reference for the details. For the
editing model and the decisions behind it, see Editor design.
The library is plain JavaScript (ES modules, JSDoc types, no build step for the source) made of Lit web components. It has one rule that shapes everything else:
The editor owns the document; cells are views of their Texl source.
The document is a list of cells, each a {type, name, texl} record. The
<texl-editor> element holds that list and is the only thing that changes
it. Each cell element receives its source (texl) and its rendered output
(output) as properties, and reports an edit by an event. No data lives
in the cell elements beyond the edit in progress, so the document is always
exactly the text that is saved.
┌─────────────────────────── <texl-editor> ─────────────────────────┐
value ──────▶ │ parseDocument ─▶ cells [{type,name,texl}] ─▶ serializeDocument │ ──▶ value
(text) │ │ ▲ │ (text)
│ render pass │ │ cell-change {texl} │
│ (render + split) ▼ │ │
│ outputs[] ─▶ <texl-cell-markdown .texl .output .mode> │ ──▶ change,
│ <texl-cell-text …> <texl-cell-quantity …> … │ selection-change,
└────────────────────────────────────────────────────────────────────┘ comments-click,
name-conflict, cell-menu
| Module | Role | Depends on | API |
|---|---|---|---|
web/src/editor/index.js |
Entry point: registers the built-in cells, defines <texl-editor>, re-exports the public API |
all | Importing |
web/src/editor/texl-editor.js |
TexlEditor: holds the cells, selection, undo history, keyboard, clipboard, type menu, rendering |
document, registry, engine, texl-cell | <texl-editor> |
web/src/editor/texl-cell.js |
TexlCell: base class of the cells; modes, layout, commit protocol |
Lit, DOMPurify | TexlCell |
web/src/editor/cells/text-cell.js |
TextCell: Texl template edited in CodeMirror 6; fallback type |
texl-cell, swan, CodeMirror | TextCell |
web/src/editor/cells/markdown-cell.js |
MarkdownCell: TextCell with Markdown highlighting and Markdown output, equations included |
text-cell, swan, marked, DOMPurify | MarkdownCell |
web/src/editor/cells/rich-cell.js |
RichCell: WYSIWYG editing of Markdown with ProseMirror; toolbar, formula chips, the field under a chip |
||
web/src/editor/rich/ |
schema.js (what it can hold), markdown.js (source ↔ document, acceptsRich), commands.js (keys, typing shortcuts) |
||
web/src/editor/cells/grid-cell.js |
GridCell: base of the cells edited as a grid of fields (not a type): grid, buttons, Tab and arrow keys |
markdown-cell | — |
web/src/editor/cells/table-cell.js |
TableCell: a Markdown pipe table edited as a grid; parseTable, serializeTable |
grid-cell, swan | TableCell |
web/src/editor/cells/data-cell.js |
DataCell: a stilo.dataframe formula edited as a name and a grid of Swan values; parseData, serializeData, entryError, STILO_IMPORT |
grid-cell, formula-cell, expression | DataCell |
web/src/editor/cells/form-cell.js |
FormCell: base of the cells edited as a form (not a type): one tag function {key: value, ...}, the kind drop-down, field checks; parseCall, serializeCall |
text-cell, formula-cell, texl-form, expression | FormCell |
web/src/editor/cells/chart-cell.js |
ChartCell: a stilo.charts formula edited as a form |
form-cell, data-cell | ChartCell |
web/src/editor/texl-form.js |
<texl-form>: the form, one line per field (description, input); fires form-input |
Lit | <texl-form> |
web/src/editor/expression.js |
expressionError: why a Swan value written inside a structured cell’s tag would break it |
engine, swan | FormCell |
web/src/editor/cells/formula-cell.js |
FormulaCell: one tag, edited without its delimiters; parseFormula, serializeFormula |
text-cell, swan | FormulaCell |
web/src/editor/math.js |
Equations in Markdown: finds $...$ and $$...$$, typesets them, declares the fonts in the document |
KaTeX, errors | |
web/src/editor/registry.js |
Maps cell types to custom element tags | — | Cell registry |
web/src/editor/commands.js |
editorCommands(): the commands as the user sees them (label, keys, group), changesDocument |
registry | Commands |
web/src/editor/document.js |
The file format: parse, serialise, names, comments, split a rendering. Pure functions, no DOM | — | Document functions |
web/src/editor/render.js |
The HTML of rendered cells (cellsHtml, what renderedHtml() gives) and a text rendered without an editor (renderHtml, S29) |
document, registry, engine, errors, texl-cell | Rendering without an editor |
web/src/editor/errors.js |
The errors of a rendering (findErrors), their marks in the output (markErrors, sanitizeOutput), excerptAt |
document, @onlabsorg/texl, DOMPurify |
Errors |
web/src/editor/engine.js |
Loads the Texl WebAssembly module once, creates engines | @onlabsorg/texl |
Engine |
web/src/editor/swan.js |
Swan highlighting and the tag/comment commands for CodeMirror | CodeMirror | Swan helpers |
The dependency graph has no cycles. The bottom layer (document.js,
registry.js, engine.js, swan.js) knows nothing about the editor; the
cells know nothing about the editor either, only the events they fire.
graph TD
index[index.js] --> editor[texl-editor.js]
index --> text[cells/text-cell.js]
index --> md[cells/markdown-cell.js]
index --> table[cells/table-cell.js]
index --> formula[cells/formula-cell.js]
editor --> document[document.js]
editor --> registry[registry.js]
editor --> engine[engine.js]
editor --> cell[texl-cell.js]
table --> md
formula --> text
formula --> swan
md --> text
text --> cell
text --> swan[swan.js]
md --> swan
engine --> texl["@onlabsorg/texl (wasm)"]
cell --> lit[Lit, DOMPurify]
text --> cm[CodeMirror 6]
md --> marked[marked]
md --> math[math.js]
math --> katex[KaTeX]
document.jsA document is one Texl text file. parseDocument splits it at marker lines,
<!--{ name : type }-->, into CellData records; serializeDocument joins
them back. The round trip is exact, so opening and saving a file without
edits leaves it byte for byte the same.
import { parseDocument, serializeDocument } from "@onlabsorg/stilo-web/editor";
const cells = parseDocument(`Notes
<!--{ bek4 : markdown }-->
# Beam <% L = 6 %>
`);
// [ { type: "text", marker: false, texl: "Notes\n" },
// { type: "markdown", name: "bek4", texl: "# Beam <% L = 6 %>\n" } ]
serializeDocument(cells); // the same text
text cell with marker: false,
so any plain Texl file opens in the editor.nameCells gives every cell with a marker a unique random name (bak7);
nameConflicts finds names shared by hand-edited cells.tagSpans
finds the tags as Texl does), so a tag never spans cells. spanningTag finds
a change that would make one; cellsFromSource gives the cells a new source
becomes.cellComments extracts the cell comments, <!--[ ... ]-->.splitRendering cuts the rendering of a whole document into the outputs
of its cells, at the places of the cells’ markers, which it works out from
the positions of the tags (outputSpans).The module is pure: no DOM, no Texl. It can run anywhere, e.g. on a server. → Document functions
TexlEditorTexlEditor (web/src/editor/texl-editor.js) is the application. Its state is a few
private reactive properties:
| State | Meaning |
|---|---|
_cells |
The document: CellData[]. Never mutated; replaced by a new array on each change. |
_outputs |
The rendered output of each cell, from the last rendering pass. |
_anchor, _selected |
The selection: from the anchor line to the active line. |
_editing |
The line in edit mode, or -1. |
_menu, _menuItem |
The line whose type menu is open, and its highlighted item. |
_notice |
A message shown at a line, {index, text}, e.g. why a type key was refused; or null. |
_undoStack, _redoStack |
Earlier states {cells, anchor, selected} (not reactive). |
render() draws one grid row per line: left margin, cell element, right
margin. The sheet has max(rows, cells.length) lines; lines below the
document show an empty rich cell that is not part of the document.
For each line the editor asks the registry which element to use
(cellTagName(type)) and creates it with Lit’s static templates, binding
the cell’s state as properties:
// Simplified from TexlEditor.render()
const tag = unsafeStatic(cellTagName(cell.type));
html`<${tag}
.texl=${cell.texl}
.output=${this._outputs[i]}
.mode=${i === this._editing ? "edit" : "render"}
.selected=${isSelected}
@cell-change=${(e) => this._onCellChange(i, e.detail.texl)}
@cell-exit=${() => this._onCellExit()}
></${tag}>`;
So a custom cell type gets the same treatment as a built-in one.
Every change goes through one method, _setCells(cells):
rich/markdown/text cells at the end (they look like the empty
lines below the document);nameCells);name-conflict if they changed;rendered);change.Inserting, deleting, moving, pasting, changing type and committing an edit
all build a new cell array and call _setCells. Undo and redo swap whole
states, which is cheap because cell arrays are never mutated. Setting
value replaces the cells directly and clears the history, without firing
change.
// TexlEditor._renderCells()
const generation = ++this._generation;
const cells = this._cells;
this._engine ??= createEngine(); // with `loader` for http(s), if set
const engine = await this._engine;
let outputs = [];
try {
const doc = await engine.render(this.url, serializeDocument(cells));
outputs = splitRendering(doc, cells);
} catch {
// The URL cannot be resolved: the cells show no output
}
if (generation === this._generation) this._outputs = outputs;
url may change at
any time (the editor renders again) and a changed library shows on the
next pass.url: what any other Texl host renders, imports included, with each cell
seeing the names bound above it. splitRendering (document.js) cuts it
into the cells’ outputs at the places of their markers, worked out from the
tags’ positions; the rules (markers in a tag’s output, markers inside a
tag, line breaks) are in
Editor design._renderCells passes the document to findErrors (errors.js), which goes
through doc.tags and collects the undefined values returned, directly or as
items of a tuple. Each is assigned to a line by its tag’s source position
(lineAtOffset). Then:
markErrors takes a cell’s span of the rendering (outputSpans) and replaces
the text of each value in it with a mark of private-use characters holding its
index. It has to happen here: only doc.text has the positions, and they are
lost once Markdown has run.renderView passes its HTML to sanitizeOutput, which sanitises
it and then replaces the marks in text nodes with a highlighted <span>. A
mark in an attribute becomes plain [[Undefined]]; Markdown percent-encodes
the marks in a link’s address, so both forms are matched there.A plain string replacement after sanitising would not do: a mark in an attribute
would put an element inside it. A click on a value is matched to its place by
the span’s data-error.
The editor listens to keydown on itself. Keys from the cells reach it
because keyboard events are composed and bubble out of shadow roots. The
rules:
accept a selected cell’s source (_canSetType);exitEdit(commit) on the editing cell;key (Shift
allowed, no other modifier) runs make-<type>, which calls
_editAs(type): it selects the active
line alone, changes it to the type with _setType and edits it, or, if
the type refuses the source, sets _notice to the menu’s reason
(_typeRefusal). typeKey reads the key as an own property of the
class, so subclasses do not inherit it; the first registered type wins.
The notice is cleared by the next key or pointer press.Copy, cut and paste use the browser’s clipboard events rather than keys, so
every platform shortcut works. The clipboard holds the selected cells as
Texl with their markers (serializeDocument, in _copiedText); a paste
parses it (parseDocument, in _paste) and renames pasted cells whose
names are already in use.
Every action a key triggers, apart from moving the selection, is a named
command in one table, _commands(): edit, commit, insert-below,
move-up, undo, cell-type, make-<type> for each registered type,
and so on. The key handler maps the key to a name and runs the command;
runCommand(name) runs the same function for a page, after the checks a
key gets (edit mode allows only commit and discard; an open menu is
closed). A command returns false when it does not apply, which
runCommand reports. Its copy, cut and paste go through
navigator.clipboard (_writeClipboard, _readClipboard), since a page
cannot fire trusted clipboard events. select(line) sets the selection as
a click does. A new editor action is added to _commands(), so its key
and runCommand stay the same, and to commands.js, which describes it
for the user (label, keys, group, whether it changes the document);
editorCommands() lists them, and a test checks that both have the same
names. See Commands.
Read-only mode (readonly): _commands() replaces every command that
changes the document (changesDocument) with one that returns false;
_edit, _openMenu, _onCellChange and the paste and cut events do
nothing. Selecting, copying, showing comments and errors and showing the
hidden cells still work.
TexlCell and its subclassesLitElement
└─ TexlCell modes, lined-paper layout, commit protocol, renderView
├─ TextCell CodeMirror editor, Swan highlighting (type "text")
│ ├─ MarkdownCell Markdown highlighting and output (type "markdown")
│ │ └─ GridCell a grid of fields (not a type)
│ │ ├─ TableCell a Markdown table (type "table")
│ │ └─ DataCell a stilo.dataframe (type "data")
│ ├─ FormulaCell one tag, edited as its expression (type "formula")
│ └─ FormCell a form of fields (not a type)
│ └─ ChartCell a stilo.charts chart (type "chart")
└─ your cells e.g. QuantityCell (type "quantity")
A cell is in render mode (shows renderView()) or edit mode (shows
renderEditor()). The editor switches it by setting mode.
sequenceDiagram
participant U as User
participant E as TexlEditor
participant C as Cell (TexlCell subclass)
U->>E: Enter / F2 / double click
E->>C: mode = "edit"
C->>C: willUpdate: fromTexl(texl) → input
C->>C: render: renderEditor()
C->>C: updated: focusEditor()
U->>C: types (widget updates input)
U->>E: Ctrl+Enter (keydown bubbles out of the cell)
E->>C: exitEdit(true)
C->>C: toTexl() → new source
C-->>E: cell-change {texl} (only if changed)
C-->>E: cell-exit
E->>E: _setCells → render pass → change
E->>C: mode = "render", texl, output
C->>C: render: renderView() (output, sanitised)
Escape follows the same path with exitEdit(false): no toTexl(), no
cell-change, only cell-exit.
Shapes. A type that needs a source of a certain shape (table,
formula) overrides the static accepts(source) and sets needs. White
space and HTML comments around the content never make a source
unacceptable (isBlank in document.js tells a source that has nothing
else). The type menu offers a type only if it accepts every selected
cell’s source, so a type change never converts content. On commit,
exitEdit checks a changed source with inputError(texl); a refused one
is not committed, and the cell stays in edit mode with the message (the
round-trip check: e.g. %> in a formula would split its tag). The same goes
for commitError(texl), set by the editor, which refuses a source whose tag
would run into a later cell; _setCells refuses the same of a paste or a move.
Imports a type needs. A type whose cells call a library sets the
static requires to {url, source}: DataCell and ChartCell require
the Stilo library. In _setCells, when a change writes more non-empty cells of such
a type than there were and no cell’s source mentions url, the editor adds
a formula cell with source at the top (_withImports); the selection
moves down with its cells, and one undo takes back both.
A committed source with marker lines outside tags becomes those cells
(_onCellChange). A cell whose
source lacks its type’s shape (edited by hand) is edited as text, and can
be committed unchanged or once it has the shape.
The contract for a subclass is three methods:
class MyCell extends TexlCell {
static type = "mine";
fromTexl(texl) { this.input = parse(texl); } // source → widget input
toTexl() { return generate(this.input); } // widget input → source
renderEditor() { return html`…uses this.input…`; } // the widget
}
The guide builds a complete example:
Write your own cell type.
→ TexlCell
TextCell and MarkdownCellTextCell edits the source itself in a CodeMirror 6 view. The view is
created in updated() when the cell enters edit mode and destroyed when it
leaves, so a document with hundreds of cells has at most one editor alive.
A CodeMirror update listener keeps input current; the line break that
ends the body belongs to the file format and is kept out of input.
Its language comes from languageExtensions(): Swan highlighting
(swanTags()) and the keymap for Mod+E (insert a tag) and Shift+F2
(insert a comment). MarkdownCell adds Markdown highlighting in front of
them, with a small Markdown parser extension so that Markdown does not
interpret what is inside a tag, and overrides the static viewHtml() to
convert its output with marked before sanitising it; renderView()
shows it, and the editor’s renderedHtml() (the document as rendered, for
an export) uses it too.
A new text-based cell type follows the same pattern (a sketch;
latexLanguage stands for any CodeMirror language support):
class LatexCell extends TextCell {
static type = "latex";
static label = "LaTeX";
languageExtensions() {
return [latexLanguage(), super.languageExtensions()];
}
static viewHtml(output, errorMessages) { /* typeset output, then sanitizeOutput */ }
}
registry.jsA map from cell type (the word in the marker) to custom element tag.
registerCell(CellClass) defines texl-cell-<type> and records it;
cellTagName(type) is what the editor uses to pick an element, and returns
the text element for unknown types, so a document with a type this page
does not know still opens, shows its source and keeps its type on save.
cellTypes() and cellClass(type) feed the type menu (labels and icons).
import { registerCell, cellTagName, cellTypes } from "@onlabsorg/stilo-web/editor";
registerCell(QuantityCell);
cellTagName("quantity"); // "texl-cell-quantity"
cellTagName("chart"); // "texl-cell-text" (not registered)
cellTypes(); // ["text", "markdown", "table", "formula", "quantity"]
engine.jsA thin wrapper around @onlabsorg/texl. The WebAssembly module is
initialised once per page, on the first createEngine() call, and every
call returns a new TexlEngine. An engine holds configuration only
(globals, base URL); each engine.render(url, source) evaluates a whole
document in a new scope and resolves its texl.imports against url.
swan.jsTexl finds its tags before any other syntax is read, so a tag is a tag
wherever it is, also inside a Markdown code block. Highlighting follows
that: it is not part of a CodeMirror language but a layer of mark
decorations over it. findTags locates <% … %> spans (an unclosed tag
runs to the end), and swanTokens splits their content into comments,
strings, numbers, names and operators, which get cm-swan-* classes.
insertTag and insertComment are CodeMirror commands that wrap the
selection.
Documents come from other people, so their output is untrusted HTML. Every
cell output is sanitised with DOMPurify before it reaches the DOM
(TexlCell.renderView, MarkdownCell.renderView). Custom cells that
override renderView() must do the same.
Tests run in a real headless Chrome with @web/test-runner, because cells
are custom elements and Texl is WebAssembly: test/document.test.js (file
format), test/cells.test.js (cell output, highlighting, commands) and
test/texl-editor.test.js (editing, keys, clipboard, undo). Run them with
npm test.