Merge branch 'feat/responsive'

# Conflicts:
#	app/components/editor/Help.vue
This commit is contained in:
Fabian @ Blax Software 2026-10-26 18:54:49 +01:00
commit ab47235e38
8 changed files with 380 additions and 64 deletions

View File

@ -8,6 +8,8 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- 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), 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.
- 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.
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)). - Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open. - Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.

View File

@ -64,8 +64,13 @@ kbd {
.workspace { .workspace {
--left: 272px; --left: 272px;
--right: 280px; --right: 280px;
/* The top bar keeps the width it has with both panels open, centred, whatever is open. */ /* The bars keep the width they have with both panels open, centred, whatever is open.
--bar-inset: calc(280px + 12px); On a smaller window they stay at least 760px wide as far as the panels leave room,
moving off the centre rather than under a panel. */
--bar-start: calc(var(--left) + 12px);
--bar-end: 12px;
--bar-w: min(max(100% - 2 * (280px + 12px), 760px), 100% - var(--bar-start) - var(--bar-end));
--bar-x: clamp(var(--bar-start), (100% - var(--bar-w)) / 2, 100% - var(--bar-end) - var(--bar-w));
position: relative; position: relative;
display: grid; display: grid;
grid-template-columns: var(--left) 1fr; grid-template-columns: var(--left) 1fr;
@ -77,6 +82,7 @@ kbd {
} }
.workspace.has-selection { .workspace.has-selection {
--bar-end: calc(var(--right) + 12px);
grid-template-columns: var(--left) 1fr var(--right); grid-template-columns: var(--left) 1fr var(--right);
} }
@ -112,10 +118,32 @@ kbd {
} }
} }
/* A smaller window: the selection's panel floats over the canvas edge between
the bars instead of narrowing the canvas, and the bars run past it. */
@media (min-width: 821px) and (max-width: 1100px) {
.workspace.has-selection {
--bar-end: 12px;
grid-template-columns: var(--left) 1fr;
}
.workspace > .selection-panel {
position: absolute;
top: 62px;
right: 10px;
bottom: 72px;
z-index: 15;
width: var(--right);
overflow: hidden;
border: 1px solid var(--border);
border-radius: 12px;
box-shadow: 0 18px 50px rgb(0 0 0 / 0.5);
}
}
@media (max-width: 820px) { @media (max-width: 820px) {
.workspace, .workspace,
.workspace.has-selection { .workspace.has-selection {
--bar-inset: 12px; --bar-start: 12px;
--bar-end: 12px;
grid-template-columns: 1fr; grid-template-columns: 1fr;
grid-template-rows: 1fr 40%; grid-template-rows: 1fr 40%;
} }
@ -1656,6 +1684,25 @@ kbd {
text-align: center; text-align: center;
} }
/* Where the parts bar reaches the canvas's lower right corner (beside the
selection's panel, or on a window under 760 + 2 × 292px), the zoom buttons
sit above it. */
.workspace.has-selection .zoom-controls {
bottom: 72px;
}
@media (max-width: 1343px) {
.zoom-controls {
bottom: 72px;
}
}
@media (min-width: 821px) and (max-width: 1100px) {
.workspace.has-selection .zoom-controls {
right: calc(var(--right) + 22px);
}
}
.empty-hint { .empty-hint {
position: absolute; position: absolute;
inset: 0; inset: 0;
@ -3681,7 +3728,7 @@ kbd {
.quick-add { .quick-add {
position: fixed; position: fixed;
z-index: 60; z-index: 60;
width: 340px; width: min(340px, calc(100vw - 16px));
padding-bottom: 6px; padding-bottom: 6px;
border: 1px solid #2d3745; border: 1px solid #2d3745;
border-radius: 10px; border-radius: 10px;
@ -3713,6 +3760,26 @@ kbd {
flex-shrink: 0; flex-shrink: 0;
} }
/* The circuit you are in: listed, not offered. */
.quick-add .item:disabled {
background: none;
color: var(--muted);
cursor: default;
}
/* The pencil that opens a component shows on the row pointed at or chosen with the arrows. */
.quick-add .comp-row:has(.item.active) .open {
opacity: 1;
}
.quick-foot {
margin-top: 4px;
padding: 6px 12px 0;
border-top: 1px solid var(--border);
font-size: 11px;
color: var(--muted);
}
/* ── Title screen ───────────────────────────────────────────────── */ /* ── Title screen ───────────────────────────────────────────────── */
.brand { .brand {
padding: 4px 8px 4px 4px; padding: 4px 8px 4px 4px;
@ -4568,8 +4635,8 @@ table.board {
/* Same width and place as the top bar, whatever panels are open. */ /* Same width and place as the top bar, whatever panels are open. */
.bottom-dock { .bottom-dock {
position: absolute; position: absolute;
left: var(--bar-inset); left: var(--bar-x);
right: var(--bar-inset); width: var(--bar-w);
bottom: 14px; bottom: 14px;
z-index: 20; z-index: 20;
container-type: inline-size; container-type: inline-size;
@ -4829,8 +4896,8 @@ table.board {
.top-dock { .top-dock {
position: absolute; position: absolute;
top: 10px; top: 10px;
left: var(--bar-inset); left: var(--bar-x);
right: var(--bar-inset); width: var(--bar-w);
z-index: 30; z-index: 30;
container-type: inline-size; container-type: inline-size;
pointer-events: none; pointer-events: none;
@ -4884,8 +4951,11 @@ table.board {
border-radius: 8px; border-radius: 8px;
} }
/* On a narrow bar the project's name gives way first, down to the logo. */
.brand-btn { .brand-btn {
color: var(--on) !important; color: var(--on) !important;
flex-shrink: 1;
min-width: 38px;
max-width: 260px; max-width: 260px;
} }
@ -4895,15 +4965,16 @@ table.board {
font-weight: 700; font-weight: 700;
} }
/* Main never shrinks; the names after it do, cut off with "…". */
.crumbs { .crumbs {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 1px; gap: 1px;
min-width: 0; min-width: 0;
overflow: hidden;
} }
.crumb { .crumb {
flex-shrink: 1;
min-width: 0; min-width: 0;
max-width: 180px; max-width: 180px;
} }
@ -4924,7 +4995,7 @@ table.board {
position: absolute; position: absolute;
top: calc(100% + 10px); top: calc(100% + 10px);
left: 50%; left: 50%;
width: 340px; width: min(340px, calc(100vw - 16px));
max-height: min(72vh, 640px); max-height: min(72vh, 640px);
overflow-y: auto; overflow-y: auto;
padding: 10px; padding: 10px;
@ -4950,8 +5021,9 @@ table.board {
translate: 0 -4px; translate: 0 -4px;
} }
/* The bars follow the width of the canvas, which shrinks while the selection panel is open. */ /* On a narrower bar the words go first, the icons stay (the buttons used least
@container (max-width: 1000px) { move into "⋯", see Toolbar.vue); Main keeps its house. */
@container (max-width: 1180px) {
.top-bar .status, .top-bar .status,
.top-bar .cycles, .top-bar .cycles,
.top-bar .bar-count, .top-bar .bar-count,
@ -4962,13 +5034,28 @@ table.board {
@container (max-width: 760px) { @container (max-width: 760px) {
.top-bar .project-name, .top-bar .project-name,
.top-bar .crumbs .bar-btn > span:not(.truncate),
.top-bar .tb-select { .top-bar .tb-select {
display: none; display: none;
} }
.top-bar .bar-btn { .top-bar .bar-btn {
padding: 0 7px; padding: 0 7px;
} }
.top-bar .brand-btn {
min-width: 34px;
}
}
@container (max-width: 640px) {
.top-bar .main-label {
display: none;
}
}
/* A narrow parts bar: the kinds of parts close up so all of them fit. */
@container (max-width: 420px) {
.bottom-bar .bar-btn {
padding: 0 7px;
}
} }
/* Pinned parts at the start of the parts bar. */ /* Pinned parts at the start of the parts bar. */
@ -5485,6 +5572,10 @@ button.tile:hover {
.bottom-dock { .bottom-dock {
bottom: calc(40% + 14px); bottom: calc(40% + 14px);
} }
/* The canvas is the top 60%: a flyout stays below the top bar. */
.flyout {
max-height: min(460px, calc(60dvh - 140px));
}
} }
.panel-rows .row-side.hz { .panel-rows .row-side.hz {

View File

@ -361,7 +361,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
</button> </button>
</div> </div>
<div class="bb-group end"> <div class="bb-group end">
<button class="bar-btn" title="Find a part or an action (Space or /)" @click="ed.partSearch.value++"> <button class="bar-btn" title="Find a part, a circuit to open or an action (Space or /)" @click="ed.partSearch.value++">
<Icon name="lucide:search" class="size-[18px]" /> <Icon name="lucide:search" class="size-[18px]" />
<kbd class="bar-label">Space</kbd> <kbd class="bar-label">Space</kbd>
</button> </button>

View File

@ -26,8 +26,9 @@ 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)'],
['Main (top bar)', 'Back to the main circuit; the names after it lead back to each component you entered'], ['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'],
['[', 'Hide or show the panel on the left (This and Pins)'], ['[', 'Hide or show the panel on the left (This and Pins)'],
['Library (bottom bar: Components, or Space)', 'Components everyone published: search, add one to this project (what it uses comes along; not in a campaign) and place it. Publish your own, or a new version, from the menu on the circuit’s name'], ['Library (bottom bar: Components, or Space)', 'Components everyone published: search, add one to this project (what it uses comes along; not in a campaign) and place it. Publish your own, or a new version, from the menu on the circuit’s name'],
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'], ['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
@ -44,6 +45,7 @@ const SHORTCUTS: [string, string][] = [
['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'], ['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'],
['Ctrl+F', 'Find a part, signal or component in every circuit, and where a component is used'], ['Ctrl+F', 'Find a part, signal or component in every circuit, and where a component is used'],
['Space (tap)', 'Search at the mouse: recent parts and actions like a new component; type a few letters, arrows to choose, Enter to take it'], ['Space (tap)', 'Search at the mouse: recent parts and actions like a new component; type a few letters, arrows to choose, Enter to take it'],
['Shift+Enter in the search', 'Open the chosen component to edit it instead of placing it (or click its pencil); typing any circuit\'s name also offers "Open …"'],
['/, Shift+A or Ctrl+K', 'The same search box'], ['/, Shift+A or Ctrl+K', 'The same search box'],
['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'], ['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'],
['Select switches or buttons, Combine', 'One input panel (all rows can become buttons); lamps or output pins combine into an output panel'], ['Select switches or buttons, Combine', 'One input panel (all rows can become buttons); lamps or output pins combine into an output panel'],

View File

@ -1,9 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
// The search box at the mouse (Space, /, Shift+A or Ctrl+K): parts to place // The search box at the mouse (Space, /, Shift+A or Ctrl+K): parts to place
// right there, and things to do. Empty, it shows the parts used lately and // right there, and things to do. Empty, it shows the parts used lately and
// the common actions; typing narrows both. Arrows choose, Enter takes it. // the common actions; typing narrows both and offers to open the circuits
// of that name. Arrows choose, Enter takes it, Shift+Enter opens a component.
import { matchScore } from '~/lib/match' import { matchScore } from '~/lib/match'
import type { NodeKind } from '~/lib/logic/types' import { circuitsNamed, wayTo } from '~/lib/nav'
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
const props = defineProps<{ x: number; y: number }>() const props = defineProps<{ x: number; y: number }>()
const emit = defineEmits<{ pick: [p: { kind: NodeKind; chip?: string }]; fit: []; close: [] }>() const emit = defineEmits<{ pick: [p: { kind: NodeKind; chip?: string }]; fit: []; close: [] }>()
@ -14,6 +16,7 @@ const query = ref('')
const at = ref(0) const at = ref(0)
const input = ref<HTMLInputElement>() const input = ref<HTMLInputElement>()
const el = ref<HTMLElement>() const el = ref<HTMLElement>()
const list = ref<HTMLElement>()
interface Action { interface Action {
id: string id: string
@ -69,7 +72,10 @@ const ACTIONS: Action[] = [
{ id: 'menu', label: 'Menu: save, load, main menu', icon: 'lucide:menu', keys: 'Esc', aka: 'pause quit', run: () => ed.pause() }, { id: 'menu', label: 'Menu: save, load, main menu', icon: 'lucide:menu', keys: 'Esc', aka: 'pause quit', run: () => ed.pause() },
] ]
type Item = { type: 'part'; id: string; kind: NodeKind; chip?: string; label: string; icon: string; note?: string } | { type: 'action'; id: string; act: Action; label: string; icon: string; note?: string } type Item =
| { type: 'part'; id: string; kind: NodeKind; chip?: string; label: string; icon: string; note?: string }
| { type: 'action'; id: string; act: Action; label: string; icon: string; note?: string }
| { type: 'open'; id: string; def: string; label: string; icon: string; note?: string; here?: boolean }
const partItem = (p: { kind: NodeKind; chip?: string; name: string; icon: string }, note?: string): Item => ({ const partItem = (p: { kind: NodeKind; chip?: string; name: string; icon: string }, note?: string): Item => ({
type: 'part', type: 'part',
@ -81,9 +87,14 @@ const partItem = (p: { kind: NodeKind; chip?: string; name: string; icon: string
note, note,
}) })
const actItem = (a: Action): Item => ({ type: 'action', id: `a:${a.id}`, act: a, label: a.label, icon: a.icon, note: a.keys }) const actItem = (a: Action): Item => ({ type: 'action', id: `a:${a.id}`, act: a, label: a.label, icon: a.icon, note: a.keys })
// Any circuit can be opened, placeable here or not; the one you are in is only shown.
const openItem = (d: ComponentDef): Item =>
d.id === ed.def.value.id
? { type: 'open', id: `o:${d.id}`, def: d.id, label: d.name, icon: 'lucide:map-pin', note: 'you are here', here: true }
: { type: 'open', id: `o:${d.id}`, def: d.id, label: `Open ${d.name}`, icon: 'lucide:log-in' }
const offered = () => ACTIONS.filter(a => !a.when || a.when()) const offered = () => ACTIONS.filter(a => !a.when || a.when())
/** Sections to show: parts first, then actions. */ /** Sections to show: parts first, then circuits to open, then actions. */
const sections = computed(() => { const sections = computed(() => {
const q = query.value.trim() const q = query.value.trim()
if (!q) { if (!q) {
@ -101,27 +112,44 @@ const sections = computed(() => {
.sort((x, y) => y.s - x.s) .sort((x, y) => y.s - x.s)
.slice(0, 5) .slice(0, 5)
.map(x => actItem(x.a)) .map(x => actItem(x.a))
const circuits = circuitsNamed(ed.project.value.components, q).map(openItem)
return [ return [
{ title: 'Parts', items: parts }, { title: 'Parts', items: parts },
{ title: 'Circuits', items: circuits },
{ title: 'Actions', items: acts }, { title: 'Actions', items: acts },
].filter(s => s.items.length) ].filter(s => s.items.length)
}) })
const flat = computed(() => sections.value.flatMap(s => s.items)) /** What the arrows walk through: everything but the circuit you are in. */
const flat = computed(() => sections.value.flatMap(s => s.items).filter(it => !(it.type === 'open' && it.here)))
const indexOf = (it: Item) => flat.value.indexOf(it) const indexOf = (it: Item) => flat.value.indexOf(it)
watch(query, () => (at.value = 0)) watch(query, () => (at.value = 0))
function take(it: Item | undefined) { /** Takes what was chosen; `edit` opens a component instead of placing it. */
if (!it) return function take(it: Item | undefined, edit = false) {
if (!it || (it.type === 'open' && it.here)) return
if (it.type === 'open') return go(it.def)
if (it.type === 'part' && it.chip && edit) return go(it.chip)
if (it.type === 'part') return emit('pick', { kind: it.kind, chip: it.chip }) if (it.type === 'part') return emit('pick', { kind: it.kind, chip: it.chip })
emit('close') emit('close')
it.act.run() it.act.run()
} }
/** Into a circuit: back along the way when it is on it, else one step further in. */
function go(id: string) {
emit('close')
const way = wayTo(ed.nav.value, ed.mainId.value, id)
if (way === 'main') ed.goMain()
else if (way === 'open') ed.open(id)
else ed.goTo(way)
}
const pos = ref({ left: props.x, top: props.y }) const pos = ref({ left: props.x, top: props.y })
onMounted(() => { onMounted(() => {
input.value?.focus() input.value?.focus()
const r = el.value!.getBoundingClientRect() const r = el.value!.getBoundingClientRect()
pos.value = { left: Math.max(8, Math.min(props.x, window.innerWidth - r.width - 8)), top: Math.max(8, Math.min(props.y, window.innerHeight - 440)) } // Room below for the list at its longest, so typing never pushes the box off the window.
const tall = r.height - list.value!.offsetHeight + Math.min(420, window.innerHeight * 0.6)
pos.value = { left: Math.max(8, Math.min(props.x, window.innerWidth - r.width - 8)), top: Math.max(8, Math.min(props.y, window.innerHeight - tall - 8)) }
window.addEventListener('pointerdown', outside, true) window.addEventListener('pointerdown', outside, true)
}) })
onBeforeUnmount(() => window.removeEventListener('pointerdown', outside, true)) onBeforeUnmount(() => window.removeEventListener('pointerdown', outside, true))
@ -139,7 +167,7 @@ function onKey(e: KeyboardEvent) {
nextTick(() => el.value?.querySelector('.item.active')?.scrollIntoView({ block: 'nearest' })) nextTick(() => el.value?.querySelector('.item.active')?.scrollIntoView({ block: 'nearest' }))
} else if (e.key === 'Enter') { } else if (e.key === 'Enter') {
e.preventDefault() e.preventDefault()
take(flat.value[at.value]) take(flat.value[at.value], e.shiftKey || e.ctrlKey || e.metaKey)
} else if (e.key === 'Escape') { } else if (e.key === 'Escape') {
e.preventDefault() e.preventDefault()
emit('close') emit('close')
@ -152,25 +180,35 @@ function onKey(e: KeyboardEvent) {
<div ref="el" class="quick-add" :style="{ left: `${pos.left}px`, top: `${pos.top}px` }" @keydown="onKey"> <div ref="el" class="quick-add" :style="{ left: `${pos.left}px`, top: `${pos.top}px` }" @keydown="onKey">
<div class="search part-search"> <div class="search part-search">
<Icon name="lucide:search" class="size-3.5 text-(--muted)" /> <Icon name="lucide:search" class="size-3.5 text-(--muted)" />
<input ref="input" v-model="query" placeholder="Find a part or an action…" /> <input ref="input" v-model="query" placeholder="Find a part, a circuit or an action…" />
</div> </div>
<div class="quick-list"> <div ref="list" class="quick-list">
<template v-for="s in sections" :key="s.title"> <template v-for="s in sections" :key="s.title">
<p class="quick-head">{{ s.title }}</p> <p class="quick-head">{{ s.title }}</p>
<ul class="items"> <ul class="items">
<li v-for="it in s.items" :key="it.id"> <li v-for="it in s.items" :key="it.id" class="comp-row">
<button class="item" :class="{ active: indexOf(it) === at }" @pointerenter="at = indexOf(it)" @click="take(it)"> <button
class="item"
:class="{ active: indexOf(it) === at }"
:disabled="it.type === 'open' && it.here"
@pointerenter="indexOf(it) >= 0 && (at = indexOf(it))"
@click="take(it)"
>
<span v-if="it.type === 'part' && it.kind === 'nand'" class="nand-badge">&amp;</span> <span v-if="it.type === 'part' && it.kind === 'nand'" class="nand-badge">&amp;</span>
<Icon v-else :name="it.icon" class="size-4 shrink-0" :class="it.type === 'action' ? 'text-(--accent)' : 'text-(--muted)'" /> <Icon v-else :name="it.icon" class="size-4 shrink-0" :class="it.type === 'part' ? 'text-(--muted)' : 'text-(--accent)'" />
<span class="grow truncate">{{ it.label }}</span> <span class="grow truncate">{{ it.label }}</span>
<kbd v-if="it.type === 'action' && it.note">{{ it.note }}</kbd> <kbd v-if="it.type === 'action' && it.note">{{ it.note }}</kbd>
<span v-else-if="it.note" class="group-tag">{{ it.note }}</span> <span v-else-if="it.note" class="group-tag">{{ it.note }}</span>
</button> </button>
<button v-if="it.type === 'part' && it.chip" class="open" title="Open it and edit inside (Shift+Enter)" @click="take(it, true)">
<Icon name="lucide:pencil" class="size-3.5" />
</button>
</li> </li>
</ul> </ul>
</template> </template>
<p v-if="!flat.length" class="hint px-3 pb-2">Nothing called "{{ query.trim() }}" here.</p> <p v-if="!sections.length" class="hint px-3 pb-2">Nothing called "{{ query.trim() }}" here.</p>
</div> </div>
<p class="quick-foot"><kbd>Enter</kbd> takes it, <kbd>Shift+Enter</kbd> opens a component to edit it.</p>
</div> </div>
</Teleport> </Teleport>
</template> </template>

View File

@ -1,7 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
// The bar along the top, floating like the parts bar below: menu and where // The bar along the top, floating like the parts bar below: menu and where
// you are on the left, the clock in the middle, the rest on the right. // you are on the left, the clock in the middle, the rest on the right. On a
// narrow bar the names on the way fold into "…" and the buttons used least
// move into a "⋯" menu, so Main always stays in reach.
import { CHALLENGES } from '~/lib/logic/challenges' import { CHALLENGES } from '~/lib/logic/challenges'
import { foldCrumbs } from '~/lib/nav'
import type { MenuEntry } from '~/composables/useMenu' import type { MenuEntry } from '~/composables/useMenu'
const ed = useEditor() const ed = useEditor()
@ -26,11 +29,25 @@ const path = computed(() =>
) )
const atMain = computed(() => ed.def.value.id === ed.mainId.value) const atMain = computed(() => ed.def.value.id === ed.mainId.value)
// How wide the bar is decides what fits in it.
const dock = ref<HTMLElement>()
const width = ref(Infinity)
let sizer: ResizeObserver | undefined
/** Buttons moved into the "⋯" menu: none; sound, settings and help; also undo, redo and share; also challenges and search. */
const tucked = computed(() => (width.value > 640 ? 0 : width.value > 520 ? 1 : width.value > 420 ? 2 : 3))
/** The names on the way here, the last ones in the bar and those before them under "…". */
const crumbs = computed(() => foldCrumbs(path.value, width.value > 1180 ? 3 : width.value > 900 ? 2 : 1))
/** Where a menu opens: under the button that opened it. */
function below(e: MouseEvent) {
const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
return { x: r.left, y: r.bottom + 6 }
}
// The circuit you are in: its name opens what can be done with all of it. // The circuit you are in: its name opens what can be done with all of it.
const circuitMenu = ref<{ x: number; y: number } | null>(null) const circuitMenu = ref<{ x: number; y: number } | null>(null)
function openCircuitMenu(e: MouseEvent) { function openCircuitMenu(e: MouseEvent) {
const r = (e.currentTarget as HTMLElement).getBoundingClientRect() circuitMenu.value = circuitMenu.value ? null : below(e)
circuitMenu.value = circuitMenu.value ? null : { x: r.left, y: r.bottom + 6 }
} }
const circuitEntries = computed<MenuEntry[]>(() => { const circuitEntries = computed<MenuEntry[]>(() => {
const d = ed.def.value const d = ed.def.value
@ -86,8 +103,27 @@ const solvedCount = computed(() => CHALLENGES.filter(c => ed.project.value.solve
function outside(e: PointerEvent) { function outside(e: PointerEvent) {
if (showChallenges.value && !challengesEl.value?.contains(e.target as Node)) showChallenges.value = false if (showChallenges.value && !challengesEl.value?.contains(e.target as Node)) showChallenges.value = false
} }
onMounted(() => window.addEventListener('pointerdown', outside, true)) /** The drop-down is centred under its button, moved sideways as far as it takes to stay on screen. */
onBeforeUnmount(() => window.removeEventListener('pointerdown', outside, true)) const popShift = ref(0)
function placePop() {
const r = challengesEl.value?.getBoundingClientRect()
if (!showChallenges.value || !r) return
const w = Math.min(340, window.innerWidth - 16)
const left = r.left + r.width / 2 - w / 2
popShift.value = Math.max(8, Math.min(left, window.innerWidth - 8 - w)) - left
}
watch(showChallenges, placePop)
onMounted(() => {
window.addEventListener('pointerdown', outside, true)
window.addEventListener('resize', placePop)
sizer = new ResizeObserver(([e]) => (width.value = e!.contentRect.width))
sizer.observe(dock.value!)
})
onBeforeUnmount(() => {
window.removeEventListener('pointerdown', outside, true)
window.removeEventListener('resize', placePop)
sizer?.disconnect()
})
const cloudText = computed(() => ({ off: '', syncing: 'syncing', synced: 'all saved', offline: 'offline', error: 'sync failed' })[ed.cloudState.value]) const cloudText = computed(() => ({ off: '', syncing: 'syncing', synced: 'all saved', offline: 'offline', error: 'sync failed' })[ed.cloudState.value])
const linkIcon = computed(() => { const linkIcon = computed(() => {
switch (ed.linkState.value) { switch (ed.linkState.value) {
@ -102,14 +138,43 @@ const linkIcon = computed(() => {
return 'lucide:share-2' return 'lucide:share-2'
} }
}) })
// The names folded into "…": each leads back to it.
const foldMenu = ref<{ x: number; y: number } | null>(null)
const foldEntries = computed<MenuEntry[]>(() => crumbs.value.folded.map(p => ({ label: p.name, icon: 'lucide:box', run: () => ed.goTo(p.i) })))
// The buttons that did not fit, in the order they have in the bar.
const moreMenu = ref<{ x: number; y: number } | null>(null)
const moreEntries = computed<MenuEntry[]>(() => {
const list: MenuEntry[] = []
if (tucked.value > 2) {
list.push(
{ label: 'Challenges and puzzles', icon: 'lucide:flag', note: `${solvedCount.value}/${CHALLENGES.length}`, run: () => (showChallenges.value = true) },
{ label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', run: () => (ed.dialog.value = 'search') },
)
}
if (tucked.value > 1) {
list.push(
{ label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', disabled: !ed.canUndo.value, run: () => ed.undo() },
{ label: 'Redo', icon: 'lucide:redo-2', keys: 'Ctrl+Shift+Z', disabled: !ed.canRedo.value, run: () => ed.redo() },
)
}
list.push(
{ label: 'Sound', icon: 'lucide:volume-x', checked: ed.sound.value.on, run: () => ed.setSound({ on: !ed.sound.value.on }) },
{ label: 'Settings', icon: 'lucide:settings', run: () => (ed.dialog.value = 'settings') },
{ label: 'How to play', icon: 'lucide:circle-help', keys: '?', run: () => (ed.showHelp.value = true) },
)
if (tucked.value > 1) list.push('sep', { label: 'Share', icon: linkIcon.value, run: () => (ed.dialog.value = 'share') })
return list
})
</script> </script>
<template> <template>
<div class="top-dock"> <div ref="dock" class="top-dock">
<header class="top-bar"> <header class="top-bar">
<div class="tb-group min-w-0"> <div class="tb-group min-w-0">
<button class="bar-btn brand-btn" title="Menu: save, load, settings, main menu (Esc)" @click="ed.pause()"> <button class="bar-btn brand-btn" title="Menu: save, load, settings, main menu (Esc)" @click="ed.pause()">
<svg viewBox="0 0 32 32" class="size-5" aria-hidden="true"> <svg viewBox="0 0 32 32" class="size-5 shrink-0" aria-hidden="true">
<path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.5" /> <path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.5" />
<circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.2" /> <circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.2" />
</svg> </svg>
@ -124,10 +189,21 @@ const linkIcon = computed(() => {
@click="atMain ? openCircuitMenu($event) : ed.goMain()" @click="atMain ? openCircuitMenu($event) : ed.goMain()"
> >
<Icon name="lucide:house" class="size-4" /> <Icon name="lucide:house" class="size-4" />
<span>Main</span> <span class="main-label">Main</span>
<Icon v-if="atMain" name="lucide:chevron-down" class="size-3.5 text-(--muted)" /> <Icon v-if="atMain" name="lucide:chevron-down" class="size-3.5 text-(--muted)" />
</button> </button>
<template v-for="p in path" :key="`${p.id}-${p.i}`"> <template v-if="crumbs.folded.length">
<Icon name="lucide:chevron-right" class="crumb-sep size-3.5" />
<button
class="bar-btn"
:class="{ open: !!foldMenu }"
:title="`${crumbs.folded.length} more on the way here: ${crumbs.folded.map(p => p.name).join(', ')}`"
@click="foldMenu = foldMenu ? null : below($event)"
>
<Icon name="lucide:ellipsis" class="size-4" />
</button>
</template>
<template v-for="p in crumbs.shown" :key="`${p.id}-${p.i}`">
<Icon name="lucide:chevron-right" class="crumb-sep size-3.5" /> <Icon name="lucide:chevron-right" class="crumb-sep size-3.5" />
<button <button
class="bar-btn crumb" class="bar-btn crumb"
@ -141,22 +217,25 @@ const linkIcon = computed(() => {
</template> </template>
</nav> </nav>
<EditorContextMenu v-if="circuitMenu" :x="circuitMenu.x" :y="circuitMenu.y" :entries="circuitEntries" @close="circuitMenu = null" /> <EditorContextMenu v-if="circuitMenu" :x="circuitMenu.x" :y="circuitMenu.y" :entries="circuitEntries" @close="circuitMenu = null" />
<EditorContextMenu v-if="foldMenu" :x="foldMenu.x" :y="foldMenu.y" :entries="foldEntries" @close="foldMenu = null" />
</div> </div>
<div class="tb-group"> <div class="tb-group">
<div ref="challengesEl" class="relative"> <div ref="challengesEl" class="relative">
<button class="bar-btn" :class="{ open: showChallenges }" title="Challenges, puzzles and the puzzle of the week" @click="showChallenges = !showChallenges"> <button v-if="tucked < 3" class="bar-btn" :class="{ open: showChallenges }" title="Challenges, puzzles and the puzzle of the week" @click="showChallenges = !showChallenges">
<Icon name="lucide:flag" class="size-4" /> <Icon name="lucide:flag" class="size-4" />
<span class="bar-text">Challenges</span> <span class="bar-text">Challenges</span>
<span class="bar-count">{{ solvedCount }}/{{ CHALLENGES.length }}</span> <span class="bar-count">{{ solvedCount }}/{{ CHALLENGES.length }}</span>
</button> </button>
<Transition name="drop"> <Transition name="drop">
<div v-if="showChallenges" class="top-pop"> <div v-if="showChallenges" class="top-pop" :style="{ marginLeft: `${popShift}px` }">
<EditorChallengesPanel @close="showChallenges = false" /> <EditorChallengesPanel @close="showChallenges = false" />
</div> </div>
</Transition> </Transition>
</div> </div>
<span class="bar-sep" /> <!-- On the narrowest bar Challenges is in "⋯" and the clock buttons are there only for a circuit with a clock. -->
<template v-if="hasClock || tucked < 3">
<span v-if="tucked < 3" class="bar-sep" />
<button <button
class="bar-btn" class="bar-btn"
:class="{ active: ed.running.value && hasClock }" :class="{ active: ed.running.value && hasClock }"
@ -169,6 +248,7 @@ const linkIcon = computed(() => {
<button class="bar-btn" title="One clock cycle" :disabled="!hasClock" @click="ed.running.value = false; ed.step()"> <button class="bar-btn" title="One clock cycle" :disabled="!hasClock" @click="ed.running.value = false; ed.step()">
<Icon name="lucide:step-forward" class="size-4" /> <Icon name="lucide:step-forward" class="size-4" />
</button> </button>
</template>
<select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock"> <select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock">
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option> <option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select> </select>
@ -179,9 +259,12 @@ const linkIcon = computed(() => {
</div> </div>
<div class="tb-group"> <div class="tb-group">
<button class="bar-btn" title="Find anything in the project (Ctrl+F)" @click="ed.dialog.value = 'search'"><Icon name="lucide:search" class="size-4" /></button> <button v-if="tucked < 3" class="bar-btn" title="Find anything in the project (Ctrl+F)" @click="ed.dialog.value = 'search'"><Icon name="lucide:search" class="size-4" /></button>
<template v-if="tucked < 2">
<button class="bar-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button> <button class="bar-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button>
<button class="bar-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button> <button class="bar-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button>
</template>
<template v-if="!tucked">
<button class="bar-btn" :title="ed.sound.value.on ? 'Sound on (volume and clock ticks in Settings)' : 'Sound off'" @click="ed.setSound({ on: !ed.sound.value.on })"> <button class="bar-btn" :title="ed.sound.value.on ? 'Sound on (volume and clock ticks in Settings)' : 'Sound off'" @click="ed.setSound({ on: !ed.sound.value.on })">
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" /> <Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
</button> </button>
@ -189,8 +272,13 @@ const linkIcon = computed(() => {
<Icon name="lucide:settings" class="size-4" /> <Icon name="lucide:settings" class="size-4" />
</button> </button>
<button class="bar-btn" title="Help (?)" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /></button> <button class="bar-btn" title="Help (?)" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /></button>
</template>
<button v-else class="bar-btn" :class="{ open: !!moreMenu }" title="More: sound, settings, help, …" @click="moreMenu = moreMenu ? null : below($event)">
<Icon name="lucide:ellipsis" class="size-4" />
</button>
<EditorContextMenu v-if="moreMenu" :x="moreMenu.x" :y="moreMenu.y" :entries="moreEntries" @close="moreMenu = null" />
<span class="bar-sep" /> <span class="bar-sep" />
<button class="bar-btn share-btn" :class="ed.linkState.value" title="Save online, share a link, export or import a file" @click="ed.dialog.value = 'share'"> <button v-if="tucked < 2" class="bar-btn share-btn" :class="ed.linkState.value" title="Save online, share a link, export or import a file" @click="ed.dialog.value = 'share'">
<Icon :name="linkIcon" class="size-4" /> <Icon :name="linkIcon" class="size-4" />
<span class="bar-text">Share</span> <span class="bar-text">Share</span>
</button> </button>

34
app/lib/nav.ts Normal file
View File

@ -0,0 +1,34 @@
// Getting around the circuits: the way back shown in the top bar, folded
// when it is long, and how to reach a circuit picked in the search box.
import { matchScore } from './match'
/** The names after Main: the last `keep` stay in the bar, the ones before fold into "…". */
export function foldCrumbs<T>(path: T[], keep: number): { folded: T[]; shown: T[] } {
const n = Math.max(1, keep)
if (path.length <= n) return { folded: [], shown: path }
return { folded: path.slice(0, path.length - n), shown: path.slice(-n) }
}
/**
* How to get to circuit `id` from where you are: Main starts the way anew,
* one on the way here goes back to it (its step in `nav`), any other opens
* one step further in.
*/
export function wayTo(nav: string[], mainId: string, id: string): 'main' | 'open' | number {
if (id === mainId) return 'main'
const back = nav.indexOf(id)
return back >= 0 ? back : 'open'
}
/** Circuits whose name matches what was typed, best first; nothing typed, none. */
export function circuitsNamed<T extends { name: string }>(defs: T[], query: string, limit = 5): T[] {
const q = query.trim().toLowerCase()
if (!q) return []
return defs
.map(d => ({ d, score: matchScore(d.name, q) }))
.filter(x => x.score > 0)
.sort((a, b) => b.score - a.score || a.d.name.length - b.d.name.length)
.slice(0, limit)
.map(x => x.d)
}

61
tests/nav.test.ts Normal file
View File

@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest'
import { circuitsNamed, foldCrumbs, wayTo } from '../app/lib/nav'
describe('the way back in the top bar', () => {
const path = ['Adder 4', 'Full Adder', 'Half Adder', 'XOR']
it('shows a short way whole', () => {
expect(foldCrumbs(path.slice(0, 2), 3)).toEqual({ folded: [], shown: ['Adder 4', 'Full Adder'] })
expect(foldCrumbs([], 2)).toEqual({ folded: [], shown: [] })
})
it('folds the names before the last ones into the menu, in order', () => {
expect(foldCrumbs(path, 2)).toEqual({ folded: ['Adder 4', 'Full Adder'], shown: ['Half Adder', 'XOR'] })
expect(foldCrumbs(path, 3).folded).toEqual(['Adder 4'])
})
it('always keeps the circuit you are in', () => {
expect(foldCrumbs(path, 1)).toEqual({ folded: ['Adder 4', 'Full Adder', 'Half Adder'], shown: ['XOR'] })
expect(foldCrumbs(path, 0).shown).toEqual(['XOR'])
})
})
describe('getting to a circuit from the search box', () => {
it('starts anew at Main', () => {
expect(wayTo(['main', 'adder'], 'main', 'main')).toBe('main')
})
it('goes back to a circuit on the way here', () => {
// Main → Adder 4 → Full Adder, now in Half Adder: Adder 4 is step 1 of the way.
expect(wayTo(['main', 'adder', 'full'], 'main', 'adder')).toBe(1)
expect(wayTo(['main', 'adder', 'full'], 'main', 'full')).toBe(2)
})
it('opens any other one step further in', () => {
expect(wayTo(['main'], 'main', 'xor')).toBe('open')
expect(wayTo([], 'main', 'xor')).toBe('open')
})
})
describe('circuits found by name', () => {
const defs = [{ name: 'Main' }, { name: 'Half Adder' }, { name: 'Adder 4' }, { name: 'Full Adder' }, { name: 'XOR' }, { name: 'D Flip-Flop' }]
const names = (q: string, limit?: number) => circuitsNamed(defs, q, limit).map(d => d.name)
it('finds nothing before something is typed', () => {
expect(names('')).toEqual([])
expect(names(' ')).toEqual([])
})
it('puts the best match first: the start of the name, then a word in it', () => {
expect(names('adder')).toEqual(['Adder 4', 'Half Adder', 'Full Adder'])
expect(names('XOR')).toEqual(['XOR'])
})
it('finds a name by its letters in order', () => {
expect(names('dff')).toEqual(['D Flip-Flop'])
})
it('lists at most the limit', () => {
expect(names('a', 2)).toHaveLength(2)
})
})