Skip to content

Writing an editor package

A package can bring tools for the editor along with what it does in the game: a scene tool, a panel, an inspector part, Agent tools. Nothing in the editor names them. The editor finds them through the package’s package.json and installs them, as it installs its own bone, path and particle tools.

Terminal window
pnpm new-package spawners

This makes packages/spawners from packages/editor/package-template. It has its name, a plugin with a scene tool and a panel drawn with the editor’s own parts, and their test, laid out to pass its own lint. A second argument puts it elsewhere: pnpm new-package @acme/spawners examples/editor/spawners.

A project has it once its package.json lists it among its dependencies, from the workspace:

{ "dependencies": { "spawners": "workspace:*" } }

Then run pnpm install again, and start the project’s dev server anew: its editor installs the package’s editor part.

One rule: shell.editor names the editor part

Section titled “One rule: shell.editor names the editor part”

A package’s package.json names its editor plugin in its shell field, exported from the package’s ./editor entry:

{
"name": "@acme/spawners",
"exports": { ".": "./src/index.ts", "./editor": "./src/editor.ts" },
"shell": {
"title": "Spawners",
"description": "Enemies come in waves from spawn points you place.",
"plugin": "SpawnersPlugin",
"editor": "SpawnersEditorPlugin",
"summary": "Waves of enemies from spawn points",
"features": ["Spawn points you place in the scene", "Waves: what comes, when and from where"]
}
}
  • A package with a game side names both. Its ./editor entry is imported only by the editor, so a game’s build has none of the editor code. @shell/tilemap-2d is one.
  • A package for the editor alone has no plugin and names its own editor plugin. The editor’s own bone, path and particle tools are such packages, and so is the template.
  • A project has the package when its package.json depends on it. shellPackages() in its Vite config reads that list. The editor’s createEditor({ packages: ProjectEditorPackages }) installs the editor parts: the editor’s own first, then the project’s, each once.
  • File › Packages lists the project’s Packages and the editor’s own, one entry for each thing a person adds. It does not offer a package for the editor alone to add: those are the editor’s, or the project’s own.
  • What File › Packages shows of it, besides its title and description, is optional and plain words for a game maker: summary, its line in the list, and features, a few lines of what it gives, shown before it is added, when none of it is loaded yet. partOf names the package an editor part is shown inside: @shell/editor-tilemap is part of @shell/tilemap-2d, and the Particle Editor of Particles. One that is wrong is left out with a warning.

A package that builds on another lists it in its own package.json dependencies. It names the other’s plugins as its plugins’ dependencies, on the game side and on the editor side:

// @acme/waves, built on @acme/spawners
export const WavesPlugin = Define.plugin('waves')
.dependencies(SpawnersPlugin)
.build((world) => {
/* … */
});
export const WavesEditorPlugin = Define.plugin('editor:waves')
.dependencies(SpawnersEditorPlugin)
.build((world) => {
/* … */
});

The editor and the game read only the project’s own dependencies (and, for the editor’s own tools, those of @shell/editor). So a package that only another package depends on is not one of the project’s Packages:

  • Its plugins are installed through that chain: when the package that depends on it is installed, a plugin installed twice is installed once.
  • File › Packages does not show it as added. The dialog lists its editor parts under the package whose part installed them. In a workspace, the dialog still offers it as a Package to add, as it offers every Package there.
  • A project that wants it in its own right lists it in its own dependencies too.
import { Define } from '@shell/ecs';
import { Method } from '@shell/editor-protocol';
export const SpawnersEditorPlugin = Define.plugin('editor:spawners').build((world) => {
const session = world.get('editorSession');
const selection = world.get('editorSelection');
world.get('editorTools').register({
id: 'spawners.place', // editorTools.active while it is picked; its action is tool.spawners.place
label: 'Spawner Tool', // menus, the palette, its button: "Spawner Tool (N)"
icon: 'target', // the editor's own, or one the package adds to editorIcons
key: 'N',
group: 'spawners', // its toolbar group, beside the package's other buttons
// A click in the scene view at a point of the world: what goes through step is one undo step.
// This one puts the chosen entity there.
press: (at, step) => {
const uid = selection.primary;
if (uid === undefined) return;
const fields = { x: at.x, y: at.y };
return void step.execute([
session.call(Method.SetFields, { uid, component: 'position', fields }),
]);
},
});
});

It is installed in the page’s world and in each Animate tab’s world. An Animate tab’s world has no interface of its own: it shows the page’s. So what goes on the interface (a panel, an inspector part, an asset preview) is added only where the world has EditorUiPlugin:

if (!world.hasPlugin(EditorUiPlugin.name)) return; // an Animate tab's world: the page's interface shows it

Tools, actions and Agent tools are added in every world.

