Skip to content

Editors and projections

A concept's editor describes how a node is drawn and which cells inside it are editable. It is written as JSX using the components in src/editor-jsx.ts inside this.template(...) and produces plain tokens that src/projection.ts and the SolidJS NodeRenderer turn into DOM. This page is the how-to; the full rules and edge cases are in Projection.

This is not SolidJS JSX

An editor template uses a custom JSX runtime (the classic h/Fragment pragma) that builds plain token objects. There is no DOM and no reactivity in the template body. A concept file is plain JavaScript named *.concept.js (JSX is compiled for it) and must import h and Fragment from editor-jsx.ts next to the components it uses. A template needs no <>...</> wrapper around a single element: template() turns the result into a token array itself. (An older editor() method must still return a fragment, which npm run lint:concepts checks.)

A first editor

import { h, Fragment, Child, Br, Indent, Text } from "../../../src/editor-jsx.ts";
import { ChildSlot } from "../../../src/base-concept.ts";
import { Concept, IStatement, IExpression } from "../../../src/concept-interfaces.ts";

export class While extends Concept(IStatement) {
    head = "while";
    cond = ChildSlot({ type: IExpression });
    body = ChildSlot({ type: IStatement });

    editor = this.template((self) => (
        <>
            <Text class="kw">while </Text>
            <Child link={self.cond} />
            <Text class="punct">:</Text>
            <Br />
            <Indent><Child link={self.body} body /></Indent>
        </>
    ));
}

self.cond is a slot handle (a frozen identity object per class), distinct from this.cond, which is the slot's live value. The template takes handles, never values, because an empty slot or a primitive carries no identity of its own. self is typed from the class's own fields, so self.condd is a compile error and renaming the field renames the handle. Passing a plain string or another class's handle to link throws, so a typo fails loudly instead of rendering a broken cell. Because the slot-declaration helper is named ChildSlot, the JSX component Child and the helper sit side by side without clashing.

editor, inspector, notations and computed are class properties initialised with this.template(...), not methods: a method's parameter would not be contextually typed from the base class, so self could not be inferred. A multi-statement template is a block arrow (this.template((self) => { const label = …; return <>…</>; })). The property is non-enumerable on a live node, so cloning or comparing nodes structurally is unaffected.

Components

Component Use
<Text class="kw">if </Text> Decoration text. The one generic decoration tag; give it any CSS class. Conventional classes: kw, op, punct, quote, num, str, err. Omit class for plain text. It also carries wrapTrigger/wrapContext for side-transformations.
<Br /> Hard line break.
<Indent>...</Indent> Indented block with a guide bar.
<Child link={self.x} style="sym" inline /> The cell for a single slot. style picks a built-in look (kw, op, punct, sym, string, type, comment) or a concept-specific class. inline stops a statement-kind slot getting its own line.
<Children link={self.xs} sep={...} vertical emptyText="..." items /> A variadic slot: separator between items, stacked layout, placeholder text when empty. items says it is a list of values built item by item, so Enter on an item adds one.
<Child link={self.body} body /> body says the slot is the construct's own statement body: a second statement wraps it in a block.
<Optional link={self.x}>...</Optional> Shown only when an optional slot is filled; otherwise a "+ slot" affordance appears. Use <WhenPresent>/<WhenAbsent> children for distinct branches; showWhenEmpty and revealOnHover tune the empty case.
<Computed of="name" tokens /> A read-only cell from the concept's computed() map. Pass tokens when the function returns tokens rather than text.
<Grid of="slot" columns={[...]} />, <Table of="slot" columns={[...]} emptyText bordered filterable footer /> A variadic slot rendered as rows and columns. A column is { header, slot }.
<Diagram of="slot" shape directed width height liveLabel /> A variadic slot as an SVG node/edge diagram (Sprotty).
<Widget of="slot" as="kobalteSwitch" /> A live Kobalte control on the canvas; see plugins/lang-uikit/ for all 18.
<Collapsible id collapsed defaultState>...</Collapsible> Any region collapsible from a ▸/▾ toggle, with its own state per node and id (view-only, not saved). collapsed is the summary shown while closed. Unlike Alt+. folding it is not tied to <Indent>; focusing a hidden cell expands it.
<Dropdown>...</Dropdown> Wraps cells with a ▾ arrow that opens the usual completion popup on the first completable cell inside (what Ctrl+Space does).
<StateCell of="slot" states={[{ value, icon, label }]} /> A button cycling a slot through fixed states on click, Enter or Space (Shift+Enter goes back). Two states give a boolean with custom labels.
<Paginate pageSize searchable><Children .../></Paginate> One page of a long variadic slot at a time, with pager and a search box (match case, whole word, regex). Only the page's items are in the DOM, so editing keys behave as in a normal list, and the page follows focus.
<QueryList placeholder addable><Children .../></QueryList> A filterable list: a filter box above a variadic slot that shows only items containing every whitespace-separated term (case-insensitive), an "n of m" count and a "+" button that appends an item. Rejected items are not rendered, so arrow keys and Enter/Shift+Enter only see visible rows; Down/Enter in the box moves to the first row, Escape clears it. Unfilled placeholders stay visible, and the query clears itself when the editor must focus a hidden item. The query is view-only (kept per node, survives re-renders, not saved).
<Tree addable defaultState><Child .../><Children .../></Tree> One row of a hierarchical collapsible tree: a chevron, the label tokens and the nested items (the one <Children>, shown vertically, indented) below. Put it in an item concept's editor() whose variadic slot holds items of the same concept, so the tree recurses. The chevron appears only while the item has children: Left collapses, Right expands (the other direction navigates as usual), Enter/Space toggle. A hover "+" adds a child (also how a leaf gets its first one); Enter/Shift+Enter on a label add a sibling item after/before. Collapsed items are not rendered, so Up/Down only visit visible rows. Expanded state is view-only (per node, kept for the session, not saved).
<RichText plain toggles><Children .../></RichText> A paragraph of inline-styled runs: the one <Children> (a variadic slot of run concepts) flows as wrapping prose instead of one run per line. A run's style is its concept: a plain run concept (plain, also the slot's type) and one concept per style (each parenting the plain one, same text slot, editor <Child link={self.text} style="bold" />). Mod+Alt+B / Mod+Alt+E / Mod+Alt+K switch the focused run to the first / second / third head in toggles (again: back to plain); Enter/Shift+Enter add a plain run after/before it, arrows cross runs. A run concept can offer the same through intentions() with editor.setConceptOf. Saved as ordinary concept calls, e.g. boldRun("text").
<Table ... mergeHeaders editable newRow> Also: a column's headerGroup draws a spanning group header (adjacent equal groups merge), rowHeader: true makes a column's cells row headers, mergeHeaders merges adjacent equal headers, editable adds "×" and "+ Add row" buttons (newRow() builds the row). Rows carry data-table-parent and data-child-index (absolute child index) so Shift+click can select a row range, withheld while a filter is active. A row no column can address (a concept without the column slots, e.g. a row group) renders as one full-width cell.
<Tooltip>...<Tip>...</Tip></Tooltip> Click-triggered, editable hover overlay with a "More info" button into the Inspector.
<Card>, <StatRow>, <Badge>, <Meter> Card-style visual vocabulary with shared chrome in styles/editor.css.

