Plugins - Development


Writing a Plugin is a loop of editing, testing and uploading. The starter kit below shortens that loop: it is a working Plugin you can run on your own machine with no upload, and a command to upload it when it is ready.

This article will cover setting up the starter kit, the parts of a Plugin's lifecycle that most often go wrong, how to test a Plugin locally, and how to upload it and see the change in Navigator. You can read about what a Plugin is handed in Plugins.

Starter kit

The starter kit is a Selection panel. It shows how many Entities are selected, looks up their names through the API, and has a button to clear the selection. It is built with the UI toolkit and runs both as a side bar Plugin and in the cursor bar.

Download starter kit

plugin/
    index.js            The Plugin. Navigator calls Run(params) when it opens.
    plugin-ui.min.js    The UI toolkit, loaded by index.js at runtime.
types/
    plugin-ui.d.ts      Types for the toolkit, so your editor can suggest its calls.
test/
    run.mjs             Runs the Plugin in a headless browser with no upload.
scripts/
    deploy.mjs          Zips plugin/ and uploads it to your Plugin record.
config.example.json     Copy to config.json and fill in your account details.

Only the plugin folder is uploaded. Everything in it is served from your account, so keep notes, tests and build files outside it.

Setting up

The kit needs Node.js 20 or newer. Install its packages and the browser the tests run in:

npm install
npx playwright install chromium

The bruce-models, bruce-cesium and cesium packages are the libraries Navigator hands your Plugin. They are installed for your editor and for the test host, not bundled into the Plugin. The typedefs at the top of index.js point at them, so your editor can suggest the params and you can ctrl + click a type such as import("bruce-cesium").VisualsRegister.Register to read its definition.

Disposing what you add

Run returns a function, and Navigator calls it when the Plugin closes. Navigator removes the Plugin's element itself. Everything else the Plugin added is its own to remove: event subscriptions, timers, viewer entities, Menu Items and anything appended outside its element.

A Plugin that skips this keeps working until it is opened a second time, when two copies react to every event. Navigator also disposes and reruns a side bar Plugin when the Project View changes, so the same leak appears without the user closing anything.

function Run(params) {
    const { viewer, visualRegister } = params.pluginParams;

    const marker = viewer.entities.add({
        position: params.pluginParams.Cesium.Cartesian3.fromDegrees(174.76, -36.85),
        point: { pixelSize: 10 }
    });
    const unsubscribe = visualRegister.OnUpdate.Subscribe(() => {
        // React to the scene.
    });
    const timer = setInterval(() => {
        // Poll something.
    }, 5000);

    return () => {
        clearInterval(timer);
        unsubscribe();
        viewer.entities.remove(marker);
    };
}

Building after an async load

Run has to return its dispose function straight away, but a Plugin often has to wait for something before it can draw: a library it ships in its ZIP, or a first API request. Return the dispose function first and let it close over whatever the load produces. Navigator can close the Plugin before the load finishes, so check for that before building.

function Run(params) {
    let dispose = null;
    let closed = false;

    loadSomething().then((thing) => {
        if (closed) {
            return;
        }
        dispose = build(thing, params);
    }).catch((e) => {
        // Always log as well as display, or a failure reads as an empty panel.
        console.error("[my-plugin] could not build the panel", e);
        params.element.textContent = "Could not load the panel: " + e.message;
    });

    return () => {
        closed = true;
        if (dispose) {
            dispose();
        }
    };
}

Following the selection

No location is handed the selected Entity. Read the selection from the visual register and subscribe to its updates. The register reports every visual change in the scene, so filter for selection changes, and drop an answer that arrives after a newer selection.

const { visualRegister: register, BEngine, BModels, getters } = params.pluginParams;
const api = getters.GetBruceApi();
const DESELECT_ALL = BEngine.VisualsRegister.EVisualUpdateType.DeselectAll;

// Increases with every selection, so a slow answer for an older one is dropped.
let generation = 0;

async function onSelectionChange() {
    const ids = register.GetSelected();
    const mine = ++generation;
    const names = await Promise.all(ids.map((entityId) => {
        return BModels.Entity.CalculateNameAsync({ api, entityId });
    }));
    if (mine !== generation) {
        return;
    }
    console.log("Selected", names);
}

const unsubscribe = register.OnUpdate.Subscribe((update) => {
    if (update.selected != null || update.type === DESELECT_ALL) {
        onSelectionChange();
    }
});
onSelectionChange();

Running in more than one location

Each location passes its own set of params, so a Plugin written for the side bar most often fails in the cursor bar, which is not handed "view" or the cursor calls. Check for a param before using it. You can read the full list in Params by location.

