Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ The agent writes `.stackmap/<name>/diagram.json`, validates and repairs it, and
- **Find:** search titles, ids and types; the **lens** dims the node types you don't need.
- **Guided views:** tabs the agent defines, like "Checkout path", that focus one part of the diagram. **Present** steps through them full screen.
- **Flow:** **Play** sends pulses along whatever you're looking at: the whole diagram, a view, a trace or a route, hop by hop.
- **Share:** the URL keeps the view, selection, route and playback. Export PNG, JPEG, WebP, SVG, or a short video of the flow.
- **Share:** the URL keeps the view, selection, route and playback. Export PNG, JPEG, WebP, SVG, a short video of the flow, or the diagram again as one offline HTML file.
- **Keyboard:** `/` search, `R` route, `F` present, `P` play, `M` minimap, `Esc` clear; Tab and the arrow keys reach everything else.
- **Themes:** dark and light, and animations respect reduced motion.

Expand Down
24 changes: 23 additions & 1 deletion packages/cli/e2e/offline.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -28,6 +28,28 @@ test('a delivered file renders from file:// with no network', async ({ page }) =
expect(requests).toEqual([]);
});

test('Export saves the delivered page as HTML that opens offline, and the mark links to the website', async ({ page }) => {
const dir = mkdtempSync(join(tmpdir(), 'stackmap-e2e-'));
const input = join(dir, 'platform.json');
writeFileSync(input, JSON.stringify(groupedPlatform));
execFileSync('node', [fileURLToPath(new URL('../dist/cli.js', import.meta.url)), 'deliver', input, '-o', join(dir, 'delivered.html')]);
await page.goto(pathToFileURL(join(dir, 'delivered.html')).href);
await expect(page.locator('.sm-card')).toHaveCount(groupedPlatform.nodes.length);
await expect(page.getByRole('link', { name: /stackmap website/ })).toHaveAttribute('href', 'https://stackmap.omsimos.com/');

await page.getByRole('button', { name: 'Export' }).click();
const [dl] = await Promise.all([page.waitForEvent('download'), page.getByRole('menuitem', { name: /^HTML/ }).click()]);
expect(dl.suggestedFilename()).toBe('platform.html');
const saved = join(dir, 'saved.html');
await dl.saveAs(saved);
// The page as delivered, not as rendered: the viewer's own markup is left out and rebuilt on open.
expect(readFileSync(saved, 'utf8')).toMatch(/<div id="root"><\/div>/);

await page.goto(pathToFileURL(saved).href);
await expect(page.locator('.sm-card')).toHaveCount(groupedPlatform.nodes.length);
await expect(page).toHaveTitle('Platform · stackmap');
});