Helpers that build token lists: commaSep(link, { vertical, emptyText }), parens(children), call(name, children) and lineComment(link). They take a SlotRef, so they also work in functions that have no this. Plain JavaScript composes: locals, {cond && <X/>} and {items.map(...)} all work, so extract repeated shapes into functions rather than inventing new tags.

Conditional rendering

For class-authored concepts the template runs against the live node, so a ternary or && on real slot values (this.x) works. Two caveats from Projection:

  • The template is also harvested once per class into a default-state snapshot that node-free consumers read (the completion label, side-transform scan, persistence). If a conditionally rendered token carries wrapTrigger or a kw-classed label, declare wrapTrigger, wrapContext and alias as static fields instead.
  • Put derived values (not just branching) in computed() and show them with <Computed>, since that hook is the one guaranteed to receive the real current node.

Flag words (<Flag>)

A boolean slot can be shown as a word instead of a true/false cell. Put a <Flag> where the word belongs in the editor template; that one element is both the display and the declaration:

class Method extends Concept(IStatement) {
    isStatic = Prop({ type: "boolean", default: false });
    mutable = Prop({ type: "boolean", default: true });
    editor = this.template((self) => (
        <>
            <Flag word="static" link={self.isStatic} />
            <Flag word="final" link={self.mutable} inverted />
            <Text class="kw">method </Text>...
        </>
    ));
}
  • The word is shown only while its slot says so: static while isStatic is true; the inverted final while mutable is false.
  • Typing the word: Ctrl+Space (or typing a letter into an empty cell) on any cell of that node lists its still-unset words under a modifiers section of the ordinary completion popup. Picking one writes the slot (true, or false for an inverted flag). On a filled cell Ctrl+Space seeds the query with the text before the caret, which filters the words out; press Home first, or use an empty cell.
  • Deleting the word: Backspace or Delete on the word writes the opposite value instead of deleting the statement. Focus moves to the next editable cell.
  • A flag adds no key handling of its own; it only feeds the editor, completion list and decoration-delete paths that already exist. The engine's cell list (concept.grammar) is derived from the template (deriveGrammarCells), and the flag tokens persist in .lang.js/.lang.kdl, so a saved or duplicated copy keeps displaying, typing and deleting its words.

Optional words (<Flag optional>)

