diff --git a/.changeset/structure-rx-map.md b/.changeset/structure-rx-map.md new file mode 100644 index 0000000..875ba22 --- /dev/null +++ b/.changeset/structure-rx-map.md @@ -0,0 +1,5 @@ +--- +'@solidjs/start-devtools': minor +--- + +The Structure view hosts the live map of a ReactiveScript app. When the app sets `globalThis.__RX__` with a `mount(element)` function, as `@reactivescript/map/live` does in development, a third chip, Map, mounts the map into the view and disposes it when you leave Map or close the dock. Without a map, the chip is not there, and a remembered Map falls back to Owners. diff --git a/README.md b/README.md index de4f503..bd4ed1f 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,8 @@ The dock has three views, picked in the header: - **Health**: thrown errors and the issues the runtime reports, in one list. - **Activity**: one stream of actions, server-function calls, async loads and errors, with a strip of lanes over time. -- **Structure**: the ownership tree, or the reactivity graph. +- **Structure**: the ownership tree, or the reactivity graph. In a ReactiveScript app it also + has a **Map** chip for the app's live map. Press ⌘K (Ctrl+K) while the dock is open to find a component, signal, memo, action or server function by name. @@ -166,6 +167,18 @@ extra setup. Clicking it asks the dev server to open the file in your editor. The panel reads the tree through the development hooks in `solid-js`, so it is empty in a production build of the runtime. It only watches while it is open. +## ReactiveScript map + +An app written in ReactiveScript can register a live map of its reactive graph in +development, by setting `globalThis.__RX__` to an object with a `mount(element)` function +that returns a dispose function. `@reactivescript/map/live` does this from the app's dev +entry. The Structure view then has a third chip, **Map**, which mounts the map into the +view, and lights the nodes each update changed. + +The toolbar looks for `__RX__` each time the view opens, and takes the map out again when you +leave Map or close the dock. It does not depend on any ReactiveScript package. On a page with +no map, a remembered Map chip falls back to Owners. + ## Copy for an agent Each panel has a copy button that puts a Markdown report on the clipboard. Paste it into diff --git a/src/dev-toolbar/index.tsx b/src/dev-toolbar/index.tsx index 323f028..20f9734 100644 --- a/src/dev-toolbar/index.tsx +++ b/src/dev-toolbar/index.tsx @@ -48,7 +48,8 @@ const CommandPalette = clientOnly(() => import('./palette/index.js'), { lazy: tr /** A view of the dock. */ type Tab = 'health' | 'activity' | 'structure'; -type StructureMode = 'owners' | 'graph'; +/** Map is offered only while the app has a ReactiveScript map. The view falls back to Owners. */ +type StructureMode = 'owners' | 'graph' | 'map'; const VIEWS: { value: Tab; label: string }[] = [ { value: 'health', label: 'Health' }, @@ -297,7 +298,11 @@ export function DevToolbar(props: DevToolbarProps) { const saved = readDockState(); const restored = savedTab(saved.tab); if (restored) setTab(restored); - if (saved.structureMode === 'owners' || saved.structureMode === 'graph') { + if ( + saved.structureMode === 'owners' || + saved.structureMode === 'graph' || + saved.structureMode === 'map' + ) { setStructureMode(saved.structureMode); } void loadSolidVersion().then((value) => { diff --git a/src/dev-toolbar/structure/index.tsx b/src/dev-toolbar/structure/index.tsx index 1799eb5..72ba71d 100644 --- a/src/dev-toolbar/structure/index.tsx +++ b/src/dev-toolbar/structure/index.tsx @@ -1,16 +1,26 @@ import type { JSX } from '@solidjs/web'; -import { createSignal, For } from 'solid-js'; +import { createEffect, createMemo, createSignal, For, onSettled, Show } from 'solid-js'; import OwnershipViewer, { type SignalChange } from '../ownership/index.js'; import ReactivityViewer from '../reactivity/index.js'; +import { + mountRxMap, + readRxMapHost, + type RxMapHost, + shownStructureMode, + type StructureMode, + stepStructureMode, + structureModes, +} from './rx-map.js'; import './styles.css'; -export type StructureMode = 'owners' | 'graph'; - -export type { SignalChange }; +export type { RxMapHost, SignalChange, StructureMode }; export interface StructureViewerProps { show?: boolean; - /** Which of the two the view shows. Leave it out to let the view keep its own. */ + /** + * Which pane the view shows. Leave it out to let the view keep its own. Map + * falls back to Owners while the app has no ReactiveScript map. + */ mode?: StructureMode; onModeChange?: (mode: StructureMode) => void; /** A signal, memo or effect another panel asked the graph to show. */ @@ -32,46 +42,52 @@ export interface StructureViewerProps { onShowActivity?: (owner: object, name: string) => void; } -const MODES: { value: StructureMode; label: string; name: string }[] = [ - { value: 'owners', label: 'Owners', name: 'Ownership' }, - { value: 'graph', label: 'Graph', name: 'Reactivity' }, -]; +const MODES: Record = { + owners: { label: 'Owners', name: 'Ownership' }, + graph: { label: 'Graph', name: 'Reactivity' }, + map: { label: 'Map', name: 'ReactiveScript map' }, +}; interface ModeChipsProps { + modes: StructureMode[]; mode: StructureMode; onChange: (mode: StructureMode) => void; } -/** The Owners and Graph chips. Both sides of the view show them. */ +/** The Owners, Graph and Map chips. Every pane of the view shows them. */ function ModeChips(props: ModeChipsProps): JSX.Element { function moveMode(event: KeyboardEvent): void { if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return; event.preventDefault(); - props.onChange(props.mode === 'owners' ? 'graph' : 'owners'); + // Each pane has its own chips, so the pane that takes over is searched from + // the dock body: this chip leaves the page with its pane. + const chip = event.currentTarget as HTMLElement | null; + const body = chip?.closest('[data-solid-dev-toolbar-body]') ?? chip?.parentElement; + props.onChange(stepStructureMode(props.modes, props.mode, event.key === 'ArrowLeft' ? -1 : 1)); // The chip that takes over is the one that is now selected. queueMicrotask(() => { - (event.currentTarget as HTMLElement | null)?.parentElement - ?.querySelector('[aria-selected="true"]') + body + ?.querySelector('[data-solid-structure-chip][aria-selected="true"]') ?.focus(); }); } return (
- - {(entry) => ( + + {(value) => ( )} @@ -79,21 +95,64 @@ function ModeChips(props: ModeChipsProps): JSX.Element { ); } +interface RxMapPaneProps { + host: RxMapHost; + lead: JSX.Element; +} + +/** + * The live map of a ReactiveScript app. The app's `__RX__.mount` draws it into + * the frame once the pane is on the page, and the pane takes it out again when + * it closes. + */ +function RxMapPane(props: RxMapPaneProps): JSX.Element { + let frame: HTMLDivElement | undefined; + const host = props.host; + onSettled(() => (frame ? mountRxMap(host, frame) : undefined)); + + return ( +
+
+
{props.lead}
+
{ + frame = element; + }} + /> +
+
+ ); +} + /** - * The Structure view: the ownership tree and the reactivity graph behind one - * pair of chips. Selecting a chip swaps the pane, and each pane keeps its own - * selection while it is hidden. + * The Structure view: the ownership tree and the reactivity graph behind a row + * of chips, plus the ReactiveScript map when the app registered one. Selecting + * a chip swaps the pane, and the tree and the graph keep their own selection + * while they are hidden. */ export default function StructureViewer(props: StructureViewerProps): JSX.Element { const [ownMode, setOwnMode] = createSignal('owners'); - const mode = () => props.mode ?? ownMode(); + + // The app's dev entry registers the map, usually before the toolbar mounts. + // It is read again each time the view opens, in case it came later. + const [mapHost, setMapHost] = createSignal(readRxMapHost()); + createEffect( + () => !!props.show, + (shown) => { + if (shown) setMapHost(readRxMapHost()); + }, + ); + + const modes = createMemo(() => structureModes(!!mapHost())); + const mode = () => shownStructureMode(props.mode ?? ownMode(), !!mapHost()); function changeMode(next: StructureMode): void { setOwnMode(next); props.onModeChange?.(next); } - const chips = () => ; + const chips = () => ; return ( <> @@ -114,6 +173,9 @@ export default function StructureViewer(props: StructureViewerProps): JSX.Elemen onViewOwner={props.onViewOwner} lead={chips()} /> + + {(host) => } + ); } diff --git a/src/dev-toolbar/structure/rx-map.test.ts b/src/dev-toolbar/structure/rx-map.test.ts new file mode 100644 index 0000000..dd9ac3f --- /dev/null +++ b/src/dev-toolbar/structure/rx-map.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + mountRxMap, + readRxMapHost, + type RxMapHost, + shownStructureMode, + stepStructureMode, + structureModes, +} from './rx-map.js'; + +const el = {} as HTMLElement; + +describe('readRxMapHost', () => { + it('finds a host with a mount function', () => { + const host = { graphs: [], mount: () => () => {} }; + expect(readRxMapHost({ __RX__: host })).toBe(host); + }); + + it('ignores a missing host, or one without mount', () => { + expect(readRxMapHost({})).toBeUndefined(); + expect(readRxMapHost({ __RX__: null })).toBeUndefined(); + expect(readRxMapHost({ __RX__: { graphs: [] } })).toBeUndefined(); + expect(readRxMapHost({ __RX__: { mount: 'no' } })).toBeUndefined(); + }); + + it('ignores a getter that throws', () => { + const scope = { + get __RX__() { + throw new Error('blocked'); + }, + }; + expect(readRxMapHost(scope)).toBeUndefined(); + }); +}); + +describe('structure modes', () => { + it('offers Map only when the app has a map', () => { + expect(structureModes(false)).toEqual(['owners', 'graph']); + expect(structureModes(true)).toEqual(['owners', 'graph', 'map']); + }); + + it('shows Owners for a saved Map mode when the app has no map', () => { + expect(shownStructureMode('map', false)).toBe('owners'); + expect(shownStructureMode('map', true)).toBe('map'); + expect(shownStructureMode('graph', false)).toBe('graph'); + }); + + it('steps through the modes it offers, wrapping around', () => { + const modes = structureModes(true); + expect(stepStructureMode(modes, 'graph', 1)).toBe('map'); + expect(stepStructureMode(modes, 'map', 1)).toBe('owners'); + expect(stepStructureMode(modes, 'owners', -1)).toBe('map'); + expect(stepStructureMode(structureModes(false), 'graph', 1)).toBe('owners'); + }); +}); + +describe('mountRxMap', () => { + it('mounts into the element and disposes once', () => { + const dispose = vi.fn(); + const host: RxMapHost = { mount: vi.fn(() => dispose) }; + const unmount = mountRxMap(host, el); + expect(host.mount).toHaveBeenCalledWith(el); + expect(dispose).not.toHaveBeenCalled(); + unmount(); + unmount(); + expect(dispose).toHaveBeenCalledTimes(1); + }); + + it('survives a map that throws', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const failing: RxMapHost = { + mount: () => { + throw new Error('no map'); + }, + }; + expect(() => mountRxMap(failing, el)()).not.toThrow(); + const throwing: RxMapHost = { + mount: () => () => { + throw new Error('no dispose'); + }, + }; + expect(() => mountRxMap(throwing, el)()).not.toThrow(); + expect(warn).toHaveBeenCalledTimes(2); + warn.mockRestore(); + }); +}); diff --git a/src/dev-toolbar/structure/rx-map.ts b/src/dev-toolbar/structure/rx-map.ts new file mode 100644 index 0000000..8471c5d --- /dev/null +++ b/src/dev-toolbar/structure/rx-map.ts @@ -0,0 +1,74 @@ +/** + * The ReactiveScript map. An app compiled from `.rx` files can register a live + * map of its reactive graph on `globalThis.__RX__` in development. The toolbar + * only hosts it: it never imports a ReactiveScript package. + */ + +/** What the app puts on `globalThis.__RX__`. The toolbar only calls `mount`. */ +export interface RxMapHost { + /** Puts the map into `el` and returns a function that takes it out again. */ + mount(el: HTMLElement): () => void; +} + +export type StructureMode = 'owners' | 'graph' | 'map'; + +/** The map host the app registered, or undefined when it has none. */ +export function readRxMapHost(scope: object = globalThis): RxMapHost | undefined { + let host: unknown; + try { + host = Reflect.get(scope, '__RX__'); + } catch { + // A getter another script put there can throw. + return undefined; + } + if (!host || typeof host !== 'object') return undefined; + return typeof (host as { mount?: unknown }).mount === 'function' + ? (host as RxMapHost) + : undefined; +} + +/** The modes the Structure view offers. Map is there only when the app has a map. */ +export function structureModes(hasMap: boolean): StructureMode[] { + return hasMap ? ['owners', 'graph', 'map'] : ['owners', 'graph']; +} + +/** The mode the view shows. A Map mode saved by an earlier load falls back to Owners. */ +export function shownStructureMode(mode: StructureMode, hasMap: boolean): StructureMode { + return structureModes(hasMap).includes(mode) ? mode : 'owners'; +} + +/** The mode after `mode` in `modes`, wrapping around. A negative step goes back. */ +export function stepStructureMode( + modes: StructureMode[], + mode: StructureMode, + step: 1 | -1, +): StructureMode { + const index = modes.indexOf(mode); + if (index === -1) return modes[0]; + return modes[(index + step + modes.length) % modes.length]; +} + +/** + * Mounts the map into `el`. The function it returns takes the map out once, + * however often it is called. A map that fails to mount is reported and leaves + * the toolbar alone. + */ +export function mountRxMap(host: RxMapHost, el: HTMLElement): () => void { + let dispose: (() => void) | undefined; + try { + const result = host.mount(el); + if (typeof result === 'function') dispose = result; + } catch (error) { + console.warn('[solid dev toolbar] failed to mount the ReactiveScript map', error); + } + return () => { + const current = dispose; + dispose = undefined; + if (!current) return; + try { + current(); + } catch (error) { + console.warn('[solid dev toolbar] failed to unmount the ReactiveScript map', error); + } + }; +} diff --git a/src/dev-toolbar/structure/styles.css b/src/dev-toolbar/structure/styles.css index 1b4ea94..e561c56 100644 --- a/src/dev-toolbar/structure/styles.css +++ b/src/dev-toolbar/structure/styles.css @@ -46,3 +46,48 @@ [data-solid-structure-modes] { display: contents; } + +/* The ReactiveScript map. The app's map page fills the pane below the chips. */ + +[data-solid-rx-map-viewer] { + display: flex; + flex-direction: column; + + height: 100%; + min-height: 0; + + color: var(--start-dt-text); +} + +[data-solid-rx-map-nav] { + display: flex; + flex-direction: row; + align-items: center; + + gap: 0.5rem; + + padding: 0.5rem 0.75rem; + + border-bottom: var(--start-dt-border-soft) 1px solid; +} + +[data-solid-rx-map-frame] { + position: relative; + + flex: 1; + min-width: 0; + min-height: 0; + + overflow: hidden; +} + +[data-solid-rx-map-frame] > iframe { + position: absolute; + inset: 0; + + display: block; + width: 100%; + height: 100%; + + border: 0; +} diff --git a/tests/e2e/devtools.spec.ts b/tests/e2e/devtools.spec.ts index ca0d66e..cf98082 100644 --- a/tests/e2e/devtools.spec.ts +++ b/tests/e2e/devtools.spec.ts @@ -574,6 +574,75 @@ test('maps the ownership tree', async ({ page }) => { ).toHaveAttribute('data-solid-reactivity-node', 'selected'); }); +test('hosts the ReactiveScript map only when the app registers one', async ({ page, context }) => { + // Without `__RX__` the Structure view has no Map chip. + await page.goto('/'); + await openTab(page, 'Ownership'); + await expect(page.getByRole('tab', { name: 'ReactiveScript map', exact: true })).toHaveCount(0); + + // A stand-in for `@reactivescript/map/live`, registered after the toolbar + // mounted: the view reads it again when it opens. + await page.evaluate(() => { + const calls: string[] = []; + Reflect.set(window, '__rxCalls', calls); + Reflect.set(globalThis, '__RX__', { + graphs: [], + mount(el: HTMLElement) { + calls.push(el.isConnected ? 'mount' : 'mount detached'); + const frame = document.createElement('iframe'); + frame.srcdoc = '

map

'; + el.append(frame); + return () => { + calls.push('dispose'); + frame.remove(); + }; + }, + }); + }); + const calls = () => page.evaluate(() => Reflect.get(window, '__rxCalls') as string[]); + await page.getByRole('tab', { name: 'Health', exact: true }).click(); + await page.getByRole('tab', { name: 'Structure', exact: true }).click(); + + const mapChip = page.getByRole('tab', { name: 'ReactiveScript map', exact: true }); + await mapChip.click(); + await expect(mapChip).toHaveAttribute('aria-selected', 'true'); + const frame = page.locator('[data-solid-rx-map-frame] iframe'); + await expect(frame).toBeVisible(); + await expect( + page.frameLocator('[data-solid-rx-map-frame] iframe').locator('#rx-map-page'), + ).toHaveText('map'); + expect(await calls()).toEqual(['mount']); + // The map fills the pane under the chips. + const pane = (await page.locator('[data-solid-rx-map-frame]').boundingBox())!; + const box = (await frame.boundingBox())!; + expect(box.width).toBe(pane.width); + expect(box.height).toBe(pane.height); + + // The arrow keys move between the three chips. + await mapChip.focus(); + await page.keyboard.press('ArrowRight'); + await expect(page.getByRole('tab', { name: 'Ownership', exact: true })).toBeFocused(); + await expect.poll(calls).toEqual(['mount', 'dispose']); + + // Coming back mounts it again, and closing the dock takes it out. + await page.keyboard.press('ArrowLeft'); + await expect(mapChip).toBeFocused(); + await expect.poll(calls).toEqual(['mount', 'dispose', 'mount']); + await page.getByRole('button', { name: 'Close Start Devtools' }).click(); + await expect.poll(calls).toEqual(['mount', 'dispose', 'mount', 'dispose']); + + // The dock remembers Map. A load without a map falls back to Owners. + await page.getByRole('button', { name: 'Open Start Devtools' }).click(); + await expect(frame).toBeVisible(); + const other = await context.newPage(); + await other.goto('/'); + await expect(other.getByRole('tab', { name: 'Ownership', exact: true })).toHaveAttribute( + 'aria-selected', + 'true', + ); + await expect(other.getByRole('tab', { name: 'ReactiveScript map', exact: true })).toHaveCount(0); +}); + test('lists runtime issues', async ({ page }) => { await page.goto('/');