test('the bare template says no diagram is embedded', async ({ page }) => {
await page.goto(new URL('../dist/viewer.html', import.meta.url).href);
await expect(page.getByRole('status')).toHaveText(/No diagram embedded/);
Expand Down
14 changes: 13 additions & 1 deletion packages/cli/e2e/serve.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -51,6 +51,18 @@ test('edits reload the page; a broken edit keeps the last good version and says
await expect(toast).toHaveCount(0);
});

test('an HTML export of a served page is the offline file, without the live connection', async ({ page }) => {
await start(commerceApi);
await page.goto(url);
await expect(page.locator('.sm-card')).toHaveCount(commerceApi.nodes.length);
await page.getByRole('button', { name: 'Export' }).click();
const [dl] = await Promise.all([page.waitForEvent('download'), page.getByRole('menuitem', { name: /^HTML/ }).click()]);
const html = readFileSync((await dl.path())!, 'utf8');
expect(html).toContain('<script type="application/json" id="stackmap-data">{');
// The bundle names the block's id too; it's the element that must be gone.
expect(html).not.toContain('<script type="application/json" id="stackmap-live">');
});

test('the camera, selection and theme survive a live reload', async ({ page }) => {
await start(commerceApi);
await page.goto(url);
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/src/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const HANDED_OFF = 3000;
// A Windows program started through WSL interop can take longer than that to load, and its exit code is the only
// sign that nothing opened.
const WINDOWS_START = 15000;
// macOS `open` returns once the browser has the file, which can take seconds while the browser wakes. Exiting before
// then can leave it to be killed with the caller's shell (an agent's tool), so the file never opens and no warning shows.
const MAC_OPEN = 15000;

// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt.
const inWindows = (path: string) => (): string => {
Expand Down Expand Up @@ -57,7 +60,7 @@ export function browserCommands(
platform: NodeJS.Platform = process.platform,
wsl = platform === 'linux' && isWsl(),
): Opener[] | { refused: string } {
if (platform === 'darwin') return [{ cmd: 'open', args: [file] }];
if (platform === 'darwin') return [{ cmd: 'open', args: [file], wait: MAC_OPEN }];
// `start` is a cmd builtin, and its first quoted argument is the window title.
// Quoted, cmd takes & | < > ^ ( ) literally; it still expands %VAR% inside quotes, and " would end the quoting.
if (platform === 'win32')
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/test/open.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const posix = it.skipIf(process.platform === 'win32');

describe('browserCommands', () => {
it('uses the native opener on darwin and linux', () => {
expect(browserCommands('/tmp/a b.html', 'darwin')).toEqual([{ cmd: 'open', args: ['/tmp/a b.html'] }]);
expect(browserCommands('/tmp/a b.html', 'darwin')).toEqual([{ cmd: 'open', args: ['/tmp/a b.html'], wait: 15000 }]);
expect(browserCommands('/tmp/a.html', 'linux', false)).toEqual([{ cmd: 'xdg-open', args: ['/tmp/a.html'] }]);
});

Expand Down
3 changes: 2 additions & 1 deletion packages/viewer/e2e/explore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ test('keyboard only: tab to a card, arrow between cards, Enter selects, Escape c
test('Tab reaches the toolbar before the canvas, and the canvas is one tab stop (roving)', async ({ page }) => {
await page.locator('body').click({ position: { x: 5, y: 5 } });
const order: string[] = [];
for (let i = 0; i < 12; i++) {
// The header's stackmap link comes first, then the view tabs and the toolbar.
for (let i = 0; i < 14; i++) {
await page.keyboard.press('Tab');
order.push(
await page.evaluate(() => {
Expand Down
Binary file modified packages/viewer/e2e/visual.spec.ts-snapshots/grouped-dark-linux.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/viewer/e2e/visual.spec.ts-snapshots/sample-dark-linux.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/viewer/e2e/visual.spec.ts-snapshots/stages-dark-linux.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions packages/viewer/src/chrome/ExportMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { popIn } from '../motion/motion';
import { PANEL_CLASS, PANEL_STYLE } from './ui';
import { useExplore } from '../explore/ExploreContext';
import { useScene, useSceneContent } from '../canvas/ViewportContext';
import { standalonePage } from '../standalone';

type Status = { kind: 'idle' } | { kind: 'busy'; text?: string } | { kind: 'done'; text: string } | { kind: 'error'; text: string };

Expand Down Expand Up @@ -98,6 +99,19 @@ export function ExportMenu() {
return 'Saved SVG';
}),
},
...(standalonePage !== undefined
? [
{
label: 'HTML',
hint: 'offline',
act: () =>
run(async () => {
download(new Blob([standalonePage!], { type: 'text/html' }), exportFileName(draft.title, 'html'));
return 'Saved HTML';
}),
},
]
: []),
...(formats.video
? [
{
Expand Down
29 changes: 25 additions & 4 deletions packages/viewer/src/chrome/ViewerShell.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Eye, Workflow } from 'lucide-react';
import { Eye } from 'lucide-react';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { KIND_LABELS, type LaidOutDiagram } from '@stackmap/core';
import { CanvasPanel } from '../canvas/CanvasPanel';
Expand All @@ -19,6 +19,19 @@ const INSPECTOR_BREAKPOINT = 1100;

const DIAGRAM_ID = 'sm-diagram';

const SITE_URL = 'https://stackmap.omsimos.com/';

/** The stackmap mark in the theme's own colours: the lockup's ink, edge grey and database blue. */
function StackmapMark() {
return (
<svg width="20" height="20" viewBox="3 3 42 42" aria-hidden="true">
<path d="M12 28.5v-1.5q0-3 3-3h18q3 0 3-3v-1.5" fill="none" stroke="var(--sm-text)" strokeWidth="3.5" strokeLinejoin="round" />
<rect x="3" y="30" width="18" height="12" rx="3.5" fill="var(--sm-edge)" />
<rect x="27" y="6" width="18" height="12" rx="3.5" fill="var(--sm-database-accent)" />
</svg>
);
}

function ViewCaption() {
const { draft, state } = useExplore();
const caption = draft.views?.find((v) => v.id === state.view)?.caption;
Expand Down Expand Up @@ -101,9 +114,17 @@ export function ViewerShell({
{!presenting && !focused && (
<header className="mx-8 mt-4 flex gap-8 border-b border-divider @max-2xl:mx-4 @max-2xl:mt-2 @max-md:flex-wrap @max-md:gap-x-4 @max-md:gap-y-0">
<div className="flex max-w-[45%] min-w-0 items-center gap-3 py-3 @max-md:max-w-full @max-md:basis-full @max-md:pb-1">
<span aria-hidden="true" className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-panel text-fg-muted" style={{ boxShadow: 'inset 0 0 0 1px var(--sm-panel-border)' }}>
<Workflow size={16} strokeWidth={1.75} />
</span>
<a
href={SITE_URL}
target="_blank"
rel="noopener"
title="Made with stackmap"
className="sm-press grid size-8 shrink-0 place-items-center rounded-[10px] bg-panel hover:bg-page"
style={{ boxShadow: 'inset 0 0 0 1px var(--sm-panel-border)' }}
>
<StackmapMark />
<span className="sr-only">stackmap website (opens in a new tab)</span>
</a>
<Title className="truncate text-[20px] leading-7 font-semibold tracking-tight">{draft.title}</Title>
<span
className="shrink-0 rounded-lg bg-panel px-2 py-0.5 text-[13px] text-fg-muted"
Expand Down
2 changes: 2 additions & 0 deletions packages/viewer/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// First, so it reads the page before anything below changes it.
import './standalone';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { tokens, tokensToCss } from '@stackmap/core';
Expand Down
29 changes: 29 additions & 0 deletions packages/viewer/src/standalone.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

const load = async () => {
vi.resetModules();
return (await import('./standalone')).standalonePage;
};

afterEach(() => {
document.body.innerHTML = '';
});

describe('standalonePage', () => {
it('keeps the delivered page, without the live block a served page carries', async () => {
document.body.innerHTML =
'<div id="root"></div><script type="application/json" id="stackmap-data">{"draft":{}}</script>' +
'<script type="application/json" id="stackmap-live">{"events":"/events","build":"b1"}</script>';
const page = await load();
expect(page).toMatch(/^<!doctype html>\n<html/);
expect(page).toContain('<script type="application/json" id="stackmap-data">{"draft":{}}</script>');
expect(page).not.toContain('stackmap-live');
// The live page itself is left alone.
expect(document.getElementById('stackmap-live')).not.toBeNull();
});

it('is undefined when the page embeds no diagram', async () => {
document.body.innerHTML = '<div id="root"></div><script type="application/json" id="stackmap-data"></script>';
expect(await load()).toBeUndefined();
});
});
15 changes: 15 additions & 0 deletions packages/viewer/src/standalone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { DATA_ELEMENT_ID } from './data';
import { LIVE_ELEMENT_ID } from './live';

/**
* The page as delivered, read when this module loads, before the viewer renders into it, so Export can save it
* again as an offline file. main.tsx imports it first for that reason. Undefined where there is no embedded
* diagram to save (the website's embedded viewer, the dev gallery).
*/
export const standalonePage: string | undefined = (() => {
if (typeof document === 'undefined' || !document.getElementById(DATA_ELEMENT_ID)?.textContent?.trim()) return undefined;
const root = document.documentElement.cloneNode(true) as HTMLElement;
// A page from `stackmap serve` would otherwise keep reconnecting to a server that isn't there.
root.querySelector(`#${LIVE_ELEMENT_ID}`)?.remove();
return `<!doctype html>\n${root.outerHTML}`;
})();
4 changes: 4 additions & 0 deletions site/app/docs/viewer/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ export default function ViewerPage() {
<C>JPEG</C> and <C>WebP</C>, where the browser can encode them
</>,
<C key="svg">SVG</C>,
<>
<C>HTML</C>: the diagram as one offline file, the same as <C>deliver</C> writes. Opened from <C>serve</C>, it leaves out the live
connection. The viewers on this site don’t have it.
</>,
'A short video of the flow, in the format your browser records',
]}
/>
Expand Down
Loading