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
14 changes: 8 additions & 6 deletions packages/viewer/src/canvas/DiagramCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useFlow } from '../motion/useFlow';
import { hasFlow } from '../motion/flowOf';
import { useSceneReveal } from '../motion/useSceneReveal';
import { useExplore } from '../explore/ExploreContext';
import { routeOf } from '../explore/state';
import { useInScope } from '../explore/scope';
import { routeBetween } from '../explore/graph';
import { inMenu } from '../chrome/Toolbar';
Expand Down Expand Up @@ -45,15 +46,16 @@ function useCameraEffects(scene: Scene, camera: Camera, restored: boolean) {
else camera.fit();
}, [state.view, draft, rectOf, camera]);
// A new route frames everything on it.
const shownRoute = useRef(restored ? state.route : null);
const route = routeOf(state.mode);
const shownRoute = useRef(restored ? route : null);
useEffect(() => {
if (shownRoute.current === state.route) return;
shownRoute.current = state.route;
if (!state.route) return;
const on = routeBetween(graph, state.route.from, state.route.to)?.nodes ?? new Set([state.route.from, state.route.to]);
if (shownRoute.current === route) return;
shownRoute.current = route;
if (!route) return;
const on = routeBetween(graph, route.from, route.to)?.nodes ?? new Set([route.from, route.to]);
const box = union([...on].flatMap((id) => rectOf.get(id) ?? []));
if (box) camera.fitRect(box);
}, [state.route, graph, rectOf, camera]);
}, [route, graph, rectOf, camera]);
// The reveal a live reload restores from the hash is already on screen.
const restoredReveal = useRef(restored ? state.reveal : -1);
const latest = useRef({ state, draft });
Expand Down
18 changes: 11 additions & 7 deletions packages/viewer/src/chrome/ExportMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { useExplore } from '../explore/ExploreContext';
import { useScene, useSceneContent } from '../canvas/ViewportContext';
import { standalonePage } from '../standalone';

/** idle → busy → done | error; opening the menu again returns to idle (the button is disabled while busy). */
type Status = { kind: 'idle' } | { kind: 'busy'; text?: string } | { kind: 'done'; text: string } | { kind: 'error'; text: string };
const IDLE: Status = { kind: 'idle' };

