@foxglove/embed 0.1.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.
Files changed (40) hide show
  1. package/README.md +9 -0
  2. package/dist/cjs/FoxgloveViewer.d.ts +67 -0
  3. package/dist/cjs/FoxgloveViewer.d.ts.map +1 -0
  4. package/dist/cjs/FoxgloveViewer.js +246 -0
  5. package/dist/cjs/FoxgloveViewer.js.map +1 -0
  6. package/dist/cjs/commands.d.ts +32 -0
  7. package/dist/cjs/commands.d.ts.map +1 -0
  8. package/dist/cjs/commands.js +3 -0
  9. package/dist/cjs/commands.js.map +1 -0
  10. package/dist/cjs/index.d.ts +3 -0
  11. package/dist/cjs/index.d.ts.map +1 -0
  12. package/dist/cjs/index.js +7 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/types.d.ts +27 -0
  15. package/dist/cjs/types.d.ts.map +1 -0
  16. package/dist/cjs/types.js +3 -0
  17. package/dist/cjs/types.js.map +1 -0
  18. package/dist/esm/FoxgloveViewer.d.ts +67 -0
  19. package/dist/esm/FoxgloveViewer.d.ts.map +1 -0
  20. package/dist/esm/FoxgloveViewer.js +242 -0
  21. package/dist/esm/FoxgloveViewer.js.map +1 -0
  22. package/dist/esm/commands.d.ts +32 -0
  23. package/dist/esm/commands.d.ts.map +1 -0
  24. package/dist/esm/commands.js +2 -0
  25. package/dist/esm/commands.js.map +1 -0
  26. package/dist/esm/index.d.ts +3 -0
  27. package/dist/esm/index.d.ts.map +1 -0
  28. package/dist/esm/index.js +4 -0
  29. package/dist/esm/index.js.map +1 -0
  30. package/dist/esm/types.d.ts +27 -0
  31. package/dist/esm/types.d.ts.map +1 -0
  32. package/dist/esm/types.js +2 -0
  33. package/dist/esm/types.js.map +1 -0
  34. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  35. package/dist/tsconfig.tsbuildinfo +1 -0
  36. package/package.json +29 -0
  37. package/src/FoxgloveViewer.ts +357 -0
  38. package/src/commands.ts +44 -0
  39. package/src/index.ts +3 -0
  40. package/src/types.ts +33 -0