editorTools.register takes:

  • id, label, icon, key, group, and submenu for its place in the Tool menu.
  • enabled: whether it can be picked now.
  • when: a tool of a context. Its button shows and its key works only in that context, before a tool of none on the same key. The tile tools are there while a tile map is chosen, so B is Paint’s then and the Bone tool’s otherwise. Two tools of one rank on one key: the one registered first takes it, and Settings › Shortcuts and File › Packages say so.
  • press(at, step): a click.
  • drag: { start, move, end, cancel }: a drag past a few pixels. Each is one undo step named after the tool, and Escape takes a drag back. The tool’s code runs in order, and the step is recorded once it has ended. Opening another document, closing the Animate tab, or Play takes it back at that moment.
  • draw(): its gizmo, each frame while it is active, on a gizmo layer editor:*.

A tool that needs more than these, such as handles to hit or a status line, has a system of its own that checks editorTools.active. See the ecs-editor-viewport skill.

Panels, inspector parts, asset kinds, Agent tools

Section titled “Panels, inspector parts, asset kinds, Agent tools”
  • A panel: editorPanels.register({ id, title, slot, component }). A panel there only in a context gives when and calls editorPanels.recheck() as the context changes. The Tiles tab is one, there while a tile map is chosen. Register it in the plugin’s build, so File › Packages lists it as the package’s.

  • An inspector part: editorInspectorParts.set(Component.serialKey, Part). Its buttons are PartButtons in a PartRow, both from @shell/editor-ui, as the Animator’s Animate and the Particle emitter’s Open in Particle Editor are. A PartRow has no label, so its buttons start on the field column, 4 px apart. A PartButton is 24 px high, takes an icon (an Icon name) and words that say where it goes, and can be disabled:

    <PartRow>
    <PartButton icon="square-arrow-out-up-right" onclick={() => openEffect(path)}>
    Open in Particle Editor
    </PartButton>
    </PartRow>
  • An asset kind: editorAssets.registerImporter({ kind, matches }).

  • An Agent tool: editorAgentTools.register({ name, description, inputSchema, run }).

File › Packages lists each of these in the package’s technical details. Its Get started is built from them: each Entity › Create action (a button runs it), each kind it makes in the Assets panel’s New menu (editorAssetMakers: a button starts a new one there), the tools with their keys, and each panel (a button opens it, while it is there). A key one of its tools shares with a tool registered before it shows there, with a button to change it.

The Inspector draws a package’s components from their schema’s meta, as it draws the engine’s. Nothing is registered for it but the look of a category of the package’s own. Spawners’ Spawner uses a group, a pair, a unit and its own category:

export const Spawner = Define.component('spawner')
.withSchema({
count: { type: StoreType.Int32, default: 3, meta: { group: 'Wave', min: 1, step: 1 } },
every: {
type: StoreType.Float32,
default: 10,
meta: { group: 'Wave', min: 0.5, step: 0.5, unit: 's' },
},
width: { type: StoreType.Float32, default: 0, meta: { group: 'Area', min: 0, unit: 'px' } },
height: { type: StoreType.Float32, default: 0, meta: { group: 'Area', min: 0, unit: 'px' } },
})
.serializable('spawners:spawner')
.showInEditor()
.withMeta({ category: 'Waves' });
  • Groups. group puts a field under a heading that folds, here Wave and then Area: groups come in the order of their first field. more: true folds a field into its group’s More, closed to start with; more: 'Min and max' names the fold; where two fields of a group name it, the first one’s name is used. when: { shape: 'circle' } shows a field only while another has that value.

  • Pairs. Fields that stand next to each other in the schema, of one kind, share a row by their names, each after its letter: width and height are W · H, and so are x, y and z, offsetX and offsetY, minA and maxA, and left, top, right and bottom. Two other fields share one when the first says pair with the name of the one right after it. linked: true, also on a row’s first field, keeps the row’s ratio as one is changed. On the second field, or naming a field further on, neither does anything.

  • Units. unit is drawn inside the field: px, °, ms, s, px/s, °/s, × or %. A measured number, such as a width, a speed or a delay, says its unit. One whose name sounds measured but is not says unit: '', and why in its description.

  • Choices and ranges. Up to four options sit side by side, each as its icon where it has one; five or more are a dropdown. A number with both a min and a max is a slider beside the number.

  • Lists and objects. An Object field whose meta says what it holds (items for a list, fields for an object; see “A list or an object” in Components) is drawn with the Inspector’s own rows. An object is a group that folds. A list has its count, Add and ×, and each item a ⋯ menu and keys: Duplicate (Mod+D), Move up (Alt+↑), Move down (Alt+↓) and Remove (Delete, on the item’s own line, ⋯ or ×). One value each is a row each; two or three share a row; more fold, each closed item’s line saying what it holds (“slime × 5”). max turns Add off and min turns Remove off, in the Inspector only. Each change is one undo step. An entity inside a list or an object is not taken yet. The widgets are “Lists and objects” (@shell/editor-field-lists), which every project has.

  • A category. category puts the component under a heading in the Inspector, also when it is the only one of its category, and names it in Add component. The heading’s icon and colour are the category’s. The package’s editor plugin gives a category of its own its look, so the editor’s code names none of it:

    world.get('editorIcons').register('spawner', SPAWNER_ICON); // its SVG, drawn in currentColor
    world
    .get('editorInspector')
    .registerCategory('Waves', { icon: 'spawner', color: 'var(--ed-palette-red)' });

    The colour is one of the Theme’s palette variables, so every Theme keeps it readable: --ed-palette-red, -orange, -yellow, -green, -cyan, -blue, -purple or -subtle. A category with no look has Other’s.

