@team581/doglog-studio-embed 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jonah Snider
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,219 @@
1
- # Temporary Holding Version
1
+ # @team581/doglog-studio-embed
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Show DogLog Studio's dashboards in your own web app, ex. a match review tool that plays match video. Your app gives Studio its logs, dashboards, and options, and can drive Studio's timeline from its own video player.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @team581/doglog-studio-embed
9
+ ```
10
+
11
+ ## Show Studio in a React app
12
+
13
+ ```tsx
14
+ import { StudioEmbedFrame } from '@team581/doglog-studio-embed/react';
15
+
16
+ export function MatchReview({ logUrl }: { logUrl: string }) {
17
+ return (
18
+ <StudioEmbedFrame
19
+ style={{ height: 600 }}
20
+ sources={[{ id: 'log', url: logUrl }]}
21
+ dashboards={[
22
+ {
23
+ id: 'arm',
24
+ name: 'Arm',
25
+ layout: { kind: 'pane', widget: { type: 'graph', bindings: [{ entry: '/Robot/Arm/Angle' }] } },
26
+ },
27
+ ]}
28
+ />
29
+ );
30
+ }
31
+ ```
32
+
33
+ The component sends each prop to Studio when it changes. To call a method that has no prop, ex. `applyUpdate()`, pass a ref.
34
+
35
+ ## Show Studio without React
36
+
37
+ ```ts
38
+ import { mountStudio } from '@team581/doglog-studio-embed';
39
+
40
+ const studio = mountStudio(document.querySelector('#studio')!, {
41
+ sources: [{ id: 'log', url: 'https://example.com/qual12.wpilog' }],
42
+ dashboards: [{ id: 'arm', layout: { kind: 'pane', widget: { type: 'graph' } } }],
43
+ });
44
+ await studio.ready;
45
+ ```
46
+
47
+ `mountStudio()` adds an iframe to the element, so give the element a height.
48
+
49
+ ## Sync Studio with your video player
50
+
51
+ 1. Hide Studio's timeline bar and let only your app move the cursor:
52
+
53
+ ```ts
54
+ const studio = mountStudio(container, {
55
+ options: { cursorControl: 'host', timelineBar: 'hidden' },
56
+ sources: [{ id: 'log', url: logUrl }],
57
+ });
58
+ ```
59
+
60
+ 2. Send the video's playback state when it plays, pauses, seeks, or changes speed, and while it plays. `videoStart` is the log time, in seconds, at the video's first frame, ex. from when the robot was enabled:
61
+
62
+ ```ts
63
+ const sendPlayback = () =>
64
+ void studio.setPlayback({
65
+ time: videoStart + video.currentTime,
66
+ playing: !video.paused,
67
+ rate: video.playbackRate,
68
+ });
69
+ for (const event of ['play', 'pause', 'seeked', 'ratechange', 'timeupdate']) {
70
+ video.addEventListener(event, sendPlayback);
71
+ }
72
+ ```
73
+
74
+ 3. Handle your player's shortcuts while Studio has focus. Studio sends you each key it doesn't use:
75
+
76
+ ```ts
77
+ studio.on('key', (key) => {
78
+ if (key.code === 'Space') {
79
+ void (video.paused ? video.play() : video.pause());
80
+ }
81
+ });
82
+ ```
83
+
84
+ To draw your own cursor between messages, call `timeAt()` with the last playback state you sent.
85
+
86
+ ## Show logs from more than one device
87
+
88
+ List the sources in order. The first source is the time base, and every time is on its clock. Studio lines up the others automatically. If you already know where a source starts, give it an `offset`:
89
+
90
+ ```ts
91
+ await studio.setSources([
92
+ { id: 'rio', url: rioLogUrl },
93
+ { id: 'canivore', name: 'qual12.hoot', data: hootBlob, offset: 1.25 },
94
+ ]);
95
+ ```
96
+
97
+ Studio reopens only the sources whose URL, name, or data changed.
98
+
99
+ ## Save users' dashboard edits
100
+
101
+ Set `dashboards: 'editable'` and store the dashboards from each `dashboards` event. Studio saves nothing itself.
102
+
103
+ ```ts
104
+ studio.on('dashboards', (dashboards) => saveDashboards(userId, dashboards));
105
+ ```
106
+
107
+ Pass the saved dashboards back with `setDashboards()` or the `dashboards` prop. Dashboards Studio sent you don't reset the user's undo history.
108
+
109
+ ## Update Studio
110
+
111
+ Studio keeps running its loaded version, even offline, until you switch it. When a newer version is ready, Studio sends `updateavailable`. Call `applyUpdate()` when reloading won't interrupt the user. Studio reloads and gets your app's state again.
112
+
113
+ ## Reference
114
+
115
+ ### `mountStudio(container, init)`
116
+
117
+ `init` takes `options`, `dashboards`, `shownDashboard`, `sources`, `playback`, and `url`, the embed page's URL, `https://doglog.studio/embed/` by default. It returns:
118
+
119
+ | Member | Does |
120
+ | --------------------------- | --------------------------------------------------------------------------------------------- |
121
+ | `iframe` | The iframe it added |
122
+ | `ready` | Resolves when Studio first connects. Rejects when Studio refuses, ex. for a version mismatch. |
123
+ | `setOptions(options)` | Replaces every option. Options you leave out use their defaults. |
124
+ | `setDashboards(dashboards)` | Replaces the dashboards |
125
+ | `showDashboard(id)` | Shows a dashboard |
126
+ | `setSources(sources)` | Replaces the sources, in order |
127
+ | `setPlayback(playback)` | Moves the cursor and sets playback |
128
+ | `applyUpdate()` | Reloads Studio into its newer version |
129
+ | `on(event, listener)` | Listens for an event. Returns a function that stops listening. |
130
+ | `destroy()` | Removes the iframe and stops listening |
131
+
132
+ Calls made before Studio connects wait for it. When the iframe reloads, the package sends your latest state again.
133
+
134
+ ### `StudioEmbedFrame`
135
+
136
+ Takes `url`, `options`, `dashboards`, `shownDashboard`, `sources`, and `playback` as props, plus `className` and `style` for the iframe's container. Changing `url` mounts a new embed. Its ref is the object `mountStudio()` returns.
137
+
138
+ ### Options
139
+
140
+ | Option | Values | Default |
141
+ | ---------------------- | ------------------------------------------------------------------------------------------------- | ------------ |
142
+ | `timelineBar` | `visible`, `hidden` | `visible` |
143
+ | `cursorControl` | `shared`: users move the cursor too. `host`: only your app does. | `shared` |
144
+ | `dashboards` | `single`: one dashboard. `predefined`: users switch between yours. `editable`: users change them. | `predefined` |
145
+ | `dashboardSwitcher` | Shows the dashboards in a sidebar | `false` |
146
+ | `entryBrowser` | Shows the log's entries | `false` |
147
+ | `theme` | `light`, `dark`, `system` | `system` |
148
+ | `themePreset` | `doglog`, `match13`, `froglog`, `hoglog`, `neutral`, `frc-colors`, `custom` | `doglog` |
149
+ | `themeColor` | Hex color for `custom`, ex. `#1c1816` | |
150
+ | `teamNumber` | Team whose colors `frc-colors` uses | |
151
+ | `highContrast` | `boolean` | `false` |
152
+ | `visualizationPalette` | `default`, `protan`, `deutan`, `tritan` | `default` |
153
+ | `reduceMotion` | `boolean` | `false` |
154
+ | `naturalScrolling` | `boolean` | `true` |
155
+ | `timelineAlerts` | Shows alerts on the timeline | `true` |
156
+ | `timelineCompress` | Skips idle time on the timeline | `true` |
157
+ | `timelineShifts` | Shows active hub shifts on the timeline | `true` |
158
+
159
+ ### Events
160
+
161
+ | Event | React prop | Data |
162
+ | ----------------- | -------------------- | ---------------------------------------------------------------------------------------------- |
163
+ | `playback` | `onPlaybackChange` | Playback state, after the user moves the cursor or plays. Only with `cursorControl: 'shared'`. |
164
+ | `timerange` | `onTimeRangeChange` | `{ start, end }` of the time base in seconds, or `null` without data |
165
+ | `source` | `onSourceChange` | `{ id, status }`, with `progress` while `loading` and `error` on `error` |
166
+ | `dashboards` | `onDashboardsChange` | Every dashboard, after a user's change. Only with `dashboards: 'editable'`. |
167
+ | `dashboard` | `onDashboardShown` | `{ id }` of the shown dashboard |
168
+ | `key` | `onKey` | A key Studio didn't use: `key`, `code`, and modifier flags |
169
+ | `updateavailable` | `onUpdateAvailable` | |
170
+ | `reconnect` | `onReconnect` | Studio reloaded and got your state again |
171
+ | `error` | `onError` | `{ message }` when Studio refuses to connect |
172
+
173
+ ### Sources
174
+
175
+ | Field | Value |
176
+ | -------- | ----------------------------------------------------------------------------------------------- |
177
+ | `id` | Your ID for the source |
178
+ | `url` | HTTP(S) URL of a `.wpilog`, `.wpilogxz`, or `.hoot` file |
179
+ | `data` | The file as a `Blob` or `ArrayBuffer`, instead of `url`, ex. for logs behind your app's sign-in |
180
+ | `name` | The file's name with its extension. Required with `data`. |
181
+ | `offset` | Seconds after the time base that this source starts |
182
+
183
+ ### Times and playback
184
+
185
+ Every time is in seconds on the time base's clock: its log's timestamps divided by 1,000,000. Playback state is `{ time, playing, rate }`, where `rate` 1 is real time. Send it on every change and seek, and at least every 500 ms while playing.
186
+
187
+ `timeAt(playback, at, now)` returns the cursor's time at `now`, for playback sent or received at `at`. Both are in milliseconds from `performance.now()`.
188
+
189
+ ### Dashboards
190
+
191
+ A dashboard has an `id`, an optional `name`, and a `layout`. A layout is a pane, `{ kind: 'pane', widget }`, or a split, `{ kind: 'split', direction: 'row' | 'column', children }`. Panes and splits take an optional `size`. A widget has a `type`, ex. `graph`, `field`, or `swerve`, plus `options` and `bindings`. These match the layouts Studio's agent commands take. Notepads aren't available in embeds.
192
+
193
+ ### Protocol
194
+
195
+ Use the protocol directly to embed Studio without this package. Its types are in `src/protocol.ts`.
196
+
197
+ 1. Show `https://doglog.studio/embed/` in an iframe.
198
+ 2. Studio posts `{ tag: 'doglog-studio-embed', type: 'ready' }` to the parent window when it loads, and again after each reload.
199
+ 3. Reply by posting `{ tag: 'doglog-studio-embed', type: 'connect', version: 1 }` to the iframe's window, transferring a `MessagePort`.
200
+ 4. Studio replies on the port with `{ type: 'connected' }` or `{ type: 'refused', error }`.
201
+ 5. Send commands on the port as `{ type: 'command', id, command, input }`. Studio replies with `{ type: 'reply', id, ok, result }` or `{ type: 'reply', id, ok: false, error }`, and sends events as `{ type: 'event', event, data }`.
202
+
203
+ | Command | Input |
204
+ | ----------------- | --------------------------------------------------------- |
205
+ | `options_update` | Options |
206
+ | `dashboards_set` | `{ dashboards }` |
207
+ | `dashboard_show` | `{ id }` |
208
+ | `source_create` | A source |
209
+ | `source_update` | `{ id, offset }`, with `null` to line it up automatically |
210
+ | `source_delete` | `{ id }` |
211
+ | `source_order` | `{ ids }` |
212
+ | `timeline_update` | Playback state |
213
+ | `update_apply` | `{}` |
214
+
215
+ After a reload, Studio has none of your state, so send it again.
216
+
217
+ ### Versions
218
+
219
+ The package's major version is the protocol's version. Studio refuses to connect to a package with a different major version.
@@ -0,0 +1,240 @@
1
+ /** The protocol's major version, always the same as this package's major version */
2
+ declare const protocolVersion = 1;
3
+ /** Marks messages on `window` as Studio embed messages, so other messages on the page are ignored */
4
+ declare const messageTag = "doglog-studio-embed";
5
+ type EmbedOptions = {
6
+ /** Whether Studio shows its timeline bar, `visible` by default */
7
+ timelineBar?: 'visible' | 'hidden';
8
+ /**
9
+ * `shared` (the default) lets the host and the user move the cursor, and Studio sends `playback` events. With `host`,
10
+ * Studio only follows the playback state the host sends.
11
+ */
12
+ cursorControl?: 'shared' | 'host';
13
+ /**
14
+ * `single` shows one dashboard without a switcher, `predefined` (the default) lets the user switch between the host's
15
+ * dashboards without changing them, and `editable` lets the user change them, sending `dashboards` events.
16
+ */
17
+ dashboards?: 'single' | 'predefined' | 'editable';
18
+ /** Whether Studio's sidebar shows the dashboards to switch between, off by default */
19
+ dashboardSwitcher?: boolean;
20
+ /** Whether Studio shows its entry browser, off by default */
21
+ entryBrowser?: boolean;
22
+ theme?: 'light' | 'dark' | 'system';
23
+ themePreset?: 'doglog' | 'match13' | 'froglog' | 'hoglog' | 'neutral' | 'frc-colors' | 'custom';
24
+ /** Hex color the `custom` theme preset is generated from, ex. `#1c1816` */
25
+ themeColor?: string;
26
+ /** The team whose colors the `frc-colors` theme preset uses */
27
+ teamNumber?: number;
28
+ highContrast?: boolean;
29
+ visualizationPalette?: 'default' | 'protan' | 'deutan' | 'tritan';
30
+ reduceMotion?: boolean;
31
+ naturalScrolling?: boolean;
32
+ /** Whether the timeline shows alerts */
33
+ timelineAlerts?: boolean;
34
+ /** Whether the timeline skips idle time */
35
+ timelineCompress?: boolean;
36
+ /** Whether the timeline shows active hub shifts */
37
+ timelineShifts?: boolean;
38
+ };
39
+ /**
40
+ * Where the cursor is, in seconds on the time base's own clock: its log's timestamps divided by 1,000,000. Sent on every
41
+ * change and seek, and at least every 500 ms while playing.
42
+ */
43
+ type PlaybackState = {
44
+ time: number;
45
+ playing: boolean;
46
+ /** How fast the cursor moves while playing, 1 is real time */
47
+ rate: number;
48
+ };
49
+ /** A log for Studio to show, by bytes or by URL */
50
+ type EmbedSource = {
51
+ /** Chosen by the host, sources are matched by it when they change */
52
+ id: string;
53
+ /** The file's name with its extension, ex. `qual12.wpilog`, needed with `data` */
54
+ name?: string;
55
+ /** HTTP(S) URL of a WPILOG, `.wpilogxz`, or HOOT file */
56
+ url?: string;
57
+ /** The file's contents, instead of `url` */
58
+ data?: Blob | ArrayBuffer;
59
+ /** Seconds after the time base this source starts, lined up automatically when left out */
60
+ offset?: number;
61
+ };
62
+ /** A dashboard's layout, in the same form as Studio's agent commands take */
63
+ type EmbedLayout = {
64
+ kind: 'pane';
65
+ widget?: EmbedWidget;
66
+ size?: number;
67
+ } | {
68
+ kind: 'split';
69
+ direction: 'row' | 'column';
70
+ size?: number;
71
+ children: EmbedLayout[];
72
+ };
73
+ type EmbedWidget = {
74
+ type: string;
75
+ options?: Record<string, string>;
76
+ bindings?: {
77
+ entry: string;
78
+ role?: string;
79
+ color?: number;
80
+ hidden?: boolean;
81
+ robot?: string;
82
+ connectedFrom?: number[];
83
+ }[];
84
+ };
85
+ type EmbedDashboard = {
86
+ /** Chosen by the host, or by Studio for dashboards users add in `editable` mode */
87
+ id: string;
88
+ /** Left out, Studio suggests one from its entries */
89
+ name?: string;
90
+ layout?: EmbedLayout;
91
+ };
92
+ type SourceStatus = {
93
+ id: string;
94
+ status: 'loading';
95
+ progress?: number;
96
+ } | {
97
+ id: string;
98
+ status: 'loaded';
99
+ } | {
100
+ id: string;
101
+ status: 'error';
102
+ error: string;
103
+ };
104
+ /** What each event sends the host */
105
+ type EmbedEvents = {
106
+ /** The cursor moved or playback changed, only with `shared` cursor control */
107
+ playback: PlaybackState;
108
+ /** The time base's range changed, in seconds on its own clock. `null` without data. */
109
+ timerange: {
110
+ start: number;
111
+ end: number;
112
+ } | null;
113
+ source: SourceStatus;
114
+ /** The user changed dashboards, only in `editable` mode */
115
+ dashboards: EmbedDashboard[];
116
+ /** Another dashboard is shown */
117
+ dashboard: {
118
+ id: string;
119
+ };
120
+ /** A key the embed didn't handle, while it had focus */
121
+ key: {
122
+ key: string;
123
+ code: string;
124
+ altKey: boolean;
125
+ ctrlKey: boolean;
126
+ metaKey: boolean;
127
+ shiftKey: boolean;
128
+ };
129
+ /** A newer version of Studio is ready, switch to it with `applyUpdate()` */
130
+ updateavailable: undefined;
131
+ /** The embed reloaded and got the host's state again */
132
+ reconnect: undefined;
133
+ /** The embed couldn't connect, ex. because of a protocol version mismatch */
134
+ error: {
135
+ message: string;
136
+ };
137
+ };
138
+ /** What each command takes */
139
+ type EmbedCommands = {
140
+ options_update: EmbedOptions;
141
+ dashboards_set: {
142
+ dashboards: EmbedDashboard[];
143
+ };
144
+ dashboard_show: {
145
+ id: string;
146
+ };
147
+ source_create: EmbedSource;
148
+ source_update: {
149
+ id: string;
150
+ offset: number | null;
151
+ };
152
+ source_delete: {
153
+ id: string;
154
+ };
155
+ source_order: {
156
+ ids: string[];
157
+ };
158
+ timeline_update: PlaybackState;
159
+ update_apply: Record<string, never>;
160
+ };
161
+ /** Sent by the embed to the window that framed it once it loads, and again after every reload */
162
+ type ReadyMessage = {
163
+ tag: typeof messageTag;
164
+ type: 'ready';
165
+ };
166
+ /** Sent by the host to the embed's window with a `MessagePort` that carries every other message */
167
+ type ConnectMessage = {
168
+ tag: typeof messageTag;
169
+ type: 'connect';
170
+ version: number;
171
+ };
172
+ /** On the port */
173
+ type ConnectReply = {
174
+ type: 'connected';
175
+ version: number;
176
+ } | {
177
+ type: 'refused';
178
+ version: number;
179
+ error: string;
180
+ };
181
+ type CommandMessage = {
182
+ type: 'command';
183
+ id: number;
184
+ command: keyof EmbedCommands;
185
+ input: unknown;
186
+ };
187
+ type ReplyMessage = {
188
+ type: 'reply';
189
+ id: number;
190
+ ok: true;
191
+ result?: unknown;
192
+ } | {
193
+ type: 'reply';
194
+ id: number;
195
+ ok: false;
196
+ error: string;
197
+ };
198
+ type EventMessage = {
199
+ type: 'event';
200
+ event: keyof EmbedEvents;
201
+ data: unknown;
202
+ };
203
+ /**
204
+ * The cursor's time `now` milliseconds (on `performance.now()`'s clock) after `at`, when `playback` was sent or
205
+ * received. Studio moves its cursor with the same calculation between messages.
206
+ */
207
+ declare function timeAt(playback: PlaybackState, at: number, now: number): number;
208
+ type MountOptions = {
209
+ /** The embed page, `https://doglog.studio/embed/` by default */
210
+ url?: string;
211
+ options?: EmbedOptions;
212
+ dashboards?: EmbedDashboard[];
213
+ /** The dashboard to show first, the first one by default */
214
+ shownDashboard?: string;
215
+ sources?: EmbedSource[];
216
+ playback?: PlaybackState;
217
+ /** Whether the browser's agent can use the embed's agent commands, off by default */
218
+ agents?: boolean;
219
+ };
220
+ type StudioEmbed = {
221
+ readonly iframe: HTMLIFrameElement;
222
+ /** Resolves once the embed first connects, rejects if it refuses to, ex. because of a version mismatch */
223
+ readonly ready: Promise<void>;
224
+ /** Replace every option, options left out use their defaults */
225
+ setOptions(options: EmbedOptions): Promise<void>;
226
+ /** Replace the dashboards, passing the ones the embed sent in a `dashboards` event changes nothing */
227
+ setDashboards(dashboards: EmbedDashboard[]): Promise<void>;
228
+ showDashboard(id: string): Promise<void>;
229
+ /** Set the sources in order, the first is the time base. Only sources that changed are opened again. */
230
+ setSources(sources: EmbedSource[]): Promise<void>;
231
+ setPlayback(playback: PlaybackState): Promise<void>;
232
+ /** Reload the embed into a newer version of Studio, after an `updateavailable` event */
233
+ applyUpdate(): Promise<void>;
234
+ on<Event extends keyof EmbedEvents>(event: Event, listener: (data: EmbedEvents[Event]) => void): () => void;
235
+ /** Remove the iframe and stop listening */
236
+ destroy(): void;
237
+ };
238
+ /** Show DogLog Studio in an iframe added to `container` */
239
+ declare function mountStudio(container: HTMLElement, init?: MountOptions): StudioEmbed;
240
+ export { ReplyMessage as _, ConnectMessage as a, protocolVersion as b, EmbedDashboard as c, EmbedOptions as d, EmbedSource as f, ReadyMessage as g, PlaybackState as h, CommandMessage as i, EmbedEvents as l, EventMessage as m, StudioEmbed as n, ConnectReply as o, EmbedWidget as p, mountStudio as r, EmbedCommands as s, MountOptions as t, EmbedLayout as u, SourceStatus as v, timeAt as x, messageTag as y };
@@ -0,0 +1,2 @@
1
+ import { _ as ReplyMessage, a as ConnectMessage, b as protocolVersion, c as EmbedDashboard, d as EmbedOptions, f as EmbedSource, g as ReadyMessage, h as PlaybackState, i as CommandMessage, l as EmbedEvents, m as EventMessage, n as StudioEmbed, o as ConnectReply, p as EmbedWidget, r as mountStudio, s as EmbedCommands, t as MountOptions, u as EmbedLayout, v as SourceStatus, x as timeAt, y as messageTag } from "./index-CINOgTzn.mjs";
2
+ export { type CommandMessage, type ConnectMessage, type ConnectReply, type EmbedCommands, type EmbedDashboard, type EmbedEvents, type EmbedLayout, type EmbedOptions, type EmbedSource, type EmbedWidget, type EventMessage, MountOptions, type PlaybackState, type ReadyMessage, type ReplyMessage, type SourceStatus, StudioEmbed, messageTag, mountStudio, protocolVersion, timeAt };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { n as messageTag, t as mountStudio, r as protocolVersion, i as timeAt } from "./src-DvaiFo74.mjs";
@@ -0,0 +1,29 @@
1
+ import { c as EmbedDashboard, d as EmbedOptions, f as EmbedSource, h as PlaybackState, l as EmbedEvents, n as StudioEmbed, v as SourceStatus } from "./index-CINOgTzn.mjs";
2
+ import { CSSProperties } from "react";
3
+ export type StudioEmbedProps = {
4
+ /** The embed page, `https://doglog.studio/embed/` by default. Changing it mounts a new embed. */
5
+ url?: string;
6
+ /** Whether the browser's agent can use the embed's agent commands. Changing it mounts a new embed. */
7
+ agents?: boolean;
8
+ options?: EmbedOptions;
9
+ dashboards?: EmbedDashboard[];
10
+ /** The dashboard to show, by its ID */
11
+ shownDashboard?: string;
12
+ /** In order, the first is the time base. Sources are matched by `id`, so only ones that changed are opened again. */
13
+ sources?: EmbedSource[];
14
+ /** Set it when playback changes or the host seeks, not on every frame, see `PlaybackState` */
15
+ playback?: PlaybackState;
16
+ onPlaybackChange?: (playback: PlaybackState) => void;
17
+ onTimeRangeChange?: (range: EmbedEvents['timerange']) => void;
18
+ onSourceChange?: (source: SourceStatus) => void;
19
+ onDashboardsChange?: (dashboards: EmbedDashboard[]) => void;
20
+ onDashboardShown?: (id: string) => void;
21
+ onKey?: (key: EmbedEvents['key']) => void;
22
+ onUpdateAvailable?: () => void;
23
+ onReconnect?: () => void;
24
+ onError?: (error: EmbedEvents['error']) => void;
25
+ className?: string;
26
+ style?: CSSProperties;
27
+ };
28
+ /** DogLog Studio in an iframe. Its ref is the same object `mountStudio()` returns, for commands that aren't props. */
29
+ export declare const StudioEmbedFrame: import("react").ForwardRefExoticComponent<StudioEmbedProps & import("react").RefAttributes<StudioEmbed | undefined>>;
package/dist/react.mjs ADDED
@@ -0,0 +1,57 @@
1
+ import { t as mountStudio } from "./src-DvaiFo74.mjs";
2
+ import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ // src/react.tsx
5
+ const ignore = () => {};
6
+ /** DogLog Studio in an iframe. Its ref is the same object `mountStudio()` returns, for commands that aren't props. */
7
+ const StudioEmbedFrame = forwardRef(function StudioEmbedFrame({ url, agents, options, dashboards, shownDashboard, sources, playback, className, style, ...callbacks }, ref) {
8
+ const container = useRef(null);
9
+ const [embed, setEmbed] = useState();
10
+ const latest = useRef(callbacks);
11
+ latest.current = callbacks;
12
+ useImperativeHandle(ref, () => embed, [embed]);
13
+ useEffect(() => {
14
+ const mountOptions = {};
15
+ if (url !== void 0) mountOptions.url = url;
16
+ if (agents !== void 0) mountOptions.agents = agents;
17
+ const mounted = mountStudio(container.current, mountOptions);
18
+ const unsubscribes = [
19
+ mounted.on("playback", (data) => latest.current.onPlaybackChange?.(data)),
20
+ mounted.on("timerange", (data) => latest.current.onTimeRangeChange?.(data)),
21
+ mounted.on("source", (data) => latest.current.onSourceChange?.(data)),
22
+ mounted.on("dashboards", (data) => latest.current.onDashboardsChange?.(data)),
23
+ mounted.on("dashboard", (data) => latest.current.onDashboardShown?.(data.id)),
24
+ mounted.on("key", (data) => latest.current.onKey?.(data)),
25
+ mounted.on("updateavailable", () => latest.current.onUpdateAvailable?.()),
26
+ mounted.on("reconnect", () => latest.current.onReconnect?.()),
27
+ mounted.on("error", (data) => latest.current.onError?.(data))
28
+ ];
29
+ setEmbed(mounted);
30
+ return () => {
31
+ for (const unsubscribe of unsubscribes) unsubscribe();
32
+ mounted.destroy();
33
+ setEmbed(void 0);
34
+ };
35
+ }, [url, agents]);
36
+ useEffect(() => {
37
+ embed?.setOptions(options ?? {}).catch(ignore);
38
+ }, [embed, options]);
39
+ useEffect(() => {
40
+ if (dashboards !== void 0) embed?.setDashboards(dashboards).catch(ignore);
41
+ }, [embed, dashboards]);
42
+ useEffect(() => {
43
+ if (shownDashboard !== void 0) embed?.showDashboard(shownDashboard).catch(ignore);
44
+ }, [embed, shownDashboard]);
45
+ useEffect(() => {
46
+ embed?.setSources(sources ?? []).catch(ignore);
47
+ }, [embed, sources]);
48
+ useEffect(() => {
49
+ if (playback !== void 0) embed?.setPlayback(playback).catch(ignore);
50
+ }, [embed, playback]);
51
+ return /* @__PURE__ */ jsx("div", {
52
+ ref: container,
53
+ className,
54
+ style
55
+ });
56
+ });
57
+ export { StudioEmbedFrame };
@@ -0,0 +1,197 @@
1
+ // src/protocol.ts
2
+ /** The protocol's major version, always the same as this package's major version */
3
+ const protocolVersion = 1;
4
+ /** Marks messages on `window` as Studio embed messages, so other messages on the page are ignored */
5
+ const messageTag = "doglog-studio-embed";
6
+ /**
7
+ * The cursor's time `now` milliseconds (on `performance.now()`'s clock) after `at`, when `playback` was sent or
8
+ * received. Studio moves its cursor with the same calculation between messages.
9
+ */
10
+ function timeAt(playback, at, now) {
11
+ return playback.playing ? playback.time + (now - at) / 1e3 * playback.rate : playback.time;
12
+ }
13
+ // src/index.ts
14
+ function sameSource(a, b) {
15
+ return a.url === b.url && a.data === b.data && a.name === b.name;
16
+ }
17
+ function samePlayback(a, b) {
18
+ return a !== void 0 && a.time === b.time && a.playing === b.playing && a.rate === b.rate;
19
+ }
20
+ /** Show DogLog Studio in an iframe added to `container` */
21
+ function mountStudio(container, init = {}) {
22
+ const url = new URL(init.url ?? "https://doglog.studio/embed/", location.href);
23
+ const iframe = document.createElement("iframe");
24
+ iframe.src = url.href;
25
+ iframe.title = "DogLog Studio";
26
+ iframe.allow = [
27
+ "fullscreen",
28
+ "clipboard-write",
29
+ "autoplay",
30
+ "encrypted-media",
31
+ "picture-in-picture"
32
+ ].concat(init.agents === true ? ["tools"] : []).join("; ");
33
+ iframe.style.border = "0";
34
+ iframe.style.width = "100%";
35
+ iframe.style.height = "100%";
36
+ iframe.style.display = "block";
37
+ let options = init.options ?? {};
38
+ let dashboards = init.dashboards;
39
+ let shown = init.shownDashboard;
40
+ let sources = new Map((init.sources ?? []).map((source) => [source.id, source]));
41
+ let playback = init.playback;
42
+ const listeners = /* @__PURE__ */ new Map();
43
+ const emit = (event, data) => {
44
+ for (const listener of listeners.get(event) ?? []) listener(data);
45
+ };
46
+ let port;
47
+ let connections = 0;
48
+ let nextId = 0;
49
+ const pending = /* @__PURE__ */ new Map();
50
+ let waiting = [];
51
+ let resolveReady;
52
+ let rejectReady;
53
+ const ready = new Promise((resolve, reject) => {
54
+ resolveReady = resolve;
55
+ rejectReady = reject;
56
+ });
57
+ ready.catch(() => {});
58
+ const post = (connected, command, input) => {
59
+ const id = nextId++;
60
+ const message = {
61
+ type: "command",
62
+ id,
63
+ command,
64
+ input
65
+ };
66
+ connected.postMessage(message);
67
+ return new Promise((resolve, reject) => pending.set(id, {
68
+ resolve,
69
+ reject
70
+ }));
71
+ };
72
+ /** Send a command once connected, resolving with its result */
73
+ const send = async (command, input) => {
74
+ while (port === void 0) await new Promise((resolve) => waiting.push(resolve));
75
+ return post(port, command, input);
76
+ };
77
+ const createSource = (source) => send("source_create", source);
78
+ /** Send all the host's state to a newly connected embed */
79
+ const replay = (connected) => {
80
+ const sends = [post(connected, "options_update", options)];
81
+ if (dashboards !== void 0) sends.push(post(connected, "dashboards_set", { dashboards }));
82
+ if (shown !== void 0) sends.push(post(connected, "dashboard_show", { id: shown }));
83
+ for (const source of sources.values()) sends.push(post(connected, "source_create", source));
84
+ sends.push(post(connected, "source_order", { ids: [...sources.keys()] }));
85
+ if (playback !== void 0) sends.push(post(connected, "timeline_update", playback));
86
+ for (const sent of sends) sent.catch(() => {});
87
+ };
88
+ const onPortMessage = (event) => {
89
+ const message = event.data;
90
+ if (message.type === "reply") {
91
+ const request = pending.get(message.id);
92
+ pending.delete(message.id);
93
+ if (message.ok) request?.resolve(message.result);
94
+ else request?.reject(new Error(message.error));
95
+ return;
96
+ }
97
+ if (message.event === "playback") playback = message.data;
98
+ else if (message.event === "dashboards") dashboards = message.data;
99
+ else if (message.event === "dashboard") shown = message.data.id;
100
+ emit(message.event, message.data);
101
+ };
102
+ const onWindowMessage = (event) => {
103
+ const data = event.data;
104
+ if (event.source !== iframe.contentWindow || event.origin !== url.origin || data?.tag !== "doglog-studio-embed" || data.type !== "ready") return;
105
+ port?.close();
106
+ port = void 0;
107
+ for (const request of pending.values()) request.reject(/* @__PURE__ */ new Error("DogLog Studio reloaded before replying"));
108
+ pending.clear();
109
+ const channel = new MessageChannel();
110
+ const connecting = channel.port1;
111
+ connecting.onmessage = (reply) => {
112
+ if (reply.data.type === "refused") {
113
+ emit("error", { message: reply.data.error });
114
+ rejectReady(new Error(reply.data.error));
115
+ return;
116
+ }
117
+ connecting.onmessage = onPortMessage;
118
+ port = connecting;
119
+ replay(connecting);
120
+ connections++;
121
+ if (connections === 1) resolveReady();
122
+ else emit("reconnect", void 0);
123
+ const resume = waiting;
124
+ waiting = [];
125
+ for (const resolve of resume) resolve();
126
+ };
127
+ const connect = {
128
+ tag: messageTag,
129
+ type: "connect",
130
+ version: 1
131
+ };
132
+ iframe.contentWindow?.postMessage(connect, url.origin, [channel.port2]);
133
+ };
134
+ addEventListener("message", onWindowMessage);
135
+ container.append(iframe);
136
+ return {
137
+ iframe,
138
+ ready,
139
+ async setOptions(next) {
140
+ options = next;
141
+ await send("options_update", next);
142
+ },
143
+ async setDashboards(next) {
144
+ dashboards = next;
145
+ await send("dashboards_set", { dashboards: next });
146
+ },
147
+ async showDashboard(id) {
148
+ shown = id;
149
+ await send("dashboard_show", { id });
150
+ },
151
+ async setSources(next) {
152
+ const previous = sources;
153
+ sources = new Map(next.map((source) => [source.id, source]));
154
+ const sends = [];
155
+ for (const [id, source] of previous) {
156
+ const replacement = sources.get(id);
157
+ if (replacement === void 0 || !sameSource(source, replacement)) sends.push(send("source_delete", { id }));
158
+ }
159
+ for (const source of next) {
160
+ const before = previous.get(source.id);
161
+ if (before === void 0 || !sameSource(before, source)) sends.push(createSource(source));
162
+ else if (before.offset !== source.offset) sends.push(send("source_update", {
163
+ id: source.id,
164
+ offset: source.offset ?? null
165
+ }));
166
+ }
167
+ const order = [...sources.keys()];
168
+ if (order.join("\n") !== [...previous.keys()].join("\n") || sends.length > 0) sends.push(send("source_order", { ids: order }));
169
+ await Promise.all(sends);
170
+ },
171
+ async setPlayback(next) {
172
+ if (samePlayback(playback, next)) return;
173
+ playback = next;
174
+ await send("timeline_update", next);
175
+ },
176
+ async applyUpdate() {
177
+ await send("update_apply", {});
178
+ },
179
+ on(event, listener) {
180
+ let set = listeners.get(event);
181
+ if (set === void 0) {
182
+ set = /* @__PURE__ */ new Set();
183
+ listeners.set(event, set);
184
+ }
185
+ const added = listener;
186
+ set.add(added);
187
+ return () => set.delete(added);
188
+ },
189
+ destroy() {
190
+ removeEventListener("message", onWindowMessage);
191
+ port?.close();
192
+ port = void 0;
193
+ iframe.remove();
194
+ }
195
+ };
196
+ }
197
+ export { timeAt as i, messageTag as n, protocolVersion as r, mountStudio as t };
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@team581/doglog-studio-embed",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Embed DogLog Studio's dashboards in your own web app",
5
+ "homepage": "https://github.com/jonahsnider/doglog/tree/main/packages/doglog-studio-embed#readme",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "Jonah Snider",
9
+ "email": "jonah@jonahsnider.com",
10
+ "url": "https://jonahsnider.com"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jonahsnider/doglog.git",
15
+ "directory": "packages/doglog-studio-embed"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "type": "module",
21
+ "exports": {
22
+ ".": "./dist/index.mjs",
23
+ "./react": "./dist/react.mjs",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "devDependencies": {
30
+ "@tsconfig/recommended": "1.0.14",
31
+ "@tsconfig/strictest": "2.0.9",
32
+ "@types/react": "19.3.3",
33
+ "@typescript/native-preview": "7.0.0-dev.20260707.2",
34
+ "react": "19.3.1",
35
+ "vite-plus": "1.8.0"
36
+ },
37
+ "peerDependencies": {
38
+ "react": "^18.0.0 || ^19.0.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "react": {
42
+ "optional": true
43
+ }
44
+ },
45
+ "scripts": {
46
+ "build": "vp pack",
47
+ "check": "vp check",
48
+ "check:fix": "vp check --fix"
49
+ }
6
50
  }