export function ExportMenu() {
const { draft, state, graph, emphasis } = useExplore();
Expand All @@ -17,12 +19,18 @@ export function ExportMenu() {
// What this browser can write, checked once.
const [formats] = useState(() => ({ jpeg: canEncode('image/jpeg'), webp: canEncode('image/webp'), video: videoType() }));
const [open, setOpen] = useState(false);
const [status, setStatus] = useState<Status>({ kind: 'idle' });
const [status, setStatus] = useState<Status>(IDLE);
const root = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
const menu = useRef<HTMLDivElement>(null);
// Opened from the keyboard (ArrowDown, or Enter/Space: a click with detail 0) the menu appears at once.
const byKey = useRef(false);
const toggle = (keyboard: boolean) => {
byKey.current = keyboard;
// The last export's message makes way for the menu, which would otherwise open on top of an error.
if (!open) setStatus(IDLE);
setOpen(!open);
};
// The menu is right-aligned under the button: grow it from the button's centre.
useLayoutEffect(() => {
if (!open || !menu.current || byKey.current) return;
Expand Down Expand Up @@ -140,15 +148,11 @@ export function ExportMenu() {
aria-haspopup="menu"
aria-expanded={open}
disabled={status.kind === 'busy'}
onClick={(e) => {
byKey.current = e.detail === 0;
setOpen((v) => !v);
}}
onClick={(e) => toggle(e.detail === 0)}
onKeyDown={(e) => {
if (e.key === 'ArrowDown' && !open) {
e.preventDefault();
byKey.current = true;
setOpen(true);
toggle(true);
}
}}
className="sm-press flex h-9 items-center gap-2 rounded-full bg-primary px-4 text-[14px] font-medium text-primary-fg disabled:opacity-60 @max-md:px-2.5"
Expand Down
15 changes: 9 additions & 6 deletions packages/viewer/src/chrome/Inspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { countByType, TYPE_LABELS, type DiagramDraft, type DiagramEdge, type Dia
import { focusCard } from '../canvas/SceneLayers';
import { routeBetween } from '../explore/graph';
import { useExplore } from '../explore/ExploreContext';
import { isRouting, routeOf } from '../explore/state';
import { useViewerRoot } from '../explore/scope';
import { useInFlight } from '../motion/inFlight';
import { swapIn } from '../motion/motion';
Expand Down Expand Up @@ -265,22 +266,23 @@ function RouteDetail({ toggle }: { toggle: ReactNode }) {
</div>
</div>
);
if (!state.route) {
const { mode } = state;
if (mode.kind !== 'route') {
return (
<>
{header}
<p className="mt-2 text-[13px] text-fg-muted">
{state.routing?.next === 'to' ? `From ${title(state.routing.start)}: pick where the route ends.` : 'Pick the node the route starts from.'}
{mode.kind === 'pickEnd' ? `From ${title(mode.from)}: pick where the route ends.` : 'Pick the node the route starts from.'}
</p>
</>
);
}
const route = routeBetween(graph, state.route.from, state.route.to);
const route = routeBetween(graph, mode.from, mode.to);
return (
<>
{header}
<H className="mt-1 text-[18px] font-semibold tracking-tight break-words text-fg">
{title(state.route.from)} → {title(state.route.to)}
{title(mode.from)} → {title(mode.to)}
</H>
{!route ? (
<p className="mt-2 text-[13px] text-fg-muted">No directed connections lead from one to the other.</p>
Expand Down Expand Up @@ -390,7 +392,8 @@ export function Inspector({
// Collapsed, a selection or route would change nothing visible beyond the canvas (a phone starts collapsed):
// the toggle names what it would show, so a tapped card visibly has details waiting.
const name = (id: string) => draft.nodes.find((n) => n.id === id)?.card.title ?? id;
const showing = state.route ? `${name(state.route.from)} → ${name(state.route.to)}` : selected?.card.title;
const route = routeOf(state.mode);
const showing = route ? `${name(route.from)} → ${name(route.to)}` : selected?.card.title;
return (
<aside aria-label="Inspector" className={`shrink-0 self-start rounded-2xl bg-panel p-1.5 ${narrow ? NARROW_COLLAPSED : ''}`} style={PANEL_STYLE}>
{showing ? (
Expand Down Expand Up @@ -419,7 +422,7 @@ export function Inspector({
<Level.Provider value={headingLevel}>
<aside aria-label="Inspector" className={`relative shrink-0 overflow-y-auto rounded-[20px] bg-panel p-5 ${narrow ? `w-[300px] ${NARROW_OPEN}` : ''}`} style={PANEL_STYLE}>
<div ref={body}>
{state.route || state.routing ? (
{isRouting(state.mode) ? (
<RouteDetail toggle={toggle} />
) : selected ? (
<NodeDetail node={selected} toggle={toggle} />
Expand Down
48 changes: 48 additions & 0 deletions packages/viewer/src/chrome/Toolbar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { commerceApiLayout } from '../samples/commerce-api.layout';
import { ExploreProvider, useExplore } from '../explore/ExploreContext';
import { Toolbar } from './Toolbar';

let explore: ReturnType<typeof useExplore>;
function Spy() {
explore = useExplore();
return null;
}

describe('Toolbar', () => {
it('shows one popover at a time, even when search is opened from outside the toolbar', () => {
render(
<ExploreProvider draft={commerceApiLayout.draft} syncHash={false}>
<Toolbar theme="light" onToggleTheme={() => {}} exports={false} />
<Spy />
</ExploreProvider>,
);
fireEvent.click(screen.getByRole('button', { name: 'Filter by type' }));
expect(screen.getByRole('button', { name: 'Filter by type' })).toHaveAttribute('aria-expanded', 'true');
// A page beside the viewer (the website's demo buttons) opens search through the explorer, without a click here.
act(() => explore.dispatch({ type: 'search', query: 'orders' }));
expect(screen.getByRole('button', { name: 'Filter by type' })).toHaveAttribute('aria-expanded', 'false');
expect(screen.getByRole('button', { name: 'Search nodes (/)' })).toHaveAttribute('aria-expanded', 'true');
// Closing search doesn't bring the lens back.
act(() => explore.dispatch({ type: 'search', query: null }));
expect(screen.getByRole('button', { name: 'Filter by type' })).toHaveAttribute('aria-expanded', 'false');
});

it('presses Trace or Route for the mode that is on, and disables Trace while routing', () => {
render(
<ExploreProvider draft={commerceApiLayout.draft} syncHash={false}>
<Toolbar theme="light" onToggleTheme={() => {}} exports={false} />
</ExploreProvider>,
);
const trace = screen.getByRole('button', { name: 'Trace upstream and downstream of the selection' });
const route = screen.getByRole('button', { name: 'Route between two nodes (R)' });
fireEvent.click(trace);
expect(trace).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(route);
expect(route).toHaveAttribute('aria-pressed', 'true');
expect(trace).toHaveAttribute('aria-pressed', 'false');
expect(trace).toBeDisabled();
expect(screen.getByRole('status')).toHaveTextContent('Pick where the route starts');
});
});
41 changes: 24 additions & 17 deletions packages/viewer/src/chrome/Toolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EyeOff, Filter, Focus, Moon, Presentation, Route, Search, Sun, Waypoints } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useExplore } from '../explore/ExploreContext';
import { isRouting } from '../explore/state';
import { useInScope } from '../explore/scope';
import type { ThemeChoice } from '../theme/theme';
import { ExportMenu } from './ExportMenu';
Expand Down Expand Up @@ -38,8 +39,9 @@ export function Toolbar({
const { state, dispatch } = useExplore();
const inScope = useInScope();
const [lensOpen, setLensOpen] = useState(false);
const routing = isRouting(state.mode);
const routingRef = useRef(false);
routingRef.current = !!state.routing || !!state.route;
routingRef.current = routing;
const root = useRef<HTMLDivElement>(null);
const searchButton = useRef<HTMLButtonElement>(null);
const lensButton = useRef<HTMLButtonElement>(null);
Expand All @@ -57,6 +59,13 @@ export function Toolbar({
};
const next = theme === 'dark' ? 'light' : 'dark';
const searchOpen = state.query !== null;
// One popover at a time. Search lives in the explorer, where a page beside the viewer can open it too, so it wins;
// the lens is hidden in the same render and closed for good just after.
const lensShown = lensOpen && !searchOpen;
useEffect(() => {
if (searchOpen) setLensOpen(false);
}, [searchOpen]);
const picking = state.mode.kind === 'pickStart' || state.mode.kind === 'pickEnd' ? state.mode : null;

// "/" opens search from anywhere except a text field; Escape from the page body clears the selection
// (cards, the stage and the popovers handle their own Escape and stop it).
Expand All @@ -78,7 +87,6 @@ export function Toolbar({
}
if (e.key !== '/') return;
e.preventDefault();
setLensOpen(false);
setSearchByKey(true);
dispatch({ type: 'search', query: '' });
};
Expand All @@ -88,23 +96,23 @@ export function Toolbar({

// Clicking outside closes the popovers.
useEffect(() => {
if (!searchOpen && !lensOpen) return;
if (!searchOpen && !lensShown) return;
const onDown = (e: PointerEvent) => {
if (root.current?.contains(e.target as Node)) return;
setLensOpen(false);
if (searchOpen) dispatch({ type: 'search', query: null });
};
addEventListener('pointerdown', onDown);
return () => removeEventListener('pointerdown', onDown);
}, [searchOpen, lensOpen, dispatch]);
}, [searchOpen, lensShown, dispatch]);

return (
<div
ref={root}
className={`${PANEL_CLASS} relative flex shrink-0 items-center gap-0.5 p-1.5 @max-md:shrink @max-md:flex-wrap`}
style={PANEL_STYLE}
onKeyDown={(e) => {
if (e.key !== 'Escape' || !lensOpen) return;
if (e.key !== 'Escape' || !lensShown) return;
e.preventDefault();
e.stopPropagation();
closeLens();
Expand All @@ -116,7 +124,6 @@ export function Toolbar({
pressed={searchOpen}
expanded={searchOpen}
onClick={(e) => {
setLensOpen(false);
setSearchByKey(e.detail === 0);
dispatch({ type: 'search', query: searchOpen ? null : '' });
}}
Expand All @@ -126,27 +133,27 @@ export function Toolbar({
<IconButton
ref={lensButton}
label="Filter by type"
pressed={lensOpen || state.hiddenTypes.size > 0}
expanded={lensOpen}
pressed={lensShown || state.hiddenTypes.size > 0}
expanded={lensShown}
onClick={(e) => {
dispatch({ type: 'search', query: null });
setLensByKey(e.detail === 0);
setLensOpen((v) => !v);
setLensOpen(!lensShown);
}}
>
<Filter size={17} strokeWidth={1.75} />
</IconButton>
{trace && (
<IconButton
label="Trace upstream and downstream of the selection"
pressed={state.trace && !state.route && !state.routing}
disabled={!!state.route || !!state.routing}
pressed={state.mode.kind === 'trace'}
disabled={routing}
onClick={() => dispatch({ type: 'toggleTrace' })}
>
<Route size={17} strokeWidth={1.75} />
</IconButton>
)}
<IconButton label="Route between two nodes (R)" pressed={!!state.routing || !!state.route} onClick={() => dispatch({ type: 'toggleRoute' })}>
<IconButton label="Route between two nodes (R)" pressed={routing} onClick={() => dispatch({ type: 'toggleRoute' })}>
<Waypoints size={17} strokeWidth={1.75} />
</IconButton>
<PlayButton />
Expand Down Expand Up @@ -177,19 +184,19 @@ export function Toolbar({
{/* Always mounted, so screen readers announce the hint when its text arrives. */}
<p
role="status"
className={`${state.routing ? `${PANEL_CLASS} absolute top-full left-0 mt-2 w-max px-3 py-2 text-[12.5px] text-fg` : 'sr-only'}`}
style={state.routing ? PANEL_STYLE : undefined}
className={`${picking ? `${PANEL_CLASS} absolute top-full left-0 mt-2 w-max px-3 py-2 text-[12.5px] text-fg` : 'sr-only'}`}
style={picking ? PANEL_STYLE : undefined}
>
{state.routing && (
{picking && (
<>
{state.routing.next === 'from' ? 'Pick where the route starts' : 'Now pick where it ends'}
{picking.kind === 'pickStart' ? 'Pick where the route starts' : 'Now pick where it ends'}
{/* The space keeps the two phrases apart for screen readers; ml-2 alone only spaces them visually. */}{' '}
<span className="ml-1 text-fg-muted">Esc cancels</span>
</>
)}
</p>
{searchOpen && <SearchPanel onClose={closeSearch} origin={searchByKey ? undefined : originOf(searchButton.current)} />}
{lensOpen && <LensPanel origin={lensByKey ? undefined : originOf(lensButton.current)} />}
{lensShown && <LensPanel origin={lensByKey ? undefined : originOf(lensButton.current)} />}
</div>
);
}
12 changes: 12 additions & 0 deletions packages/viewer/src/chrome/ViewerShell.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,16 @@ describe('ViewerShell', () => {
render(<ViewerShell diagram={commerceApiLayout} theme="light" onToggleTheme={() => {}} />);
for (const name of [/add/i, /undo/i, /redo/i, /lock/i]) expect(screen.queryByRole('button', { name })).toBeNull();
});

it('clears a failed export once the menu opens again, so the menu never opens over the error', async () => {
render(<ViewerShell diagram={commerceApiLayout} theme="light" onToggleTheme={() => {}} />);
const button = screen.getByRole('button', { name: 'Export' });
fireEvent.click(button);
// jsdom has no clipboard, so Copy PNG fails before it draws anything.
fireEvent.click(screen.getByRole('menuitem', { name: /Copy PNG/ }));
expect(await screen.findByText('Export failed: clipboard not available here', { selector: 'p' })).toBeInTheDocument();
fireEvent.click(button);
expect(screen.getByRole('menu', { name: 'Export' })).toBeInTheDocument();
expect(screen.queryByText('Export failed: clipboard not available here', { selector: 'p' })).not.toBeInTheDocument();
});
});
Loading
Loading