@nullplatform/ui-plugin-sdk 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,78 @@
1
+ import "./polyfill.js";
2
+ import type { CanvasInput, CanvasTheme, CanvasTooltip, HostMessage } from "./protocol.js";
3
+ import type { CanvasCursor } from "./catalog.js";
4
+ export type { CanvasInput, CanvasTheme, CanvasTooltip } from "./protocol.js";
5
+ /** What a draw call gets: the size in CSS pixels (the context is already scaled to it) and the host theme. */
6
+ export interface CanvasFrame {
7
+ width: number;
8
+ height: number;
9
+ dpr: number;
10
+ theme: CanvasTheme;
11
+ }
12
+ export interface CanvasOptions {
13
+ /** Draws the whole picture. The context is cleared and scaled to CSS pixels before each call. */
14
+ draw(ctx: OffscreenCanvasRenderingContext2D, frame: CanvasFrame): void;
15
+ /** Pointer, wheel and key input in CSS pixels. Call `invalidate()` on the handle when the picture changes. */
16
+ onInput?(input: CanvasInput, frame: CanvasFrame): void;
17
+ }
18
+ export interface CanvasHandle {
19
+ /** The id to pass to `<Canvas surface>`. */
20
+ readonly surface: string;
21
+ /** The current size and theme, once the host sent them. */
22
+ readonly frame: CanvasFrame | null;
23
+ /** Redraws: right after the input being handled, or on the next task outside one. */
24
+ invalidate(): void;
25
+ /** Asks the host to draw its own tooltip at `x`, `y`, or to clear it with `null`. Anchor it to the item, not the pointer. */
26
+ tooltip(tooltip: CanvasTooltip | null): void;
27
+ }
28
+ /** Whether this worker can draw: OffscreenCanvas with a 2D context (Safari before 16.4 has neither). */
29
+ export declare const canDrawCanvas: boolean;
30
+ /** Called by the worker runtime once it has the host port. */
31
+ export declare function attachCanvasPort(next: MessagePort): void;
32
+ /** Handles the host's canvas messages; the worker runtime routes them here. */
33
+ export declare function receiveCanvas(message: Extract<HostMessage, {
34
+ type: "canvas-size" | "canvas-input";
35
+ }>): void;
36
+ /**
37
+ * A surface to draw on with `<Canvas>`. `draw` runs on every redraw with a cleared context in CSS pixels; `onInput`
38
+ * gets the pointer, wheel and keys. Both may change between renders: the latest ones run.
39
+ */
40
+ export declare function useCanvas(options: CanvasOptions): CanvasHandle;
41
+ export interface CanvasItem {
42
+ id: string;
43
+ label: string;
44
+ description?: string;
45
+ }
46
+ export type CanvasProps = {
47
+ /** The handle from `useCanvas`. */
48
+ canvas: CanvasHandle;
49
+ height?: number;
50
+ /** What the drawing shows, for assistive technology. */
51
+ label: string;
52
+ /** What the drawing contains, as a list for assistive technology, and shown where the worker can't draw. */
53
+ items?: CanvasItem[];
54
+ cursor?: CanvasCursor;
55
+ /** Takes the wheel for zoom instead of scrolling the page. */
56
+ captureWheel?: boolean;
57
+ /** An item activated in that list. */
58
+ onItemPress?: (id: string) => void;
59
+ };
60
+ /**
61
+ * A surface the plugin draws itself. Needs `permissions.canvas` in the manifest; without it, or on a host that
62
+ * predates the element, `hostRenders(Canvas)` is false: draw something else then.
63
+ */
64
+ export declare const Canvas: {
65
+ ({ canvas, ...props }: CanvasProps): import("react").ReactElement<{
66
+ surface: string;
67
+ height?: number;
68
+ label: string;
69
+ items?: CanvasItem[];
70
+ cursor?: CanvasCursor;
71
+ captureWheel?: boolean;
72
+ fallback?: boolean;
73
+ onItemPress?: (id: string) => void;
74
+ } & {
75
+ children?: import("react").ReactNode;
76
+ }, string | import("react").JSXElementConstructor<any>>;
77
+ displayName: string;
78
+ };
package/dist/canvas.js ADDED
@@ -0,0 +1,151 @@
1
+ import "./polyfill.js";
2
+ /**
3
+ * Worker side of np-canvas: the surfaces a plugin draws, each an OffscreenCanvas the host sizes. A plugin draws with
4
+ * Canvas 2D in CSS pixels; each frame leaves as an ImageBitmap, transferred to the host with no copy.
5
+ *
6
+ * Input arrives paced by the host: a pointer move only after the plugin answered the previous one. So the plugin
7
+ * draws right away, inside the input handler, and answers with that frame (or an ack when nothing changed).
8
+ */
9
+ import { createElement, useEffect, useRef, useState } from "react";
10
+ import { component } from "./component.js";
11
+ import { registerTag } from "./host.js";
12
+ /** Whether this worker can draw: OffscreenCanvas with a 2D context (Safari before 16.4 has neither). */
13
+ export const canDrawCanvas = (() => {
14
+ try {
15
+ return typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ })();
21
+ let port = null;
22
+ const surfaces = new Map();
23
+ let counter = 0;
24
+ /** Called by the worker runtime once it has the host port. */
25
+ export function attachCanvasPort(next) {
26
+ port = next;
27
+ }
28
+ function present(surface) {
29
+ const { canvas, ctx, frame } = surface;
30
+ if (!port || !canvas || !ctx || !frame)
31
+ return;
32
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
33
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
34
+ // `transferToImageBitmap` gives the canvas a fresh backing but keeps the context state, transform included.
35
+ ctx.setTransform(frame.dpr, 0, 0, frame.dpr, 0, 0);
36
+ surface.options.current.draw(ctx, frame);
37
+ const bitmap = canvas.transferToImageBitmap();
38
+ port.postMessage({ type: "canvas-frame", surface: surface.id, bitmap, seq: surface.seq }, [bitmap]);
39
+ }
40
+ function invalidate(surface) {
41
+ if (surface.handling) {
42
+ surface.dirty = true;
43
+ return;
44
+ }
45
+ if (surface.scheduled)
46
+ return;
47
+ surface.scheduled = true;
48
+ setTimeout(() => {
49
+ surface.scheduled = false;
50
+ if (surfaces.get(surface.id) === surface)
51
+ present(surface);
52
+ }, 0);
53
+ }
54
+ /** Handles the host's canvas messages; the worker runtime routes them here. */
55
+ export function receiveCanvas(message) {
56
+ const surface = surfaces.get(message.surface);
57
+ if (!surface) {
58
+ // An input for a surface already gone still needs an answer, or the host holds the next one back.
59
+ if (message.type === "canvas-input")
60
+ port?.postMessage({ type: "canvas-ack", surface: message.surface, seq: message.seq });
61
+ return;
62
+ }
63
+ if (message.type === "canvas-size") {
64
+ const { width, height, dpr, theme } = message;
65
+ surface.frame = { width, height, dpr, theme };
66
+ if (!canDrawCanvas)
67
+ return;
68
+ const pixelWidth = Math.max(1, Math.round(width * dpr));
69
+ const pixelHeight = Math.max(1, Math.round(height * dpr));
70
+ if (!surface.canvas) {
71
+ surface.canvas = new OffscreenCanvas(pixelWidth, pixelHeight);
72
+ surface.ctx = surface.canvas.getContext("2d");
73
+ }
74
+ else {
75
+ surface.canvas.width = pixelWidth;
76
+ surface.canvas.height = pixelHeight;
77
+ }
78
+ present(surface);
79
+ return;
80
+ }
81
+ surface.seq = message.seq;
82
+ surface.handling = true;
83
+ surface.dirty = false;
84
+ try {
85
+ if (surface.frame)
86
+ surface.options.current.onInput?.(message.input, surface.frame);
87
+ }
88
+ finally {
89
+ surface.handling = false;
90
+ }
91
+ if (surface.dirty && surface.frame)
92
+ present(surface);
93
+ else
94
+ port?.postMessage({ type: "canvas-ack", surface: surface.id, seq: message.seq });
95
+ surface.dirty = false;
96
+ }
97
+ /**
98
+ * A surface to draw on with `<Canvas>`. `draw` runs on every redraw with a cleared context in CSS pixels; `onInput`
99
+ * gets the pointer, wheel and keys. Both may change between renders: the latest ones run.
100
+ */
101
+ export function useCanvas(options) {
102
+ const latest = useRef(options);
103
+ latest.current = options;
104
+ const [surface] = useState(() => {
105
+ const created = {
106
+ id: `cv-${++counter}`,
107
+ options: latest,
108
+ canvas: null,
109
+ ctx: null,
110
+ frame: null,
111
+ seq: 0,
112
+ dirty: false,
113
+ handling: false,
114
+ scheduled: false,
115
+ lastTooltip: "null",
116
+ };
117
+ // Registered while rendering, not in an effect: the host may answer the element with its size before effects run.
118
+ surfaces.set(created.id, created);
119
+ return created;
120
+ });
121
+ const [handle] = useState(() => ({
122
+ surface: surface.id,
123
+ get frame() {
124
+ return surface.frame;
125
+ },
126
+ invalidate: () => invalidate(surface),
127
+ tooltip(tooltip) {
128
+ const key = JSON.stringify(tooltip);
129
+ // Unchanged tooltips don't cross: a hover sends one per item, not one per pointer move.
130
+ if (key === surface.lastTooltip)
131
+ return;
132
+ surface.lastTooltip = key;
133
+ port?.postMessage({ type: "canvas-overlay", surface: surface.id, tooltip });
134
+ },
135
+ }));
136
+ useEffect(() => {
137
+ surfaces.set(surface.id, surface);
138
+ return () => {
139
+ surfaces.delete(surface.id);
140
+ };
141
+ }, [surface]);
142
+ return handle;
143
+ }
144
+ const RemoteCanvas = component("np-canvas");
145
+ /**
146
+ * A surface the plugin draws itself. Needs `permissions.canvas` in the manifest; without it, or on a host that
147
+ * predates the element, `hostRenders(Canvas)` is false: draw something else then.
148
+ */
149
+ export const Canvas = ({ canvas, ...props }) => createElement(RemoteCanvas, { ...props, surface: canvas.surface, ...(canDrawCanvas ? {} : { fallback: true }) });
150
+ Canvas.displayName = "Canvas";
151
+ registerTag(Canvas, "np-canvas");
package/dist/catalog.d.ts CHANGED
@@ -23,6 +23,7 @@ export interface CatalogElementSpec {
23
23
  /**
24
24
  * Closed lists for string props. The host drops any other value, so the element draws its default. `prop[].key`
25
25
  * names a key of each item in an array prop, which the host drops from an item whose value isn't in the list.
26
+ * `prop[]` names the items of an array of plain values: the host drops each item that isn't in the list.
26
27
  */
27
28
  values?: Readonly<Record<string, readonly string[]>>;
28
29
  /**
@@ -82,6 +83,15 @@ export declare const CATALOG_PROP_VALUES: {
82
83
  readonly Scatter: {
83
84
  readonly xScale: readonly ["linear", "log"];
84
85
  };
86
+ readonly Canvas: {
87
+ readonly cursor: readonly ["default", "pointer", "grab", "grabbing", "crosshair", "move"];
88
+ };
89
+ };
90
+ /** Caps the host holds a canvas element's props to: the catalog only types them. */
91
+ export declare const CANVAS_LIMITS: {
92
+ readonly height: 1600;
93
+ readonly items: 2000;
94
+ readonly label: 200;
85
95
  };
86
96
  /**
87
97
  * Every element a plugin can render: the SDK's own, then the design-system components whose contracts
@@ -104,5 +114,6 @@ export type AlertSeverity = (typeof CATALOG_PROP_VALUES.Alert.severity)[number];
104
114
  export type LinkColor = (typeof CATALOG_PROP_VALUES.Link.color)[number];
105
115
  export type LinkUnderline = (typeof CATALOG_PROP_VALUES.Link.underline)[number];
106
116
  export type ScatterScale = (typeof CATALOG_PROP_VALUES.Scatter.xScale)[number];
117
+ export type CanvasCursor = (typeof CATALOG_PROP_VALUES.Canvas.cursor)[number];
107
118
  /** Name of the wrapper element remote-dom uses for React elements passed as props. */
108
119
  export declare const FRAGMENT_TAG = "remote-fragment";
package/dist/catalog.js CHANGED
@@ -56,7 +56,12 @@ export const CATALOG_PROP_VALUES = {
56
56
  Scatter: {
57
57
  xScale: ["linear", "log"],
58
58
  },
59
+ Canvas: {
60
+ cursor: ["default", "pointer", "grab", "grabbing", "crosshair", "move"],
61
+ },
59
62
  };
63
+ /** Caps the host holds a canvas element's props to: the catalog only types them. */
64
+ export const CANVAS_LIMITS = { height: 1600, items: 2000, label: 200 };
60
65
  /** The elements the SDK defines itself. */
61
66
  const OWN_CATALOG = [
62
67
  {
@@ -402,6 +407,26 @@ const OWN_CATALOG = [
402
407
  values: CATALOG_PROP_VALUES.Scatter,
403
408
  cssValues: ["points[].color"],
404
409
  },
410
+ {
411
+ // A surface the plugin draws itself, with Canvas 2D in its worker, sent to the host as frames. Needs the
412
+ // `permissions.canvas` manifest permission, which the install flow should show: the plugin can paint anything inside
413
+ // its rectangle. `items` lists what it draws for assistive technology (and as the fallback where the worker can't
414
+ // draw); `itemPress` sends the id of the one activated there. Not every host draws it: see `hostRenders`.
415
+ tag: "np-canvas",
416
+ component: "Canvas",
417
+ properties: {
418
+ surface: "string",
419
+ height: "number",
420
+ label: "string",
421
+ items: "array",
422
+ cursor: "string",
423
+ captureWheel: "boolean",
424
+ fallback: "boolean",
425
+ },
426
+ events: { itemPress: "onItemPress" },
427
+ values: CATALOG_PROP_VALUES.Canvas,
428
+ defaults: { height: 360, cursor: "default" },
429
+ },
405
430
  {
406
431
  // Groups as soft circles with their members inside as bubbles, sized by `size`. `groups: [{ id?, label, color?,
407
432
  // nodes: [{ id, label, size? }] }]`; a node may sit in several groups. Not every host draws it: see `hostRenders`.
@@ -444,6 +469,8 @@ const OWN_CATALOG = [
444
469
  disabled: "boolean",
445
470
  },
446
471
  events: { change: "onChange" },
472
+ // Never below an application, whatever a bundle asks for; the host drops any other level.
473
+ values: { "levels[]": ["organization", "account", "namespace", "application"] },
447
474
  },
448
475
  {
449
476
  // Shows one platform resource by its NRN: kind badge, name and, with `showPath`, where it lives
@@ -37,6 +37,11 @@ export interface PluginManifest {
37
37
  api?: ApiPermission[];
38
38
  http?: HttpPermission[];
39
39
  topics?: TopicPermissions;
40
+ /**
41
+ * Draws its own pixels with `Canvas`. Shown at install: inside its rectangle the plugin can paint anything,
42
+ * including something that looks like the host's own UI. It can't read the page or paint outside the rectangle.
43
+ */
44
+ canvas?: boolean;
40
45
  };
41
46
  contributes: Contribution[];
42
47
  }
@@ -100,6 +100,12 @@ export function validateManifest(input) {
100
100
  if (rawPermissions.topics !== undefined) {
101
101
  permissions.topics = readTopicPermissions(rawPermissions.topics, m.id);
102
102
  }
103
+ if (rawPermissions.canvas !== undefined) {
104
+ if (typeof rawPermissions.canvas !== 'boolean')
105
+ throw new ManifestError('permissions.canvas must be true or false');
106
+ if (rawPermissions.canvas)
107
+ permissions.canvas = true;
108
+ }
103
109
  return {
104
110
  protocol: PROTOCOL_VERSION,
105
111
  id: m.id,
@@ -3,8 +3,14 @@ export type WhenQuery = Record<string, unknown>;
3
3
  * Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time.
4
4
  * `locale` and `route` are in the plugin context but are not roots: the platform resolves installations without
5
5
  * knowing either, so a condition on them could only ever hold in developer mode.
6
+ *
7
+ * `scope` holds on pages under a scope (the scope itself, its deployments), where the host resolves for the scope's
8
+ * NRN. Besides its fields a custom scope carries `specification` (`id`, `slug`, `name`): the scope type, so a
9
+ * contribution can target one kind of scope (`"scope.specification.slug": "release"`) in every organization. A
10
+ * built-in scope has none (its `provider` is not a specification): `scope.type` tells those apart. Anywhere else
11
+ * `scope` is `undefined`, so a condition on it does not match.
6
12
  */
7
- export declare const CONTEXT_ROOTS: readonly ["nrn", "organization", "account", "namespace", "application", "user"];
13
+ export declare const CONTEXT_ROOTS: readonly ["nrn", "organization", "account", "namespace", "application", "scope", "user"];
8
14
  export type ContextRoot = (typeof CONTEXT_ROOTS)[number];
9
15
  export declare const WHEN_LIMITS: {
10
16
  readonly depth: 16;
@@ -8,13 +8,19 @@ import sift from 'sift';
8
8
  * Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time.
9
9
  * `locale` and `route` are in the plugin context but are not roots: the platform resolves installations without
10
10
  * knowing either, so a condition on them could only ever hold in developer mode.
11
+ *
12
+ * `scope` holds on pages under a scope (the scope itself, its deployments), where the host resolves for the scope's
13
+ * NRN. Besides its fields a custom scope carries `specification` (`id`, `slug`, `name`): the scope type, so a
14
+ * contribution can target one kind of scope (`"scope.specification.slug": "release"`) in every organization. A
15
+ * built-in scope has none (its `provider` is not a specification): `scope.type` tells those apart. Anywhere else
16
+ * `scope` is `undefined`, so a condition on it does not match.
11
17
  */
12
- export const CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'user'];
18
+ export const CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'scope', 'user'];
13
19
  /**
14
- * In the plugin context, but not usable in a condition yet. Installations resolve for the application's NRN, so the
15
- * platform never loads a scope, a deployment or a build and a condition on any would silently never match.
20
+ * In the plugin context, but not usable in a condition yet. Installations resolve for the application's NRN (or the
21
+ * scope's), so the platform never loads a deployment or a build and a condition on either would silently never match.
16
22
  */
17
- const UNSUPPORTED_ROOTS = new Set(['scope', 'deployment', 'build']);
23
+ const UNSUPPORTED_ROOTS = new Set(['deployment', 'build']);
18
24
  /** Operators that would execute code or are meaningless outside MongoDB. */
19
25
  const ALLOWED_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in', '$nin', '$exists', '$size', '$all', '$elemMatch', '$not', '$and', '$or', '$nor', '$mod']);
20
26
  export const WHEN_LIMITS = { depth: 16, nodes: 512, array: 100, string: 1024 };
@@ -106,6 +106,12 @@ function validateManifest(input) {
106
106
  if (rawPermissions.topics !== undefined) {
107
107
  permissions.topics = readTopicPermissions(rawPermissions.topics, m.id);
108
108
  }
109
+ if (rawPermissions.canvas !== undefined) {
110
+ if (typeof rawPermissions.canvas !== 'boolean')
111
+ throw new ManifestError('permissions.canvas must be true or false');
112
+ if (rawPermissions.canvas)
113
+ permissions.canvas = true;
114
+ }
109
115
  return {
110
116
  protocol: exports.PROTOCOL_VERSION,
111
117
  id: m.id,
@@ -18,13 +18,19 @@ const sift_1 = __importDefault(require("sift"));
18
18
  * Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time.
19
19
  * `locale` and `route` are in the plugin context but are not roots: the platform resolves installations without
20
20
  * knowing either, so a condition on them could only ever hold in developer mode.
21
+ *
22
+ * `scope` holds on pages under a scope (the scope itself, its deployments), where the host resolves for the scope's
23
+ * NRN. Besides its fields a custom scope carries `specification` (`id`, `slug`, `name`): the scope type, so a
24
+ * contribution can target one kind of scope (`"scope.specification.slug": "release"`) in every organization. A
25
+ * built-in scope has none (its `provider` is not a specification): `scope.type` tells those apart. Anywhere else
26
+ * `scope` is `undefined`, so a condition on it does not match.
21
27
  */
22
- exports.CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'user'];
28
+ exports.CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'scope', 'user'];
23
29
  /**
24
- * In the plugin context, but not usable in a condition yet. Installations resolve for the application's NRN, so the
25
- * platform never loads a scope, a deployment or a build and a condition on any would silently never match.
30
+ * In the plugin context, but not usable in a condition yet. Installations resolve for the application's NRN (or the
31
+ * scope's), so the platform never loads a deployment or a build and a condition on either would silently never match.
26
32
  */
27
- const UNSUPPORTED_ROOTS = new Set(['scope', 'deployment', 'build']);
33
+ const UNSUPPORTED_ROOTS = new Set(['deployment', 'build']);
28
34
  /** Operators that would execute code or are meaningless outside MongoDB. */
29
35
  const ALLOWED_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in', '$nin', '$exists', '$size', '$all', '$elemMatch', '$not', '$and', '$or', '$nor', '$mod']);
30
36
  exports.WHEN_LIMITS = { depth: 16, nodes: 512, array: 100, string: 1024 };
package/dist/index.d.ts CHANGED
@@ -5,5 +5,6 @@ export { nullplatform, type NullplatformBridge } from './bridge.js';
5
5
  export { useTopic, useSetTopic, type UseTopicOptions, type UseTopicResult, type UseSetTopicOptions, type SetTopicState, type TopicMap, type ServiceDraftV1, } from './topics.js';
6
6
  export * from './components.js';
7
7
  export { hostRenders } from './host.js';
8
+ export { Canvas, useCanvas, canDrawCanvas, type CanvasProps, type CanvasHandle, type CanvasOptions, type CanvasFrame, type CanvasItem, type CanvasInput, type CanvasTheme, type CanvasTooltip, } from './canvas.js';
8
9
  export type { PluginContext, ApiRequest, HttpRequest, HttpResponse, NavigationTarget, SnackbarOptions, ConfirmOptions, TopicSnapshot, TopicStatus } from './protocol.js';
9
10
  export { BridgeError } from './protocol.js';
package/dist/index.js CHANGED
@@ -5,4 +5,5 @@ export { nullplatform } from './bridge.js';
5
5
  export { useTopic, useSetTopic, } from './topics.js';
6
6
  export * from './components.js';
7
7
  export { hostRenders } from './host.js';
8
+ export { Canvas, useCanvas, canDrawCanvas, } from './canvas.js';
8
9
  export { BridgeError } from './protocol.js';
@@ -35,11 +35,19 @@ export interface PluginContext {
35
35
  slug?: string;
36
36
  name?: string;
37
37
  };
38
- /** Set on scope pages. Not usable in `when` yet (see `CONTEXT_ROOTS`). */
38
+ /**
39
+ * Set on pages under a scope (the scope, its deployments). `specification` is the scope type, the same a `when`
40
+ * reads as `scope.specification.*` (see `CONTEXT_ROOTS`); a host that does not know it leaves it out.
41
+ */
39
42
  scope?: {
40
43
  id: number | string;
41
44
  slug?: string;
42
45
  name?: string;
46
+ specification?: {
47
+ id: string;
48
+ slug?: string;
49
+ name?: string;
50
+ };
43
51
  };
44
52
  /** Set on deployment pages. Not usable in `when` yet (see `CONTEXT_ROOTS`). */
45
53
  deployment?: {
@@ -150,11 +158,81 @@ export interface TopicSnapshot<T = unknown> {
150
158
  /** Increases on every change, so a late reply never overwrites a newer value. */
151
159
  rev: number;
152
160
  }
161
+ /** The host theme as a canvas draws it: resolved colors, so the plugin never reads the host's styles. */
162
+ export interface CanvasTheme {
163
+ mode: 'light' | 'dark';
164
+ /** The page and the card the canvas sits on. */
165
+ background: string;
166
+ surface: string;
167
+ text: string;
168
+ textSecondary: string;
169
+ divider: string;
170
+ primary: string;
171
+ success: string;
172
+ warning: string;
173
+ error: string;
174
+ /** Categorical colors for groups that aren't states, in order. */
175
+ palette: string[];
176
+ fontFamily: string;
177
+ }
178
+ interface CanvasModifiers {
179
+ shift: boolean;
180
+ alt: boolean;
181
+ ctrl: boolean;
182
+ meta: boolean;
183
+ }
184
+ /** Input on a canvas, in CSS pixels from its top left corner. */
185
+ export type CanvasInput = ({
186
+ kind: 'down' | 'move' | 'up' | 'leave';
187
+ x: number;
188
+ y: number;
189
+ button: number;
190
+ buttons: number;
191
+ } & CanvasModifiers) | ({
192
+ kind: 'wheel';
193
+ x: number;
194
+ y: number;
195
+ dx: number;
196
+ dy: number;
197
+ } & CanvasModifiers) | ({
198
+ kind: 'key';
199
+ key: string;
200
+ } & CanvasModifiers);
201
+ /** A tooltip the host draws over the canvas with its own components, anchored at `x`, `y` (CSS pixels). */
202
+ export interface CanvasTooltip {
203
+ x: number;
204
+ y: number;
205
+ title: string;
206
+ rows?: Array<{
207
+ label: string;
208
+ value: string;
209
+ }>;
210
+ }
153
211
  export type WorkerMessage = {
154
212
  type: 'ready';
155
213
  protocol: number;
156
214
  pluginId: string;
157
215
  widgets: string[];
216
+ }
217
+ /**
218
+ * A drawn frame for a canvas surface, transferred rather than cloned. `seq` is the last input the plugin had
219
+ * handled when it drew, which is how the host paces the pointer moves it sends.
220
+ */
221
+ | {
222
+ type: 'canvas-frame';
223
+ surface: string;
224
+ bitmap: ImageBitmap;
225
+ seq: number;
226
+ }
227
+ /** The plugin handled input `seq` without drawing. */
228
+ | {
229
+ type: 'canvas-ack';
230
+ surface: string;
231
+ seq: number;
232
+ } | {
233
+ type: 'canvas-overlay';
234
+ surface: string;
235
+ tooltip: CanvasTooltip | null;
158
236
  } | {
159
237
  type: 'mutate';
160
238
  mountId: string;
@@ -216,6 +294,20 @@ export type HostMessage =
216
294
  } | {
217
295
  type: 'topic';
218
296
  snapshot: TopicSnapshot;
297
+ }
298
+ /** The surface's size in CSS pixels, the device pixel ratio to draw at and the theme; sent again on every change. */
299
+ | {
300
+ type: 'canvas-size';
301
+ surface: string;
302
+ width: number;
303
+ height: number;
304
+ dpr: number;
305
+ theme: CanvasTheme;
306
+ } | {
307
+ type: 'canvas-input';
308
+ surface: string;
309
+ seq: number;
310
+ input: CanvasInput;
219
311
  };
220
312
  export interface SerializedError {
221
313
  message: string;
@@ -250,3 +342,4 @@ export declare function createIdGenerator(prefix: string): () => string;
250
342
  export declare function assertWireValue(value: unknown): void;
251
343
  /** Deadline also covers custom adapters/loaders that ignore cancellation. */
252
344
  export declare function withDeadline<T>(promise: Promise<T>, timeoutMs?: number, signal?: AbortSignal): Promise<T>;
345
+ export {};
package/dist/worker.js CHANGED
@@ -11,6 +11,7 @@ import { bridge } from './bridge.js';
11
11
  import { PluginContextProvider, broadcastContext } from './context.js';
12
12
  import { setHostElements } from './host.js';
13
13
  import { receiveTopic } from './topics.js';
14
+ import { attachCanvasPort, receiveCanvas } from './canvas.js';
14
15
  import { PROTOCOL_VERSION, createIdGenerator, serializeError, serializeFunctions, } from './protocol.js';
15
16
  const nextFunctionId = createIdGenerator('fn');
16
17
  const mounts = new Map();
@@ -113,6 +114,10 @@ function handle(port, message) {
113
114
  case 'topic':
114
115
  receiveTopic(message.snapshot);
115
116
  break;
117
+ case 'canvas-size':
118
+ case 'canvas-input':
119
+ receiveCanvas(message);
120
+ break;
116
121
  default:
117
122
  break;
118
123
  }
@@ -125,6 +130,7 @@ function handle(port, message) {
125
130
  /** Connects this worker to the host through the port handed over by the sandbox. */
126
131
  export function connect(port) {
127
132
  bridge.attach(port);
133
+ attachCanvasPort(port);
128
134
  globalThis.addEventListener('unhandledrejection', (event) => {
129
135
  port.postMessage({ type: 'error', error: serializeError(event.reason) });
130
136
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullplatform/ui-plugin-sdk",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "SDK for nullplatform UI plugins: catalog components, bridge client and defineUI",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",