A browser back and forward through the circuits (mouse side buttons)

Every step into or out of a circuit, and to another project, is a browser
history entry holding the circuit and its crumbs. The mouse's back and
forward buttons, Alt + arrows and the browser's buttons go through them as
visited; a reload, or going back to an entry from before one, opens that
entry's circuit. In Chrome the mouse's back button on the first entry goes
up a crumb instead of leaving the editor. Share and puzzle pages open their
link only on the first load, so history landing on them does not reload it,
and the account sync starts once per page load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-26 23:04:32 +01:00
parent a29215162c
commit 4dfd97d192
7 changed files with 309 additions and 15 deletions

View File

@ -7,7 +7,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
## What it does ## What it does
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note. - Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note.
- Layout like Figma: two floating rounded bars over the canvas, a panel on the left for the circuit you are in and one on the right for what is selected. The top bar, across the whole width: menu (pause menu) with the project name, "Main" and the way into the open component (each name leads back; every other circuit is a component and opens with a double-click, or the pencil in the Components list), Challenges (campaign, puzzle of the week, puzzles, challenges in a drop-down), the clock, search, undo, sound, settings, help, share and account. The bottom bar: your pinned parts first (NAND, AND, OR, NOT, XOR, input, output, lamp, clock to start with; pin from the lists, right-click to unpin, kept per browser, components by name), then one button per kind of part (Logic, Inputs, Outputs, Wiring, Notes, Connectors, Components) that opens its parts on pointing, and a search that opens quick add. - Layout like Figma: two floating rounded bars over the canvas, a panel on the left for the circuit you are in and one on the right for what is selected. The top bar, across the whole width: menu (pause menu) with the project name, "Main" and the way into the open component (each name leads back; every other circuit is a component and opens with a double-click, or the pencil in the Components list); every step into or out of a circuit, and to another project, is an entry in the browser's history, so the mouse's back and forward buttons (and Alt + ← →, the browser's buttons) go through them as visited, crumbs included, also after a reload. In Chrome the mouse's back button never leaves the editor: on the first entry it goes up a crumb. A share or puzzle address opens its link only when the page is loaded with it, not when going back or forward lands on it, Challenges (campaign, puzzle of the week, puzzles, challenges in a drop-down), the clock, search, undo, sound, settings, help, share and account. The bottom bar: your pinned parts first (NAND, AND, OR, NOT, XOR, input, output, lamp, clock to start with; pin from the lists, right-click to unpin, kept per browser, components by name), then one button per kind of part (Logic, Inputs, Outputs, Wiring, Notes, Connectors, Components) that opens its parts on pointing, and a search that opens quick add.
- Small windows: the bars keep their steady centred width on wide screens and are never narrower than 760px as far as the panels leave room; they move off the centre rather than under a panel. On a narrow bar the words go first, then the names between Main and the open component fold into "…" (a menu leading back to each), and sound, settings and help (then undo, redo and share, then challenges and search) move into a "⋯" menu; Main is always there. From 821 to 1100px the selection's panel floats over the canvas edge between the bars instead of narrowing the canvas; below that the panels sit under the canvas. Drop-downs, flyouts and the search box stay on screen. - Small windows: the bars keep their steady centred width on wide screens and are never narrower than 760px as far as the panels leave room; they move off the centre rather than under a panel. On a narrow bar the words go first, then the names between Main and the open component fold into "…" (a menu leading back to each), and sound, settings and help (then undo, redo and share, then challenges and search) move into a "⋯" menu; Main is always there. From 821 to 1100px the selection's panel floats over the canvas edge between the bars instead of narrowing the canvas; below that the panels sit under the canvas. Drop-downs, flyouts and the search box stay on screen.
- Quick add (Space, /, Shift+A, Ctrl+K): parts and actions at the mouse. Shift+Enter (or Ctrl+Enter, or the pencil on its line) opens the chosen component to edit it instead of placing it, and typing a name lists "Open <name>" for every circuit of the project, also those that cannot be placed here; the one you are in shows as where you are. Going to one on the way here goes back along the way ([app/lib/nav.ts](app/lib/nav.ts)). - Quick add (Space, /, Shift+A, Ctrl+K): parts and actions at the mouse. Shift+Enter (or Ctrl+Enter, or the pencil on its line) opens the chosen component to edit it instead of placing it, and typing a name lists "Open <name>" for every circuit of the project, also those that cannot be placed here; the one you are in shows as where you are. Going to one on the way here goes back along the way ([app/lib/nav.ts](app/lib/nav.ts)).
- Lamps and output pins pass their signal on: the pin on their right carries the same value, so a lamp can sit in the middle of a wire. - Lamps and output pins pass their signal on: the pin on their right carries the same value, so a lamp can sit in the middle of a wire.

View File

@ -26,6 +26,7 @@ const SHORTCUTS: [string, string][] = [
['Mouse wheel', 'Zoom'], ['Mouse wheel', 'Zoom'],
['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'], ['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'],
['Bar at the bottom', 'Point at a kind of part to see them all; click to place, drag onto the canvas, pin the ones you use most to the bar itself (right-click a pinned part to unpin it)'], ['Bar at the bottom', 'Point at a kind of part to see them all; click to place, drag onto the canvas, pin the ones you use most to the bar itself (right-click a pinned part to unpin it)'],
['Mouse back / forward buttons, Alt + ← →', 'Back and forward through the circuits you went into and out of, like pages in the browser (the browser\'s own buttons do the same)'],
['Main (top bar)','Back to the main circuit; the names after it lead back to each component you entered (on a narrow bar the ones in between fold into …)'], ['Main (top bar)','Back to the main circuit; the names after it lead back to each component you entered (on a narrow bar the ones in between fold into …)'],
['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'], ['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'],
['⋯ (top bar, small window)', 'Sound, settings, help and whatever else no longer fits in the bar'], ['⋯ (top bar, small window)', 'Sound, settings, help and whatever else no longer fits in the bar'],

View File

@ -530,10 +530,41 @@ function create() {
} }
// ── Navigation ──────────────────────────────────────────────────── // ── Navigation ────────────────────────────────────────────────────
function open(id: string, push = true) { // Every step to another circuit is also an entry in the browser's history,
// so its back and forward (the mouse's side buttons, Alt + ← →, the
// browser's buttons) go through the circuits the way they were visited,
// the crumbs along with them.
/** Where the editor is, as kept in a browser history entry. */
interface NavEntry {
/** Project, open circuit, and the crumbs to it. */
p: string
id: string
nav: string[]
/** Steps from the first entry the editor wrote. */
i: number
}
const browserHistory = typeof history !== 'undefined' && typeof history.pushState === 'function'
const entryNow = () => (history.state as { lg?: NavEntry } | null)?.lg
/** Going back or forward to an entry: what that changes is written into it, not as a new one. */
let restoring = false
/** Writes where the editor is into the browser's history: as a new entry (`push`), or into the current one. */
function record(push: boolean) {
if (!browserHistory) return
push &&= !restoring
const i = (entryNow()?.i ?? 0) + (push ? 1 : 0)
// Whatever else the entry holds (the router's own bookkeeping) stays as it is.
const state = { ...(history.state ?? {}), lg: { p: meta.value.id, id: def.value.id, nav: [...nav.value], i } satisfies NavEntry }
if (push) history.pushState(state, '')
else history.replaceState(state, '')
}
/** Shows another circuit; what the one left was holding is kept for when it opens again. */
function show(id: string) {
if (id === def.value.id || !getDef.value(id)) return if (id === def.value.id || !getDef.value(id)) return
keepState() keepState()
if (push) nav.value.push(def.value.id)
project.value.openId = id project.value.openId = id
clearSelection() clearSelection()
placing.value = null placing.value = null
@ -542,9 +573,39 @@ function create() {
rebuild() rebuild()
} }
/** Shows a circuit with the crumbs to it: a new step in the browser's history when it is another circuit. */
function go(id: string, crumbs: string[]) {
if (!getDef.value(id)) return
const moved = id !== def.value.id
nav.value = crumbs
show(id)
record(moved)
}
/** Goes into a circuit, one step further along the way. */
function open(id: string) {
if (id !== def.value.id) go(id, [...nav.value, def.value.id])
}
/** The browser went back or forward (or reloaded): to the circuit of that entry, in its project, as far as they still exist. */
function restoreEntry(s: NavEntry | undefined) {
if (!s) return
restoring = true
try {
if (s.p !== meta.value.id && listProjects().some(m => m.id === s.p)) switchProject(s.p)
if (s.p === meta.value.id && getDef.value(s.id)) {
nav.value = s.nav.filter(id => getDef.value(id) && id !== s.id)
show(s.id)
}
record(false)
} finally {
restoring = false
}
}
/** One step back along the crumbs. */
function back() { function back() {
const id = nav.value.pop() goTo(nav.value.length - 1)
if (id) open(id, false)
} }
/** The project's top circuit: "main", or else the first one no other circuit uses. */ /** The project's top circuit: "main", or else the first one no other circuit uses. */
@ -555,18 +616,15 @@ function create() {
return (list.find(d => !used.has(d.id) && !d.challenge) ?? list[0]!).id return (list.find(d => !used.has(d.id) && !d.challenge) ?? list[0]!).id
}) })
/** Back to the top circuit; the way back is forgotten. */ /** Back to the top circuit; the crumbs are forgotten, the browser's back still leads where you were. */
function goMain() { function goMain() {
nav.value = [] go(mainId.value, [])
open(mainId.value, false)
} }
/** Back to step `i` of the way here (0 is where it started). */ /** Back to step `i` of the way here (0 is where it started). */
function goTo(i: number) { function goTo(i: number) {
const id = nav.value[i] const id = nav.value[i]
if (!id) return if (id) go(id, nav.value.slice(0, i))
nav.value = nav.value.slice(0, i)
open(id, false)
} }
// ── Editing ─────────────────────────────────────────────────────── // ── Editing ───────────────────────────────────────────────────────
@ -1948,6 +2006,8 @@ function create() {
// ── Projects ────────────────────────────────────────────────────── // ── Projects ──────────────────────────────────────────────────────
function activate(m: ProjectMeta, p: Project) { function activate(m: ProjectMeta, p: Project) {
// Another project is a step in the browser's history; a newer save of this one is not.
const moved = m.id !== meta.value.id
placeholder = false placeholder = false
meta.value = m meta.value = m
project.value = p project.value = p
@ -1960,6 +2020,7 @@ function create() {
for (const k of Object.keys(views)) delete views[k] for (const k of Object.keys(views)) delete views[k]
linkState.value = m.link ? (m.link.key ? 'saved' : 'viewer') : 'none' linkState.value = m.link ? (m.link.key ? 'saved' : 'viewer') : 'none'
projects.value = listProjects() projects.value = listProjects()
record(moved)
syncUrl() syncUrl()
// A project that arrives (another computer's newer save, a savegame) runs from the bits it brings, even with the same circuit open. // A project that arrives (another computer's newer save, a savegame) runs from the bits it brings, even with the same circuit open.
simRoot = '' simRoot = ''
@ -2200,6 +2261,25 @@ function create() {
document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && saveState(true)) document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && saveState(true))
setInterval(saveState, 30_000) setInterval(saveState, 30_000)
if (browserHistory) {
window.addEventListener('popstate', e => restoreEntry((e.state as { lg?: NavEntry } | null)?.lg))
// The mouse's back button on the first entry would leave the editor: it goes up the crumbs instead,
// or stays (Chrome lets a page stop it; other browsers go back as usual).
window.addEventListener('mouseup', e => {
if (e.button !== 3 || screen.value !== 'editor' || (entryNow()?.i ?? 0) > 0) return
e.preventDefault()
back()
})
}
/** The page the app was loaded with opens its link once; the browser's back or forward landing on such a page later does not. */
let landed = false
function firstPage(): boolean {
const first = !landed
landed = true
return first
}
// ── Account ─────────────────────────────────────────────────────── // ── Account ───────────────────────────────────────────────────────
// Signed in, every project in this browser is also kept in the account and // Signed in, every project in this browser is also kept in the account and
// other devices get it on their next sync. Each upload names the revision // other devices get it on their next sync. Each upload names the revision
@ -2492,7 +2572,11 @@ function create() {
} }
/** Checks the session with the server, then syncs; again on focus and every minute. */ /** Checks the session with the server, then syncs; again on focus and every minute. */
let accountStarted = false
async function startAccount() { async function startAccount() {
// Once per page load, however often the editor is shown.
if (accountStarted) return
accountStarted = true
try { try {
const res = await authCall<{ user: AccountUser | null; status: number }>('GET', '/api/auth/me') const res = await authCall<{ user: AccountUser | null; status: number }>('GET', '/api/auth/me')
setAccount(res.user) setAccount(res.user)
@ -2519,8 +2603,14 @@ function create() {
} }
rebuild() rebuild()
// A reload, or back or forward to an entry from before one: where that entry was. A fresh tab starts its first entry here.
if (browserHistory) {
if (entryNow()) restoreEntry(entryNow())
else record(false)
}
return { return {
firstPage,
project, project,
meta, meta,
projects, projects,

View File

@ -1,6 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
const ed = useEditor() const ed = useEditor()
onMounted(() => ed.syncUrl()) onMounted(() => {
ed.firstPage()
ed.syncUrl()
})
</script> </script>
<template> <template>

View File

@ -2,7 +2,8 @@
// A share link: /p/<id> opens that project (or your own copy of it). // A share link: /p/<id> opens that project (or your own copy of it).
const route = useRoute() const route = useRoute()
const ed = useEditor() const ed = useEditor()
onMounted(() => ed.openLink(String(route.params.id))) // Only when the app was loaded with it: going back or forward to it later just shows that entry.
onMounted(() => (ed.firstPage() ? ed.openLink(String(route.params.id)) : ed.syncUrl()))
</script> </script>
<template> <template>

View File

@ -2,7 +2,8 @@
// A puzzle link: /puzzle/<id> adds that puzzle to the open project and opens it. // A puzzle link: /puzzle/<id> adds that puzzle to the open project and opens it.
const route = useRoute() const route = useRoute()
const ed = useEditor() const ed = useEditor()
onMounted(() => ed.openPuzzle(String(route.params.id))) // Only when the app was loaded with it: going back or forward to it later just shows that entry.
onMounted(() => (ed.firstPage() ? ed.openPuzzle(String(route.params.id)) : ed.syncUrl()))
</script> </script>
<template> <template>

198
tests/nav-history.test.ts Normal file
View File

@ -0,0 +1,198 @@
// Going into components and out again with the browser's back and forward
// (the mouse's side buttons): every step is a browser history entry. Runs
// the real composable in a stand-in browser with its own history.
import * as vue from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createProject } from '../app/lib/logic/ops'
import { saveProject, setCurrentId, type ProjectMeta } from '../app/lib/logic/storage'
import type { Project } from '../app/lib/logic/types'
/** Top holds Mid, Mid holds Leaf. */
function nested(name = 'Nested'): Project {
const p = createProject({ examples: false })
p.name = name
p.components = [
{ id: 'top', name: 'Top', symbol: 'box', nodes: [{ id: 'm', kind: 'chip', chip: 'mid', x: 0, y: 0 }], wires: [] },
{ id: 'mid', name: 'Mid', symbol: 'box', nodes: [{ id: 'l', kind: 'chip', chip: 'leaf', x: 0, y: 0 }], wires: [] },
{ id: 'leaf', name: 'Leaf', symbol: 'box', nodes: [{ id: 'g', kind: 'nand', x: 0, y: 0 }], wires: [] },
]
p.openId = 'top'
return p
}
function stored(p: Project, id: string): ProjectMeta {
const m: ProjectMeta = { id, name: p.name, updated: Date.now() }
saveProject(m, p)
return m
}
/** This browser: its storage and its tab's history, kept across reloads. */
let store: Map<string, string>
let entries: unknown[]
let at: number
/** A tab with the editor open, on the history entry `at`. */
async function openTab() {
const events = new Map<string, ((e: unknown) => void)[]>()
const on = (type: string, f: (e: unknown) => void) => events.set(type, [...(events.get(type) ?? []), f])
const fire = (type: string, e: unknown = {}) => events.get(type)?.forEach(f => f(e))
const history = {
get state() {
return entries[at] ?? null
},
pushState(s: unknown) {
entries.splice(at + 1)
entries.push(structuredClone(s))
at++
},
replaceState(s: unknown) {
entries[at] = structuredClone(s)
},
back() {
if (at === 0) return
at--
fire('popstate', { state: history.state })
},
forward() {
if (at === entries.length - 1) return
at++
fire('popstate', { state: history.state })
},
}
vi.stubGlobal('window', { addEventListener: on })
vi.stubGlobal('document', { addEventListener: on, visibilityState: 'visible' })
vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' })
vi.stubGlobal('history', history)
for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch'] as const) vi.stubGlobal(k, vue[k])
vi.resetModules()
const { useEditor } = await import('../app/composables/useEditor')
const ed = useEditor()
ed.enterGame()
return {
ed,
history,
/** The open circuit and the crumbs to it. */
where: () => [...ed.nav.value, ed.def.value.id].join(' > '),
/** A press of the mouse's back button: whether the page stopped the browser going back. */
mouseBack() {
const e = { button: 3, defaultPrevented: false, preventDefault: () => (e.defaultPrevented = true) }
fire('mouseup', e)
if (!e.defaultPrevented) history.back()
return e.defaultPrevented
},
}
}
beforeEach(() => {
store = new Map()
entries = [null]
at = 0
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
})
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] })
stored(nested(), 'p1')
setCurrentId('p1')
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
describe('the browser history walking the circuits', () => {
it('goes back and forward through the components as they were entered, crumbs and all', async () => {
const tab = await openTab()
tab.ed.open('mid')
tab.ed.open('leaf')
expect(tab.where()).toBe('top > mid > leaf')
tab.history.back()
expect(tab.where()).toBe('top > mid')
tab.history.back()
expect(tab.where()).toBe('top')
tab.history.forward()
expect(tab.where()).toBe('top > mid')
tab.history.forward()
expect(tab.where()).toBe('top > mid > leaf')
})
it('takes Main and the crumbs as steps too, so back returns to where you were', async () => {
const tab = await openTab()
tab.ed.open('mid')
tab.ed.open('leaf')
tab.ed.goMain()
expect(tab.where()).toBe('top')
tab.history.back()
expect(tab.where()).toBe('top > mid > leaf')
tab.ed.goTo(1)
expect(tab.where()).toBe('top > mid')
tab.history.back()
expect(tab.where()).toBe('top > mid > leaf')
// Clicking Main while there writes no step.
tab.ed.goMain()
const steps = entries.length
tab.ed.goMain()
expect(entries.length).toBe(steps)
})
it('forgets the steps ahead when you go somewhere new, like a browser', async () => {
const tab = await openTab()
tab.ed.open('mid')
tab.ed.open('leaf')
tab.history.back()
tab.history.back()
tab.ed.open('leaf')
tab.history.forward()
expect(tab.where()).toBe('top > leaf')
})
it('opens the circuit of the entry after a reload, and after going back to an entry from before one', async () => {
let tab = await openTab()
tab.ed.open('mid')
tab.ed.open('leaf')
tab = await openTab()
expect(tab.where()).toBe('top > mid > leaf')
// Back from here loads the page anew on the entry before (the saved project has Leaf open).
at--
tab = await openTab()
expect(tab.where()).toBe('top > mid')
})
it('stops the mouse back button on the first entry instead of leaving the editor', async () => {
const tab = await openTab()
tab.ed.open('mid')
expect(tab.mouseBack()).toBe(false)
expect(tab.where()).toBe('top')
expect(tab.mouseBack()).toBe(true)
expect(tab.where()).toBe('top')
})
it('takes another project as a step: back opens the one before at the circuit it had open', async () => {
stored(nested('Other'), 'p2')
const tab = await openTab()
tab.ed.open('mid')
tab.ed.switchProject('p2')
expect(tab.ed.meta.value.id).toBe('p2')
tab.ed.open('leaf')
tab.history.back()
expect([tab.ed.meta.value.id, tab.where()]).toEqual(['p2', 'top'])
tab.history.back()
expect([tab.ed.meta.value.id, tab.where()]).toEqual(['p1', 'top > mid'])
tab.history.forward()
tab.history.forward()
expect([tab.ed.meta.value.id, tab.where()]).toEqual(['p2', 'top > leaf'])
})
it('passes over circuits that were deleted since', async () => {
const tab = await openTab()
tab.ed.open('mid')
tab.ed.open('leaf')
tab.ed.goMain()
tab.ed.project.value.components = tab.ed.project.value.components.filter(d => d.id !== 'leaf')
tab.history.back()
expect(tab.where()).toBe('top')
})
})