Each plugin is a folder here. The app ships what index.ts
lists, and the Plugins panel (left column) switches each on or off. Zarr
Vectors, the view aids and the scale navigator are on by default; the others
are offered when data they work with is opened (below).
plugins/
index.ts one entry per plugin: its manifest, and how to load its code
workers.ts the worker modules of data-type plugins, by plugin id
zarr-vectors/ a data type: Zarr Vectors stores in Neuroglancer (an npm package)
view-aids/ a tool, on by default: orientation cube, labels, Hide graphics and bookmarks in the 3-D view
scale-navigator/ a tool, on by default: breadcrumb, pyramid level and zoom boxes for image layers nested in space (HiP-CT zooms)
track-filtering/ a tool: TrackVis-style track groups, saved as .trk
volume-view/ not a plugin: volume readers (OME-Zarr, precomputed, NIfTI) the tools share
luxar/ a tool: chosen Zarr Vectors layers drawn as Luxar draws lines, in the 2-D and 3-D views
atlas/ a tool: a segmentation's regions as a tree (Allen CCF, FreeSurfer), shown, gone to, under the cursor
Three empty plugins to copy, each with a panel that lists the scene's layers and a command (the TypeScript and JavaScript ones also keep a counter in the scene's state):
| Starter | For | How to use it |
|---|---|---|
starter_ts/ |
A TypeScript plugin built into the app | Copy the folder, rename it and its ids, list it in index.ts (below) |
starter_ts/starter.mjs |
The same as one JavaScript file, no build | Plugins → Add, then Reload after each edit |
starter_py/ |
Python, in the page's Python (Pyodide): only .py files and a README |
Plugins → Add its starter.py; @ngp.command adds a command (its id python.<plugin>.<function>), @ngp.panel a panel in the Tools section; what it prints goes to the Python panel, or the Activity log when that is closed |
- Make a folder (or copy
starter_ts/),plugins/<name>/, with at least:manifest.ts:export const MY_MANIFEST: Manifest = { id, name, version, kind, … }(see The manifest). Theidis reverse-DNS and unique, e.g.org.my-lab.layer-stats.plugin.ts(a tool):export const plugin: PluginModule = { activate(ctx) { … } }.tests/*.test.ts: run bynpm testwith the platform's tests.README.md: what it does, who looks after it.
- Import the platform only through the SDK,
@ngplatform/sdk(types,checkManifest),@ngplatform/sdk/workers(for a worker of your own that reads chunks through Neuroglancer's codecs),@ngplatform/sdk/dom(the parts a panel is built from: see Building a panel; andel,svgEl,downloadBlob,safeFileName),@ngplatform/sdk/testing(a stand-in document for panel tests),@ngplatform/sdk/format(csv,csvField,ticks,mmText,bytesText,parseBytes) and@ngplatform/sdk/worker_rpc(WorkerRpc: requests to a worker of your own, with progress, cancel and a worker that fails). Everything a plugin may do goes through thectxit is given; nothing insrc/is imported directly. Neuroglancer itself can be imported (neuroglancer/unstable/…) when a plugin needs its internals, as the data types do. - List it in
index.ts:{ manifest: MY_MANIFEST, load: async () => (await import("./my-plugin/plugin.js")).plugin, summary: "One line for the Plugins panel.", group: "images", offer: OFFERS[MY_MANIFEST.id], // when to offer it while it is off (offers.ts) },
groupplaces it in the Plugins panel (data types, vectors, images, segmentations and atlases, annotation). A data type instead givesneuroglancer: () => import("…")(its main-thread module, which registers the data source) and adds its worker modules toworkers.ts. - Check it:
npm test(the catalogue test checks every manifest and entry),npm run typecheck,npm run e2eagainst a build. A plugin with its ownpackage.json(aszarr-vectors/) can also run its own tests, as the rootnpm testdoes for zarr-vectors. - Describe it: the catalogue entry's
summaryis the one line the Plugins panel shows;descriptionis one sentence, andguidea short user guide in Markdown (##headings, lists,`code`, links) withlinksits repositories and papers, all shown behind About.
The Plugins panel's Add loads a plugin from this computer: a JavaScript
module (one file, bundled) exporting manifest (a tool) and plugin, or a
folder with manifest.json and the module it names as main; or a Python
file, run in the Python panel's interpreter, where @ngp.command("Title")
adds a function to the command palette and @ngp.panel("Title") a panel
in the Tools section, under Python or group="…" (drawn by a function given
the panel's element, when shown and whenever the workspace changes; the
page's DOM is reachable through Pyodide's js). Reload reads it again after an
edit. In Chrome and Edge the file is remembered between visits.
Add → From a URL… (in the Plugins panel) loads a tool plugin someone has published: the URL of
its manifest.json (the module named by main beside it) or of the module
itself, over https and served with CORS (GitHub Pages and jsDelivr are).
The manifest is read first and shown, with a warning that the code will run
in the page with the app's access; nothing runs until the person agrees.
The URL is remembered and the plugin loads again on later visits until it is
removed; Reload fetches it afresh.
Owning a plugin is owning its folder: another team can amend or replace one
without touching the platform or the other plugins, and review stays inside
that folder plus one line in index.ts.
Zarr Vectors, the view aids and the scale navigator are on by default (enabledByDefault); every other plugin
is off until someone turns it on, from the Plugins panel or from an offer.
The choice is kept in this browser.
- A tool plugin turns on at once, without a reload (
PluginHost.switchOn): its panels, commands and keys appear, and it activates as its manifest says. A data type plugin turns on with a reload, as its Neuroglancer modules load only with the page. Turning any plugin off reloads the page. A reload keeps the link, so the workspace comes back as it was. - Turning a plugin on also turns on the plugins it requires; turning one off also turns off the plugins that require it. The confirmation says which.
- A plugin whose requirement is off is off, and the Plugins panel says why.
- Offers. When data a tool plugin works with is opened while it is
off, the Layers panel lists it under Tools for this data, with a button
to turn it on and one for "Not now"; some offers also show once in a
toast. Each entry in
index.tshas anoffer(offers.ts): a few words on what it does, whether it is worth a toast, andapplies(scene), which looks at the scene's layers (and, at most once per URL, a store's metadata). Settings › View → Offer tools that are off when the data suits them turns them all off. - A workspace that holds state of a plugin that is off (a link with track groups, say) says "This workspace uses Track filtering, which is off", with Turn on. The state stays in the workspace either way.
- An example can name the tool plugins it is shown with (
pluginsin its spec): opening it turns them on for this browser tab only, unless this browser turned them off. The S-21-46 and HCP-1065 examples do so for Track filtering. - A workspace with data in a format whose plugin is off says so when it opens, and shows the Plugins panel.
Loading plugins from a URL at run time is not supported yet: plugins are built with the app.
| Kind | What it does | Its code | Example |
|---|---|---|---|
Data type (kind: "datatype") |
Teaches Neuroglancer a format: a data source, with code in Neuroglancer's workers | A Neuroglancer plugin package: a main-thread module (registers the data source) and worker modules | zarr-vectors/ |
Tool (kind: "tool") |
Adds to the workspace around the viewer: a panel in the Tools section, commands, a view beside Neuroglancer's, analyses | A platform module with activate(ctx), using only the PlatformContext |
track-filtering/ (requires Zarr Vectors), filters/ |
A data type plugin has no platform code and contributes no commands or
panels; tools that work on its data are separate tool plugins that declare
requires: { plugins: [<the data type>] }.
At start, before the viewer exists, the app imports the main-thread module of
each data type that is on, and tells Neuroglancer to start its workers from
the app's own scripts (src/engine/workers/), named with the plugins that are
on. Each worker script imports those plugins' modules from
workers.ts and then Neuroglancer's own worker contents. This
uses the worker factories in the Neuroglancer the app builds on
(setChunkWorkerFactory, setAsyncComputationWorkerFactory); see
zarr-vectors/README.md.
A data type can also read files on this computer without converting them,
as virtual stores. Its catalogue entry lists them (virtualFormats, each a
VirtualFormat from @ngplatform/sdk: a file-name pattern, extensions for
the file pickers, the layer source for the store's URL, and a worker). Local
data then lists such files in folders and Open a file…, and sends every
key under a file's URL to the worker, which answers with
serveVirtualStores from @ngplatform/sdk/virtual:
// my_format/worker.ts
import { serveVirtualStores } from "@ngplatform/sdk/virtual";
serveVirtualStores((file) => openMyFormat(file)); // { get(key), list?(prefix) }Zarr Vectors uses this for tractograms, meshes and surfaces, SWC neurons
and point tables (src/virtual/vectors/formats.ts); the
platform's NIfTI and TIFF reader is the same kind of worker. list answers
folder listings (directory keys end in "/"), which Neuroglancer's http store
reads. A text format can set collect to offer a folder of its files as one
dataset (the folder's @all<extension>): the worker then gets one text,
each file after a # @file <name> line (SWC does).
A tool plugin can list a virtual format too, for data it makes in the page:
Segmentation serves the label volumes being drawn this way (a format whose
"worker" answers in the page), and calls viewer.reloadData(url) after each
stroke so Neuroglancer reads the changed store again.
@ngplatform/sdk/precomputed reads Neuroglancer precomputed volumes in a
plugin's own worker (images and segmentations, sharded or not; httpJson
and gunzip too); @ngplatform/sdk/sources recognises source URLs without
loading readers (layerSourceUrl: a layer's first source);
@ngplatform/sdk/tensors has the closed-form eigen-decomposition of a
diffusion tensor the platform's NIfTI reader uses.
The types are in src/sdk/types.ts, and the manifest
schema and its checks in src/sdk/manifest.ts, both
imported as @ngplatform/sdk. Track filtering is a complete example;
tests/plugins.test.ts exercises every part of the
host.
| Word | Meaning |
|---|---|
| Workspace | Everything in one link: its scenes, its datasets, every plugin's state. |
| Scene | One Neuroglancer state: which datasets are shown, how, where, in what layout. |
| Dataset | A piece of data, identified by its source URL. It belongs to the workspace, so any scene can show it. |
| Layer | One way a scene shows a dataset (colours, shader, segments). A scene can show a dataset through several layers. |
ctx.workspace.addLayer(datasetId, overrides) shows a derived view: the same
dataset with a different shader, subsources or segment set. Track filtering
shows its result that way.
Read without running any code: enough to list the plugin, show its commands in the palette and its panel in a dock, and decide when to load the code.
export const MANIFEST: Manifest = {
id: "org.example.layer-stats",
name: "Layer statistics",
version: "0.1.0",
kind: "tool",
enabledByDefault: false,
license: "Apache-2.0",
requires: { plugins: ["org.ngplatform.zarr-vectors"] },
contributes: {
panels: [{ id: "layerStats.panel", title: "Statistics", slot: "left", group: "Vectors", order: 50 }],
commands: [
{
id: "layerStats.show",
title: "Statistics of the selected layer",
when: "sourceFormat == zarr-vectors",
args: { type: "object", properties: { bins: { type: "integer", minimum: 2, default: 64 } } },
},
],
keybindings: [{ key: "alt+s", command: "layerStats.show" }],
appState: { key: "layerStats", version: 1 },
},
};- Activation: using a declared contribution loads the plugin. Activation
events (
onStartup,onCommand:<id>,onView:<panel>,onDatasetKind:<kind>,onOpen:<regex>) load it earlier. - Panels (
contributes.panels): a panel in a dock, inorder. A tool's panel (left, orrightas before) goes to the Tools section, in the left column below the layers, listed under itsgroup:Image,Labels,Space,Vectors, orOtherwhen it names none, and only while itswhenholds (when: "selectedLayerType == image"lists it while an image is selected);bottomkeeps it in the Activity dock at the bottom;minSize(pixels) grows the dock to at least that while the panel is shown (the annotation table asks for 300), without changing the size the person set. - Scene kinds (
contributes.sceneKinds: [{kind, title, panel}]): a kind of scene the plugin adds, shown in the scene bar while the plugin is on. Before one exists its scene tab (dashed) makes it; switching to it showspanel. The plugin sees the active scene'skindinworkspace.scenes()and makes one withworkspace.newScene({kind}); its state slice is that scene's, as in any scene. OME Collections' scenes are one. whenclauses read context keys: the platform's own (hasLayers,sceneIsEmpty,sceneCount,selectedLayer,selectedLayerType,datasetKind,sourceFormat,canUndo,canRedo,framed) and any the plugin lists incontributes.contextKeysand sets withctx.context.set. Syntax:a,!a,a == x,a != x, joined with&&and||.- Checks (
checkManifest): the schema, commands named by keys and dataset actions exist, activation events name declared things,whenclauses read only declared keys, and data types contribute no UI.
export const plugin: PluginModule = {
activate(ctx) {
ctx.commands.register("layerStats.show", async ({ bins }: { bins: number }) => {
const layer = ctx.workspace.selectedLayer();
const props = layer && ctx.viewer.segmentProperties(layer);
ctx.state.set({ layer, bins, n: props?.ids.length });
});
ctx.ui.panel("layerStats.panel", (host) => {
host.textContent = "…";
return ctx.viewer.onLayersChanged(() => { /* redraw */ }); // disposed with the panel
});
},
};Everything registered through ctx is owned by the plugin and removed when
it is deactivated. Subscriptions a plugin makes itself go in
ctx.subscriptions.
| Part | For |
|---|---|
commands.register / invoke |
Supply declared commands; call any command with arguments (validated against the declared schema, defaults filled in). |
ui.panel / showPanel |
Render declared panels; return a disposer for cleanup. A panel declared in the left slot is a tool: it shows in the Tools section of the left column, below the layers, under its group (bottom panels stay in the Activity dock). Build it from the SDK's parts: see Building a panel. |
ui.view |
Show a view beside Neuroglancer's, where its 3-D panel would be; one at a time, with a draggable divider. |
ui.viewToggle |
A switch beside "Sections" in the 3-D panel (volume rendering's "Volume"); order (lower first, 100 when not given) keeps one plugin's switches together. On a 3-D panel narrower than 560 px they fold into one View menu before Sections. |
ui.overlay / screenshotOverlay |
An element over the views, and painting into Neuroglancer's screenshots (labels use both). |
ui.statusItem |
An element on the right of the status line below the views (also while the Activity dock is collapsed), { order, label }, until its disposer is called or the plugin stops: a short value kept up to date in place, such as a scale breadcrumb or the level on screen. Drawn in the mono face (a child with the class status-label in the interface's), lower order further left, and shortened with … when the line is full. |
views |
Shapes with handles in the 2-D and 3-D views (points, spheres, boxes, planes, frames), dragged in place, and a floating card while one is selected; a picker for clicks in the views. See In-view tools. |
ui.toast / confirm / form / sheet |
Messages, confirmation, a dialog generated from a schema, and a sheet whose body the plugin draws. |
workspace |
Scenes, datasets, layers and the selection; add datasets and derived layers, remove layers. undoSteps gives the change the workspace's undo and redo would take, with when it was made (Segmentation undoes strokes and workspace changes as one history with it). |
viewer |
The active scene's Neuroglancer state as JSON (patchState applies only what changed, as one undo step), layers, the pointer, the position, a segmentation layer's segment properties, and a temporary set of visible segments (not saved in the link). draw3d draws in the 3-D view with a layer (raw WebGL2, Neuroglancer's camera and depth; volume rendering uses it); panels and onRendered place things over the views; layerTransform and setLayerTransform read and set a layer's transform (registration); thumbnail(w, h, "3d") a small picture of the 3-D view once loaded (bookmarks); layerBounds gives a layer's box in global coordinates, its finest voxel and its pyramid's levels, and renderedLevel the level Neuroglancer drew in the sections in its last frame (the scale navigator); reloadData has Neuroglancer read again what it holds from a URL (data a plugin serves and changed: Segmentation's label volumes). lookupTables lists the lookup tables that come with the app, reads one, and reads or sets a segmentation layer's (Atlas). |
workspace.local |
Files of data opened from this computer: whether a URL is one, writing into it (track filtering saves groups this way), and opening a file the plugin made in the page as data (track filtering's density maps). |
state |
The plugin's slice of the workspace state: in the link, undoable, versioned. |
settings |
Per-user settings kept in this browser, never in the link. |
jobs.run |
Long work with progress and cancel, shown in the Activity dock. |
runner |
Jobs on the user's own computer, through the runner they paired in Settings → Compute (see below). |
services.provide / get |
Share an API with other plugins (get waits for the provider). |
open.handler |
Handle pasted text matching a declared pattern. |
log |
Lines in the Activity log, tagged with the plugin. |
auth.register |
Add a sign-in method to Settings → Sign-in (see below). |
ctx.views puts shapes over Neuroglancer's views, with handles that drag
them: what a region, a crop, a cut plane or a landmark is edited with,
where it is, instead of sliders in a dock. Each shape is drawn on a canvas
over each view (never into captures) after every frame: in a 2-D view where
the section cuts it (a sphere's ellipse, a box's rectangle, a plane's
line), in the 3-D view as a wireframe (a box's edges, a sphere's three
circles, a plane's square). Coordinates are global, all global dimensions
as ViewPanelInfo.project takes them.
const region = ctx.views.add({
id: "r1",
kind: "sphere", // or "point", "box", "plane"
centre: [10, 20, 30],
radii: [5, 5, 5],
uniform: true, // one radius: its knobs scale all three
label: "Sphere 1", // the card's title (a point shows it beside itself)
colour: "#e4572e", // its lines when not selected
onChange: ({ centre, radii }, done) => save({ centre, radius: radii[0] }, { quiet: !done }),
card: (host) => { // shown over the view while it is selected
host.append(numberInput(radius, setRadius, { "aria-label": "Radius" }));
},
});
region.update({ centre: [11, 20, 30] }); // when the plugin's own state changes
ctx.views.select("r1"); // a new shape, ready to dragA frame is a box turned any way: a layer's data as it is placed (Registration's moving layer). Its drags are reported as what they did, from the frame as the drag found it, so the plugin applies them to its own transform:
ctx.views.add({
id: "frame",
kind: "frame",
views: "2d",
centre, // global
axes: [a0, a1, a2], // half-edge vectors, global units
pivot, // what its ring turns about (else its centre)
title: "brain", // the card's heading (else the label)
onChange: ({ change }, done) => {
// { kind: "move", by } | { kind: "turn", axis, angle, about } | { kind: "scale", factors, uniform }
apply(change, done);
},
});In a 2-D view a frame is its outline where the section cuts it: a drag inside it (once selected) or on its edge moves it in the section's plane, its ring (taken on its rim) turns it about the section's normal through the pivot, and the knobs at the outline's corners scale its axes (Shift: all three alike). In the 3-D view it is a wireframe that moves. Until it is selected its inside is the view's, so a click there is Neuroglancer's.
- Handles. Clicking a shape selects it (one at a time; Escape or a
click on an empty part of a view clears it, and that click still reaches
Neuroglancer). A selected shape shows its handles: its centre moves it in
the view's plane (the section, or the plane facing the camera in 3-D); a
box's corners and face centres resize it along their axes; a sphere's
knobs, one each way along each axis shown, change its radii; a plane's
centre moves it along its normal and its ring turns it (
turns: falsefor one that only moves). Alt+wheel over a selected sphere or box scales it; the arrow keys move it a unit (Shift: ten) while the mouse is over a view and nothing else has the keyboard. A press anywhere else is Neuroglancer's. onChange(value, done)gets each new value:doneis false while the mouse moves and true when it is let go, so a plugin keeps the moves out of undo and writes its state once per drag (as a slider'soninputandonchangedo). The shape follows the mouse by itself;updatewith the value the plugin kept (rounded or clamped) puts it there.- The card is the one panel that floats: at the top left of the view
the shape was selected in, 8 px in from the top and 8 px right of
Neuroglancer's axis labels, only while the shape is selected. Its
heading is the shape's
title(else itslabel: give a point labelled "1" the title "Pair 1"). It holds what the handles do not: exact numbers (shown ones asreadout()s, in rows under the axes' names in aview-card-valuesgrid), choices (AND, OR, NOT), delete. The dock's controls for the same things keep working; both edit the same state. - Links and captions.
caption: { text, value }puts a small label at a shape's top left on screen (the name in the interface's face, the value in the readouts');onClickmakes the shape a link: a click on its line or caption calls it instead of selecting it (witheditable: false, the scale navigator's zoom boxes);minSizeleaves it out of a view where it is fewer pixels across. pick(onPick)turns clicks in the views into points until disposed: a click not on a shape gives the global position under the mouse (Registration's Place pairs).lookingAt()is where the user is looking: the place the mouse was last over in a view while it is still in sight, else the views' centre; a new shape starts there.
In tests, fakeViewTools() from @ngplatform/sdk/testing keeps the shapes a
plugin adds and drags them as a person would (drag(id, value, done),
click(at) for a picker).
Every module of @ngplatform/sdk, with its main exports, is listed in the
SDK reference.
Every panel is built from the same parts, from @ngplatform/sdk/dom, so
plugins keep no private copies of controls or styles. Each part returns an
element to append; the controls also have set(value).
| Part | For |
|---|---|
card(id, title, {open, badge, attention, info}, …children) |
A group of controls: a collapsible card whose open state is kept per browser under id ("myplugin.output"). The first card of a panel is open. |
field(label, control, hint | {hint, info}) |
A label above a control. |
toggle(label, on, onchange, {disabled, hideLabel, info}) |
A switch: turns a feature on (Render, a plugin, a layer's drawing). |
checkbox(label, checked, onchange, {disabled, hideLabel, info}) |
A checkbox: picks items or options. |
slider(value, {min, max, step, unit, label, oninput, onchange, unbounded, disabled}) |
The one slider, its number box beside it, kept in step. oninput follows the drag (a preview); onchange gets the settled value (let go, a key, a typed number). |
select(options, value, onchange, label), numberInput(value, onchange, attrs) |
A select and a number box. |
button(label, onclick, title, cls), iconButton(name, label, onclick), icon(name) |
Buttons (btn with primary, outline or none, and small), and the app's icons by name. |
info(text, label) |
An explanation behind a small (i): shown on click, Enter or Space and on hover, read by screen readers. Use it rather than title, which keyboard and touch cannot reach. |
emptyState(text, {label, run}) |
What a panel shows with nothing to work on: one line and the action that supplies it ("Open data…"). |
statusLine() |
progress(text), error(text, {label, run}) and clear(): progress and errors only, hidden otherwise. |
readout(value, unit, attrs) |
A value shown, not edited (a size, a count, a coordinate, a status line item): Source Code Pro with tabular digits, the unit in the muted grey after a thin space. set(value) or set({value, unit}) shows another. |
region(render, attrs) |
A part drawn again only when its key changes: update(key). |
Shared classes, in the app's stylesheet: row (controls on a line),
stack, grid-2, spacer, muted, faint, hint (a short note),
readout (a caption line of changing numbers or a path), list, empty,
and float-surface (anything that floats over the views or the page
without dimming it, such as a card beside a handle in a view: the overlay
grey, a 1 px line, the one floating shadow).
Colours. A panel's chrome is black and white at the stylesheet's
opacities (--text, --muted, --faint, --line, --line-strong); the
one hue is --err, for errors and what deletes. What is chosen or on is
inverted (--accent fill, --accent-ink words) or outlined in white, never
green. Colour on screen is the data's.
The rules the parts keep:
- A switch turns a feature on; a checkbox picks items or options.
- Icons come from
icon(), never a character (×, ⋯, ▸, ✓) standing in for one; an icon-only button has a name (iconButton()). - A value shown and not edited is a
readout(). - A control has a label (
field(), or the label oftoggle()andcheckbox()). - Explanations go behind an
info(), not in the panel or intitle. - An empty state is one line plus its action.
- A status line reports progress and errors only: no "Ready", nothing the panel already shows.
- At most one primary button per panel.
Update in place. Draw the panel once, and on a change of state bring
it up to date rather than drawing it again: drawing again closes an open
select, ends a drag and loses what is being typed. Keep the controls, call
their set() (it waits while the person types in or drags one), and put
what changes shape (a list, a section for one kind of data) in a region():
ctx.ui.panel("myplugin.panel", (host) => {
const status = statusLine();
const empty = emptyState("No image in this scene.", { label: "Open data…", run: () => void ctx.commands.invoke("dataset.add") });
const exposure = slider(1, { min: 0, max: 5, step: 0.05, label: "Exposure", onchange: (v) => save({ exposure: v }) });
const layers = region((names: string[]) => names.map((n) => el("li", {}, n)), { class: "list" });
host.append(empty, card("myplugin.look", "Look", { open: true }, field("Exposure", exposure), layers), status);
const sync = () => {
const images = ctx.viewer.layers().filter((l) => l.type === "image");
empty.hidden = images.length > 0;
exposure.set(saved().exposure);
layers.update(images.map((l) => l.name));
};
sync();
const offLayers = ctx.viewer.onLayersChanged(sync);
const offState = ctx.state.onChanged(sync);
return () => (offLayers(), offState());
});Tests. @ngplatform/sdk/testing's fakeDocument() is a stand-in
document for Node: draw the panel into dom.host(), act as a person would
(dom.type, dom.check, dom.find(host, "button", "Add one").click())
and read dom.text(host). The starter's
tests have a panel test and a disposal
test to copy.
Settings → Sign-in lists the sign-ins available, with who is signed in, and
buttons to sign in, sign out and check; below them, each layer of the
active scene has a drop-down of the sign-ins its data can be read with.
Built in are Google (one or more accounts for the browser, read as
gs+google://, with rules choosing the account per bucket), middleauth
(the Google sign-in CAVE-style servers use, for middleauth+https:// data,
with its tokens where Neuroglancer keeps them, so either can sign in for the
other) and ngauth (gs+ngauth+https://). A plugin adds another with an
AuthProvider:
ctx.auth.register({
id: "my-lab",
title: "My lab's data",
accepts: (server) => server.startsWith("https://data.my-lab.org"),
async services({ sources, manual }) {
// One service per thing to sign in to, found from the workspace's
// data sources and the servers typed into Settings → Sign-in for this provider.
return [{
id: "my-lab:main",
title: "data.my-lab.org",
async status() { return { state: "signed-out" }; },
async signIn() { /* open the sign-in window first, before any await */ },
async signOut() {},
}];
},
});signIn is called straight from the click, so a window it opens before its
first await is not blocked. Data that a viewer layer already opened keeps
the sign-in it had; Settings › Sign-in offers a reload, which keeps the workspace.
A provider whose sign-in a layer chooses by its source's scheme (as
Neuroglancer chooses credentials) adds sourceSignIns, which the layers'
drop-downs offer. Each says how to turn a plain address (gs://bucket/path
or https://host/path) into one read with it, and back:
sourceSignIns: () => [{
id: "my-lab",
title: "My lab",
storage: "http",
wrap: (plain) => `mylab+${plain}`,
unwrap: (address) => address.match(/^mylab\+(https?:\/\/.*)$/)?.[1],
}],The scheme itself (mylab+https://) is registered with Neuroglancer by a
data type plugin.
The sign-in rules of Settings → Sign-in (an address prefix and a sign-in, kept in
the browser) can name a provider's source sign-in by its id: a layer from
an address a rule covers is given that sign-in when it is added or its
workspace opens, through wrap. Keep ids stable, since rules store them.
Work too large for the page (a whole tractogram filtered into a new file,
a conversion) runs as a Python process on the user's computer, through the
runner (runner/ in this repository; the guide).
The runner offers known job kinds only (convert, filter, density),
reads and writes only under the folders it was started with, and the app
must be paired with it in Settings → Compute. ctx.runner is the plugin's way to
it:
if (!ctx.runner.available()) return; // not paired, or not running
// The file behind a layer the runner serves; else ask the user for it.
const input = (await ctx.runner.pathOf(source)) ?? (await ctx.runner.choose({ title: "The tractogram", mode: "open", find: { name: "tracks.trk" } }));
if (input === undefined) return;
const job = await ctx.runner.start("filter", {
input,
filter: { format: "zvf-predicate", version: 1, tree: { op: "passes", mode: "path", region: { type: "sphere", center: [10, 0, 0], radius: 8 } } },
trk: input.replace(/\.trk$/, "_sphere.trk"),
});
const done = await ctx.runner.wait(job.id, (now) => console.log(now.progress, now.message));
if (done.state === "done") await ctx.runner.open(done.outputs[0].path); // a layer, served by the runner| Call | What |
|---|---|
available(), onChanged(cb) |
Whether a paired runner answers, and a callback when that or its jobs change |
folders() |
The folders the runner may read and write |
jobs() |
Its jobs as last fetched: id, kind, title, args, pid, state (queued, running, done, failed, cancelled), progress (0–1 or null), message, outputs ([{path, type}]) |
start(kind, args) |
Starts a job; rejects with the runner's reason when it refuses the arguments (a path outside its folders, an output that exists) |
wait(id, onProgress?, signal?) |
The job once it has finished |
cancel(id) |
Ends the job's process and what it started |
pathOf(source) |
The path behind a layer source the runner serves |
choose({title, mode, suggested?, find?, note?}) |
A dialog for a path under the runner's folders: one to read ("open", with find looking for a file by name and size first) or a new one to write ("save") |
open(path, {name?}) |
Adds a store, tractogram or NIfTI under the runner's folders to the active scene, served by the runner |
A filter job's filter is zarr-vectors-tools' filter tree, in the
coordinates the viewer shows the input in (Track filtering's
runner_job.ts turns a group into one). The kinds and their arguments are
in runner/README.md.
ctx.runner is the runner on This computer. The app may be paired with
runners on other computers too (a workstation, a cluster node, reached
through an SSH tunnel), and a runner may run services beside it
(--service render=COMMAND), which answer at /svc/<name>/ on it.
ctx.hosts lists them all and reaches their services:
const host = ctx.hosts.pick({ gpu: true, service: "render" }); // a GPU computer first
if (host === undefined) return ctx.ui.toast("No computer with the render service answers", "error");
const response = await host.fetch("render/sessions", { method: "POST", body: JSON.stringify({ layer: "brain" }), headers: { "Content-Type": "application/json" } });
const session = await response.json();
// A long answer streams: response.body is read as it arrives.| Call | What |
|---|---|
list() |
[{name, address, available, info?, error?}]: This computer (when paired) first. info is {hostname, platform, gpus, services}: gpus as nvidia-smi lists them (name, memoryTotal, memoryFree in MiB, ok false for a card that cannot be used), services as {name: {ready, error, pid}} |
onChanged(cb) |
Called when a computer is added or removed, goes up or down (checked every 5 s), or what it reports changes |
get(name) |
A computer by its name ("This computer", "workstation"), or undefined |
pick({gpu?, service?}) |
The first computer that answers with a usable GPU and/or that service ready, a GPU computer before others |
host.fetch(path, init) |
fetch of <address>/svc/<path> with the pairing token; resolves with the Response as it arrives, whatever its status |
host.available(), host.info() |
As in list(), now |
- A plugin's exceptions are logged against it and never reach the shell or Neuroglancer; three in a session stop it until the next load.
- Plugins run in the page with full privileges.
permissionsin the manifest are shown to the user, not enforced. - Plugins that wrap GPL code (NAVis, a Lead-DBS port) are distributed
separately and say so in
license.