An optional (0..1) child slot can be introduced by a word. Put the flag inside the slot's <Optional> present branch, before the <Child>:

editor = this.template((self) => (
    <>
        <Child link={self.ctx} />
        <Optional link={self.asVar} showWhenEmpty>
            <Flag word="as" link={self.asVar} optional showWhenEmpty />
            <Child link={self.asVar} />
        </Optional>
    </>
));
  • Typing the word: the still-absent words of the node are listed under modifiers in the completion popup, next to flag words. Picking one creates the child through the editor's existing "+ slot" path, so the child's empty cell appears. The <Optional>'s own "+ slot" affordance keeps working.
  • Deleting the word: Backspace or Delete on the word removes the child, including any value in it; undo restores it.
  • showWhenEmpty has the same meaning as on <Optional>. Use it when typing the word should show an empty editable cell. Without it an empty placeholder counts as absent, so the word would not appear until the child is filled.
  • Limitation: the slot is "present" per <Optional>'s rule, so an optional followed by another slot cannot be used with showWhenEmpty, because removing it leaves an __Empty__ placeholder that still counts as present. Keep it the last non-variadic slot, as Core's with item does for as.

Wrap cells (<Wrap>)

A concept that is just a child between two delimiters is one element:

editor = this.template((self) => <><Wrap link={self.value} left="|" right="|" /></>);
  • Typing: the left delimiter is registered as a unary operator key of the concept, so typing it after a filled expression wraps that expression through the normal operator side-transform (the wrap climbs to precedence 9, the immediate atom). Pick a delimiter no other concept claims as an operatorKey; Core's | is bit-or, which is why the formula language (which does not import it) owns |.
  • Deleting: Backspace or Delete on either delimiter replaces the concept with its child (unwrap), unless the parent slot would not accept the child.
  • The tokens are plain: the left delimiter carries wrapTrigger/wrapContext="wrap", the right one wrapContext="wrapClose", so the cell survives .lang.js persistence and a saved copy keeps typing and unwrapping.
  • Do not use (, ., ?, , or = as left: those keys have bespoke handlers that run first.

Brackets (<Brackets>)

<Brackets link={self.value} left="(" right=")" /> is <Wrap> with distinct delimiters: the same cell, so typing the opener after a filled expression wraps it, typing it in an empty cell seeds an empty pair, and Backspace/Delete on a delimiter deco unwraps. The opener may be (. The editor's ( handler builds a call first and only yields to a brackets opener when the language has no call concept, so use ( in a math or grouping language, never in one that already has calls. The printer is untouched: a bracket concept persists through its own surface form and operand parenthesization stays the printer's job, so saved text is unchanged.

A concept that draws its delimiters itself (stretchy MathML, as formulaParens does) implements IWrapper and declares the typing half as data: wrapper = { slot: "value", left: "(", right: ")" } as const. It has no delimiter deco to unwrap from, and the declaration is class-only (not persisted). The slot name is checked against the class's slots when the concept loads.

Operator priority and associativity (the operator spec)

An operator concept implements IOperator and declares operator = { key, kind, precedence, assoc? }. Completion, the Language pane and every side-transform lookup read key, kind and precedence as the concept's operatorKey/operatorType/operatorPrecedence; a loose field the class sets explicitly still wins.

assoc decides how a chain of equal-precedence operators nests when you type the operator again. With the editor's default (and "right"/"none"), a - b followed by - nests into the operand: a - (b - _). With assoc: "left" it reshuffles to (a - b) - _; typing it after the first operand stays local ((a - _) - b). A precedence difference always wins first: a tighter operator wraps only its operand, a looser one climbs. assoc applies to binary operators (a variadic one appends to its own head) and is class-only, so a persisted copy of the language falls back to the default. Examples: Core's Minus and lang-formula's formulaMinus.

Splittable literals (ISplittable)

A concept whose text lives in a slot (lang-formula's formulaVar) can implement ISplittable: an operator key typed in the middle of the text then splits it, ab|c + + gives ab + c, two literals joined by the operator concept. Typing at the end (or start) still just wraps, as for any literal. Only binary and variadic operator keys split, and only for a concept that opted in; plain Core symbols and strings are untouched.

HTML and MathML in the editor

Lowercase JSX tags are plain HTML intrinsics and mix freely with the components:

<div className="row" style={{ color: "red" }}>
    <Text>label</Text><Child link={self.value} />
    <button onClick="run">Run</button>
</div>

Props are class/className, a camelCase style object, any other attribute (data-*, aria-*), and on* handlers. A handler must be a string naming an entry in the concept's actions() map ({ [name]: (node, lang, event) => void }), not a closure, because a persisted concept cannot serialize a closure.

A tag named for a MathML element (math, mfrac, msup, msqrt, munderover, mtable, ...) renders as real browser MathML. Wrap the top-level <math> in a fragment like any editor(), and nest Child and Text directly inside it; non-MathML content is wrapped in mtext automatically. plugins/lang-formula/languages/concepts.concept.js is the worked example. Do not make a MathML element itself a click target.

A separate mechanism exists for drawing an HTML tree held as model data: an html token ({kind: "html", tree}) takes a tree of capitalized heads where each head names an HTML tag and the children are its content. It is rendered through a safe-list, not arbitrary tags:

Tree Rendered
B("Hello") bold Hello
Div(B("hi"), " world") a div containing bold hi and text
Span(Attrs("class", "tag"), "x") a span with class="tag"; a leading Attrs(key, value, ...) sets attributes
Raw("<svg>...</svg>") raw HTML, run through the HTML sanitizer first

Tag names match case-insensitively against SAFE_HTML_TAGS in src/projection-html.ts: text and structure tags (b, i, u, em, strong, span, div, p, br, hr, lists, tables, code, pre, kbd, small, sub, sup, mark, blockquote, section, article, header, footer, nav, aside, main, h1 to h6, and a few more). An unknown tag renders as a <tag> placeholder.

Styling

A concept's css field is scoped automatically to [data-head="head"] by src/concept-styles.ts; & targets the node's .node-body. Keep concept-specific rules there, not in styles/*.css, which is for chrome shared across concepts. Declare it next to the class:

export const DECISION_TABLE_CSS = `...`;   // see plugins/lang-core-decision-table/
export class DecisionTable extends BaseConcept { css = DECISION_TABLE_CSS; /* ... */ }

No comments in concept CSS

The scoper is a tiny selector-boundary scanner that does not understand comments. A // or /* */ between two rules gets glued onto the next selector and silently breaks it. npm run lint:concepts catches this.

Colours, radii and shadows should use the design tokens in styles/base.css; see Theming.

Inspector

inspector() is the same kind of token template, consumed by the Inspector info panel instead of the canvas. It adds <Section title>, <Row label> and <Field of="slot" as="..."> (an editable form widget for a primitive slot, inferred from the slot or forced with as). Content tokens in the Inspector are genuinely editable when a live editor is available. Wrap the sections in <PropertyGrid> to draw them as a property grid (filter box, categorized or alphabetical order, collapsible category bands, a draggable name column, and a footer showing the focused row's description, an optional prop of <Row>; <Field of="slot" as="color" /> and as="icon" give a colour and an icon picker for string slots; a <Row> that contains further <Row>s is an expandable sub-object row, defaultCollapsed starts it closed): <PropertyGrid><Section title="Identity"><Row label="Name" description="The display name."><Field of="name" /></Row></Section></PropertyGrid>. See Inspector. A concept that writes its own inspector() replaces the Inspector's default header (the concept's name, the names around the node as a path with a type tag, what the node refers to, where it is defined); put <Fact /> in it to bring all of that back, or <Fact of="path" />, of="kind", of="refers-to" or of="defined-in" for one piece. The verdict line and the documentation stay the pane's own. Worked examples are Symbol/SymbolReference in plugins/lang-core/languages/concepts-symbols.concept.js and Params in concepts-functions-defs.tsx.

Alternate notations

notations() returns [{ name, editor, grammars? }]. A badge on the node cycles through the alternatives; the choice is stored per node. See Language authoring guide.

One authoring style

JSX is the only text format for an editor, wherever it is authored. A concept written in a class has editor = this.template((self) => <>…</>). A concept created in the Language Pane (no class) stores the same thing as plain token objects, and the pane shows and edits them as the very same JSX (src/editor-jsx-codec.ts), in the cells editor, with slots written self.name exactly as in a class. The pane covers the tokens such a concept can hold (Text, Br, Child, Children, Indent, Optional, Computed, Grid, Table, Diagram, Widget, Tooltip and plain HTML or MathML tags); an editor that uses richer components (Dropdown, Collapsible, QueryList, …) is shown read-only there and is edited in class source. The earlier XML/ed text format is gone.

The token kinds produced are text, newline, element, indent, child, children, optional, computed, html, grid, diagram, table, widget, tooltip and field.

Rules that save debugging time

  • A template reads slot handles (self.x). A value read (this.x) is fine for conditional text on a live node, but the harvest must not depend on it: tests/test-harvest-slot-poison.mjs harvests every concept with all slots holding junk and requires identical metadata (the few concepts whose snapshot spells a Prop's value are listed there).
  • The Editor class never imports the SolidJS rendering stack; UI-layer code supplies rendering hooks from above. Do not import NodeRenderer from src/editor.ts or anything under src/editor/.
  • A single-character non-alphanumeric alias needs an operatorKey or the keystroke is silently swallowed.
  • Test projection changes in a real browser, not only jsdom, which has no layout engine (MathML stretch sizing in particular). See Testing.