Skip to content

Commit 478d56a

Browse files
David Engelhartclaude
andcommitted
lumopolis: bookmarks, and a 2D map you can switch on for accessibility
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 39bfdd1 commit 478d56a

14 files changed

Lines changed: 716 additions & 34 deletions

‎e2e/world-view.spec.ts‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,8 @@ async function buildings(root: string): Promise<Array<{ id: string; name: string
220220
}
221221

222222
interface Drawn { layers: { processes: boolean }; processShells: number; conduits: number; highlighted: string[] }
223-
interface Probe { screenPoint(id: string): { x: number; y: number } | null; drawn(): Drawn }
223+
interface Cam { pos: number[]; target: number[] }
224+
interface Probe { screenPoint(id: string): { x: number; y: number } | null; drawn(): Drawn; cameraState(): Cam | null }
224225
const drawn = (): Promise<Drawn | null> =>
225226
page.evaluate(() => (window as unknown as { __termpolis_world?: Probe }).__termpolis_world?.drawn() ?? null)
226227

@@ -590,7 +591,50 @@ test.describe.serial('Lumopolis in the real app', () => {
590591
await expect.poll(async () => (await drawn())?.highlighted.length ?? 0).toBeGreaterThanOrEqual(2)
591592
})
592593

593-
test('8. over the whole session, the renderer logged no console errors and threw no page errors', async () => {
594+
test('8. a saved view comes back after moving away, and the 2D map switch draws an svg map', async () => {
595+
const cam = (): Promise<Cam | null> =>
596+
page.evaluate(() => (window as unknown as { __termpolis_world?: Probe }).__termpolis_world?.cameraState() ?? null)
597+
await page.getByTestId('world-bookmarks').click()
598+
await page.getByTestId('world-bookmark-name').fill('Home view')
599+
await page.getByTestId('world-bookmark-save').click()
600+
// The pose the bookmark holds (the camera may drift a little between a read and the click).
601+
const saved = await page.evaluate(() => {
602+
for (let i = 0; i < localStorage.length; i++) {
603+
const k = localStorage.key(i) as string
604+
if (!k.startsWith('termpolis.world.bookmarks.')) continue
605+
const list = JSON.parse(localStorage.getItem(k) as string) as Array<{ name: string; camera: { pos: number[]; target: number[] } }>
606+
const mine = list.find((b) => b.name === 'Home view')
607+
if (mine) return mine.camera
608+
}
609+
return null
610+
})
611+
expect(saved).not.toBeNull()
612+
await page.getByTestId('world-bookmarks').click() // close the menu
613+
await clickABuilding() // the camera moves to frame it
614+
await expect.poll(async () => {
615+
const c = await cam()
616+
return c ? Math.max(...c.pos.map((v, i) => Math.abs(v - saved!.pos[i]))) : 0
617+
}, { timeout: 8000 }).toBeGreaterThan(0.5)
618+
await page.getByTestId('world-bookmarks').click()
619+
await page.getByTestId('world-bookmark-go').filter({ hasText: 'Home view' }).click()
620+
await expect.poll(async () => {
621+
const c = await cam()
622+
if (!c) return 99
623+
return Math.max(...c.pos.map((v, i) => Math.abs(v - saved!.pos[i])), ...c.target.map((v, i) => Math.abs(v - saved!.target[i])))
624+
}, { timeout: 8000 }).toBeLessThan(0.5)
625+
// The 2D map: an svg with a rect per building, and a click on one opens its card.
626+
await page.getByTestId('world-map2d').click()
627+
const map = page.locator('svg[role=img]')
628+
await expect(map).toBeVisible()
629+
const rects = map.locator('rect[data-kind="building"]')
630+
expect(await rects.count()).toBeGreaterThan(0)
631+
await rects.first().click()
632+
await expect(card()).toBeVisible()
633+
await page.getByTestId('world-map2d').click() // off again
634+
await expect(map).toHaveCount(0)
635+
})
636+
637+
test('9. over the whole session, the renderer logged no console errors and threw no page errors', async () => {
594638
expect(consoleErrors).toEqual([])
595639
})
596640
})