The container differs as well. A side bar Plugin is drawn into a panel of its own, while a cursor bar or background Plugin is drawn over the viewer. The starter kit checks its location and puts its panel in a floating box when it is not in the side bar:

const inPanel = params.plugin.Location === "NAVIGATOR_SIDE_BAR";
const parent = inPanel ? null : ui.addDock(null, { anchor: "top-left", width: 280 }).body;

The starter kit as a side bar Plugin

As a side bar Plugin.

The starter kit in the cursor bar

In the cursor bar, in a box over the viewer.

Both screenshots are from the starter kit's own test run, which has no account, so the names read as unavailable.

Testing without uploading

The starter kit includes a small stand-in for Navigator. It loads your Plugin the same way Navigator does, through bruce-models, and passes each location its own params.

npm test

This runs the Plugin as a side bar Plugin and in the cursor bar. For each it:

  1. Mounts the Plugin and checks it drew something.
  2. Selects two Entities and takes a screenshot.
  3. Clicks every button and input the Plugin drew, one at a time, and reports any error that follows.
  4. Closes the Plugin and reports anything it left behind: nodes, stylesheets, viewer entities, data sources or primitives.
PASS sidebar
FAIL cursorbar
  left behind after dispose: 24 nodes, starting div[data-ui=dock] in VIEWER_CONTENT, ...
  left behind after dispose: styleSheets was 3, now 5
Screenshots and reports are in out/test/

Above is a run where the dispose function was left out. Screenshots and a JSON report per location are written to "out/test". The report also lists every call the Plugin made back to Navigator, such as "select" or "setPanelWidth", which is often the quickest way to check behaviour without reading screenshots.

Without a config.json the test runs offline and every API request the Plugin makes fails. These are listed in the output but do not fail the run. With a config.json, requests go to your account using its session.

npm test -- --location sidebar        # Only one location: sidebar, cursorbar or background.
npm test -- --select id1,id2          # Entity IDs to select instead of the demo ones.
npm test -- --settings settings.json  # The Plugin record's Settings.
npm test -- --plugin ../other-plugin  # Test a different plugin folder.
npm test -- --headed                  # Show the browser window.
npm test -- --offline                 # Ignore config.json.

The test host draws no Project View, so test anything that depends on the scene, such as Menu Items or tilesets, in Navigator itself.

Uploading

Create the Plugin record first, in Navigator's Plugins menu or in Operator. Pick its location, note its ID, and enable it on the Project View you will test in. Then copy config.example.json to config.json:

{
    "env": "PROD",
    "accountId": "your-account-id",
    "pluginId": "your-plugin-id",
    "sessionId": "your-session-id"
}

The session needs permission to edit Plugins. Then upload:

npm run deploy

This zips the plugin folder and uploads it, replacing the Plugin's code. Each upload increases the Plugin's Version. To upload through Navigator's Plugins menu or Operator instead, run npm run zip and use out/plugin.zip. The ZIP must have index.js at its root.

An upload replaces the previous code and the API keeps no history, so keep your own copy of anything you have uploaded. The Plugins menu can download the current ZIP.

Caching while you develop

A Plugin's code is cached against its Version. That is right for users and awkward while iterating, because a browser that already holds a version keeps serving it.

Turn on "Disable plugin cache" in Navigator's Plugins menu while you develop. It is stored on your own user, and with it on every Plugin apart from background ones fetches its code again each time it opens, so you can reopen the Plugin to see an upload without reloading the page. Leave it off in normal use, since it costs a request per Plugin per load.

Two things are not covered by it. Background Plugins are always cached, so reload the page to see a new upload of one. The Plugin record itself, including its Settings, is also kept for the session, so reload the page after editing Settings.

When something is wrong

  • The Plugin does nothing: check it is enabled on the Project View, that "Enabled" is set on its record, and that its location is the one you are looking in. You can read about this in Enabling a Plugin.
  • The old code still runs: turn on "Disable plugin cache", or reload the page for a background Plugin.
  • It works in one location and throws in another: the location lacks a param the Plugin uses. Run npm test, which tries both.
  • The user is told they do not have access: the Plugin is restricted and they have not been granted it. Unless the Plugin itself must be hidden, turn the restriction off and rely on Project View and Entity Type access control instead.
  • One background Plugin stops the others loading: a background Plugin that throws inside Run stops the ones after it, so catch errors inside Run.
  • Something fails with no message: open the browser's devtools console, where errors thrown inside a Plugin are logged.