@@ -0,0 +1,357 @@
1
+ // foxglove-depcheck-used: tslib
2
+
3
+ import type {
4
+ IframeCommand,
5
+ IframeEvent,
6
+ IframeSetDatasourceCommand,
7
+ IframeSetLayoutCommand,
8
+ IframeInstallExtensionCommand,
9
+ IframeHandshakeAckCommand,
10
+ } from "./commands";
11
+ import type {
12
+ DataSource,
13
+ OpaqueLayoutData,
14
+ FoxgloveViewerEventMap,
15
+ FoxgloveViewerEventType,
16
+ LiveSourceProtocol,
17
+ } from "./types";
18
+
19
+ interface FoxgloveEventTarget extends EventTarget {
20
+ // Override the addEventListener method to add type safety.
21
+ addEventListener<K extends keyof FoxgloveViewerEventMap>(
22
+ type: K,
23
+ listener: (ev: FoxgloveViewerEventMap[K]) => void,
24
+ options?: boolean | AddEventListenerOptions,
25
+ ): void;
26
+ // Override the removeEventListener method to add type safety.
27
+ removeEventListener<K extends keyof FoxgloveViewerEventMap>(
28
+ type: K,
29
+ listener: (ev: FoxgloveViewerEventMap[K]) => void,
30
+ options?: boolean | EventListenerOptions,
31
+ ): void;
32
+ }
33
+
34
+ /**
35
+ * Strongly typed EventTarget.
36
+ */
37
+ const TypedEventTarget = EventTarget as unknown as new () => FoxgloveEventTarget;
38
+
39
+ const DEFAULT_SERVER = "https://embed.foxglove.dev/";
40
+
41
+ export type FoxgloveViewerOptions = {
42
+ /** The parent element to append the iframe to. This is required if `iframe` is not provided. */
43
+ parent: HTMLElement;
44
+ /** The URL where the Foxglove app is hosted. Defaults to `https://embed.foxglove.dev/`. */
45
+ src?: string;
46
+ /**
47
+ * The Foxglove organization the user should be signed into. Passing this parameter is
48
+ * recommended so the user can be prompted to switch to the correct org if necessary.
49
+ */
50
+ orgSlug: string | undefined;
51
+ /** The initial data source to set when the frame is ready. */
52
+ initialDataSource?: DataSource;
53
+ /** The initial layout to set when the frame is ready. */
54
+ initialLayout?: OpaqueLayoutData;
55
+ /**
56
+ * The initial extensions to install when the frame is ready.
57
+ * This parameter is not supported by all Foxglove versions and plans, so it may result in an `error` event.
58
+ * */
59
+ initialExtensions?: Array<string | File>;
60
+ /**
61
+ * If set, forces the frame to use a specific color scheme. When set to "auto" (the default), the
62
+ * system color scheme is used.
63
+ */
64
+ colorScheme?: "light" | "dark" | "auto";
65
+ };
66
+
67
+ const SUPPORTED_CONNECTION_DATA_SOURCE_FILE_TYPES = [".bag", ".mcap"];
68
+
69
+ /**
70
+ * A class that manages an iframe that contains the Foxglove app.
71
+ */
72
+ export class FoxgloveViewer extends TypedEventTarget {
73
+ /** The iframe element that contains the Foxglove app. */
74
+ #iframe: HTMLIFrameElement;
75
+ /** The URL where the Foxglove app is hosted. */
76
+ #server: URL;
77
+ #orgSlug: string | undefined;
78
+ /** Whether the frame is ready to receive commands. */
79
+ #isReady = false;
80
+ /** Latest commands that have been queued to be executed when the frame is ready. */
81
+ #latestCommands: {
82
+ dataSource: IframeSetDatasourceCommand | undefined;
83
+ layout: IframeSetLayoutCommand | undefined;
84
+ extension: Array<IframeInstallExtensionCommand>;
85
+ } = {
86
+ dataSource: undefined,
87
+ layout: undefined,
88
+ extension: [],
89
+ };
90
+ /** Whether the frame has been destroyed. */
91
+ #isDestroyed = false;
92
+
93
+ public constructor(options: FoxgloveViewerOptions) {
94
+ super();
95
+ const {
96
+ parent,
97
+ src,
98
+ orgSlug,
99
+ initialDataSource,
100
+ initialLayout,
101
+ initialExtensions,
102
+ colorScheme = "auto",
103
+ } = options;
104
+
105
+ this.#orgSlug = orgSlug;
106
+
107
+ const srcUrl = src ?? DEFAULT_SERVER;
108
+
109
+ // Validate the server URL.
110
+ try {
111
+ this.#server = new URL(srcUrl);
112
+ } catch {
113
+ throw new Error(`[FoxgloveViewer] Invalid server URL: ${srcUrl}`);
114
+ }
115
+
116
+ // Register event listener for messages from the iframe.
117
+ window.addEventListener("message", this.#handleMessage);
118
+
119
+ if (initialDataSource) {
120
+ this.setDataSource(initialDataSource);
121
+ }
122
+
123
+ if (initialLayout != undefined) {
124
+ this.setLayoutData(initialLayout);
125
+ }
126
+
127
+ if (initialExtensions) {
128
+ this.installExtensions(initialExtensions);
129
+ }
130
+
131
+ // Create the iframe element.
132
+ this.#iframe = document.createElement("iframe");
133
+ this.#iframe.src = srcUrl;
134
+ this.#iframe.title = "Foxglove";
135
+ this.#iframe.allow = "cross-origin-isolated";
136
+ this.#iframe.style.width = "100%";
137
+ this.#iframe.style.height = "100%";
138
+ this.#iframe.style.border = "none";
139
+
140
+ this.setColorScheme(colorScheme);
141
+ parent.appendChild(this.#iframe);
142
+ }
143
+
144
+ /** Set the data source of the Foxglove app. */
145
+ public setDataSource(dataSource: DataSource): void {
146
+ if (dataSource.type === "live") {
147
+ const error = this.#validateLiveSourceUrl(dataSource.protocol, dataSource.url);
148
+ if (error) {
149
+ throw new Error(`[FoxgloveViewer] Error setting data source: ${error}`);
150
+ }
151
+ }
152
+
153
+ this.#queueCommand({
154
+ type: "set-data-source",
155
+ payload: dataSource,
156
+ });
157
+ }
158
+
159
+ /**
160
+ * Set the layout of the embedded viewer. The layout data should be a JSON file that was exported
161
+ * from the Foxglove app.
162
+ */
163
+ public setLayoutData(layout: OpaqueLayoutData): void {
164
+ this.#queueCommand({
165
+ type: "set-layout",
166
+ payload: layout,
167
+ });
168
+ }
169
+
170
+ /**
171
+ * Install a collection of extensions in the Foxglove app.
172
+ * `extensions` is an array of `.foxe` file handles and/or URLs to a `.foxe` files.
173
+ *
174
+ * This method is not supported by all Foxglove versions and plans, so it may result in an `error` event.
175
+ */
176
+ public installExtensions(extensions: Array<string | File>): void {
177
+ const invalidExtension = extensions.find((ext) => this.#validateExtension(ext));
178
+ if (invalidExtension != undefined) {
179
+ throw new Error(
180
+ `[FoxgloveViewer] Error installing extension: ${this.#validateExtension(invalidExtension)}`,
181
+ );
182
+ }
183
+
184
+ this.#queueCommand({
185
+ type: "install-extension",
186
+ payload: extensions,
187
+ });
188
+ }
189
+
190
+ /** Whether the frame is ready to receive commands. */
191
+ public isReady(): boolean {
192
+ return this.#isReady;
193
+ }
194
+
195
+ /** Destroy the frame. This will remove the iframe from the DOM and stop listening for messages. */
196
+ public destroy(): void {
197
+ this.#isDestroyed = true;
198
+ this.#iframe.remove();
199
+ window.removeEventListener("message", this.#handleMessage);
200
+ }
201
+
202
+ /** Whether the frame has been destroyed. */
203
+ public isDestroyed(): boolean {
204
+ return this.#isDestroyed;
205
+ }
206
+
207
+ /**
208
+ * Change the color scheme used by the frame. When set to "auto", the system color scheme is used.
209
+ */
210
+ public setColorScheme(colorScheme: "light" | "dark" | "auto"): void {
211
+ this.#iframe.style.colorScheme = colorScheme === "auto" ? "normal" : colorScheme;
212
+ }
213
+
214
+ /**
215
+ * Queue a command to be executed when the frame is ready.
216
+ *
217
+ * Commands that are not `IframeHandshakeAckCommand` will be queued and executed when the frame is ready.
218
+ * `IframeHandshakeAckCommand` commands will be posted as a response to the `HandshakeRequest` event.
219
+ */
220
+ #queueCommand(command: Exclude<IframeCommand, IframeHandshakeAckCommand>): void {
221
+ if (command.type === "install-extension") {
222
+ this.#latestCommands.extension.push(command);
223
+ } else if (command.type === "set-data-source") {
224
+ this.#latestCommands.dataSource = command;
225
+ } else {
226
+ this.#latestCommands.layout = command;
227
+ }
228
+
229
+ if (this.#isReady) {
230
+ this.#postCommand(command);
231
+ }
232
+ }
233
+
234
+ /** Post a command message to the Foxglove app. */
235
+ #postCommand(message: IframeCommand): void {
236
+ if (this.#isDestroyed) {
237
+ console.warn("[FoxgloveViewer] Unable to post command. Frame has been destroyed.");
238
+ return;
239
+ }
240
+
241
+ assert(this.#iframe.contentWindow, "Invariant: iframe should be loaded.");
242
+
243
+ this.#iframe.contentWindow.postMessage(message, this.#server.href);
244
+ }
245
+
246
+ /** Validate a URL for a connection data source. */
247
+ #validateLiveSourceUrl(protocol: LiveSourceProtocol, value: string): string | undefined {
248
+ switch (protocol) {
249
+ case "foxglove-websocket":
250
+ case "rosbridge-websocket":
251
+ if (!value.startsWith("ws://") && !value.startsWith("wss://")) {
252
+ return "Invalid URL. The URL must start with ws:// or wss://.";
253
+ }
254
+ return undefined;
255
+ case "remote-file":
256
+ try {
257
+ const extension = value.split(".").pop();
258
+
259
+ if (!extension || extension.length === 0) {
260
+ return "Invalid URL. The URL must end with a filename and extension.";
261
+ }
262
+
263
+ if (!SUPPORTED_CONNECTION_DATA_SOURCE_FILE_TYPES.includes(extension)) {
264
+ const supportedExtensions = new Intl.ListFormat("en-US", { style: "long" }).format(
265
+ SUPPORTED_CONNECTION_DATA_SOURCE_FILE_TYPES,
266
+ );
267
+ return `Invalid URL. Only ${supportedExtensions} files are supported.`;
268
+ }
269
+
270
+ return undefined;
271
+ } catch (e) {
272
+ return "Invalid URL.";
273
+ }
274
+ }
275
+ }
276
+
277
+ /** Validate an extension. */
278
+ #validateExtension(extensionData: string | File): string | undefined {
279
+ if (typeof extensionData === "string") {
280
+ const extension = extensionData.split(".").pop();
281
+
282
+ if (!extension || extension.length === 0) {
283
+ return "Invalid URL. The URL must end with a filename and extension.";
284
+ }
285
+
286
+ if (extension !== "foxe") {
287
+ return "Invalid extension. The extension must be a .foxe file.";
288
+ }
289
+ } else {
290
+ const extension = extensionData.name.split(".").pop();
291
+
292
+ if (!extension || extension.length === 0 || extension !== "foxe") {
293
+ return "Invalid extension. The extension must be a .foxe file.";
294
+ }
295
+ }
296
+
297
+ return undefined;
298
+ }
299
+
300
+ /** Handle a message from the Foxglove app. */
301
+ #handleMessage = (message: MessageEvent<IframeEvent>): void => {
302
+ const originUrl = new URL(message.origin);
303
+ if (message.source !== this.#iframe.contentWindow || originUrl.href !== this.#server.href) {
304
+ // Ignore messages from other sources.
305
+ return;
306
+ }
307
+
308
+ if (this.#isDestroyed) {
309
+ console.warn("[FoxgloveViewer] Unable to handle message. Frame has been destroyed.");
310
+ return;
311
+ }
312
+
313
+ switch (message.data.type) {
314
+ case "foxglove-handshake-request": {
315
+ this.#isReady = true;
316
+
317
+ this.#postCommand({
318
+ type: "handshake-ack",
319
+ payload: {
320
+ orgSlug: this.#orgSlug,
321
+ initialDataSource: this.#latestCommands.dataSource?.payload,
322
+ initialLayout: this.#latestCommands.layout?.payload,
323
+ initialExtensions: this.#latestCommands.extension.flatMap((command) => command.payload),
324
+ },
325
+ });
326
+
327
+ break;
328
+ }
329
+ case "foxglove-handshake-complete": {
330
+ this.dispatchEvent(new Event("ready" satisfies FoxgloveViewerEventType));
331
+ break;
332
+ }
333
+ case "foxglove-error": {
334
+ this.dispatchEvent(
335
+ new CustomEvent("error" satisfies FoxgloveViewerEventType, {
336
+ detail: message.data.payload,
337
+ }),
338
+ );
339
+ break;
340
+ }
341
+ default: {
342
+ console.warn("[FoxgloveViewer] Unhandled message type:", message.data);
343
+ break;
344
+ }
345
+ }
346
+ };
347
+ }
348
+
349
+ function assert(
350
+ condition: unknown,
351
+ message: string = "no additional info provided",
352
+ ): asserts condition {
353
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
354
+ if (!condition) {
355
+ throw new Error("Assertion Error: " + message);
356
+ }
357
+ }
@@ -0,0 +1,44 @@
1
+ import type { DataSource, OpaqueLayoutData } from "./types";
2
+
3
+ export type IframeSetDatasourceCommand = {
4
+ type: "set-data-source";
5
+ payload: DataSource;
6
+ };
7
+
8
+ export type IframeSetLayoutCommand = {
9
+ type: "set-layout";
10
+ payload: OpaqueLayoutData;
11
+ };
12
+
13
+ export type IframeInstallExtensionCommand = {
14
+ type: "install-extension";
15
+ payload: Array<string | File>;
16
+ };
17
+
18
+ export type IframeHandshakeAckCommand = {
19
+ type: "handshake-ack";
20
+ payload: {
21
+ orgSlug?: string;
22
+ initialDataSource?: DataSource;
23
+ initialLayout?: OpaqueLayoutData;
24
+ initialExtensions: Array<string | File>;
25
+ };
26
+ };
27
+
28
+ export type IframeCommand =
29
+ | IframeSetDatasourceCommand
30
+ | IframeSetLayoutCommand
31
+ | IframeInstallExtensionCommand
32
+ | IframeHandshakeAckCommand;
33
+
34
+ export type IframeEvent =
35
+ | {
36
+ type: "foxglove-handshake-request";
37
+ }
38
+ | {
39
+ type: "foxglove-handshake-complete";
40
+ }
41
+ | {
42
+ type: "foxglove-error";
43
+ payload: string;
44
+ };
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ // foxglove-depcheck-used: rimraf
2
+ export * from "./FoxgloveViewer";
3
+ export * from "./types";
package/src/types.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * An opaque JSON object representing a Foxglove layout. The layout data should be a JSON file that
3
+ * was exported from the Foxglove app.
4
+ */
5
+ export type OpaqueLayoutData = unknown;
6
+
7
+ export type RecordingSource = {
8
+ type: "recording";
9
+ projectId: string;
10
+ recordingId: string;
11
+ };
12
+
13
+ export type LiveSourceProtocol = "foxglove-websocket" | "rosbridge-websocket" | "remote-file";
14
+
15
+ export type LiveSource = {
16
+ type: "live";
17
+ protocol: LiveSourceProtocol;
18
+ url: string;
19
+ };
20
+
21
+ export type FileSource = {
22
+ type: "file";
23
+ file: File;
24
+ };
25
+
26
+ export type DataSource = RecordingSource | LiveSource | FileSource;
27
+
28
+ export type FoxgloveViewerEventMap = {
29
+ ready: Event;
30
+ error: CustomEvent<string>;
31
+ };
32
+
33
+ export type FoxgloveViewerEventType = keyof FoxgloveViewerEventMap;