‎src/renderer/src/components/World/WorldToolbar.tsx‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
// The Lumopolis toolbar: the world switcher, layer toggles, theme, tours, reset, re-layout, Build it
22
// (design worlds) and close.
3+
import { useState } from 'react'
34
import type { ReactNode } from 'react'
45
import type { Tour } from '../../../../shared/world/types'
56
import { THEMES } from '../../world/engine'
6-
import type { LayerState, ThemeName } from '../../world/engine'
7+
import type { Bookmark, LayerState, ThemeName } from '../../world/engine'
78

89
export interface WorldToolbarProps {
910
projectName: string
@@ -23,6 +24,18 @@ export interface WorldToolbarProps {
2324
onBuildIt?: () => void
2425
/** The last labelling run's cost line, shown small and muted under the controls; absent: nothing. */
2526
labelCost?: string
27+
/** The saved views of this world, newest first. */
28+
bookmarks: Bookmark[]
29+
/** Saves the camera and what is open now under this name. */
30+
onSaveBookmark: (name: string) => void
31+
/** Goes to a saved view. */
32+
onBookmark: (b: Bookmark) => void
33+
onRemoveBookmark: (name: string) => void
34+
/** Saving needs the 3D camera: off while there is none (no WebGL). */
35+
bookmarkSaveDisabled?: boolean
36+
/** The 2D map is on: a flat SVG map with a list, for screen readers and machines without WebGL. */
37+
map2d: boolean
38+
onMap2d: (on: boolean) => void
2639
}
2740

2841
const THEME_NAMES = Object.keys(THEMES) as ThemeName[]
@@ -33,6 +46,14 @@ const toggleCls = (on: boolean): string => `${btn} ${on ? 'bg-[#094771] text-whi
3346

3447
export function WorldToolbar(props: WorldToolbarProps): JSX.Element {
3548
const { layers, onLayers } = props
49+
const [menu, setMenu] = useState(false)
50+
const [name, setName] = useState('')
51+
const save = (): void => {
52+
const n = name.trim()
53+
if (n === '') return
54+
props.onSaveBookmark(n)
55+
setName('')
56+
}
3657
const toggles: { key: string; label: string; title: string; on: boolean; patch: Partial<LayerState> }[] = [
3758
{
3859
key: 'labels', label: 'Tech names', title: 'Name buildings by their technology instead of their job',
@@ -90,6 +111,73 @@ export function WorldToolbar(props: WorldToolbarProps): JSX.Element {
90111
<option value="">{props.tours.length === 0 ? 'No tours yet' : 'Take a tour…'}</option>
91112
{props.tours.map((t) => <option key={t.id} value={t.id}>{t.title}</option>)}
92113
</select>
114+
<button
115+
type="button"
116+
role="switch"
117+
aria-checked={props.map2d}
118+
title="A flat map with a list instead of the 3D city"
119+
data-testid="world-map2d"
120+
className={toggleCls(props.map2d)}
121+
onClick={() => props.onMap2d(!props.map2d)}
122+
>2D map</button>
123+
<div className="relative">
124+
<button
125+
type="button"
126+
aria-haspopup="true"
127+
aria-expanded={menu}
128+
data-testid="world-bookmarks"
129+
className={`${btn} text-[#cccccc]`}
130+
onClick={() => setMenu(!menu)}
131+
title="Saved views of this map"
132+
>Bookmarks</button>
133+
{menu && (
134+
<div
135+
role="group"
136+
aria-label="Bookmarks"
137+
data-testid="world-bookmarks-menu"
138+
className="absolute left-0 top-full mt-1 p-2 rounded border border-[#3c3c3c] shadow-xl flex flex-col gap-1 text-xs w-64"
139+
style={{ zIndex: 7, background: '#252526' }}
140+
>
141+
<div className="flex gap-1">
142+
<input
143+
aria-label="Name this view"
144+
data-testid="world-bookmark-name"
145+
value={name}
146+
maxLength={60}
147+
placeholder="Name this view"
148+
className="flex-1 min-w-0 px-1.5 py-1 rounded border border-[#3c3c3c] bg-[#1e1e1e] text-[#cccccc]"
149+
onChange={(e) => setName(e.target.value)}
150+
onKeyDown={(e) => { if (e.key === 'Enter') save() }}
151+
/>
152+
<button
153+
type="button"
154+
data-testid="world-bookmark-save"
155+
className={`${btn} text-[#cccccc]`}
156+
disabled={props.bookmarkSaveDisabled === true || name.trim() === ''}
157+
onClick={save}
158+
>Save view</button>
159+
</div>
160+
{props.bookmarks.length === 0 && <p className="text-[#9ca3af] px-1">No saved views yet</p>}
161+
{props.bookmarks.map((b) => (
162+
<div key={b.name} className="flex items-center gap-1">
163+
<button
164+
type="button"
165+
data-testid="world-bookmark-go"
166+
className="flex-1 min-w-0 text-left truncate px-1.5 py-1 rounded hover:bg-[#37373d] text-[#cccccc]"
167+
onClick={() => { props.onBookmark(b); setMenu(false) }}
168+
>{b.name}</button>
169+
<button
170+
type="button"
171+
aria-label={`Remove ${b.name}`}
172+
data-testid="world-bookmark-remove"
173+
className="px-1.5 py-1 rounded text-[#999] hover:text-white hover:bg-[#37373d]"
174+
onClick={() => props.onRemoveBookmark(b.name)}
175+
><i className="fa-solid fa-xmark" aria-hidden="true" /></button>
176+
</div>
177+
))}
178+
</div>
179+
)}
180+
</div>
93181
<div className="flex-1" />
94182
{props.onBuildIt && (
95183
<button

‎src/renderer/src/components/World/WorldView.tsx‎

Lines changed: 65 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ import { useEffect, useRef, useState } from 'react'
2929
import type { MouseEvent, ReactNode } from 'react'
3030
import type { BuildItResult, Evidence, Tour, WorldDoc } from '../../../../shared/world/types'
3131
import { formatTokens } from '../../../../shared/world/tokens'
32-
import { buildingCard, createWorldViewer, DEFAULT_LAYERS, edgeCard, hasWebGL, renderFallback, techCard, THEMES, usesTech } from '../../world/engine'
33-
import type { LayerState, ThemeName, WorldDrawn, WorldViewer } from '../../world/engine'
32+
import { buildingCard, createWorldViewer, DEFAULT_LAYERS, edgeCard, hasWebGL, loadBookmarks, removeBookmark, renderFallback, saveBookmark, techCard, THEMES, usesTech } from '../../world/engine'
33+
import type { Bookmark, CameraState, LayerState, ThemeName, WorldDrawn, WorldViewer } from '../../world/engine'
3434
import { exposesWorldProbe } from '../../lib/testAgents'
3535
import { WorldToolbar } from './WorldToolbar'
3636
import { WorldCard } from './WorldCard'
@@ -84,6 +84,7 @@ export interface WorldProbe {
8484
linePoints(id: string): Array<{ x: number; y: number }>
8585
pickAt(x: number, y: number): { kind: 'node' | 'edge'; id: string } | null
8686
drawn(): WorldDrawn
87+
cameraState(): CameraState | null
8788
}
8889

8990
const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e))
@@ -93,11 +94,22 @@ const baseName = (p: string): string => p.replace(/[\\/]+$/, '').split(/[\\/]/).
9394
const labelCostLine = (tokens: number): string =>
9495
tokens > 0 ? `Describing parts: ${formatTokens(tokens)} on the last update` : 'Describing parts: cached, no tokens'
9596

97+
/** True while the 2D map is chosen (kept between sessions). */
98+
const MAP2D_KEY = 'termpolis.world.map2d'
99+
const readMap2d = (): boolean => {
100+
try { return localStorage.getItem(MAP2D_KEY) === '1' } catch { return false }
101+
}
102+
const hasPart = (d: WorldDoc, id: string): boolean =>
103+
d.buildings.some((b) => b.id === id) || d.externals.some((x) => x.id === id) || d.edges.some((e) => e.id === id) || d.districts.some((x) => x.id === id)
104+
96105
const partCard = (d: WorldDoc, id: string): string | null => buildingCard(d, id) || edgeCard(d, id) || null
97106

98107
export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WIDTH }: WorldViewProps): JSX.Element {
99108
const { world, open, goHome, entries, refresh } = useOpenWorld(root)
100109
const [webgl] = useState(() => hasWebGL())
110+
const [map2d, setMap2d] = useState(readMap2d)
111+
/** The flat map shows: no WebGL, or the switch is on. */
112+
const flat = !webgl || map2d
101113
const [viewer, setViewer] = useState<WorldViewer | null>(null)
102114
const [resolvedRoot, setResolvedRoot] = useState<string | null>(null)
103115
const [attempt, setAttempt] = useState(0)
@@ -357,13 +369,13 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
357369

358370
// Nothing to draw while the home or a loading screen covers the map: stop the render loop.
359371
const covered = world.kind === 'home' || !doc
360-
useEffect(() => { viewer?.setPaused(covered) }, [viewer, covered])
372+
useEffect(() => { viewer?.setPaused(covered || map2d) }, [viewer, covered, map2d])
361373

362374
// The e2e probe, while this viewer is up (and only under the test flag).
363375
useEffect(() => {
364376
if (!viewer || !exposesWorldProbe()) return
365377
const w = window as unknown as { __termpolis_world?: WorldProbe }
366-
const probe: WorldProbe = { screenPoint: (id) => viewer.screenPoint(id), linePoints: (id) => viewer.linePoints(id), pickAt: (x, y) => viewer.pickAt(x, y), drawn: () => viewer.drawn() }
378+
const probe: WorldProbe = { screenPoint: (id) => viewer.screenPoint(id), linePoints: (id) => viewer.linePoints(id), pickAt: (x, y) => viewer.pickAt(x, y), drawn: () => viewer.drawn(), cameraState: () => viewer.cameraState() }
367379
w.__termpolis_world = probe
368380
return () => { if (w.__termpolis_world === probe) delete w.__termpolis_world }
369381
}, [viewer])
@@ -387,9 +399,41 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
387399
// its part is gone).
388400
useEffect(() => {
389401
const id = fallbackIdRef.current
390-
if (viewer || !doc || id === null) return
402+
if ((viewer && !map2d) || !doc || id === null) return
391403
setCard((c) => (c === null ? null : partCard(doc, id)))
392-
}, [viewer, doc])
404+
}, [viewer, map2d, doc])
405+
406+
// Saved views of this world.
407+
const projectKey = doc ? doc.projectKey : null
408+
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
409+
useEffect(() => { setBookmarks(projectKey === null ? [] : loadBookmarks(projectKey)) }, [projectKey])
410+
const onSaveBookmark = (name: string): void => {
411+
const v = viewer as WorldViewer // the save button is off without a viewer
412+
const cam = v.cameraState()
413+
if (!cam) return
414+
setBookmarks(saveBookmark((docRef.current as WorldDoc).projectKey, { name, camera: cam, selection: v.getSelection() }))
415+
}
416+
const onBookmark = (b: Bookmark): void => {
417+
if (!viewer) return
418+
const d = docRef.current as WorldDoc
419+
// A part the world no longer has is skipped.
420+
const ids = b.selection.filter((id) => hasPart(d, id))
421+
armedRef.current = false
422+
// The card's own framing flight lands first, then the saved pose takes the camera from it.
423+
if (ids.length > 0) void viewer.apply({ type: 'openCard', id: ids[0] }).then(() => viewer.setCamera(b.camera, false))
424+
else {
425+
viewer.resetView()
426+
void viewer.setCamera(b.camera, false)
427+
}
428+
}
429+
const onRemoveBookmark = (name: string): void => setBookmarks(removeBookmark((docRef.current as WorldDoc).projectKey, name))
430+
const onMap2d = (on: boolean): void => {
431+
try { localStorage.setItem(MAP2D_KEY, on ? '1' : '0') } catch { /* not remembered */ }
432+
armedRef.current = false
433+
fallbackIdRef.current = null
434+
setCard(null)
435+
setMap2d(on)
436+
}
393437