A package’s panel is drawn with the editor’s own parts, from @shell/editor-ui, so it looks and behaves as the editor’s panels do. The template’s panel is one: the chosen entity’s place, in the Inspector’s own fields.

<script lang="ts">
import { EntityFields, getEditor } from '@shell/editor-ui';
import { Spawner } from './index';
const selection = getEditor().world.get('editorSelection');
</script>
{#if $selection.primary !== undefined}
<EntityFields
uid={$selection.primary}
component={Spawner.serialKey}
fields={['count', 'every']}
/>
{/if}
  • EntityFields: one entity’s fields of a component, edited as the Inspector edits them. Each edit is one undo step, and Escape puts the value back.

  • ComponentFields: the Inspector’s list of a component’s fields, for values a panel holds itself.

  • fieldEdit(world, { uids, component }): the edit behind them, for a widget of the package’s own. change while typing, commit on Enter or blur, cancel on Escape.

  • The field widgets: NumberField, AngleField, SelectField, CheckboxField, TextField, AssetField, ColorField, EntityField, PrefabField, ReadonlyField. Each takes FieldProps: value, then onchange, oncommit and oncancel. A number field’s oncommit gives the number it ends with, for a panel that writes only then.

  • The colour field opens the editor’s picker. A colour whose meta names its alpha field (meta.alpha) is edited with it, as one undo step, and the alpha has no row of its own.

  • SearchBox: the panels’ search box, bind:value. Where it sits is the panel’s: .panel :global(.search).

  • ContextMenu with MenuEntry[]: the right-click menu. It needs label, its accessible name, and onclose, which it calls on a press elsewhere, Escape or a choice. Hold where it is in a $state and draw it while that is set:

    <script lang="ts">
    import { ContextMenu, type MenuEntry } from '@shell/editor-ui';
    const entries: MenuEntry[] = [{ label: 'Delete', enabled: true, run: () => {} }];
    let menu = $state<{ entries: MenuEntry[]; x: number; y: number }>();
    function open(event: MouseEvent) {
    event.preventDefault();
    menu = { entries, x: event.clientX, y: event.clientY };
    }
    </script>
    <button oncontextmenu={open}>Spawner</button>
    {#if menu}
    <ContextMenu {...menu} label="Spawner" onclose={() => (menu = undefined)} />
    {/if}
  • Switch, Badge and ActionButtons: an on/off control, a short coloured word, a row of buttons that run actions.

  • The searchable list a reference field chooses from is one dialog, not a part to place: editorPicker.pick(request).

Its own styles take the theme from the --ed-* variables, so every Theme and Shape draws it right: --ed-text and --ed-text-muted for words, --ed-panel and --ed-input for what is behind them, --ed-border, --ed-accent, --ed-focus for a focus ring, and --ed-radius for corners.

import { editorTestWorld } from '@shell/editor/testing';
import { HierarchyTransformPlugin, Position } from '@shell/transform';
const editor = await editorTestWorld({ plugins: [HierarchyTransformPlugin, SpawnersEditorPlugin] });
const crate = editor.spawn('crate');
crate.addComponent(Position, { x: 0, y: 0 });
// The editor hears of the entity a frame later, and of the frame a moment after.
editor.tick();
await vi.waitFor(() => expect(editor.session.entities.size).toBe(1));
editor.world.get('editorSelection').set(['crate']);
await editor.tools.choose('spawners.place');
await editor.view.press(40, 25); // a point of the world: the camera is at the origin, at zoom 1
expect(editor.world.get('editorHistory').undoLabel).toBe('Spawner Tool');

editorTestWorld({ plugins, files }) is a mounted edit world:

  • the editor’s core, with its document open on files kept in memory (files);
  • the scene view as far as a tool needs it: the camera, the pointer, the keyboard, and the press, drag and gizmo of the active tool;
  • no renderer and no interface.

It gives:

  • spawn(uid), tick() and session;
  • tools.choose(id);
  • view.press(x, y, keys), view.drag(from, to, keys) and view.frame(), each resolving once what the tool did is applied.