mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-19 20:34:22 +01:00
Add icon registry, words picker and render
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
This commit is contained in:
parent
79478225be
commit
ff7ba540d3
@ -234,3 +234,6 @@ export const TOKEN_META = 'sbe-token'
|
||||
export const TOKEN_HEADER = 'X-SBE-Token'
|
||||
|
||||
export type { BudgetSnapshot, WebDataset }
|
||||
|
||||
// Icon words (DOCS-web-control-api.md, "Icon words"): types in iconWordsContract.ts.
|
||||
export * from './iconWordsContract'
|
||||
|
||||
32
web/src/api/iconWordsContract.ts
Normal file
32
web/src/api/iconWordsContract.ts
Normal file
@ -0,0 +1,32 @@
|
||||
// Icon words: the TS mirror of DOCS-web-control-api.md, "Icon words".
|
||||
// Split out of contract.ts like jobContract.ts; contract.ts re-exports it.
|
||||
|
||||
/** One icon's picks. No `word` key: not answered; `word: null`: skipped; `glyph: null`: default. */
|
||||
export interface IconChoice {
|
||||
word?: string | null
|
||||
glyph?: string | null
|
||||
}
|
||||
|
||||
/** `web/src/ui/icon_words.json`; an absent id is unanswered. */
|
||||
export interface IconLedger {
|
||||
version: 1
|
||||
icons: Record<string, IconChoice>
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST|PUT /api/icon-words/{id}` body: `word` (text, or null to skip) and/or
|
||||
* `glyph` (one of the icon's 3 alternatives, or null / the default to reset).
|
||||
* Answers the whole `IconLedger`.
|
||||
*/
|
||||
export type IconChoiceUpdate = { word: string | null } | { glyph: string | null } | { word: string | null; glyph: string | null }
|
||||
|
||||
/** Every served page carries the ledger in `<script type="application/json" id=…>`. */
|
||||
export const ICON_WORDS_SCRIPT = 'sbe-icon-words'
|
||||
|
||||
/** A manual word: 1–40 characters after whitespace collapses, no control characters. */
|
||||
export const ICON_WORD_MAX = 40
|
||||
|
||||
export const ICON_WORDS_ENDPOINTS = {
|
||||
ledger: '/api/icon-words',
|
||||
icon: (id: string) => `/api/icon-words/${id}`,
|
||||
} as const
|
||||
@ -4,6 +4,8 @@
|
||||
// the build.
|
||||
|
||||
import type { CommandName, CommandSpec, InstalledGame } from '../api/contract'
|
||||
import type { IconId } from '../icons/registry'
|
||||
import { iconFor } from '../icons/render'
|
||||
|
||||
export type SectionPath =
|
||||
| '/'
|
||||
@ -44,35 +46,25 @@ export const COMMAND_HOME = {
|
||||
'restore-backup': '/system',
|
||||
} as const satisfies Record<CommandName, SectionPath>
|
||||
|
||||
/** The glyph a command's button paints (textgate: its label is spoken only). */
|
||||
export const COMMAND_ICON = {
|
||||
status: '📊',
|
||||
list: '📋',
|
||||
stats: '📈',
|
||||
installed: '💾',
|
||||
'gaming-status': '⏱️',
|
||||
check: '🔄',
|
||||
scan: '🔎',
|
||||
done: '🏆',
|
||||
pick: '🎲',
|
||||
'pick-manual': '📌',
|
||||
'abandon-pick': '❌',
|
||||
install: '⬇️',
|
||||
uninstall: '🗑️',
|
||||
hide: '🙈',
|
||||
unhide: '👁️',
|
||||
'buy-dlc': '💳',
|
||||
unblock: '🔓',
|
||||
'add-exception': '🎫',
|
||||
'block-gaming': '⛔',
|
||||
reset: '♻️',
|
||||
setup: '🔧',
|
||||
enforce: '🛡️',
|
||||
'gaming-reset': '⏪',
|
||||
'gaming-unblock': '🔌',
|
||||
serve: '🌐',
|
||||
'restore-backup': '🗄️',
|
||||
} as const satisfies Record<CommandName, string>
|
||||
/** A command's registered icon id (`cmd.<name>`); the compiler proves every command has one. */
|
||||
export function commandIcon(name: CommandName): IconId {
|
||||
return `cmd.${name}` as const satisfies IconId
|
||||
}
|
||||
|
||||
/**
|
||||
* The glyph a command paints, for sites not yet on `glyph(commandIcon(…))`
|
||||
* (they get the chosen alternative glyph, not the word). Live getters, so a
|
||||
* ledger change shows without re-importing.
|
||||
*/
|
||||
export const COMMAND_ICON: Readonly<Record<CommandName, string>> = Object.defineProperties(
|
||||
{},
|
||||
Object.fromEntries(
|
||||
(Object.keys(COMMAND_HOME) as CommandName[]).map((name) => [
|
||||
name,
|
||||
{ enumerable: true, get: () => iconFor(commandIcon(name)).glyph },
|
||||
]),
|
||||
),
|
||||
) as Record<CommandName, string>
|
||||
|
||||
/** Title-case label for buttons and the palette (`pick-manual` → `Pick manual`). */
|
||||
export function commandLabel(name: CommandName): string {
|
||||
|
||||
@ -6,10 +6,11 @@
|
||||
|
||||
import type { CommandName } from '../api/contract'
|
||||
import { q } from '../api/queries'
|
||||
import { iconMark, iconWord } from '../icons/render'
|
||||
import { define, h, jsonAttr } from '../lib/dom'
|
||||
import { LiveElement } from '../lib/element'
|
||||
import { pageHref, runner, type Preset } from '../lib/runner'
|
||||
import { COMMAND_HOME, COMMAND_ICON, commandLabel, findCommand } from './catalog'
|
||||
import { COMMAND_HOME, commandIcon, commandLabel, findCommand } from './catalog'
|
||||
|
||||
export interface ButtonProps {
|
||||
name: CommandName
|
||||
@ -35,7 +36,7 @@ export function commandButton({ name, preset, label, tone = 'ghost' }: ButtonPro
|
||||
const locked = spec?.locked_reason ?? null
|
||||
// Textgate: the glyph is painted, the label is spoken only.
|
||||
const spoken = label ?? (spec?.kind === 'job' ? `Run ${name}` : `Open ${commandLabel(name)}`)
|
||||
const glyph = h('span', { class: 'cmd-icon', 'aria-hidden': 'true' }, COMMAND_ICON[name])
|
||||
const glyph = [iconMark(commandIcon(name), 'cmd-icon'), iconWord(commandIcon(name))]
|
||||
if (spec && spec.kind !== 'job') {
|
||||
return h('a', { href: pageHref(COMMAND_HOME[name]), class: `btn btn-${tone}`, 'aria-label': spoken }, glyph)
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NAV } from '../shell/nav'
|
||||
import { NAV, PALETTE_PAGES } from '../shell/nav'
|
||||
import { runner, type RunRequest } from '../lib/runner'
|
||||
import { must, setValue } from '../test/events'
|
||||
import { makeSpec } from '../test/fixtures'
|
||||
@ -12,7 +12,8 @@ const SPECS = [
|
||||
makeSpec('status', { kind: 'view', description: 'Show status.' }),
|
||||
makeSpec('pick', { description: 'Pick next.', locked_reason: 'Locked by a pick' }),
|
||||
]
|
||||
const TOTAL = SPECS.length + NAV.length
|
||||
const PAGES = NAV.length + PALETTE_PAGES.length
|
||||
const TOTAL = SPECS.length + PAGES
|
||||
|
||||
const assign = vi.fn()
|
||||
const runs: RunRequest[] = []
|
||||
@ -111,7 +112,7 @@ describe('CommandPaletteElement', () => {
|
||||
expect(document.body).toHaveTextContent('catalog broken')
|
||||
})
|
||||
expect(document.body).not.toHaveTextContent('Loading commands')
|
||||
expect(options()).toHaveLength(NAV.length)
|
||||
expect(options()).toHaveLength(PAGES)
|
||||
})
|
||||
|
||||
it('filters by text and says when nothing matches', async () => {
|
||||
|
||||
@ -7,17 +7,17 @@ import { q } from '../api/queries'
|
||||
import { define, h } from '../lib/dom'
|
||||
import { uid } from '../lib/ids'
|
||||
import { pageHref, runner } from '../lib/runner'
|
||||
import { NAV } from '../shell/nav'
|
||||
import { NAV, PALETTE_PAGES } from '../shell/nav'
|
||||
import { empty, errorNotice, glyph, loading, pill } from '../ui/build'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { COMMAND_HOME, COMMAND_ICON, commandLabel } from './catalog'
|
||||
import { COMMAND_HOME, commandIcon, commandLabel } from './catalog'
|
||||
|
||||
interface Entry {
|
||||
key: string
|
||||
title: string
|
||||
detail: string
|
||||
hint: string
|
||||
/** Painted in place of the title (textgate). */
|
||||
/** A registered icon id (painted with the user's word) or a raw glyph. */
|
||||
icon: string
|
||||
/** Painted in place of the hint: ▶️ run, ↗️ open, 🧭 navigate. */
|
||||
hintIcon: string
|
||||
@ -117,7 +117,7 @@ export class CommandPaletteElement extends HTMLElement {
|
||||
title: commandLabel(c.name),
|
||||
detail: c.description,
|
||||
hint: c.kind === 'job' ? (c.friction ? 'run · confirm' : 'run') : `open ${COMMAND_HOME[c.name]}`,
|
||||
icon: COMMAND_ICON[c.name],
|
||||
icon: commandIcon(c.name),
|
||||
hintIcon: c.kind === 'job' ? (c.friction ? '▶️⌨️' : '▶️') : '↗️',
|
||||
locked: c.locked_reason,
|
||||
act: () => {
|
||||
@ -128,7 +128,7 @@ export class CommandPaletteElement extends HTMLElement {
|
||||
}
|
||||
},
|
||||
})),
|
||||
...NAV.map((n) => ({
|
||||
...[...NAV, ...PALETTE_PAGES].map((n) => ({
|
||||
key: `nav:${n.to}`,
|
||||
title: `Go to ${n.label}`,
|
||||
detail: n.blurb,
|
||||
|
||||
@ -5,11 +5,12 @@
|
||||
|
||||
import { api } from '../api/client'
|
||||
import { q } from '../api/queries'
|
||||
import { iconMark, iconWord } from '../icons/render'
|
||||
import { define, h, hx } from '../lib/dom'
|
||||
import { runner, jobHref, type RunRequest } from '../lib/runner'
|
||||
import { errorNotice, loading, notice } from '../ui/build'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { COMMAND_ICON, commandLabel, findCommand } from './catalog'
|
||||
import { commandIcon, commandLabel, findCommand } from './catalog'
|
||||
import type { PendingCountdown } from './pendingCountdown'
|
||||
import { Runner, type NextPhase } from './runnerForm'
|
||||
|
||||
@ -96,7 +97,7 @@ export class RunnerDialogElement extends HTMLElement {
|
||||
if (error) this.modal.render(errorNotice(error))
|
||||
else if (commands) {
|
||||
// ⛔ + the command's glyph; the sentence is spoken only.
|
||||
const el = notice('danger', null, h('span', { 'aria-hidden': 'true' }, COMMAND_ICON[req.name]))
|
||||
const el = notice('danger', null, h('span', { class: 'has-word' }, iconMark(commandIcon(req.name), ''), iconWord(commandIcon(req.name))))
|
||||
el.setAttribute('aria-label', `Not in the server catalog: the server does not offer "${req.name}".`)
|
||||
this.modal.render(el)
|
||||
}
|
||||
|
||||
@ -5,11 +5,12 @@
|
||||
import { ApiFailure, startJob } from '../api/client'
|
||||
import type { CommandName, CommandSpec } from '../api/contract'
|
||||
import { q } from '../api/queries'
|
||||
import { iconMark, iconWord } from '../icons/render'
|
||||
import { Action } from '../lib/action'
|
||||
import { h } from '../lib/dom'
|
||||
import type { Preset } from '../lib/runner'
|
||||
import { commandLine, errorNotice, notice, pill } from '../ui/build'
|
||||
import { COMMAND_ICON, fillPhrase, phraseMatches } from './catalog'
|
||||
import { commandIcon, fillPhrase, phraseMatches } from './catalog'
|
||||
import { enforcePreset } from './enforcePreset'
|
||||
import { gameLookup } from './gameLookup'
|
||||
import { initialValues, paramError, toParams, type ParamValues } from './params'
|
||||
@ -98,7 +99,7 @@ export class Runner {
|
||||
h(
|
||||
'div',
|
||||
{ class: 'tags' },
|
||||
h('span', { class: 'runner-glyph', 'aria-hidden': 'true' }, COMMAND_ICON[spec.name]),
|
||||
h('span', { class: 'runner-mark' }, iconMark(commandIcon(spec.name), 'runner-glyph'), iconWord(commandIcon(spec.name))),
|
||||
spec.privileged ? pill('neutral', 'Runs as root via the daemon', '🔑') : null,
|
||||
spec.mutating ? pill('neutral', 'Changes state', '✏️') : pill('neutral', 'Read-only', '👁️'),
|
||||
spec.cancellable ? pill('neutral', 'Cancellable', '⏹️') : null,
|
||||
|
||||
61
web/src/icons/ledger.test.ts
Normal file
61
web/src/icons/ledger.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { injectLedgerScript, useIcons } from '../test/iconLedger'
|
||||
import { choiceOf, isAnswered, ledger, ledgerError, setWordsHidden, wordsHidden, WORDS_HIDDEN_KEY } from './ledger'
|
||||
|
||||
describe('ledger', () => {
|
||||
it('is empty when the page carries none (dev server, tests)', () => {
|
||||
expect(ledger()).toEqual({ version: 1, icons: {} })
|
||||
expect(isAnswered('cmd.done')).toBe(false)
|
||||
expect(ledgerError()).toBeNull()
|
||||
})
|
||||
|
||||
it('reads the payload the server injected into the page, once', () => {
|
||||
injectLedgerScript({ version: 1, icons: { 'cmd.done': { word: 'Won', glyph: '🎉' } } })
|
||||
expect(choiceOf('cmd.done')).toEqual({ word: 'Won', glyph: '🎉' })
|
||||
document.getElementById('sbe-icon-words')?.remove()
|
||||
expect(choiceOf('cmd.done').word).toBe('Won')
|
||||
})
|
||||
|
||||
it('counts an id as answered only once its word is decided (text or skip)', () => {
|
||||
useIcons({ 'cmd.done': { word: null, glyph: null }, 'cmd.scan': { glyph: '📡' }, 'cmd.pick': { word: 'roll' } })
|
||||
expect(isAnswered('cmd.done')).toBe(true)
|
||||
expect(isAnswered('cmd.pick')).toBe(true)
|
||||
expect(isAnswered('cmd.scan')).toBe(false)
|
||||
expect(isAnswered('cmd.check')).toBe(false)
|
||||
expect(choiceOf('cmd.check')).toEqual({})
|
||||
})
|
||||
|
||||
it('fails loudly on a corrupt ledger the server reported', () => {
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
injectLedgerScript({ error: 'op_failed', message: 'kept aside as x.corrupt' })
|
||||
expect(ledger().icons).toEqual({})
|
||||
expect(ledgerError()).toBe('kept aside as x.corrupt')
|
||||
expect(err).toHaveBeenCalledWith(expect.stringContaining('x.corrupt'))
|
||||
})
|
||||
|
||||
it('names the failure even when the error body has no message', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
injectLedgerScript({ error: 'op_failed' })
|
||||
expect(ledgerError()).toBe('The icon-word ledger is unreadable.')
|
||||
})
|
||||
|
||||
it('fails loudly on a payload that does not parse', () => {
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
injectLedgerScript('{nope')
|
||||
expect(ledger().icons).toEqual({})
|
||||
expect(ledgerError()).toMatch(/does not parse/)
|
||||
expect(err).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('words-hidden setting', () => {
|
||||
it('defaults to words shown and persists in localStorage', () => {
|
||||
expect(wordsHidden()).toBe(false)
|
||||
setWordsHidden(true)
|
||||
expect(wordsHidden()).toBe(true)
|
||||
expect(localStorage.getItem(WORDS_HIDDEN_KEY)).toBe('1')
|
||||
setWordsHidden(false)
|
||||
expect(wordsHidden()).toBe(false)
|
||||
expect(localStorage.getItem(WORDS_HIDDEN_KEY)).toBeNull()
|
||||
})
|
||||
})
|
||||
72
web/src/icons/ledger.ts
Normal file
72
web/src/icons/ledger.ts
Normal file
@ -0,0 +1,72 @@
|
||||
// The icon-word ledger as this page knows it. The Python server injects it
|
||||
// into every page (`<script type="application/json" id="sbe-icon-words">`),
|
||||
// so it is read synchronously on first use and every renderer sees the same
|
||||
// picks; the /words picker replaces it after each save. A corrupt ledger
|
||||
// arrives as the server's error body: no words are drawn and the error is
|
||||
// logged (and shown on /words), never swallowed.
|
||||
|
||||
import { ICON_WORDS_SCRIPT, type IconChoice, type IconLedger } from '../api/iconWordsContract'
|
||||
|
||||
/** localStorage key of the one "hide all words" setting; absent = words shown. */
|
||||
export const WORDS_HIDDEN_KEY = 'sbe-icon-words-hidden'
|
||||
|
||||
const EMPTY: IconLedger = { version: 1, icons: {} }
|
||||
|
||||
let cached: IconLedger | null = null
|
||||
let failure: string | null = null
|
||||
|
||||
function readPage(): IconLedger {
|
||||
const raw = document.getElementById(ICON_WORDS_SCRIPT)?.textContent
|
||||
if (raw === undefined) return EMPTY
|
||||
let parsed: Partial<IconLedger> & { message?: string }
|
||||
try {
|
||||
parsed = JSON.parse(raw) as typeof parsed
|
||||
} catch (e) {
|
||||
parsed = { message: `The icon-word ledger in this page does not parse: ${String(e)}` }
|
||||
}
|
||||
if (parsed.icons) return parsed as IconLedger
|
||||
failure = parsed.message ?? 'The icon-word ledger is unreadable.'
|
||||
console.error(`[sbe] icon words off: ${failure}`)
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
export function ledger(): IconLedger {
|
||||
cached ??= readPage()
|
||||
return cached
|
||||
}
|
||||
|
||||
/** Use `next` from now on (the picker, after the server answered a save). */
|
||||
export function setLedger(next: IconLedger): void {
|
||||
cached = next
|
||||
failure = null
|
||||
}
|
||||
|
||||
/** Forget the cached ledger so the next read re-reads the page (tests). */
|
||||
export function resetLedger(): void {
|
||||
cached = null
|
||||
failure = null
|
||||
}
|
||||
|
||||
/** The server's message when the page carried a corrupt ledger, else null. */
|
||||
export function ledgerError(): string | null {
|
||||
ledger()
|
||||
return failure
|
||||
}
|
||||
|
||||
export function choiceOf(id: string): IconChoice {
|
||||
return ledger().icons[id] ?? {}
|
||||
}
|
||||
|
||||
/** Answered = the word is decided (text or a skip); a glyph alone is not enough. */
|
||||
export function isAnswered(id: string): boolean {
|
||||
return 'word' in choiceOf(id)
|
||||
}
|
||||
|
||||
export function wordsHidden(): boolean {
|
||||
return localStorage.getItem(WORDS_HIDDEN_KEY) === '1'
|
||||
}
|
||||
|
||||
export function setWordsHidden(hidden: boolean): void {
|
||||
if (hidden) localStorage.setItem(WORDS_HIDDEN_KEY, '1')
|
||||
else localStorage.removeItem(WORDS_HIDDEN_KEY)
|
||||
}
|
||||
109
web/src/icons/picker.flow.test.ts
Normal file
109
web/src/icons/picker.flow.test.ts
Normal file
@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { must } from '../test/events'
|
||||
import { apiError, bodiesOf, stubApi } from '../test/harness'
|
||||
import { A, B, C, N, at, count, field, input, press, q, start, url } from '../test/pickerHelpers'
|
||||
import { wordsHidden } from './ledger'
|
||||
import { ICONS } from './registry'
|
||||
|
||||
describe('<icon-words-picker>: moving, summary, errors', () => {
|
||||
it('←/→ move; a revisit shows the saved choice', async () => {
|
||||
start({ [A.id]: { word: A.words[2] ?? '', glyph: null }, [B.id]: { word: 'Mine all mine' }, [C.id]: { word: null } })
|
||||
await at(4)
|
||||
press('ArrowLeft')
|
||||
await at(3)
|
||||
expect(q('[data-skip]')).toHaveAttribute('aria-pressed', 'true')
|
||||
press('ArrowLeft')
|
||||
await at(2)
|
||||
expect(field().value).toBe('Mine all mine')
|
||||
press('ArrowLeft')
|
||||
await at(1)
|
||||
expect(q('[data-word-slot="2"]')).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(field().value).toBe('')
|
||||
press('ArrowLeft')
|
||||
await at(1)
|
||||
press('ArrowRight')
|
||||
await at(2)
|
||||
})
|
||||
|
||||
it('a failed glyph save keeps the field empty and reports the error', async () => {
|
||||
start()
|
||||
await at(3)
|
||||
stubApi({ [url(C.id)]: apiError(500, 'op_failed', 'disk full') })
|
||||
press('7')
|
||||
await vi.waitFor(() => { expect(q('.picker-status .notice-danger')).toHaveTextContent('disk full') })
|
||||
expect(field().value).toBe('')
|
||||
expect(field()).toHaveAttribute('aria-invalid', 'false')
|
||||
})
|
||||
|
||||
it('refuses a bad own word before sending and flags the field', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
field().value = 'x'.repeat(41)
|
||||
must(field().form).requestSubmit()
|
||||
expect(field()).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([])
|
||||
})
|
||||
|
||||
it('shows a server refusal and stays on the icon', async () => {
|
||||
start()
|
||||
await at(3)
|
||||
stubApi({ 'GET /api/icon-words': { version: 1, icons: {} }, [url(C.id)]: apiError(400, 'invalid_params', 'no') })
|
||||
field().value = 'fine'
|
||||
must(field().form).requestSubmit()
|
||||
await vi.waitFor(() => { expect(field()).toHaveAttribute('aria-invalid', 'true') })
|
||||
expect(q('.picker-status .notice-danger')).toHaveTextContent('no')
|
||||
expect(count()).toBe(`3 / ${N}`)
|
||||
})
|
||||
|
||||
it('ends on a summary that jumps back to the first unanswered icon', async () => {
|
||||
const all = Object.fromEntries(ICONS.slice(0, -1).map((e) => [e.id, { word: null }]))
|
||||
start(all)
|
||||
await at(N)
|
||||
press('s')
|
||||
await vi.waitFor(() => { expect(q('.picker-summary')).toHaveTextContent(`${String(N)} / ${String(N)}`) })
|
||||
expect(document.querySelector('[data-jump]')).toBeNull()
|
||||
for (const k of ['1', '7', '6', 's']) press(k)
|
||||
await Promise.resolve()
|
||||
expect(document.querySelector('.picker-count')).toBeNull()
|
||||
press('ArrowLeft')
|
||||
await at(N)
|
||||
})
|
||||
|
||||
it('opens on the summary when every icon is answered', async () => {
|
||||
start(Object.fromEntries(ICONS.map((e) => [e.id, { word: 'x' }])))
|
||||
await vi.waitFor(() => { expect(q('.picker-summary')).toHaveTextContent(`${String(N)} / ${String(N)}`) })
|
||||
expect(q('[data-go="1"]')).toBeDisabled()
|
||||
})
|
||||
|
||||
it('offers the jump when icons are left unanswered', async () => {
|
||||
start()
|
||||
await at(3)
|
||||
press('ArrowRight')
|
||||
for (let i = 4; i <= N; i++) {
|
||||
await at(i)
|
||||
press('ArrowRight')
|
||||
}
|
||||
await vi.waitFor(() => { expect(q('.picker-summary')).toHaveTextContent(`2 / ${String(N)}`) })
|
||||
q('[data-jump]').click()
|
||||
await at(3)
|
||||
})
|
||||
|
||||
it('the show-words switch flips the one setting', async () => {
|
||||
start()
|
||||
await at(3)
|
||||
const box = () => input('input[name=show-words]')
|
||||
expect(box().checked).toBe(true)
|
||||
box().click()
|
||||
expect(wordsHidden()).toBe(true)
|
||||
expect(box().checked).toBe(false)
|
||||
box().click()
|
||||
expect(wordsHidden()).toBe(false)
|
||||
})
|
||||
|
||||
it('shows the error when the ledger cannot be read', async () => {
|
||||
stubApi({ 'GET /api/icon-words': apiError(500, 'op_failed', 'kept aside as x.corrupt') })
|
||||
document.body.innerHTML = '<icon-words-picker></icon-words-picker>'
|
||||
await vi.waitFor(() => { expect(q('.picker-status .notice-danger')).toHaveTextContent('x.corrupt') })
|
||||
expect(document.querySelector('.picker-count')).toBeNull()
|
||||
})
|
||||
})
|
||||
130
web/src/icons/picker.test.ts
Normal file
130
web/src/icons/picker.test.ts
Normal file
@ -0,0 +1,130 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { must } from '../test/events'
|
||||
import { bodiesOf } from '../test/harness'
|
||||
import { C, D, N, at, count, field, input, press, q, start, url } from '../test/pickerHelpers'
|
||||
|
||||
describe('<icon-words-picker>: keys and saves', () => {
|
||||
it('starts at the first unanswered icon with its glyph, context, description and progress', async () => {
|
||||
start()
|
||||
await at(3)
|
||||
expect(q('.picker-id')).toHaveTextContent(C.id)
|
||||
expect(q('.picker-big')).toHaveTextContent(C.glyph)
|
||||
expect(q('.picker-context').textContent).toContain(C.glyph)
|
||||
expect(q('.picker-desc')).toHaveTextContent(C.desc)
|
||||
expect(q('[role=progressbar]')).toHaveAttribute('aria-valuenow', String(Math.round((2 / N) * 100)))
|
||||
const words = [...document.querySelectorAll('[data-word-slot]')].map((b) => b.textContent)
|
||||
expect(words).toEqual(C.words.map((w, i) => `${String(i + 1)}${w}`))
|
||||
})
|
||||
|
||||
it('1/2/3 save a suggestion and advance', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
press('2')
|
||||
await at(4)
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: C.words[1] }])
|
||||
expect(q('[role=progressbar]')).toHaveAttribute('aria-valuenow', String(Math.round((3 / N) * 100)))
|
||||
})
|
||||
|
||||
it('O focuses the own-word field; Enter saves a multi-word entry and advances', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
expect(press('o')).toBe(false)
|
||||
expect(document.activeElement).toBe(field())
|
||||
field().value = ' My OWN words '
|
||||
press('s', {}, field())
|
||||
must(field().form).requestSubmit()
|
||||
await at(4)
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: 'My OWN words' }])
|
||||
})
|
||||
|
||||
it('S skips (word null) and advances', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
press('S')
|
||||
await at(4)
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: null }])
|
||||
})
|
||||
|
||||
it('7/8/9 swap the glyph and stay; 6 keeps the default', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
press('8')
|
||||
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.alts[1] ?? '') })
|
||||
expect(count()).toBe(`3 / ${N}`)
|
||||
expect(q('[data-glyph-slot="1"]')).toHaveAttribute('aria-pressed', 'true')
|
||||
press('6')
|
||||
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.glyph) })
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ glyph: C.alts[1] }, { glyph: null }])
|
||||
expect(q('[data-glyph-slot="default"]')).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
it('ignores keys while typing and keys with modifiers (Alt+digit is the nav)', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
press('1', { altKey: true })
|
||||
press('2', { ctrlKey: true })
|
||||
press('3', { metaKey: true })
|
||||
press('s', {}, field())
|
||||
await Promise.resolve()
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([])
|
||||
expect(count()).toBe(`3 / ${N}`)
|
||||
})
|
||||
|
||||
it('3, 9, upper-case O and the keep-default button reach their slots', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
press('9')
|
||||
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.alts[2] ?? '') })
|
||||
q('[data-glyph-slot="default"]').click()
|
||||
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.glyph) })
|
||||
press('O')
|
||||
expect(document.activeElement).toBe(field())
|
||||
field().blur()
|
||||
press('3')
|
||||
await at(4)
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ glyph: C.alts[2] }, { glyph: null }, { word: C.words[2] }])
|
||||
})
|
||||
|
||||
it('ignores unknown keys, keys before the ledger loads and keys under an open dialog', async () => {
|
||||
const { mock } = start()
|
||||
press('1')
|
||||
await at(3)
|
||||
press('x')
|
||||
document.body.append(Object.assign(document.createElement('dialog'), { open: true }))
|
||||
press('S')
|
||||
await Promise.resolve()
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([])
|
||||
expect(count()).toBe(`3 / ${N}`)
|
||||
})
|
||||
|
||||
it('keys still work while the show-words checkbox has focus; Esc leaves the field', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
const box = input('input[name=show-words]')
|
||||
box.focus()
|
||||
press('S', {}, box)
|
||||
await at(4)
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: null }])
|
||||
press('o')
|
||||
expect(document.activeElement).toBe(field())
|
||||
press('Escape', {}, field())
|
||||
expect(document.activeElement).not.toBe(field())
|
||||
})
|
||||
|
||||
it('clicks work like keys', async () => {
|
||||
const { mock } = start()
|
||||
await at(3)
|
||||
q('[data-glyph-slot="0"]').click()
|
||||
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.alts[0] ?? '') })
|
||||
q('[data-word-slot="0"]').click()
|
||||
await at(4)
|
||||
q('[data-skip]').click()
|
||||
await at(5)
|
||||
q('[data-go="-1"]').click()
|
||||
await at(4)
|
||||
q('[data-go="1"]').click()
|
||||
await at(5)
|
||||
expect(bodiesOf(mock, url(C.id))).toEqual([{ glyph: C.alts[0] }, { word: C.words[0] }])
|
||||
expect(bodiesOf(mock, url(D.id))).toEqual([{ word: null }])
|
||||
})
|
||||
})
|
||||
172
web/src/icons/picker.ts
Normal file
172
web/src/icons/picker.ts
Normal file
@ -0,0 +1,172 @@
|
||||
// `<icon-words-picker>` on /words, after cleanup-plate's icon-word picker:
|
||||
// one icon at a time, big and as it looks in place, with what it is and does,
|
||||
// three suggested words, a field for your own words, a skip, and three
|
||||
// alternative glyphs. Every choice is saved at once (POST /api/icon-words/…);
|
||||
// a word or a skip advances, a glyph swap stays so you see it. It opens on the
|
||||
// first unanswered icon; going back shows what you saved.
|
||||
// Keys: 1 2 3 pick, O own word (Enter saves, Esc leaves the field), S skip,
|
||||
// 6 default glyph, 7 8 9 alternatives, ←/→ move. Keys never fire while you
|
||||
// type, with Alt/Ctrl/Meta held (Alt+digit is the section nav) or under a
|
||||
// dialog (the command palette).
|
||||
|
||||
import { request } from '../api/client'
|
||||
import { ICON_WORDS_ENDPOINTS, type IconChoiceUpdate, type IconLedger } from '../api/iconWordsContract'
|
||||
import { define } from '../lib/dom'
|
||||
import { loading } from '../ui/build'
|
||||
import { isAnswered, setLedger, setWordsHidden, wordsHidden } from './ledger'
|
||||
import { pickerStatus, pickerView, type PickerHandlers } from './pickerView'
|
||||
import { ICONS } from './registry'
|
||||
import { decorateChrome } from './render'
|
||||
import { normalizeWord, wordProblem } from './wordRules'
|
||||
|
||||
function firstUnanswered(): number {
|
||||
const i = ICONS.findIndex((e) => !isAnswered(e.id))
|
||||
return i === -1 ? ICONS.length : i
|
||||
}
|
||||
|
||||
/** A text field has the keys while focused; a checkbox does not. */
|
||||
function typing(target: EventTarget | null): boolean {
|
||||
return target instanceof HTMLInputElement && target.type !== 'checkbox'
|
||||
}
|
||||
|
||||
export class IconWordsPickerElement extends HTMLElement {
|
||||
private index = 0
|
||||
private loaded = false
|
||||
private error: unknown = null
|
||||
private invalid = false
|
||||
private draft: string | null = null
|
||||
private readonly onKey = (e: KeyboardEvent): void => {
|
||||
this.key(e)
|
||||
}
|
||||
|
||||
private readonly handlers: PickerHandlers = {
|
||||
word: (slot) => { this.pick(slot) },
|
||||
own: (text) => { this.own(text) },
|
||||
skip: () => { void this.commit({ word: null }, true) },
|
||||
glyph: (slot) => { this.glyph(slot) },
|
||||
go: (to) => { this.go(to) },
|
||||
jump: () => { this.go(firstUnanswered()) },
|
||||
showWords: (on) => {
|
||||
setWordsHidden(!on)
|
||||
decorateChrome()
|
||||
this.render()
|
||||
},
|
||||
}
|
||||
|
||||
private readonly keys = new Map<string, () => void>([
|
||||
['1', () => { this.pick(0) }],
|
||||
['2', () => { this.pick(1) }],
|
||||
['3', () => { this.pick(2) }],
|
||||
['6', () => { this.glyph(null) }],
|
||||
['7', () => { this.glyph(0) }],
|
||||
['8', () => { this.glyph(1) }],
|
||||
['9', () => { this.glyph(2) }],
|
||||
['o', () => { this.focusOwn() }],
|
||||
['O', () => { this.focusOwn() }],
|
||||
['s', this.handlers.skip],
|
||||
['S', this.handlers.skip],
|
||||
['ArrowLeft', () => { this.go(this.index - 1) }],
|
||||
['ArrowRight', () => { this.go(this.index + 1) }],
|
||||
])
|
||||
|
||||
connectedCallback(): void {
|
||||
document.addEventListener('keydown', this.onKey)
|
||||
this.replaceChildren(loading('icon words'))
|
||||
request<IconLedger>('GET', ICON_WORDS_ENDPOINTS.ledger).then(
|
||||
(ledger) => {
|
||||
setLedger(ledger)
|
||||
this.loaded = true
|
||||
this.go(firstUnanswered())
|
||||
},
|
||||
(e: unknown) => {
|
||||
this.replaceChildren(pickerStatus(e))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
disconnectedCallback(): void {
|
||||
document.removeEventListener('keydown', this.onKey)
|
||||
}
|
||||
|
||||
/** The shown icon; undefined on the summary page after the last one. */
|
||||
private get entry() {
|
||||
return ICONS.at(this.index)
|
||||
}
|
||||
|
||||
private go(to: number): void {
|
||||
this.index = Math.min(Math.max(0, to), ICONS.length)
|
||||
this.error = null
|
||||
this.invalid = false
|
||||
this.draft = null
|
||||
this.render()
|
||||
}
|
||||
|
||||
private focusOwn(): void {
|
||||
this.querySelector<HTMLInputElement>('input[name=own]')?.focus()
|
||||
}
|
||||
|
||||
private pick(slot: number): void {
|
||||
const word = this.entry?.words[slot]
|
||||
if (word !== undefined) void this.commit({ word }, true)
|
||||
}
|
||||
|
||||
private glyph(slot: number | null): void {
|
||||
const entry = this.entry
|
||||
if (!entry) return
|
||||
void this.commit({ glyph: slot === null ? null : entry.alts[slot] }, false)
|
||||
}
|
||||
|
||||
private own(text: string): void {
|
||||
if (wordProblem(text)) {
|
||||
this.draft = text
|
||||
this.invalid = true
|
||||
this.render()
|
||||
return
|
||||
}
|
||||
void this.commit({ word: normalizeWord(text) }, true)
|
||||
}
|
||||
|
||||
private async commit(update: IconChoiceUpdate, advance: boolean): Promise<void> {
|
||||
const entry = this.entry
|
||||
if (!entry) return
|
||||
try {
|
||||
setLedger(await request<IconLedger>('POST', ICON_WORDS_ENDPOINTS.icon(entry.id), update))
|
||||
decorateChrome()
|
||||
this.go(advance ? this.index + 1 : this.index)
|
||||
} catch (e) {
|
||||
const word = (update as { word?: unknown }).word
|
||||
this.error = e
|
||||
this.invalid = (e as { code?: string }).code === 'invalid_params'
|
||||
this.draft = typeof word === 'string' ? word : null
|
||||
this.render()
|
||||
}
|
||||
}
|
||||
|
||||
private key(e: KeyboardEvent): void {
|
||||
const act = this.keys.get(e.key)
|
||||
if (!act || !this.loaded || e.altKey || e.ctrlKey || e.metaKey || typing(e.target)) return
|
||||
if (document.querySelector('dialog[open]')) return
|
||||
e.preventDefault()
|
||||
act()
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
this.replaceChildren(
|
||||
...pickerView(
|
||||
{
|
||||
index: this.index,
|
||||
total: ICONS.length,
|
||||
answered: ICONS.filter((e) => isAnswered(e.id)).length,
|
||||
entry: this.entry ?? null,
|
||||
error: this.error,
|
||||
invalid: this.invalid,
|
||||
draft: this.draft,
|
||||
wordsShown: !wordsHidden(),
|
||||
},
|
||||
this.handlers,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
define('icon-words-picker', IconWordsPickerElement)
|
||||
128
web/src/icons/pickerView.ts
Normal file
128
web/src/icons/pickerView.ts
Normal file
@ -0,0 +1,128 @@
|
||||
// The widgets of the icon-word picker (picker.ts holds the state and keys).
|
||||
// A developer page the user asked to carry text: the description, the
|
||||
// suggestions and the key hints are meant to be read.
|
||||
|
||||
import { progressBar } from '../jobs/progress'
|
||||
import { h, type Child } from '../lib/dom'
|
||||
import { errorNotice } from '../ui/build'
|
||||
import { choiceOf } from './ledger'
|
||||
import { contextPreview } from './preview'
|
||||
import type { IconEntry } from './registry'
|
||||
import { iconFor } from './render'
|
||||
import { sentenceCase } from './textCase'
|
||||
|
||||
export interface PickerHandlers {
|
||||
word: (slot: number) => void
|
||||
own: (text: string) => void
|
||||
skip: () => void
|
||||
/** null keeps the default glyph. */
|
||||
glyph: (slot: number | null) => void
|
||||
go: (to: number) => void
|
||||
jump: () => void
|
||||
showWords: (on: boolean) => void
|
||||
}
|
||||
|
||||
export interface PickerState {
|
||||
index: number
|
||||
total: number
|
||||
answered: number
|
||||
entry: IconEntry | null
|
||||
error: unknown
|
||||
invalid: boolean
|
||||
/** The own-word text to keep in the field (a refused entry). */
|
||||
draft: string | null
|
||||
wordsShown: boolean
|
||||
}
|
||||
|
||||
const keyed = (key: string, ...label: Child[]) => [h('kbd', {}, key), ...label]
|
||||
|
||||
function choiceButton(attrs: Record<string, string>, pressed: boolean, onclick: () => void, ...label: Child[]) {
|
||||
return h('button', { type: 'button', class: 'btn btn-ghost picker-choice', 'aria-pressed': String(pressed), onclick, ...attrs }, ...label)
|
||||
}
|
||||
|
||||
function ownForm(s: PickerState, entry: IconEntry, on: PickerHandlers, saved: string | null | undefined): HTMLFormElement {
|
||||
const own = typeof saved === 'string' && !entry.words.includes(saved) ? saved : ''
|
||||
const input = h('input', { class: 'input', name: 'own', autocomplete: 'off', 'aria-invalid': String(s.invalid), value: s.draft ?? own })
|
||||
const form = h(
|
||||
'form',
|
||||
{ class: 'picker-own' },
|
||||
h('label', { class: 'picker-own-label' }, h('span', {}, ...keyed('O', ' Own word')), input),
|
||||
h('button', { type: 'submit', class: 'btn btn-primary' }, '✓ ', h('kbd', {}, '⏎')),
|
||||
)
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault()
|
||||
on.own(input.value)
|
||||
})
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') input.blur()
|
||||
})
|
||||
return form
|
||||
}
|
||||
|
||||
function choices(s: PickerState, entry: IconEntry, on: PickerHandlers): HTMLElement {
|
||||
const saved = choiceOf(entry.id)
|
||||
const glyph = saved.glyph && entry.alts.includes(saved.glyph) ? saved.glyph : null
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'picker-choices stack' },
|
||||
h('p', { class: 'picker-desc m0' }, entry.desc),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'picker-words' },
|
||||
entry.words.map((w, i) => choiceButton({ 'data-word-slot': String(i) }, saved.word === w, () => { on.word(i) }, ...keyed(String(i + 1), w))),
|
||||
),
|
||||
ownForm(s, entry, on, saved.word),
|
||||
choiceButton({ 'data-skip': '' }, saved.word === null, on.skip, ...keyed('S', ' Skip (no word)')),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'picker-glyphs', role: 'group', 'aria-label': 'Glyph' },
|
||||
choiceButton({ 'data-glyph-slot': 'default' }, glyph === null, () => { on.glyph(null) }, ...keyed('6', ` ${entry.glyph} keep default`)),
|
||||
entry.alts.map((a, i) => choiceButton({ 'data-glyph-slot': String(i) }, glyph === a, () => { on.glyph(i) }, ...keyed(String(i + 7), ` ${a}`))),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function header(s: PickerState, entry: IconEntry): HTMLElement {
|
||||
const word = choiceOf(entry.id).word
|
||||
const saved = typeof word === 'string' ? sentenceCase(word) : word === null ? '— skipped' : ''
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'picker-head' },
|
||||
h('span', { class: 'picker-count' }, `${String(s.index + 1)} / ${String(s.total)}`),
|
||||
h('code', { class: 'picker-id' }, entry.id),
|
||||
h('span', { class: 'picker-saved' }, saved),
|
||||
)
|
||||
}
|
||||
|
||||
function footer(s: PickerState, on: PickerHandlers): HTMLElement {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'picker-nav' },
|
||||
h('button', { type: 'button', class: 'btn btn-ghost', 'data-go': '-1', disabled: s.index === 0, onclick: () => { on.go(s.index - 1) } }, '← back'),
|
||||
h('label', { class: 'picker-toggle' }, h('input', { type: 'checkbox', name: 'show-words', checked: s.wordsShown, onchange: (e: Event) => { on.showWords((e.target as HTMLInputElement).checked) } }), ' Show words next to icons'),
|
||||
h('button', { type: 'button', class: 'btn btn-ghost', 'data-go': '1', disabled: s.entry === null, onclick: () => { on.go(s.index + 1) } }, 'forward →'),
|
||||
)
|
||||
}
|
||||
|
||||
function done(s: PickerState, on: PickerHandlers): HTMLElement {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'picker-done stack' },
|
||||
h('p', { class: 'picker-summary m0' }, `${String(s.answered)} / ${String(s.total)}`),
|
||||
s.answered < s.total ? h('button', { type: 'button', class: 'btn btn-primary', 'data-jump': '', onclick: on.jump }, 'Next unanswered') : h('p', { class: 'm0' }, '✅'),
|
||||
)
|
||||
}
|
||||
|
||||
/** The error slot (also all there is when the ledger could not be read). */
|
||||
export function pickerStatus(error: unknown): HTMLElement {
|
||||
return h('div', { class: 'picker-status' }, error ? errorNotice(error) : null)
|
||||
}
|
||||
|
||||
/** Everything the loaded picker shows for `s`. */
|
||||
export function pickerView(s: PickerState, on: PickerHandlers): HTMLElement[] {
|
||||
const status = pickerStatus(s.error)
|
||||
const bar = progressBar(s.answered / s.total, 'Answered')
|
||||
if (!s.entry) return [bar, status, done(s, on), footer(s, on)]
|
||||
const stage = h('div', { class: 'picker-stage' }, h('div', { class: 'picker-big', 'aria-hidden': 'true' }, iconFor(s.entry.id).glyph), contextPreview(s.entry.id))
|
||||
return [header(s, s.entry), bar, status, h('div', { class: 'picker-body' }, stage, choices(s, s.entry, on)), footer(s, on)]
|
||||
}
|
||||
28
web/src/icons/preview.test.ts
Normal file
28
web/src/icons/preview.test.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { useIcons } from '../test/iconLedger'
|
||||
import { contextPreview } from './preview'
|
||||
import type { IconId } from './registry'
|
||||
|
||||
describe('contextPreview: the icon as it looks where it is used', () => {
|
||||
it.each<[IconId, string, string]>([
|
||||
['nav.gaming', '.nav-link', '🕹️'],
|
||||
['palette.open', '.palette-btn', '⌨️'],
|
||||
['cmd.install', '.btn', '📥'],
|
||||
['job.state.failed', '.pill', '💔'],
|
||||
['notice.info', '.notice', '💡'],
|
||||
])('%s renders inside %s with the chosen glyph and word', (id, shell, alt) => {
|
||||
useIcons({ [id]: { word: 'shown here', glyph: alt } })
|
||||
const el = contextPreview(id)
|
||||
expect(el).toHaveAttribute('inert')
|
||||
const host = el.querySelector(shell)
|
||||
expect(host).not.toBeNull()
|
||||
expect(host?.textContent).toContain(alt)
|
||||
expect(host?.querySelector('.icon-word')?.textContent).toBe('Shown here')
|
||||
})
|
||||
|
||||
it('shows the default glyph and no word before any choice', () => {
|
||||
const el = contextPreview('cmd.install')
|
||||
expect(el.textContent).toContain('⬇️')
|
||||
expect(el.querySelector('.icon-word')).toBeNull()
|
||||
})
|
||||
})
|
||||
40
web/src/icons/preview.ts
Normal file
40
web/src/icons/preview.ts
Normal file
@ -0,0 +1,40 @@
|
||||
// The icon as it looks where the UI paints it, for the /words picker: inert
|
||||
// replicas built from the same pieces as the real call sites (no handlers),
|
||||
// showing the current glyph and word.
|
||||
|
||||
import type { JobState } from '../api/jobContract'
|
||||
import { stateBadge } from '../jobs/progress'
|
||||
import { h } from '../lib/dom'
|
||||
import { NAV } from '../shell/nav'
|
||||
import { notice, type Tone } from '../ui/build'
|
||||
import type { IconId } from './registry'
|
||||
import { iconMark, iconWord } from './render'
|
||||
|
||||
function inContext(id: IconId): HTMLElement {
|
||||
const [group = '', ...rest] = id.split('.')
|
||||
const tail = rest.join('.')
|
||||
const word = iconWord(id)
|
||||
const paired = word ? ' has-word' : ''
|
||||
switch (group) {
|
||||
case 'nav':
|
||||
return h(
|
||||
'span',
|
||||
{ class: `nav-link active${paired}` },
|
||||
iconMark(id, 'nav-icon'),
|
||||
word,
|
||||
NAV.filter((n) => n.icon === id).map((n) => h('kbd', {}, n.key)),
|
||||
)
|
||||
case 'palette':
|
||||
return h('span', { class: 'btn btn-ghost palette-btn' }, iconMark(id, ''), word, h('kbd', {}, '⌃K'))
|
||||
case 'job':
|
||||
return stateBadge(tail.replace(/^state\./, '') as JobState)
|
||||
case 'notice':
|
||||
return notice(tail as Tone, null)
|
||||
default:
|
||||
return h('span', { class: 'btn btn-ghost' }, iconMark(id, 'cmd-icon'), word)
|
||||
}
|
||||
}
|
||||
|
||||
export function contextPreview(id: IconId): HTMLDivElement {
|
||||
return h('div', { class: 'picker-context', inert: true }, inContext(id))
|
||||
}
|
||||
50
web/src/icons/registry.json
Normal file
50
web/src/icons/registry.json
Normal file
@ -0,0 +1,50 @@
|
||||
{
|
||||
"version": 1,
|
||||
"icons": {
|
||||
"nav.dashboard": { "glyph": "🏠", "spoken": "Dashboard", "desc": "Sidebar link to the dashboard (Alt+1). It opens the start page with the assigned game, today's gaming budget and the quick actions.", "words": ["home", "dashboard", "overview"], "alts": ["🏡", "🧭", "📟"] },
|
||||
"nav.backlog": { "glyph": "📚", "spoken": "Backlog", "desc": "Sidebar link to the backlog page (Alt+2). It opens the planner, the completion-time stats and the full game list.", "words": ["backlog", "planner", "queue"], "alts": ["📖", "🗃️", "📜"] },
|
||||
"nav.picks": { "glyph": "🎯", "spoken": "Picks", "desc": "Sidebar link to the picks page (Alt+3). It opens check, done, pick and scan, plus your manual picks.", "words": ["picks", "assignment", "target"], "alts": ["🏹", "📍", "🔭"] },
|
||||
"nav.gaming": { "glyph": "🎮", "spoken": "Gaming", "desc": "Sidebar link to the gaming page (Alt+4). It opens the daily gaming budget with its reset, block and unblock actions.", "words": ["gaming", "budget", "playtime"], "alts": ["🕹️", "👾", "⌛"] },
|
||||
"nav.library": { "glyph": "🗂️", "spoken": "Library", "desc": "Sidebar link to the library page (Alt+5). It opens every game you own, with install, uninstall and hide.", "words": ["library", "games", "collection"], "alts": ["📦", "🖼️", "💿"] },
|
||||
"nav.store": { "glyph": "🛒", "spoken": "Store", "desc": "Sidebar link to the store page (Alt+6). It opens the timed store unblock, buying DLC and game exceptions.", "words": ["store", "shop", "purchases"], "alts": ["🏪", "🛍️", "💰"] },
|
||||
"nav.jobs": { "glyph": "⚙️", "spoken": "Jobs", "desc": "Sidebar link to the jobs page (Alt+7). It lists the running and past jobs with their logs.", "words": ["jobs", "tasks", "activity"], "alts": ["🛠️", "🧰", "🏗️"] },
|
||||
"nav.system": { "glyph": "🖥️", "spoken": "System", "desc": "Sidebar link to the system page (Alt+8). It opens the root daemon, the web server, state backups, reset and setup.", "words": ["system", "daemon", "admin"], "alts": ["💻", "🔩", "📡"] },
|
||||
"palette.open": { "glyph": "🔍", "spoken": "Commands", "desc": "Top-bar button (Ctrl+K) that opens the command palette. There you search for any command or section and run or open it.", "words": ["commands", "search", "palette"], "alts": ["⌨️", "✨", "🗒️"] },
|
||||
"cmd.status": { "glyph": "📊", "spoken": "Status", "desc": "Opens the current status: the assigned game, its achievement progress and the enforcer's state.", "words": ["status", "state", "summary"], "alts": ["🩺", "🧾", "🚥"] },
|
||||
"cmd.list": { "glyph": "📋", "spoken": "List", "desc": "Opens the game list from the last scan snapshot, with achievements and completion times.", "words": ["list", "games", "snapshot"], "alts": ["📃", "📑", "🧻"] },
|
||||
"cmd.stats": { "glyph": "📈", "spoken": "Stats", "desc": "Opens the backlog estimates: how long the remaining games take to finish at your pace.", "words": ["stats", "estimates", "forecast"], "alts": ["📉", "🧮", "🔮"] },
|
||||
"cmd.installed": { "glyph": "💾", "spoken": "Installed", "desc": "Opens the list of games installed on this PC, with the assigned and protected ones marked.", "words": ["installed", "disk", "local"], "alts": ["💽", "📀", "🧊"] },
|
||||
"cmd.gaming-status": { "glyph": "⏱️", "spoken": "Gaming status", "desc": "Opens today's gaming time: minutes used, budget left and whether gaming is blocked.", "words": ["today", "playtime", "clock"], "alts": ["⏲️", "🕐", "📆"] },
|
||||
"cmd.check": { "glyph": "🔄", "spoken": "Check", "desc": "Runs check: looks for a new achievement on the assigned game. One new achievement releases the game.", "words": ["check", "verify", "refresh"], "alts": ["🔁", "🧐", "☑️"] },
|
||||
"cmd.scan": { "glyph": "🔎", "spoken": "Scan", "desc": "Runs scan: reads the achievements of every owned game and assigns a game when none is set.", "words": ["scan", "survey", "assign"], "alts": ["🛰️", "🗺️", "🧪"] },
|
||||
"cmd.done": { "glyph": "🏆", "spoken": "Done", "desc": "Runs done: confirms a new achievement on the assigned game and moves on to pick the next one.", "words": ["done", "finished", "next"], "alts": ["🥇", "🎉", "🏁"] },
|
||||
"cmd.pick": { "glyph": "🎲", "spoken": "Pick", "desc": "Runs pick: offers other candidate games to play next. It keeps the current game unless told to replace it.", "words": ["pick", "choose", "random"], "alts": ["🃏", "🎰", "🔀"] },
|
||||
"cmd.pick-manual": { "glyph": "📌", "spoken": "Pick manual", "desc": "Runs a manual pick: you choose a game by hand and the enforcer locks onto it for some days.", "words": ["manual", "lock", "own"], "alts": ["✋", "🧷", "🖐️"] },
|
||||
"cmd.abandon-pick": { "glyph": "❌", "spoken": "Abandon pick", "desc": "Runs abandon pick: undoes a manual pick, so the enforcer assigns a game again.", "words": ["abandon", "undo", "drop"], "alts": ["✖️", "↩️", "🚮"] },
|
||||
"cmd.install": { "glyph": "⬇️", "spoken": "Install", "desc": "Runs install: downloads an allowed game, trying the fast installer first.", "words": ["install", "download", "get"], "alts": ["📥", "🔽", "⏬"] },
|
||||
"cmd.uninstall": { "glyph": "🗑️", "spoken": "Uninstall", "desc": "Runs uninstall: removes every installed game that is neither assigned nor protected.", "words": ["uninstall", "remove", "clean"], "alts": ["🧹", "⏏️", "🪣"] },
|
||||
"cmd.hide": { "glyph": "🙈", "spoken": "Hide", "desc": "Runs hide: hides every game except the assigned one in the Steam library.", "words": ["hide", "conceal", "mask"], "alts": ["🫣", "🕶️", "🌫️"] },
|
||||
"cmd.unhide": { "glyph": "👁️", "spoken": "Unhide", "desc": "Runs unhide: shows every game in the Steam library again.", "words": ["unhide", "show", "reveal"], "alts": ["👀", "🔦", "🪟"] },
|
||||
"cmd.buy-dlc": { "glyph": "💳", "spoken": "Buy DLC", "desc": "Runs buy DLC: unblocks the Steam store for 15 minutes so you can buy a game or DLC.", "words": ["DLC", "buy", "purchase"], "alts": ["💵", "🪙", "🏷️"] },
|
||||
"cmd.unblock": { "glyph": "🔓", "spoken": "Unblock", "desc": "Runs unblock: opens the Steam store for a number of minutes, at most 30.", "words": ["unblock", "open", "unlock"], "alts": ["🚪", "🗝️", "🔆"] },
|
||||
"cmd.add-exception": { "glyph": "🎫", "spoken": "Add exception", "desc": "Runs add exception: allows one game right away, after a typed phrase and a logged reason.", "words": ["exception", "allow", "whitelist"], "alts": ["🎟️", "🆗", "📝"] },
|
||||
"cmd.block-gaming": { "glyph": "⛔", "spoken": "Block gaming", "desc": "Runs block gaming: blocks all gaming for a number of days. There is no undo in the app.", "words": ["block", "ban", "lockdown"], "alts": ["🧱", "📵", "🚷"] },
|
||||
"cmd.reset": { "glyph": "♻️", "spoken": "Reset", "desc": "Runs reset: wipes all enforcer state after saving a timestamped backup.", "words": ["reset", "wipe", "restart"], "alts": ["🧨", "🔃", "🆕"] },
|
||||
"cmd.setup": { "glyph": "🔧", "spoken": "Setup", "desc": "Opens setup: the Steam API key and the SteamID the enforcer needs.", "words": ["setup", "configure", "key"], "alts": ["🪛", "🎛️", "🧩"] },
|
||||
"cmd.enforce": { "glyph": "🛡️", "spoken": "Enforce", "desc": "Runs the enforcer: block, uninstall, kill and hide. The demo runs a 60-second gaming budget only.", "words": ["enforce", "guard", "shield"], "alts": ["👮", "🚔", "🔰"] },
|
||||
"cmd.gaming-reset": { "glyph": "⏪", "spoken": "Gaming reset", "desc": "Runs gaming reset: resets today's gaming counter as root, after a typed phrase and a five-minute countdown.", "words": ["rewind", "reset", "refill"], "alts": ["⏮️", "🔙", "🔂"] },
|
||||
"cmd.gaming-unblock": { "glyph": "🔌", "spoken": "Gaming unblock", "desc": "Runs gaming unblock: force-releases the playtime bind mounts. It is the root recovery hatch.", "words": ["release", "unplug", "recover"], "alts": ["🪫", "🆘", "🧯"] },
|
||||
"cmd.serve": { "glyph": "🌐", "spoken": "Serve", "desc": "Restarts this web UI server. It comes back on the current code by itself.", "words": ["server", "web", "restart"], "alts": ["🕸️", "📶", "🔗"] },
|
||||
"cmd.restore-backup": { "glyph": "🗄️", "spoken": "Restore backup", "desc": "Restores a saved state backup after you type its phrase.", "words": ["restore", "backup", "rollback"], "alts": ["💼", "🧳", "📼"] },
|
||||
"job.state.queued": { "glyph": "⏸️", "spoken": "Queued", "desc": "Job state badge: the job waits to start.", "words": ["queued", "waiting", "pending"], "alts": ["🕒", "⏳", "💤"] },
|
||||
"job.state.running": { "glyph": "▶️", "spoken": "Running", "desc": "Job state badge: the job is running now.", "words": ["running", "active", "busy"], "alts": ["🏃", "⚡", "🔵"] },
|
||||
"job.state.waiting_input": { "glyph": "⚠️", "spoken": "Waiting for input", "desc": "Job state badge: the job is paused on a question and needs your answer.", "words": ["input", "question", "answer"], "alts": ["❓", "💬", "🙋"] },
|
||||
"job.state.succeeded": { "glyph": "✅", "spoken": "Succeeded", "desc": "Job state badge: the job finished without errors.", "words": ["succeeded", "done", "ok"], "alts": ["✔️", "🟢", "👍"] },
|
||||
"job.state.failed": { "glyph": "⛔", "spoken": "Failed", "desc": "Job state badge: the job stopped on an error. Its log says why.", "words": ["failed", "error", "broken"], "alts": ["💔", "🔴", "💥"] },
|
||||
"job.state.cancelled": { "glyph": "🚫", "spoken": "Cancelled", "desc": "Job state badge: the job was stopped before it finished.", "words": ["cancelled", "stopped", "aborted"], "alts": ["⏹️", "🛑", "✂️"] },
|
||||
"notice.info": { "glyph": "ℹ️", "spoken": "Information", "desc": "Mark on an information notice: a neutral fact or a hint.", "words": ["info", "note", "hint"], "alts": ["💡", "🔷", "📢"] },
|
||||
"notice.success": { "glyph": "✅", "spoken": "Success", "desc": "Mark on a success notice: the action worked.", "words": ["success", "ok", "done"], "alts": ["✔️", "🎉", "👍"] },
|
||||
"notice.warning": { "glyph": "⚠️", "spoken": "Warning", "desc": "Mark on a warning notice: something needs your attention, but nothing failed.", "words": ["warning", "caution", "careful"], "alts": ["🟡", "🔶", "❗"] },
|
||||
"notice.danger": { "glyph": "⛔", "spoken": "Error", "desc": "Mark on an error notice: something failed or was refused. The server's message follows it.", "words": ["error", "danger", "problem"], "alts": ["🛑", "‼️", "🔴"] }
|
||||
}
|
||||
}
|
||||
51
web/src/icons/registry.test.ts
Normal file
51
web/src/icons/registry.test.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { JobState } from '../api/jobContract'
|
||||
import { COMMAND_HOME, commandIcon } from '../commands/catalog'
|
||||
import { NAV } from '../shell/nav'
|
||||
import type { Tone } from '../ui/build'
|
||||
import { ICONS, iconEntry, isIconId } from './registry'
|
||||
|
||||
const JOB_STATES: JobState[] = ['queued', 'running', 'waiting_input', 'succeeded', 'failed', 'cancelled']
|
||||
const TONES: Tone[] = ['info', 'success', 'warning', 'danger']
|
||||
|
||||
describe('icon registry', () => {
|
||||
it('registers exactly this pass: 8 nav, the palette, 26 commands, 6 job states, 4 tones', () => {
|
||||
const ids = ICONS.map((e) => e.id)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
expect(ids).toHaveLength(8 + 1 + 26 + 6 + 4)
|
||||
for (const n of NAV) expect(isIconId(n.icon)).toBe(true)
|
||||
expect(isIconId('palette.open')).toBe(true)
|
||||
for (const name of Object.keys(COMMAND_HOME) as (keyof typeof COMMAND_HOME)[]) {
|
||||
expect(isIconId(commandIcon(name))).toBe(true)
|
||||
}
|
||||
for (const s of JOB_STATES) expect(isIconId(`job.state.${s}`)).toBe(true)
|
||||
for (const t of TONES) expect(isIconId(`notice.${t}`)).toBe(true)
|
||||
})
|
||||
|
||||
it.each(ICONS.map((e) => [e.id, e] as const))('%s: glyph, name, description, 3 words, 3 alternatives', (_id, e) => {
|
||||
expect(e.glyph).not.toBe('')
|
||||
expect(e.spoken).not.toBe('')
|
||||
expect(e.desc.length).toBeGreaterThan(20)
|
||||
expect(e.desc.split(/[.!?](\s|$)/).filter((s) => s.trim()).length).toBeLessThanOrEqual(2)
|
||||
expect(e.words).toHaveLength(3)
|
||||
expect(new Set(e.words.map((w) => w.toLowerCase())).size).toBe(3)
|
||||
for (const w of e.words) expect(w).toMatch(/^\S+$/)
|
||||
expect(e.alts).toHaveLength(3)
|
||||
expect(new Set([e.glyph, ...e.alts]).size).toBe(4)
|
||||
})
|
||||
|
||||
it('keeps every default glyph the UI painted before the registry', () => {
|
||||
expect(iconEntry('nav.dashboard').glyph).toBe('🏠')
|
||||
expect(iconEntry('palette.open').glyph).toBe('🔍')
|
||||
expect(iconEntry('cmd.done').glyph).toBe('🏆')
|
||||
expect(iconEntry('cmd.restore-backup').glyph).toBe('🗄️')
|
||||
expect(iconEntry('job.state.waiting_input').glyph).toBe('⚠️')
|
||||
expect(iconEntry('notice.danger').glyph).toBe('⛔')
|
||||
})
|
||||
|
||||
it('tells registered ids from raw glyphs', () => {
|
||||
expect(isIconId('cmd.done')).toBe(true)
|
||||
expect(isIconId('🏆')).toBe(false)
|
||||
expect(isIconId('toString')).toBe(false)
|
||||
})
|
||||
})
|
||||
38
web/src/icons/registry.ts
Normal file
38
web/src/icons/registry.ts
Normal file
@ -0,0 +1,38 @@
|
||||
// The icon registry: every icon the UI paints by id, its default glyph, its
|
||||
// spoken name, what it is and does, 3 one-word suggestions and 3 alternative
|
||||
// glyphs. The data is registry.json so the Python server can check a glyph
|
||||
// choice against the same list; this module types it (IconId is the union of
|
||||
// its keys, so an unregistered id fails the build) and looks it up.
|
||||
// Order in the file is the picker's order.
|
||||
|
||||
import data from './registry.json'
|
||||
|
||||
export type IconId = keyof typeof data.icons
|
||||
|
||||
export interface IconEntry {
|
||||
id: IconId
|
||||
glyph: string
|
||||
/** The accessible name (aria-label / .sr-only) when a caller gives none. */
|
||||
spoken: string
|
||||
/** What the icon is and what it does, shown on the /words picker. */
|
||||
desc: string
|
||||
/** Three distinct one-word suggestions (keys 1/2/3 on the picker). */
|
||||
words: readonly string[]
|
||||
/** Three glyphs that may replace the default (keys 7/8/9). */
|
||||
alts: readonly string[]
|
||||
}
|
||||
|
||||
const RAW: Record<string, Omit<IconEntry, 'id'>> = data.icons
|
||||
|
||||
export const ICONS: readonly IconEntry[] = Object.entries(RAW).map(([id, e]) => ({ id: id as IconId, ...e }))
|
||||
|
||||
const BY_ID = Object.fromEntries(ICONS.map((e) => [e.id, e])) as Record<IconId, IconEntry>
|
||||
|
||||
/** True for a registered id, false for a raw glyph (the old `glyph(icon, spoken)` path). */
|
||||
export function isIconId(s: string): s is IconId {
|
||||
return Object.hasOwn(BY_ID, s)
|
||||
}
|
||||
|
||||
export function iconEntry(id: IconId): IconEntry {
|
||||
return BY_ID[id]
|
||||
}
|
||||
135
web/src/icons/render.test.ts
Normal file
135
web/src/icons/render.test.ts
Normal file
@ -0,0 +1,135 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { useIcons } from '../test/iconLedger'
|
||||
import { glyph } from '../ui/build'
|
||||
import { setWordsHidden } from './ledger'
|
||||
import { decorateChrome, decorateIcons, iconFor, iconMark, iconWord } from './render'
|
||||
|
||||
// vitest runs from web/ (vitest.config.ts); jsdom loads no CSS, so read the rule.
|
||||
const css = readFileSync(join(process.cwd(), 'src/styles/icons.css'), 'utf8')
|
||||
|
||||
describe('decorateChrome', () => {
|
||||
it('decorates the sidebar and top bar only', () => {
|
||||
useIcons({ 'nav.jobs': { word: 'jobs' }, 'palette.open': { word: 'find' } })
|
||||
document.body.innerHTML =
|
||||
'<aside class="sidebar"><a class="nav-link"><span data-icon="nav.jobs">⚙️</span></a></aside>' +
|
||||
'<header class="topbar"><button class="btn"><span data-icon="palette.open">🔍</span></button></header>' +
|
||||
'<main><span data-icon="nav.jobs">⚙️</span></main>'
|
||||
decorateChrome()
|
||||
expect([...document.querySelectorAll('.icon-word')].map((w) => w.textContent)).toEqual(['Jobs', 'Find'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('iconFor', () => {
|
||||
it('is the default glyph and no word without a ledger entry', () => {
|
||||
expect(iconFor('cmd.done')).toEqual({ id: 'cmd.done', glyph: '🏆', word: '', spoken: 'Done' })
|
||||
})
|
||||
|
||||
it('draws the stored word in sentence case and swaps in the chosen glyph', () => {
|
||||
useIcons({ 'cmd.done': { word: 'got an HLTB win', glyph: '🎉' } })
|
||||
expect(iconFor('cmd.done')).toMatchObject({ glyph: '🎉', word: 'Got an HLTB win' })
|
||||
})
|
||||
|
||||
it('has no word when skipped or hidden, but keeps the chosen glyph', () => {
|
||||
useIcons({ 'cmd.done': { word: null, glyph: '🏁' }, 'cmd.scan': { word: 'scan' } })
|
||||
expect(iconFor('cmd.done')).toMatchObject({ glyph: '🏁', word: '' })
|
||||
setWordsHidden(true)
|
||||
expect(iconFor('cmd.scan').word).toBe('')
|
||||
})
|
||||
|
||||
it('ignores a stored glyph that is not one of the registered ones', () => {
|
||||
useIcons({ 'cmd.done': { glyph: '🍕' } })
|
||||
expect(iconFor('cmd.done').glyph).toBe('🏆')
|
||||
})
|
||||
})
|
||||
|
||||
describe('glyph(id)', () => {
|
||||
it('paints the word to the right of the icon and keeps the spoken name', () => {
|
||||
useIcons({ 'nav.jobs': { word: 'my jobs' } })
|
||||
const el = glyph('nav.jobs')
|
||||
const [icon, word, spoken] = [...el.children]
|
||||
expect(icon).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(icon.textContent).toBe('⚙️')
|
||||
expect(word).toHaveClass('icon-word')
|
||||
expect(word).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(word.textContent).toBe('My jobs')
|
||||
expect(spoken).toHaveClass('sr-only')
|
||||
expect(spoken.textContent).toBe('Jobs')
|
||||
expect(el).toHaveClass('glyph', 'has-word')
|
||||
})
|
||||
|
||||
it('takes an explicit spoken name and class', () => {
|
||||
const el = glyph('cmd.scan', 'Run scan', 'job-cmd')
|
||||
expect(el.className).toBe('job-cmd')
|
||||
expect(el.querySelector('.sr-only')?.textContent).toBe('Run scan')
|
||||
expect(el.querySelector('.icon-word')).toBeNull()
|
||||
})
|
||||
|
||||
it('still paints a raw glyph with the old signature', () => {
|
||||
const el = glyph('🧭', 'navigate')
|
||||
expect(el.querySelector('[aria-hidden]')?.textContent).toBe('🧭')
|
||||
expect(el.querySelector('.sr-only')?.textContent).toBe('navigate')
|
||||
expect(el.querySelector('.icon-word')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('icon pieces', () => {
|
||||
it('iconMark is the glyph alone, tagged with its id', () => {
|
||||
useIcons({ 'nav.store': { glyph: '🏪' } })
|
||||
const el = iconMark('nav.store', 'nav-icon')
|
||||
expect(el.className).toBe('nav-icon')
|
||||
expect(el).toHaveAttribute('data-icon', 'nav.store')
|
||||
expect(el).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(el.textContent).toBe('🏪')
|
||||
})
|
||||
|
||||
it('iconWord is null without a word, a tagged span with one', () => {
|
||||
expect(iconWord('nav.store')).toBeNull()
|
||||
useIcons({ 'nav.store': { word: 'shop' } })
|
||||
const w = iconWord('nav.store')
|
||||
expect(w).toHaveAttribute('data-icon-word', 'nav.store')
|
||||
expect(w?.textContent).toBe('Shop')
|
||||
})
|
||||
|
||||
it('the CSS lays the word out on the right, vertically centred, never under', () => {
|
||||
const rule = /\.has-word\s*\{([^}]*)\}/.exec(css)?.[1] ?? ''
|
||||
expect(rule).toMatch(/display:\s*inline-flex/)
|
||||
expect(rule).toMatch(/align-items:\s*center/)
|
||||
expect(rule).not.toMatch(/column|wrap/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('decorateIcons (static Astro markup: sidebar, palette button)', () => {
|
||||
const markup = () => {
|
||||
document.body.innerHTML =
|
||||
'<a class="nav-link"><span class="nav-icon" aria-hidden="true" data-icon="nav.picks">🎯</span><kbd>3</kbd></a>' +
|
||||
'<span data-icon="no.such">❓</span>'
|
||||
return document.body
|
||||
}
|
||||
|
||||
it('swaps the glyph and puts the word right after the icon, once', () => {
|
||||
useIcons({ 'nav.picks': { word: 'target', glyph: '🏹' } })
|
||||
const root = markup()
|
||||
decorateIcons(root)
|
||||
decorateIcons(root)
|
||||
const icon = root.querySelector('[data-icon="nav.picks"]')
|
||||
expect(icon?.textContent).toBe('🏹')
|
||||
expect(icon?.nextElementSibling).toHaveClass('icon-word')
|
||||
expect(icon?.nextElementSibling?.textContent).toBe('Target')
|
||||
expect(root.querySelectorAll('.icon-word')).toHaveLength(1)
|
||||
expect(icon?.parentElement).toHaveClass('has-word')
|
||||
expect(root.querySelector('[data-icon="no.such"]')?.textContent).toBe('❓')
|
||||
})
|
||||
|
||||
it('removes the words again when they are hidden', () => {
|
||||
useIcons({ 'nav.picks': { word: 'target' } })
|
||||
const root = markup()
|
||||
decorateIcons(root)
|
||||
setWordsHidden(true)
|
||||
decorateIcons(root)
|
||||
expect(root.querySelector('.icon-word')).toBeNull()
|
||||
expect(root.querySelector('.nav-link')).not.toHaveClass('has-word')
|
||||
expect(root.querySelector('[data-icon="nav.picks"]')?.textContent).toBe('🎯')
|
||||
})
|
||||
})
|
||||
60
web/src/icons/render.ts
Normal file
60
web/src/icons/render.ts
Normal file
@ -0,0 +1,60 @@
|
||||
// Drawing a registered icon: the glyph (the user's alternative if he chose
|
||||
// one) and, when he picked a word, that word to the RIGHT of the icon,
|
||||
// vertically centred (styles/icons.css `.has-word`), in sentence case. The
|
||||
// word is aria-hidden: the icon's spoken name stays its one accessible name.
|
||||
// `glyph(id)` in ui/build.ts is the usual entry; these are its parts.
|
||||
|
||||
import { h } from '../lib/dom'
|
||||
import { choiceOf, wordsHidden } from './ledger'
|
||||
import { iconEntry, isIconId, type IconId } from './registry'
|
||||
import { sentenceCase } from './textCase'
|
||||
|
||||
export interface ResolvedIcon {
|
||||
id: IconId
|
||||
glyph: string
|
||||
/** As drawn (sentence case); '' when skipped, unanswered or hidden. */
|
||||
word: string
|
||||
spoken: string
|
||||
}
|
||||
|
||||
export function iconFor(id: IconId): ResolvedIcon {
|
||||
const entry = iconEntry(id)
|
||||
const choice = choiceOf(id)
|
||||
const glyph = choice.glyph && entry.alts.includes(choice.glyph) ? choice.glyph : entry.glyph
|
||||
const word = typeof choice.word === 'string' && !wordsHidden() ? sentenceCase(choice.word) : ''
|
||||
return { id, glyph, word, spoken: entry.spoken }
|
||||
}
|
||||
|
||||
/** The painted glyph alone, tagged with its id (decorateIcons can refresh it). */
|
||||
export function iconMark(id: IconId, className: string): HTMLSpanElement {
|
||||
return h('span', { class: className, 'aria-hidden': 'true', 'data-icon': id }, iconFor(id).glyph)
|
||||
}
|
||||
|
||||
/** The word span that goes right after the icon, or null when it has none. */
|
||||
export function iconWord(id: IconId): HTMLSpanElement | null {
|
||||
const { word } = iconFor(id)
|
||||
return word ? h('span', { class: 'icon-word', 'aria-hidden': 'true', 'data-icon-word': id }, word) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh static markup (the Astro sidebar and palette button) from the
|
||||
* ledger: each `[data-icon]` gets its current glyph and, right after it, its
|
||||
* word. Idempotent, so it can rerun after a pick or a hide toggle.
|
||||
*/
|
||||
export function decorateIcons(root: ParentNode): void {
|
||||
for (const el of root.querySelectorAll<HTMLElement>('[data-icon]')) {
|
||||
const id = String(el.dataset.icon)
|
||||
if (!isIconId(id)) continue
|
||||
const next = el.nextElementSibling
|
||||
if (next?.classList.contains('icon-word')) next.remove()
|
||||
el.textContent = iconFor(id).glyph
|
||||
const word = iconWord(id)
|
||||
if (word) el.after(word)
|
||||
el.parentElement?.classList.toggle('has-word', word !== null)
|
||||
}
|
||||
}
|
||||
|
||||
/** The static chrome every page shares (sidebar, top bar); run at boot and after a pick. */
|
||||
export function decorateChrome(doc: Document = document): void {
|
||||
for (const el of doc.querySelectorAll('.sidebar, .topbar')) decorateIcons(el)
|
||||
}
|
||||
29
web/src/icons/textCase.test.ts
Normal file
29
web/src/icons/textCase.test.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { KEEP, sentenceCase } from './textCase'
|
||||
|
||||
describe('sentenceCase', () => {
|
||||
it.each([
|
||||
['home', 'Home'],
|
||||
['gaming Reset', 'Gaming reset'],
|
||||
['My Own Words', 'My own words'],
|
||||
['buy dlc', 'Buy DLC'],
|
||||
['hltb times', 'HLTB times'],
|
||||
['app Id', 'App ID'],
|
||||
['open steam', 'Open Steam'],
|
||||
['get (dlc)!', 'Get (DLC)!'],
|
||||
['"quoted" word', '"Quoted" word'],
|
||||
['', ''],
|
||||
['42 games', '42 games'],
|
||||
])('%j -> %j', (stored, drawn) => {
|
||||
expect(sentenceCase(stored)).toBe(drawn)
|
||||
})
|
||||
|
||||
it('changes only first letters: the rest of a word stays verbatim', () => {
|
||||
expect(sentenceCase('iPhone sYnc')).toBe('IPhone sYnc')
|
||||
})
|
||||
|
||||
it('keeps the acronyms the brief names', () => {
|
||||
for (const word of ['DLC', 'HLTB', 'CDP', 'ID']) expect(KEEP).toContain(word)
|
||||
expect(sentenceCase('via cdp')).toBe('Via CDP')
|
||||
})
|
||||
})
|
||||
29
web/src/icons/textCase.ts
Normal file
29
web/src/icons/textCase.ts
Normal file
@ -0,0 +1,29 @@
|
||||
// The one casing rule for every icon word, after cleanup-plate's TextCase:
|
||||
// sentence case. The first letter of the text is upper-case, every later word
|
||||
// starts lower-case, except the acronyms / proper nouns in KEEP, which always
|
||||
// get their listed spelling. Only first letters change: typos, punctuation and
|
||||
// the rest of a word stay verbatim. Applied at render time; the user's ledger
|
||||
// is never rewritten. Add a new acronym or name HERE, nowhere else.
|
||||
|
||||
export const KEEP: readonly string[] = ['API', 'CDP', 'DLC', 'HLTB', 'ID', 'OK', 'Steam', 'UI']
|
||||
|
||||
const EDGE = /^[,.;:!?()"']*/
|
||||
const TAIL = /[,.;:!?()"']*$/
|
||||
|
||||
function caseWord(word: string, first: boolean): string {
|
||||
const lead = word.slice(0, word.length - word.replace(EDGE, '').length)
|
||||
const core = word.slice(lead.length).replace(TAIL, '')
|
||||
if (core === '') return word
|
||||
const keep = KEEP.find((k) => k.toLowerCase() === core.toLowerCase())
|
||||
if (keep) return lead + keep + word.slice(lead.length + core.length)
|
||||
const letter = word.charAt(lead.length)
|
||||
const cased = first ? letter.toUpperCase() : letter.toLowerCase()
|
||||
return lead + cased + word.slice(lead.length + 1)
|
||||
}
|
||||
|
||||
export function sentenceCase(text: string): string {
|
||||
return text
|
||||
.split(' ')
|
||||
.map((w, i) => caseWord(w, i === 0))
|
||||
.join(' ')
|
||||
}
|
||||
57
web/src/icons/wiring.test.ts
Normal file
57
web/src/icons/wiring.test.ts
Normal file
@ -0,0 +1,57 @@
|
||||
// The registered call sites look their icon up by id: a ledger word shows
|
||||
// right of the icon, a chosen alternative replaces the default glyph.
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { COMMAND_ICON, commandIcon } from '../commands/catalog'
|
||||
import { commandButton } from '../commands/commandButton'
|
||||
import { stateBadge } from '../jobs/progress'
|
||||
import { NAV } from '../shell/nav'
|
||||
import { useIcons } from '../test/iconLedger'
|
||||
import { notice } from '../ui/build'
|
||||
import { isIconId } from './registry'
|
||||
|
||||
describe('registered call sites', () => {
|
||||
it('a command button paints the word right of its icon, label still spoken', () => {
|
||||
useIcons({ 'cmd.done': { word: 'trophy', glyph: '🥇' } })
|
||||
const btn = commandButton({ name: 'done', label: 'I got an achievement' })
|
||||
const icon = btn.querySelector('.cmd-icon')
|
||||
expect(icon?.textContent).toBe('🥇')
|
||||
expect(icon?.nextElementSibling).toHaveClass('icon-word')
|
||||
expect(icon?.nextElementSibling?.textContent).toBe('Trophy')
|
||||
expect(btn).toHaveAttribute('aria-label', 'I got an achievement')
|
||||
})
|
||||
|
||||
it('a command button without a word is unchanged', () => {
|
||||
const btn = commandButton({ name: 'scan' })
|
||||
expect(btn.querySelector('.cmd-icon')?.textContent).toBe('🔎')
|
||||
expect(btn.querySelector('.icon-word')).toBeNull()
|
||||
})
|
||||
|
||||
it('a notice paints its tone word right of the tone icon', () => {
|
||||
useIcons({ 'notice.warning': { word: 'careful' } })
|
||||
const el = notice('warning', null)
|
||||
const icon = el.querySelector('.notice-icon')
|
||||
expect(icon?.nextElementSibling?.textContent).toBe('Careful')
|
||||
expect(icon?.parentElement).toHaveClass('has-word')
|
||||
})
|
||||
|
||||
it('a job state badge paints its word and keeps its aria-label', () => {
|
||||
useIcons({ 'job.state.running': { word: 'busy', glyph: '⚡' } })
|
||||
const el = stateBadge('running')
|
||||
expect(el.querySelector('.pill-icon')?.textContent).toBe('⚡')
|
||||
expect(el.querySelector('.icon-word')?.textContent).toBe('Busy')
|
||||
expect(el).toHaveAttribute('aria-label', 'running')
|
||||
})
|
||||
|
||||
it('nav entries and commands are looked up by id', () => {
|
||||
for (const n of NAV) expect(isIconId(n.icon)).toBe(true)
|
||||
expect(commandIcon('gaming-status')).toBe('cmd.gaming-status')
|
||||
})
|
||||
|
||||
it('COMMAND_ICON (sites not yet on ids) is the live glyph, alternative applied', () => {
|
||||
expect(COMMAND_ICON.done).toBe('🏆')
|
||||
useIcons({ 'cmd.done': { glyph: '🏁' } })
|
||||
expect(COMMAND_ICON.done).toBe('🏁')
|
||||
expect(Object.keys(COMMAND_ICON)).toHaveLength(26)
|
||||
})
|
||||
})
|
||||
26
web/src/icons/wordRules.test.ts
Normal file
26
web/src/icons/wordRules.test.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { normalizeWord, wordProblem } from './wordRules'
|
||||
|
||||
describe('manual words (mirror of the server rules)', () => {
|
||||
it('collapses whitespace and keeps casing', () => {
|
||||
expect(normalizeWord(' My OWN\tword\n ')).toBe('My OWN word')
|
||||
})
|
||||
|
||||
it.each(['My own words', 'x', 'HLTB 100%', 'I got an achievement!', '🏆'.repeat(40), 'a'.repeat(40)])(
|
||||
'accepts %j',
|
||||
(text) => {
|
||||
expect(wordProblem(text)).toBe('')
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
['', 'empty'],
|
||||
[' ', 'empty'],
|
||||
['a'.repeat(41), 'too_long'],
|
||||
['bad\u0000word', 'control'],
|
||||
['esc\u001b', 'control'],
|
||||
['del\u007f', 'control'],
|
||||
])('refuses %j as %s', (text, why) => {
|
||||
expect(wordProblem(text)).toBe(why)
|
||||
})
|
||||
})
|
||||
25
web/src/icons/wordRules.ts
Normal file
25
web/src/icons/wordRules.ts
Normal file
@ -0,0 +1,25 @@
|
||||
// Manual icon words, the client's copy of the server's rule
|
||||
// (_web_icon_words.normalize_word): any words, casing kept, whitespace runs
|
||||
// collapsed, 1–40 characters, no control characters. The server re-checks;
|
||||
// this only lets the picker flag a bad entry before sending it.
|
||||
|
||||
import { ICON_WORD_MAX } from '../api/iconWordsContract'
|
||||
|
||||
// Spelled out (not \s) so it matches the Python side character for character.
|
||||
const SPACE = /[\t\n\v\f\r \u00a0\u2000-\u200a\u2028\u2029\u202f\u3000]+/g
|
||||
// eslint-disable-next-line no-control-regex -- control characters are the point
|
||||
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/
|
||||
|
||||
export type WordProblem = '' | 'empty' | 'too_long' | 'control'
|
||||
|
||||
export function normalizeWord(text: string): string {
|
||||
return text.replace(SPACE, ' ').trim()
|
||||
}
|
||||
|
||||
/** '' when `text` is a storable word, else why not. Length counts code points, like Python. */
|
||||
export function wordProblem(text: string): WordProblem {
|
||||
const word = normalizeWord(text)
|
||||
if (word === '') return 'empty'
|
||||
if (Array.from(word).length > ICON_WORD_MAX) return 'too_long'
|
||||
return CONTROL.test(word) ? 'control' : ''
|
||||
}
|
||||
@ -1,16 +1,18 @@
|
||||
// Job state pill and progress bar (was jobs/ProgressBar.tsx).
|
||||
|
||||
import type { JobState } from '../api/jobContract'
|
||||
import type { IconId } from '../icons/registry'
|
||||
import { iconMark, iconWord } from '../icons/render'
|
||||
import { h } from '../lib/dom'
|
||||
|
||||
const STATE_ICON: Record<JobState, string> = {
|
||||
queued: '⏸️',
|
||||
running: '▶️',
|
||||
waiting_input: '⚠️',
|
||||
succeeded: '✅',
|
||||
failed: '⛔',
|
||||
cancelled: '🚫',
|
||||
}
|
||||
const STATE_ICON = {
|
||||
queued: 'job.state.queued',
|
||||
running: 'job.state.running',
|
||||
waiting_input: 'job.state.waiting_input',
|
||||
succeeded: 'job.state.succeeded',
|
||||
failed: 'job.state.failed',
|
||||
cancelled: 'job.state.cancelled',
|
||||
} as const satisfies Record<JobState, IconId>
|
||||
|
||||
const STATE_TONE: Record<JobState, string> = {
|
||||
queued: 'neutral',
|
||||
@ -22,7 +24,8 @@ const STATE_TONE: Record<JobState, string> = {
|
||||
}
|
||||
|
||||
export function stateBadge(state: JobState): HTMLSpanElement {
|
||||
return h('span', { class: `pill pill-${STATE_TONE[state]}`, 'aria-label': state }, h('span', { class: 'pill-icon', 'aria-hidden': 'true' }, STATE_ICON[state]))
|
||||
const id = STATE_ICON[state]
|
||||
return h('span', { class: `pill pill-${STATE_TONE[state]}`, 'aria-label': state }, iconMark(id, 'pill-icon'), iconWord(id))
|
||||
}
|
||||
|
||||
export type BarTone = 'accent' | 'success' | 'danger' | 'warning'
|
||||
|
||||
@ -9,7 +9,9 @@ import '../styles/app.css'
|
||||
import '../styles/controls.css'
|
||||
import '../styles/screens.css'
|
||||
import '../styles/library.css'
|
||||
import '../styles/icons.css'
|
||||
import DevToken from '../components/DevToken.astro'
|
||||
import { iconEntry } from '../icons/registry'
|
||||
import { BUILD_STAMP } from '../lib/buildStamp'
|
||||
import { NAV } from '../shell/nav'
|
||||
|
||||
@ -52,7 +54,7 @@ const href = (to: string) => (to === '/' ? '/' : `${to}/`)
|
||||
aria-label={n.label}
|
||||
aria-keyshortcuts={`Alt+${n.key}`}
|
||||
>
|
||||
<span class="nav-icon" aria-hidden="true">{n.icon}</span>
|
||||
<span class="nav-icon" aria-hidden="true" data-icon={n.icon}>{iconEntry(n.icon).glyph}</span>
|
||||
<kbd aria-hidden="true">{n.key}</kbd>
|
||||
</a>
|
||||
</li>
|
||||
@ -64,7 +66,7 @@ const href = (to: string) => (to === '/' ? '/' : `${to}/`)
|
||||
<div class="main-col">
|
||||
<header class="topbar">
|
||||
<button type="button" class="btn btn-ghost palette-btn" data-open-palette aria-keyshortcuts="Control+K" aria-label="Commands">
|
||||
<span aria-hidden="true">🔍</span> <kbd aria-hidden="true">⌃K</kbd>
|
||||
<span aria-hidden="true" data-icon="palette.open">{iconEntry('palette.open').glyph}</span> <kbd aria-hidden="true">⌃K</kbd>
|
||||
</button>
|
||||
<job-indicator></job-indicator>
|
||||
<span class="grow"></span>
|
||||
|
||||
16
web/src/pages/words/index.astro
Normal file
16
web/src/pages/words/index.astro
Normal file
@ -0,0 +1,16 @@
|
||||
---
|
||||
// The icon-word picker: the one page that carries text on purpose (the user
|
||||
// asked for it; descriptions and suggestions are for reading). Reached from
|
||||
// the command palette. All of it is rendered by <icon-words-picker>.
|
||||
import PageHead from '../../components/PageHead.astro'
|
||||
import Shell from '../../layouts/Shell.astro'
|
||||
---
|
||||
|
||||
<Shell title="Icon words">
|
||||
<PageHead title="Icon words" sub="Pick the word drawn next to each icon, or skip it." />
|
||||
<icon-words-picker></icon-words-picker>
|
||||
</Shell>
|
||||
|
||||
<script>
|
||||
import '../../icons/picker'
|
||||
</script>
|
||||
@ -4,7 +4,7 @@
|
||||
|
||||
import type { FastInstallRun, StatusPayload } from '../api/contract'
|
||||
import { q } from '../api/queries'
|
||||
import { COMMAND_ICON, commandLabel } from '../commands/catalog'
|
||||
import { commandIcon, commandLabel } from '../commands/catalog'
|
||||
import '../commands/commandButton'
|
||||
import { fmtDuration, fmtRemaining } from '../format'
|
||||
import { progressBar, stateBadge, type BarTone } from '../jobs/progress'
|
||||
@ -190,7 +190,7 @@ export class RecentJobsElement extends LiveElement {
|
||||
h(
|
||||
'a',
|
||||
{ href: jobHref(j.id), class: 'row-link' },
|
||||
glyph(COMMAND_ICON[j.command], commandLabel(j.command)),
|
||||
glyph(commandIcon(j.command), commandLabel(j.command)),
|
||||
// The job's summary is a server sentence: spoken here, shown in the job view.
|
||||
h('span', { class: 'sr-only' }, j.summary ?? j.progress?.label ?? ''),
|
||||
h('span', { class: 'grow' }),
|
||||
|
||||
@ -6,7 +6,7 @@ import { ApiFailure } from '../api/client'
|
||||
import { explain } from '../api/errors'
|
||||
import type { Job } from '../api/jobContract'
|
||||
import { q } from '../api/queries'
|
||||
import { COMMAND_ICON, commandLabel } from '../commands/catalog'
|
||||
import { commandIcon, commandLabel } from '../commands/catalog'
|
||||
import '../jobs/jobProgress'
|
||||
import { stateBadge } from '../jobs/progress'
|
||||
import { define, h, hx } from '../lib/dom'
|
||||
@ -29,7 +29,7 @@ function params(j: Job): string {
|
||||
|
||||
/** The command's glyph painted, its name spoken. */
|
||||
function commandGlyph(command: Job['command']): HTMLSpanElement {
|
||||
return glyph(COMMAND_ICON[command], commandLabel(command), 'job-cmd')
|
||||
return glyph(commandIcon(command), commandLabel(command), 'job-cmd')
|
||||
}
|
||||
|
||||
/** One row, plus its duration cell so ticks can refresh just that. */
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
|
||||
import { q, refreshAfterJob } from '../api/queries'
|
||||
import { go } from '../commands/palette'
|
||||
import { decorateChrome } from '../icons/render'
|
||||
import { hub } from '../jobs/hub'
|
||||
import { runner } from '../lib/runner'
|
||||
import { NAV } from './nav'
|
||||
@ -67,6 +68,8 @@ export function boot(): void {
|
||||
runner.openPalette()
|
||||
})
|
||||
watchSetup(window.location.pathname)
|
||||
// The sidebar and palette button are static HTML: give them the user's words.
|
||||
decorateChrome()
|
||||
const build = document.querySelector<HTMLMetaElement>(`meta[name="${BUILD_META}"]`)?.content
|
||||
if (build) setInterval(() => void checkBuild(build), BUILD_POLL_MS)
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
import type { Job } from '../api/jobContract'
|
||||
import { isActive, q } from '../api/queries'
|
||||
import { COMMAND_ICON, commandLabel } from '../commands/catalog'
|
||||
import { commandIcon, commandLabel } from '../commands/catalog'
|
||||
import { hub } from '../jobs/hub'
|
||||
import { progressBar } from '../jobs/progress'
|
||||
import { define, h } from '../lib/dom'
|
||||
@ -29,7 +29,7 @@ export function jobChip(job: Job): HTMLAnchorElement {
|
||||
h(
|
||||
'span',
|
||||
{ class: 'jobchip-label' },
|
||||
glyph(COMMAND_ICON[job.command], label),
|
||||
glyph(commandIcon(job.command), label),
|
||||
h('span', { class: 'jobchip-sub' }, waiting ? glyph('✋', 'needs input') : p?.total ? `${p.step}/${p.total}` : '…'),
|
||||
),
|
||||
progressBar(fraction, label, waiting ? 'warning' : 'accent', true),
|
||||
|
||||
@ -1,22 +1,36 @@
|
||||
import type { SectionPath } from '../commands/catalog'
|
||||
import type { IconId } from '../icons/registry'
|
||||
|
||||
export interface NavItem {
|
||||
to: SectionPath | '/jobs'
|
||||
/** Spoken only (aria-label); the sidebar paints `icon`. */
|
||||
/** Spoken (aria-label); the sidebar paints `icon` and the user's word for it. */
|
||||
label: string
|
||||
blurb: string
|
||||
icon: string
|
||||
icon: IconId
|
||||
/** Alt+<key> accelerator, shown in the sidebar as the bare digit. */
|
||||
key: string
|
||||
}
|
||||
|
||||
export const NAV: NavItem[] = [
|
||||
{ to: '/', label: 'Dashboard', blurb: 'Status, budget and quick actions', icon: '🏠', key: '1' },
|
||||
{ to: '/backlog', label: 'Backlog', blurb: 'Planner, stats and the full game list', icon: '📚', key: '2' },
|
||||
{ to: '/picks', label: 'Picks', blurb: 'Check, done, pick, scan, manual picks', icon: '🎯', key: '3' },
|
||||
{ to: '/gaming', label: 'Gaming', blurb: 'Daily budget, reset, block, unblock', icon: '🎮', key: '4' },
|
||||
{ to: '/library', label: 'Library', blurb: 'All your games, installed, install, uninstall, hide', icon: '🗂️', key: '5' },
|
||||
{ to: '/store', label: 'Store', blurb: 'Unblock, buy DLC, exceptions', icon: '🛒', key: '6' },
|
||||
{ to: '/jobs', label: 'Jobs', blurb: 'Running and past jobs', icon: '⚙️', key: '7' },
|
||||
{ to: '/system', label: 'System', blurb: 'Daemon, server, backups, reset, setup', icon: '🖥️', key: '8' },
|
||||
{ to: '/', label: 'Dashboard', blurb: 'Status, budget and quick actions', icon: 'nav.dashboard', key: '1' },
|
||||
{ to: '/backlog', label: 'Backlog', blurb: 'Planner, stats and the full game list', icon: 'nav.backlog', key: '2' },
|
||||
{ to: '/picks', label: 'Picks', blurb: 'Check, done, pick, scan, manual picks', icon: 'nav.picks', key: '3' },
|
||||
{ to: '/gaming', label: 'Gaming', blurb: 'Daily budget, reset, block, unblock', icon: 'nav.gaming', key: '4' },
|
||||
{ to: '/library', label: 'Library', blurb: 'All your games, installed, install, uninstall, hide', icon: 'nav.library', key: '5' },
|
||||
{ to: '/store', label: 'Store', blurb: 'Unblock, buy DLC, exceptions', icon: 'nav.store', key: '6' },
|
||||
{ to: '/jobs', label: 'Jobs', blurb: 'Running and past jobs', icon: 'nav.jobs', key: '7' },
|
||||
{ to: '/system', label: 'System', blurb: 'Daemon, server, backups, reset, setup', icon: 'nav.system', key: '8' },
|
||||
]
|
||||
|
||||
/** Pages reached from the palette only: no sidebar slot, no Alt key. */
|
||||
export interface PalettePage {
|
||||
to: string
|
||||
label: string
|
||||
blurb: string
|
||||
/** A raw glyph: these pages are not in the icon registry yet. */
|
||||
icon: string
|
||||
}
|
||||
|
||||
export const PALETTE_PAGES: PalettePage[] = [
|
||||
{ to: '/words', label: 'Icon words', blurb: 'Pick the word shown next to each icon', icon: '🏷️' },
|
||||
]
|
||||
|
||||
@ -45,8 +45,8 @@ kbd {
|
||||
/* ── Shell ── */
|
||||
.shell {
|
||||
display: grid;
|
||||
/* Icon rail: nav paints glyph + digit only (textgate). */
|
||||
grid-template-columns: 6rem minmax(0, 1fr);
|
||||
/* Icon rail: glyph + digit; it widens to fit the user's icon words (icons.css). */
|
||||
grid-template-columns: minmax(6rem, max-content) minmax(0, 1fr);
|
||||
min-height: 100dvh;
|
||||
}
|
||||
.sidebar {
|
||||
|
||||
41
web/src/styles/icons.css
Normal file
41
web/src/styles/icons.css
Normal file
@ -0,0 +1,41 @@
|
||||
/* Icon words (icons/render.ts) and the /words picker. Tokens only. */
|
||||
|
||||
/* The word sits RIGHT of its icon, vertically centred on it, never under. */
|
||||
.has-word { display: inline-flex; flex-direction: row; align-items: center; gap: var(--space-1); }
|
||||
.icon-word { white-space: nowrap; line-height: 1.2; font-size: var(--text-body); }
|
||||
.pill .icon-word { font-size: var(--text-caption); }
|
||||
.pill.has-word, .pill:has(.icon-word) { gap: var(--space-1); }
|
||||
|
||||
/* Sidebar: icon + word on the left, the Alt digit pushed right. */
|
||||
.nav-link.has-word { display: flex; justify-content: flex-start; gap: var(--space-2); }
|
||||
.nav-link.has-word kbd { margin-left: auto; }
|
||||
.notice-mark { align-self: flex-start; }
|
||||
.runner-mark { display: inline-flex; align-items: center; gap: var(--space-1); }
|
||||
|
||||
/* ── /words picker ── */
|
||||
icon-words-picker { display: flex; flex-direction: column; gap: var(--space-4); }
|
||||
.picker-head { display: flex; align-items: baseline; gap: var(--space-3); font-size: var(--text-title); }
|
||||
.picker-id { font-size: var(--text-body); color: var(--text-muted); }
|
||||
.picker-saved { color: var(--accent); }
|
||||
.picker-body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 2fr); gap: var(--space-5); align-items: start; }
|
||||
.picker-stage { display: flex; flex-direction: column; align-items: center; gap: var(--space-4); padding: var(--space-5); background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--radius-md); }
|
||||
.picker-big { font-size: 9rem; line-height: 1; }
|
||||
.picker-context { display: flex; justify-content: center; min-width: 12rem; max-width: 100%; overflow-x: auto; padding: var(--space-3); background: var(--bg); border-radius: var(--radius-sm); }
|
||||
.picker-context .nav-link { min-width: 10rem; }
|
||||
.picker-desc { font-size: var(--text-subtitle); max-width: var(--measure); }
|
||||
.picker-words, .picker-glyphs { display: flex; flex-wrap: wrap; gap: var(--space-2); }
|
||||
.picker-choice { font-size: var(--text-subtitle); justify-content: flex-start; }
|
||||
.picker-choice kbd { margin-right: var(--space-2); }
|
||||
.picker-choice[aria-pressed='true'] { border-color: var(--accent); box-shadow: inset 0 0 0 2px var(--accent); }
|
||||
.picker-own { display: flex; align-items: flex-end; gap: var(--space-2); }
|
||||
.picker-own-label { display: flex; flex-direction: column; gap: var(--space-1); flex: 1 1 auto; }
|
||||
.picker-own .input { font-size: var(--text-subtitle); }
|
||||
.picker-own .input[aria-invalid='true'] { border-color: var(--danger); box-shadow: inset 0 0 0 2px var(--danger); }
|
||||
.picker-nav { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); }
|
||||
.picker-toggle { display: flex; align-items: center; gap: var(--space-2); }
|
||||
.picker-done { align-items: center; padding: var(--space-6); }
|
||||
.picker-summary { font-size: var(--text-display); }
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.picker-body { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
21
web/src/test/iconLedger.ts
Normal file
21
web/src/test/iconLedger.ts
Normal file
@ -0,0 +1,21 @@
|
||||
// Test helpers for the icon-word ledger: set it directly, or plant the
|
||||
// `<script id="sbe-icon-words">` the Python server injects into every page.
|
||||
|
||||
import { ICON_WORDS_SCRIPT, type IconChoice } from '../api/iconWordsContract'
|
||||
import { resetLedger, setLedger } from '../icons/ledger'
|
||||
|
||||
/** Use `icons` as the loaded ledger (what a page load would have read). */
|
||||
export function useIcons(icons: Record<string, IconChoice>): void {
|
||||
setLedger({ version: 1, icons })
|
||||
}
|
||||
|
||||
/** Plant the server's injected payload, then forget the cached ledger. */
|
||||
export function injectLedgerScript(payload: unknown): void {
|
||||
document.getElementById(ICON_WORDS_SCRIPT)?.remove()
|
||||
const script = document.createElement('script')
|
||||
script.type = 'application/json'
|
||||
script.id = ICON_WORDS_SCRIPT
|
||||
script.textContent = typeof payload === 'string' ? payload : JSON.stringify(payload)
|
||||
document.head.append(script)
|
||||
resetLedger()
|
||||
}
|
||||
36
web/src/test/pickerHelpers.ts
Normal file
36
web/src/test/pickerHelpers.ts
Normal file
@ -0,0 +1,36 @@
|
||||
// Shared by the icon-word picker tests: mount it against a fake server that
|
||||
// stores what it is sent, plus key and query helpers.
|
||||
|
||||
import { expect, vi } from 'vitest'
|
||||
import type { IconChoice } from '../api/iconWordsContract'
|
||||
import { ICONS } from '../icons/registry'
|
||||
import { must } from './events'
|
||||
import { stubApi } from './harness'
|
||||
import '../icons/picker'
|
||||
|
||||
export const N = ICONS.length
|
||||
export const [A, B, C, D] = ICONS as [(typeof ICONS)[number], (typeof ICONS)[number], (typeof ICONS)[number], (typeof ICONS)[number]]
|
||||
export const url = (id: string) => `POST /api/icon-words/${id}`
|
||||
|
||||
/** Mount the picker against a fake server that stores what it is sent. */
|
||||
export function start(icons: Record<string, IconChoice> = { [A.id]: { word: 'x', glyph: null }, [B.id]: { word: null, glyph: null } }) {
|
||||
const stored: Record<string, IconChoice> = structuredClone(icons)
|
||||
const routes: Record<string, unknown> = { 'GET /api/icon-words': () => ({ version: 1, icons: stored }) }
|
||||
for (const e of ICONS) {
|
||||
routes[url(e.id)] = ({ body }: { body: IconChoice }) => {
|
||||
stored[e.id] = { ...stored[e.id], ...body }
|
||||
return { version: 1, icons: stored }
|
||||
}
|
||||
}
|
||||
const mock = stubApi(routes as never)
|
||||
document.body.innerHTML = '<icon-words-picker></icon-words-picker>'
|
||||
return { mock, stored }
|
||||
}
|
||||
|
||||
export const q = (sel: string): HTMLElement => must(document.querySelector<HTMLElement>(sel))
|
||||
export const input = (sel: string): HTMLInputElement => must(document.querySelector<HTMLInputElement>(sel))
|
||||
export const count = () => q('.picker-count').textContent
|
||||
export const field = () => input('input[name=own]')
|
||||
export const press = (key: string, init: KeyboardEventInit = {}, target: Element = document.body) =>
|
||||
target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...init }))
|
||||
export const at = (n: number) => vi.waitFor(() => { expect(count()).toBe(`${n} / ${N}`) })
|
||||
@ -1,6 +1,8 @@
|
||||
import { configure } from '@testing-library/dom'
|
||||
import * as matchers from '@testing-library/jest-dom/matchers'
|
||||
import { afterEach, expect, vi } from 'vitest'
|
||||
import { ICON_WORDS_SCRIPT } from '../api/iconWordsContract'
|
||||
import { resetLedger } from '../icons/ledger'
|
||||
import { resetAll } from '../lib/query'
|
||||
|
||||
// Registered by hand: jest-dom 7 still augments vitest's old Assertion<T>
|
||||
@ -26,8 +28,12 @@ Element.prototype.scrollIntoView = () => undefined
|
||||
window.scrollTo = () => undefined
|
||||
|
||||
// Queries are module-level singletons: no test may see another's cache.
|
||||
// The icon-word ledger and its hide setting are page-wide state too.
|
||||
afterEach(() => {
|
||||
document.body.replaceChildren()
|
||||
document.getElementById(ICON_WORDS_SCRIPT)?.remove()
|
||||
resetLedger()
|
||||
localStorage.clear()
|
||||
resetAll()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
|
||||
53
web/src/test/textgate.iconwords.guard.test.ts
Normal file
53
web/src/test/textgate.iconwords.guard.test.ts
Normal file
@ -0,0 +1,53 @@
|
||||
// Guard test (textgate-rework R6): the user's own icon words are the one
|
||||
// visible text allowed outside the /words picker, and only exactly as the
|
||||
// ledger draws them. Anything else in an `.icon-word` still counts.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeBudget } from './factories'
|
||||
import { makeJob, makeSpec, makeStatus } from './fixtures'
|
||||
import { installEventSource, mount, stubApi } from './harness'
|
||||
import { useIcons } from './iconLedger'
|
||||
import { visibleWords } from './visibleWords'
|
||||
import { notice } from '../ui/build'
|
||||
import '../sections/dashboard'
|
||||
import '../shell/jobIndicator'
|
||||
|
||||
beforeEach(installEventSource)
|
||||
|
||||
describe('textgate guard: icon words', () => {
|
||||
it('the dashboard paints the ledger words and nothing else', async () => {
|
||||
useIcons({
|
||||
'cmd.scan': { word: 'scan it' },
|
||||
'cmd.check': { word: 'look' },
|
||||
'job.state.running': { word: 'busy' },
|
||||
})
|
||||
stubApi({
|
||||
'GET /api/status': makeStatus(),
|
||||
'GET /api/budget': makeBudget(),
|
||||
'GET /api/jobs': [makeJob({ id: 'a', command: 'scan', state: 'running', summary: 'Scanned 12' })],
|
||||
'GET /api/commands': [makeSpec('check'), makeSpec('scan')],
|
||||
})
|
||||
const el = mount('<main><job-indicator></job-indicator><recent-jobs></recent-jobs></main>')
|
||||
await vi.waitFor(() => {
|
||||
expect(el.querySelectorAll('.icon-word').length).toBeGreaterThan(1)
|
||||
}, { timeout: 3000 })
|
||||
const painted = [...el.querySelectorAll('.icon-word')].map((w) => w.textContent)
|
||||
expect(painted).toEqual(expect.arrayContaining(['Scan it', 'Busy']))
|
||||
expect(visibleWords(el, ['Scanned 12'])).toEqual([])
|
||||
})
|
||||
|
||||
it('a word the ledger does not hold still counts', () => {
|
||||
useIcons({ 'notice.info': { word: 'note' } })
|
||||
const el = notice('info', null)
|
||||
expect(visibleWords(el)).toEqual([])
|
||||
const word = el.querySelector('.icon-word')
|
||||
if (word) word.textContent = 'Smuggled'
|
||||
expect(visibleWords(el)).toEqual(['Smuggled'])
|
||||
})
|
||||
|
||||
it('hidden words leave nothing to allow', () => {
|
||||
const el = notice('info', null)
|
||||
expect(el.querySelector('.icon-word')).toBeNull()
|
||||
expect(visibleWords(el)).toEqual([])
|
||||
})
|
||||
})
|
||||
@ -1,7 +1,12 @@
|
||||
// Textgate guard helper (textgate-rework R6): the words an element paints.
|
||||
// Spoken-only text (.sr-only, [hidden]) and content the caller passes in
|
||||
// `allowed` (game names, server messages) do not count. aria-hidden text
|
||||
// still paints, so it counts.
|
||||
// still paints, so it counts. The user's own icon words are the one chrome
|
||||
// text allowed: an `.icon-word` passes only when it reads exactly what the
|
||||
// ledger draws for its icon id.
|
||||
|
||||
import { iconFor } from '../icons/render'
|
||||
import { isIconId } from '../icons/registry'
|
||||
|
||||
const WORD_RE = /[A-Za-z]{2,}/
|
||||
|
||||
@ -13,13 +18,19 @@ function spokenOnly(el: Element | null): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
/** True for the text of an icon word that is the ledger's word for that icon. */
|
||||
function ledgerWord(el: Element | null, text: string): boolean {
|
||||
const id = el?.closest('.icon-word')?.getAttribute('data-icon-word') ?? ''
|
||||
return isIconId(id) && iconFor(id).word === text
|
||||
}
|
||||
|
||||
/** Visible text nodes holding a word of 2+ letters, minus `allowed` content. */
|
||||
export function visibleWords(root: Element, allowed: readonly string[] = []): string[] {
|
||||
const out: string[] = []
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
|
||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
||||
const t = n.textContent?.trim() ?? ''
|
||||
if (!WORD_RE.test(t) || spokenOnly(n.parentElement) || allowed.includes(t)) continue
|
||||
if (!WORD_RE.test(t) || spokenOnly(n.parentElement) || allowed.includes(t) || ledgerWord(n.parentElement, t)) continue
|
||||
out.push(t)
|
||||
}
|
||||
return out
|
||||
|
||||
@ -3,22 +3,24 @@
|
||||
// for content a custom element renders from live data.
|
||||
|
||||
import { explain } from '../api/errors'
|
||||
import { isIconId, type IconId } from '../icons/registry'
|
||||
import { iconFor, iconMark, iconWord } from '../icons/render'
|
||||
import { h, type Child } from '../lib/dom'
|
||||
|
||||
export type Tone = 'info' | 'success' | 'warning' | 'danger'
|
||||
|
||||
const TONE_ICON: Record<Tone, string> = {
|
||||
info: 'ℹ️',
|
||||
success: '✅',
|
||||
warning: '⚠️',
|
||||
danger: '⛔',
|
||||
}
|
||||
const TONE_ICON = {
|
||||
info: 'notice.info',
|
||||
success: 'notice.success',
|
||||
warning: 'notice.warning',
|
||||
danger: 'notice.danger',
|
||||
} as const satisfies Record<Tone, IconId>
|
||||
|
||||
export function notice(tone: Tone, title: string | null, ...children: Child[]): HTMLDivElement {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: `notice notice-${tone}`, role: tone === 'danger' ? 'alert' : 'status' },
|
||||
h('span', { class: 'notice-icon', 'aria-hidden': 'true' }, TONE_ICON[tone]),
|
||||
noticeMark(TONE_ICON[tone]),
|
||||
title ? h('strong', { class: 'notice-title' }, title) : null,
|
||||
)
|
||||
if (children.length) {
|
||||
@ -27,6 +29,13 @@ export function notice(tone: Tone, title: string | null, ...children: Child[]):
|
||||
return el
|
||||
}
|
||||
|
||||
/** The tone icon; with a word, icon and word share one row (the notice is a column). */
|
||||
function noticeMark(id: IconId): HTMLElement {
|
||||
const icon = iconMark(id, 'notice-icon')
|
||||
const word = iconWord(id)
|
||||
return word ? h('span', { class: 'notice-mark has-word' }, icon, word) : icon
|
||||
}
|
||||
|
||||
export function errorNotice(error: unknown, ...children: Child[]): HTMLDivElement {
|
||||
// Textgate: the explanation (title + hint) is spoken only; the ⛔ icon,
|
||||
// danger tone and the server's own message stay visible.
|
||||
@ -78,9 +87,27 @@ export interface CardOptions {
|
||||
icon?: string
|
||||
}
|
||||
|
||||
/** A painted glyph whose meaning is spoken only (textgate: no visible words). */
|
||||
export function glyph(icon: string, spoken: string, className = 'glyph'): HTMLSpanElement {
|
||||
return h('span', { class: className }, h('span', { 'aria-hidden': 'true' }, icon), h('span', { class: 'sr-only' }, spoken))
|
||||
/**
|
||||
* A painted glyph whose meaning is spoken (.sr-only). With a registered id the
|
||||
* glyph comes from the registry (the user's alternative applied) and his word,
|
||||
* if any, is drawn right of it; `spoken` then defaults to the registry name.
|
||||
* A raw glyph (`glyph('🧭', 'navigate')`) paints just that, as before.
|
||||
*/
|
||||
export function glyph(id: IconId, spoken?: string, className?: string): HTMLSpanElement
|
||||
export function glyph(icon: string, spoken: string, className?: string): HTMLSpanElement
|
||||
export function glyph(icon: string, spoken?: string, className = 'glyph'): HTMLSpanElement {
|
||||
if (!isIconId(icon)) {
|
||||
return h('span', { class: className }, h('span', { 'aria-hidden': 'true' }, icon), h('span', { class: 'sr-only' }, spoken))
|
||||
}
|
||||
const { glyph: painted, spoken: name } = iconFor(icon)
|
||||
const word = iconWord(icon)
|
||||
return h(
|
||||
'span',
|
||||
{ class: word ? `${className} has-word` : className },
|
||||
h('span', { 'aria-hidden': 'true', 'data-icon': icon }, painted),
|
||||
word,
|
||||
h('span', { class: 'sr-only' }, spoken ?? name),
|
||||
)
|
||||
}
|
||||
|
||||
/** A card; its title is spoken only, `icon` (if any) is painted in its place. */
|
||||
|
||||
Loading…
Reference in New Issue
Block a user