394438
const onLayers = (patch: Partial<LayerState>): void => {
395439
setLayersState((l) => ({ ...l, ...patch }))
@@ -401,7 +445,7 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
401445
}
402446
const onTour = (tour: Tour): void => {
403447
armedRef.current = false
404-
if (viewer) void viewer.play([{ type: 'tour', steps: tour.steps }])
448+
if (viewer && !map2d) void viewer.play([{ type: 'tour', steps: tour.steps }])
405449
else setCard(null)
406450
}
407451
const resetView = (): void => {
@@ -412,7 +456,7 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
412456
/** Open a part's card: through the viewer (it flies there), or straight from the doc in 2D. */
413457
const openPart = (id: string): void => {
414458
armedRef.current = false
415-
if (viewer) { void viewer.apply({ type: 'openCard', id }); return }
459+
if (viewer && !map2d) { void viewer.apply({ type: 'openCard', id }); return }
416460
const d = docRef.current as WorldDoc
417461
fallbackIdRef.current = id
418462
setCard(partCard(d, id))
@@ -421,7 +465,7 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
421465
const openTech = (techId: string): void => {
422466
armedRef.current = false
423467
const d = docRef.current as WorldDoc
424-
if (viewer) {
468+
if (viewer && !map2d) {
425469
void viewer.apply({ type: 'openCard', id: 'tech:' + techId })
426470
void viewer.apply({ type: 'highlight', ids: usesTech(d, techId) })
427471
return
@@ -547,6 +591,13 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
547591
onClose={onClose}
548592
switcher={<WorldSwitcher entries={entries} onOpen={(t) => openWorld(t)} onHome={goHome} />}
549593
onBuildIt={designKey !== null && buildIt && doc ? () => setBuilding(true) : undefined}
594+
bookmarks={bookmarks}
595+
onSaveBookmark={onSaveBookmark}
596+
onBookmark={onBookmark}
597+
onRemoveBookmark={onRemoveBookmark}
598+
bookmarkSaveDisabled={!viewer || !doc}
599+
map2d={map2d}
600+
onMap2d={onMap2d}
550601
labelCost={labelling && doc && doc.labelTokens !== undefined ? labelCostLine(doc.labelTokens) : undefined}
551602
/>
552603
<div ref={stageRef} data-testid="world-stage" style={{ position: 'relative', flex: '1 1 auto', minHeight: 0, overflow: 'hidden' }}>
@@ -556,18 +607,18 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
556607
data-testid="world-canvas-host"
557608
// Its own stacking context beneath the panels: the label layer numbers each label's
558609
// z-index up from zero, which would otherwise draw names over the card and legend.
559-
style={{ position: 'absolute', inset: 0, zIndex: 0, isolation: 'isolate', visibility: doc ? 'visible' : 'hidden' }}
610+
style={{ position: 'absolute', inset: 0, zIndex: 0, isolation: 'isolate', visibility: doc && !map2d ? 'visible' : 'hidden' }}
560611
onPointerDown={() => { armedRef.current = false }}
561612
/>
562613
)}
563-
{!webgl && doc && (
614+
{flat && doc && (
564615
<div
565616
data-testid="world-fallback"
566617
className="overflow-auto p-6 text-sm [&_h2]:text-lg [&_h2]:font-semibold [&_h3]:mt-3 [&_h3]:font-semibold [&_li]:cursor-pointer [&_ul]:pl-4 [&_p]:text-[#9ca3af]"
567618
style={{ position: 'absolute', inset: 0 }}
568619
onClick={onFallbackClick}
569620
// renderFallback escapes every string from the doc.
570-
dangerouslySetInnerHTML={{ __html: renderFallback(doc) }}
621+
dangerouslySetInnerHTML={{ __html: renderFallback(doc, projectName) }}
571622
/>
572623
)}
573624
{home && <WorldHome entries={entries} projectCwd={root} onOpen={(t) => openWorld(t)} onChanged={refresh} />}
@@ -579,7 +630,7 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
579630
onRetry={() => setAttempt((n) => n + 1)}
580631
/>
581632
)}
582-
{webgl && doc && !home && <WorldLegend doc={doc} processes={layers.processes} open={legendOpen} onToggle={() => setLegendChoice(!legendOpen)} />}
633+
{webgl && !map2d && doc && !home && <WorldLegend doc={doc} processes={layers.processes} open={legendOpen} onToggle={() => setLegendChoice(!legendOpen)} />}
583634
{confirmRelayout && (
584635
<div
585636
role="alertdialog"
@@ -623,7 +674,7 @@ export function WorldView({ root, onClose, askSlot, buildIt, width = DEFAULT_WID
623674
)}
624675
{askSlot && !home && (
625676
<div ref={askRef} style={{ position: 'absolute', bottom: ASK_BOTTOM_PX, left: '50%', transform: 'translateX(-50%)', width: ASK_SLOT_WIDTH, zIndex: 3 }} data-testid="world-ask-slot">
626-
{askSlot(viewer, doc, worldKey, askLink)}
677+
{askSlot(map2d ? null : viewer, doc, worldKey, askLink)}
627678
</div>
628679
)}
629680
</div>

0 commit comments

Comments
 (0)