From 71c19719925873b9b33c5f4864c5202e00ec6c0e Mon Sep 17 00:00:00 2001 From: James Babcock Date: Wed, 23 Sep 2026 23:57:50 -0700 Subject: [PATCH] Use animated menus in a bunch more places --- app/apps/developer/bandwidth-benchmark.ts | 71 ++++---- app/apps/developer/buzzer-demo.ts | 49 +++--- app/apps/evenhub/api-key-dialog.ts | 39 +++-- app/apps/evenhub/store-detail-layer.ts | 54 +++--- app/apps/evenhub/store-layer.ts | 151 +++++++++------- app/apps/files/file-browser.ts | 73 ++++---- app/apps/files/file-info-dialog.ts | 44 ++--- app/apps/glanceboard/glanceboard-app.ts | 134 +++++++------- app/apps/music/media-browse.ts | 132 ++++++-------- app/apps/music/music-app.ts | 10 +- app/apps/music/music-settings.ts | 44 +++-- app/apps/navigate/navigate-app.worker.ts | 126 ++++++-------- app/apps/teleprompter/teleprompter-app.ts | 10 +- app/apps/terminal/terminal-app.worker.ts | 153 +++++++--------- app/apps/timer/timer-app.ts | 193 +++++++++++---------- app/apps/weather/weather.ts | 83 ++++++--- app/ui/dashboard/settings-panel.ts | 189 ++++++++++---------- app/ui/font-picker.ts | 60 ++++--- app/ui/menu-core.ts | 55 ++++-- app/ui/menu-highlight-motion.ts | 2 +- app/ui/menu.ts | 25 ++- app/ui/metrics.ts | 70 +++++++- app/ui/notification-filter.ts | 44 +++-- app/ui/notifications.ts | 143 ++++++++------- app/ui/shell/assistant.ts | 93 +++------- app/ui/shell/input-dialog.ts | 76 +++++--- app/ui/shell/keyboard-input.ts | 30 ++-- app/ui/shell/voice-input.ts | 34 ++-- tests/evenhub-install-performance.test.cjs | 2 +- tests/evenhub-signin.test.cjs | 3 +- tests/ios-terminal-input.test.cjs | 5 +- tests/menu-core.test.cjs | 48 +++++ tests/menu-highlight-motion.test.cjs | 11 +- tests/navigate-worker.test.cjs | 1 + tests/row-metrics.test.cjs | 87 ++++++++++ tests/settings-panel.test.cjs | 112 ++++++++++++ tests/voice-finalization.test.cjs | 6 +- 37 files changed, 1457 insertions(+), 1005 deletions(-) create mode 100644 tests/row-metrics.test.cjs create mode 100644 tests/settings-panel.test.cjs diff --git a/app/apps/developer/bandwidth-benchmark.ts b/app/apps/developer/bandwidth-benchmark.ts index 8af80ceb..192b967e 100644 --- a/app/apps/developer/bandwidth-benchmark.ts +++ b/app/apps/developer/bandwidth-benchmark.ts @@ -2,8 +2,8 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage } from "../../graphics/image"; import { Layer, type LayerContext } from "../../ui/layers"; import { type InputEvent } from "../../ui/gestures"; -import { drawSelectionHighlight } from "../../ui/menu"; -import { tightRowHeight } from "../../ui/metrics"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; +import { centeredTextY, tightRowHeight } from "../../ui/metrics"; import { cancelBandwidthBenchmark, getBandwidthBenchmarkStatus, @@ -29,6 +29,7 @@ const LIST_X = 20; const VALUE_X = 150; type Phase = "config" | "arming" | "running" | "done"; +type ConfigRow = "size" | "window" | "link" | "start"; /** * BLE bandwidth benchmark: pick a message size and pipeline window, stream @@ -38,7 +39,14 @@ type Phase = "config" | "arming" | "running" | "done"; */ export class BandwidthBenchmarkLayer implements Layer { private phase: Phase = "config"; - private selectedRow = 0; // size, window, link preference, start + private readonly menu = new Menu({ + items: ["size", "window", "link", "start"], + wrap: false, + rowGap: 1, + highlight: { radius: 4 }, + getHeight: () => tightRowHeight(getDefaultSmallFont()) + 4, + draw: (args) => this.drawRow(args), + }); private sizeIndex = 2; private windowIndex = 2; private linkModeIndex = 0; @@ -134,26 +142,14 @@ export class BandwidthBenchmarkLayer implements Layer { } const rowH = tightRowHeight(font) + 4; - const rows: Array<[string, string]> = [ - ["Message size", `${MESSAGE_SIZES[this.sizeIndex]} B`], - ["Window size", `${WINDOW_SIZES[this.windowIndex]}`], - ["Link request", LINK_MODES[this.linkModeIndex]!], - [this.phase === "done" ? "Run again" : "Start", ""], - ]; - for (let index = 0; index < rows.length; index++) { - const [label, value] = rows[index]!; - const y = HEADER_HEIGHT + index * rowH; - const selected = index === this.selectedRow; - if (selected) { - drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4); - } - image.drawText(font, LIST_X, y + 2, label, selected ? 255 : 200); - if (value) { - image.drawText(font, VALUE_X, y + 2, value, selected ? 235 : 160); - } - } + const rowCount = this.menu.items.length; + this.menu.paint( + image, + { x: LIST_X - 6, y: HEADER_HEIGHT - 1, width: width - 2 * LIST_X + 12, height: rowCount * rowH }, + ctx.stack.isFocused(), + ); - let y = HEADER_HEIGHT + rows.length * rowH + 10; + let y = HEADER_HEIGHT + rowCount * rowH + 10; if (this.error) { image.drawText(font, LIST_X, y, this.error, 180); } else if (this.result) { @@ -176,6 +172,21 @@ export class BandwidthBenchmarkLayer implements Layer { return image; } + private drawRow({ image, item, x, y, height, selected }: MenuDrawArgs): void { + const font = getDefaultSmallFont(); + const [label, value]: [string, string] = + item === "size" ? ["Message size", `${MESSAGE_SIZES[this.sizeIndex]} B`] + : item === "window" ? ["Window size", `${WINDOW_SIZES[this.windowIndex]}`] + : item === "link" ? ["Link request", LINK_MODES[this.linkModeIndex]!] + : [this.phase === "done" ? "Run again" : "Start", ""]; + const textY = centeredTextY(font, y, height); + // Text sits 6px in from the row box (LIST_X), values at VALUE_X. + image.drawText(font, x + 6, textY, label, selected ? 255 : 200); + if (value) { + image.drawText(font, x + 6 + VALUE_X - LIST_X, textY, value, selected ? 235 : 160); + } + } + async handleInput(event: InputEvent, ctx: LayerContext): Promise { if (this.phase === "arming" || this.phase === "running") { // A static screen during the run: only allow bailing out. @@ -186,22 +197,22 @@ export class BandwidthBenchmarkLayer implements Layer { } switch (event.type) { case "scroll-up": - this.selectedRow = Math.max(0, this.selectedRow - 1); - return; case "scroll-down": - this.selectedRow = Math.min(3, this.selectedRow + 1); + await this.menu.handleInput(event); return; - case "click": - if (this.selectedRow === 0) { + case "click": { + const row = this.menu.selectedItem; + if (row === "size") { this.sizeIndex = (this.sizeIndex + 1) % MESSAGE_SIZES.length; - } else if (this.selectedRow === 1) { + } else if (row === "window") { this.windowIndex = (this.windowIndex + 1) % WINDOW_SIZES.length; - } else if (this.selectedRow === 2) { + } else if (row === "link") { this.linkModeIndex = (this.linkModeIndex + 1) % LINK_MODES.length; - } else { + } else if (row === "start") { this.startRun(); } return; + } case "double-click": ctx.stack.pop(); return; diff --git a/app/apps/developer/buzzer-demo.ts b/app/apps/developer/buzzer-demo.ts index c88e18c2..1772d555 100644 --- a/app/apps/developer/buzzer-demo.ts +++ b/app/apps/developer/buzzer-demo.ts @@ -1,10 +1,9 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage } from "../../graphics/image"; -import { clamp } from "../../util/numeric-util"; import { Layer, type LayerActions, type LayerContext } from "../../ui/layers"; import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures"; -import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../../ui/menu"; -import { tightRowHeight } from "../../ui/metrics"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; +import { centeredTextY, tightRowHeight } from "../../ui/metrics"; import { buildSoundSequencePayload, CFW_SEQ_MAX, @@ -28,8 +27,14 @@ function sleep(ms: number): Promise { * sequencer message lands as the previous phrase finishes. */ export class BuzzerDemoLayer implements Layer { - private selectedIndex = 0; - private scrollRow = 0; + private readonly menu = new Menu({ + items: SOUND_EFFECTS, + wrap: false, + rowGap: 1, + highlight: { radius: 4 }, + getHeight: () => tightRowHeight(getDefaultSmallFont()), + draw: (args) => drawEffectRow(args), + }); private playing: string | null = null; paint(ctx: LayerContext): GrayImage { @@ -42,21 +47,11 @@ export class BuzzerDemoLayer implements Layer { image.drawText(font, width - 24 - font.measureText(status), 8, status, 140); const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT; - const rowH = tightRowHeight(font); - const visibleRows = Math.max(1, (listHeight / rowH) | 0); - this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, SOUND_EFFECTS.length); - - const lastVisible = Math.min(SOUND_EFFECTS.length, this.scrollRow + visibleRows); - for (let index = this.scrollRow; index < lastVisible; index++) { - const effect = SOUND_EFFECTS[index]!; - const y = HEADER_HEIGHT + (index - this.scrollRow) * rowH; - const selected = index === this.selectedIndex; - if (selected) { - drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4); - } - image.drawText(font, LIST_X, y + 1, effect.name, selected ? 255 : 200); - image.drawText(font, LIST_X + 110, y + 1, effect.desc, selected ? 180 : 120); - } + this.menu.paint( + image, + { x: LIST_X - 6, y: HEADER_HEIGHT - 1, width: width - 2 * LIST_X + 12, height: listHeight }, + ctx.stack.isFocused(), + ); return image; } @@ -64,13 +59,11 @@ export class BuzzerDemoLayer implements Layer { async handleInput(event: InputEvent, ctx: LayerContext): Promise { switch (event.type) { case "scroll-up": - this.selectedIndex = Math.max(0, this.selectedIndex - 1); - return; case "scroll-down": - this.selectedIndex = Math.min(SOUND_EFFECTS.length - 1, this.selectedIndex + 1); + await this.menu.handleInput(event); return; case "click": { - const effect = SOUND_EFFECTS[clamp(this.selectedIndex, 0, SOUND_EFFECTS.length - 1)]; + const effect = this.menu.selectedItem; if (effect && !this.playing) { // Fire-and-forget: playback paces itself with sleeps between // phrases; awaiting it here would stall input for seconds. @@ -106,3 +99,11 @@ export class BuzzerDemoLayer implements Layer { } } } + +/** Effect name, then its description in a second column 110px to the right. */ +function drawEffectRow({ image, item: effect, x, y, height, selected }: MenuDrawArgs): void { + const font = getDefaultSmallFont(); + const textY = centeredTextY(font, y, height); + image.drawText(font, x + 6, textY, effect.name, selected ? 255 : 200); + image.drawText(font, x + 6 + 110, textY, effect.desc, selected ? 180 : 120); +} diff --git a/app/apps/evenhub/api-key-dialog.ts b/app/apps/evenhub/api-key-dialog.ts index bd41fec8..825357bf 100644 --- a/app/apps/evenhub/api-key-dialog.ts +++ b/app/apps/evenhub/api-key-dialog.ts @@ -3,8 +3,8 @@ import { GrayImage } from "../../graphics/image"; import { truncateText } from "../../graphics/textwrap"; import { type InputEvent } from "../../ui/gestures"; import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers"; -import { drawSelectionHighlight } from "../../ui/menu"; -import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; +import { lineStep, listRowHeight } from "../../ui/metrics"; const DIALOG_X = 8; const DIALOG_Y = 8; @@ -21,6 +21,8 @@ const SERVICE_LABELS: Record = { export type ApiKeyRequestItem = { id: string; configured: boolean }; +type ConsentAction = "Allow" | "Deny"; + /** * Consent dialog shown when an EvenHub app calls requestApiKeyAccess: lists the * requested API-key services (marking any the user hasn't configured) and asks @@ -28,8 +30,14 @@ export type ApiKeyRequestItem = { id: string; configured: boolean }; * double-click) shares nothing. */ export class EvenHubApiKeyDialogLayer implements Layer { - /** 0 = Allow, 1 = Deny. */ - private selectedIndex = 0; + private readonly menu = new Menu({ + items: ["Allow", "Deny"], + wrap: true, + rowGap: 1, + highlight: { radius: 8 }, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: (args) => drawActionRow(args), + }); private resolved = false; constructor( @@ -67,16 +75,11 @@ export class EvenHubApiKeyDialogLayer implements Layer { } y += 4; - const focused = ctx.stack.isFocused(); - const actions = ["Allow", "Deny"]; - for (let index = 0; index < actions.length; index++) { - const rowY = y + index * actionRowH; - const selected = index === this.selectedIndex; - if (selected) { - drawSelectionHighlight(image, DIALOG_X + 12, rowY, DIALOG_WIDTH - 24, actionRowH - 1, focused, 8); - } - image.drawText(font, DIALOG_X + 22, rowY + 3, actions[index]!, selected ? 255 : 200); - } + this.menu.paint( + image, + { x: DIALOG_X + 12, y, width: DIALOG_WIDTH - 24, height: Math.max(0, DIALOG_Y + height - PADDING - y) }, + ctx.stack.isFocused(), + ); return image; } @@ -84,10 +87,10 @@ export class EvenHubApiKeyDialogLayer implements Layer { switch (event.type) { case "scroll-up": case "scroll-down": - this.selectedIndex = (this.selectedIndex + 1) % 2; + void this.menu.handleInput(event); return; case "click": - this.resolve(ctx, this.selectedIndex === 0); + this.resolve(ctx, this.menu.selectedItem === "Allow"); return; case "double-click": this.resolve(ctx, false); @@ -113,3 +116,7 @@ export class EvenHubApiKeyDialogLayer implements Layer { else this.onCancel(); } } + +function drawActionRow({ image, item, x, y, selected }: MenuDrawArgs): void { + image.drawText(getDefaultSmallFont(), x + 10, y + 3, item, selected ? 255 : 200); +} diff --git a/app/apps/evenhub/store-detail-layer.ts b/app/apps/evenhub/store-detail-layer.ts index f3b93803..e7bd52f8 100644 --- a/app/apps/evenhub/store-detail-layer.ts +++ b/app/apps/evenhub/store-detail-layer.ts @@ -3,7 +3,7 @@ import { GrayImage } from "../../graphics/image"; import { truncateText, wrapText } from "../../graphics/textwrap"; import { type InputEvent } from "../../ui/gestures"; import { type Layer, type LayerContext } from "../../ui/layers"; -import { drawSelectionHighlight } from "../../ui/menu"; +import { Menu } from "../../ui/menu-core"; import { TextViewerLayer } from "../files/text-viewer"; import { evenHubApi, type EvenHubStoreApp } from "./even-api"; import { @@ -18,6 +18,9 @@ import { lineStep, listRowHeight } from "../../ui/metrics"; const X = 18; +type DetailAction = "about" | "whats-new" | "primary"; +const ACTIONS: readonly DetailAction[] = ["about", "whats-new", "primary"]; + export type EvenHubStoreDetailOptions = { launchApp: (appId: string) => Promise | void; appendLog: (message: string) => void; @@ -27,8 +30,22 @@ export type EvenHubStoreDetailOptions = { /** Storefront metadata and the Install/Launch action for one public app. */ export class EvenHubStoreDetailLayer implements Layer { - /** About, What's New, Install/Launch. */ - private selectedIndex = 2; + /** About, What's New, Install/Launch; starts on the primary action. */ + private readonly actions = new Menu({ + items: ACTIONS, + selectedIndex: 2, + rowGap: 1, + highlight: { radius: 8 }, + getHeight: () => listRowHeight(getDefaultSmallFont()) + 4, + draw: ({ image, item, x, y, width, selected }) => { + const font = getDefaultSmallFont(); + const label = item === "about" ? "About" : item === "whats-new" ? "What's New" : this.primaryLabel; + const value = this.working && item === "primary" ? 145 : selected ? 245 : 190; + image.drawText(font, x + 11, y + 5, truncateText(font, label, width - 18), value); + }, + }); + /** The primary action's label for the paint in progress. */ + private primaryLabel = ""; private working = false; private detailPromise: Promise | null = null; private status = ""; @@ -47,7 +64,7 @@ export class EvenHubStoreDetailLayer implements Layer { const actionRowH = listRowHeight(font) + 4; const installed = getInstalledEvenHubApp(this.app.packageId); - const actions = ["About", "What's New", this.working ? "Installing..." : this.primaryActionLabel(installed)]; + this.primaryLabel = this.working ? "Installing..." : this.primaryActionLabel(installed); // Detail lines as (text, shade, extra gap below); built per candidate // width so the layout choice below can measure before drawing. @@ -90,7 +107,7 @@ export class EvenHubStoreDetailLayer implements Layer { // Stacked layout (details full-width, actions at the bottom) when it // fits; otherwise the actions become a narrow top-right menu and the // details flow down a left column beside it. - const stackedActionTop = height - 6 - actions.length * actionRowH; + const stackedActionTop = height - 6 - ACTIONS.length * actionRowH; const stacked = 8 + linesHeight(buildLines(width - X * 2)) + 6 <= stackedActionTop; const menuW = 150; const menuX = width - menuW - 12; @@ -105,15 +122,11 @@ export class EvenHubStoreDetailLayer implements Layer { const actionX = stacked ? X : menuX; const actionW = stacked ? textWidth : menuW; const actionTop = stacked ? stackedActionTop : 8; - for (let index = 0; index < actions.length; index++) { - const actionY = actionTop + index * actionRowH; - const selected = index === this.selectedIndex; - if (selected) { - drawSelectionHighlight(image, actionX - 5, actionY, actionW + 10, actionRowH - 1, ctx.stack.isFocused(), 8); - } - const value = this.working && index === 2 ? 145 : selected ? 245 : 190; - image.drawText(font, actionX + 6, actionY + 5, truncateText(font, actions[index]!, actionW - 8), value); - } + this.actions.paint( + image, + { x: actionX - 5, y: actionTop, width: actionW + 10, height: ACTIONS.length * actionRowH - 1 }, + ctx.stack.isFocused(), + ); return image; } @@ -123,12 +136,8 @@ export class EvenHubStoreDetailLayer implements Layer { return; } if (this.working) return; - if (event.type === "scroll-up") { - this.selectedIndex = Math.max(0, this.selectedIndex - 1); - return; - } - if (event.type === "scroll-down") { - this.selectedIndex = Math.min(2, this.selectedIndex + 1); + if (event.type === "scroll-up" || event.type === "scroll-down") { + await this.actions.handleInput(event); return; } if (event.type !== "click") return; @@ -143,11 +152,12 @@ export class EvenHubStoreDetailLayer implements Layer { try { await this.ensureDetail(ctx); - if (this.selectedIndex === 0) { + const action = this.actions.selectedItem; + if (action === "about") { ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About")); return; } - if (this.selectedIndex === 1) { + if (action === "whats-new") { ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New")); return; } diff --git a/app/apps/evenhub/store-layer.ts b/app/apps/evenhub/store-layer.ts index a19a8c15..765593a0 100644 --- a/app/apps/evenhub/store-layer.ts +++ b/app/apps/evenhub/store-layer.ts @@ -1,10 +1,10 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage, type UiFont } from "../../graphics/image"; import { truncateText, wrapText } from "../../graphics/textwrap"; -import { clamp } from "../../util/numeric-util"; import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures"; import { type Layer, type LayerActions, type LayerContext, type LayerStack } from "../../ui/layers"; -import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu"; +import { drawSelectionHighlight, type MenuItem } from "../../ui/menu"; +import { Menu } from "../../ui/menu-core"; import { shell } from "../../ui/shell/shell"; import { ConfigSettingString } from "../../ui/dashboard-settings"; import { evenHubApi, EvenHubAuthenticationError, isEvenHubStoreConfigured, type EvenHubStoreApp, type EvenHubStorePage } from "./even-api"; @@ -24,6 +24,11 @@ function headerHeight(font: UiFont): number { return 8 + lineStep(font) + font.lineHeight + 6; } +/** Row pitch of the two-line app list (title + detail), including the 2px gap between highlights. */ +function storeRowHeight(font: UiFont): number { + return Math.max(30, 2 * lineStep(font) + 4); +} + /** Last search typed on the phone; kept so reopening the store shows it again. */ export const evenHubSearchQuerySetting = new ConfigSettingString({ id: "evenhub-search-query", @@ -64,27 +69,46 @@ type TabState = { loading: boolean; /** Progress or error text for the subtitle line. */ status: string; - selectedIndex: number; - scrollRow: number; + /** Selection and scroll over `rows` (resynced before each paint and input). */ + menu: Menu; /** Search only: the query the rows belong to. */ query: string; }; function emptyTab(): TabState { + const rows: StoreRow[] = []; return { - rows: [], + rows, total: 0, nextPage: 1, exhausted: false, loaded: false, loading: false, status: "", - selectedIndex: 0, - scrollRow: 0, + menu: new Menu({ + items: rows, + rowGap: 2, + highlight: { radius: 5 }, + getHeight: () => storeRowHeight(getDefaultSmallFont()), + draw: ({ image, item, x, y, width }) => { + const font = getDefaultSmallFont(); + const { title, detail, titleValue } = rowText(item); + const textX = x + 6; + const textW = width - 12; + image.drawText(font, textX, y + 2, truncateText(font, title, textW), titleValue); + image.drawText(font, textX, y + 2 + lineStep(font), truncateText(font, detail, textW), 115); + }, + }), query: "", }; } +/** The tab's menu, with its items brought up to date with `rows` (which loads replace or extend). */ +function tabMenu(tab: TabState): Menu { + if (tab.menu.items !== tab.rows) tab.menu.setItems(tab.rows); + return tab.menu; +} + export type EvenHubStoreLayerOptions = { launchApp: (appId: string) => Promise | void; appendLog: (message: string) => void; @@ -170,25 +194,16 @@ export class EvenHubStoreLayer implements Layer { return image; } - tab.selectedIndex = clamp(tab.selectedIndex, 0, tab.rows.length - 1); - const rowH = Math.max(30, 2 * lineStep(font) + 4); + const rowH = storeRowHeight(font); const visibleRows = Math.max(1, Math.floor((height - headerH - 4) / rowH)); - tab.scrollRow = scrollToKeepSelectionVisible(tab.scrollRow, tab.selectedIndex, visibleRows, tab.rows.length); - const last = Math.min(tab.rows.length, tab.scrollRow + visibleRows); const listFocused = ctx.stack.isFocused() && this.focus === "list"; - for (let index = tab.scrollRow; index < last; index++) { - const row = tab.rows[index]!; - const y = headerH + (index - tab.scrollRow) * rowH; - if (index === tab.selectedIndex) { - drawSelectionHighlight(image, LIST_X - 6, y, width - LIST_X * 2 + 12, rowH - 2, listFocused, 5); - } - const { title, detail, titleValue } = this.rowText(row); - image.drawText(font, LIST_X, y + 2, truncateText(font, title, width - LIST_X * 2), titleValue); - image.drawText(font, LIST_X, y + 2 + lineStep(font), truncateText(font, detail, width - LIST_X * 2), 115); - } - if (tab.rows.length > visibleRows) { - drawListScrollbar(image, width - 5, headerH, visibleRows * rowH - 3, tab.scrollRow, visibleRows, tab.rows.length); - } + const menu = tabMenu(tab); + menu.paint( + image, + { x: LIST_X - 6, y: headerH, width: width - LIST_X * 2 + 12, height: visibleRows * rowH - 2 }, + listFocused, + ); + menu.drawScrollbar(image, width - 5, headerH, visibleRows * rowH - 3); return image; } @@ -250,41 +265,6 @@ export class EvenHubStoreLayer implements Layer { } } - private rowText(row: StoreRow): { title: string; detail: string; titleValue: number } { - switch (row.kind) { - case "search-query": { - const query = evenHubSearchQuerySetting.get(); - return { - title: query ? `Search: ${query}` : "Search: (enter a query)", - detail: "Click to type on the phone, or use voice input.", - titleValue: 200, - }; - } - case "orphan": - return { - title: row.update.installed.name, - detail: row.update.error - ? `Package missing · store lookup failed: ${row.update.error}` - : "Package missing · not in the store · click to forget", - titleValue: 170, - }; - case "app": { - const { app, update } = row; - if (!update) { - return { - title: app.name, - detail: app.tagline || `${app.creatorName} · ${formatCount(app.installCount)} installs`, - titleValue: 215, - }; - } - const detail = update.packageMissing - ? `Package missing · reinstall ${app.version ? `version ${app.version}` : ""}`.trim() - : `Version ${update.installed.version} installed · ${app.version} available`; - return { title: app.name, detail, titleValue: 215 }; - } - } - } - async handleInput(event: InputEvent, ctx: LayerContext): Promise { if (this.showingLogin) { if (event.type === "click" && !this.loginBusy) { @@ -299,16 +279,17 @@ export class EvenHubStoreLayer implements Layer { return; } const tab = this.tabs[this.activeTab]; + const menu = tabMenu(tab); switch (event.type) { case "scroll-up": - tab.selectedIndex = Math.max(0, tab.selectedIndex - 1); + await menu.handleInput(event); return; case "scroll-down": - tab.selectedIndex = Math.min(Math.max(0, tab.rows.length - 1), tab.selectedIndex + 1); - if (tab.selectedIndex >= tab.rows.length - 4) void this.loadNextPage(ctx, this.activeTab); + await menu.handleInput(event); + if ((menu.selectedIndex ?? 0) >= tab.rows.length - 4) void this.loadNextPage(ctx, this.activeTab); return; case "click": - await this.activateRow(ctx, tab.rows[tab.selectedIndex]); + await this.activateRow(ctx, menu.selectedItem ?? undefined); return; case "double-click": this.focus = "tabs"; @@ -540,7 +521,7 @@ export class EvenHubStoreLayer implements Layer { state.rows = [{ kind: "search-query" }]; state.loaded = !query; // Keep the cursor on the first result once there are some. - state.selectedIndex = query ? 1 : 0; + state.menu.setItems(state.rows, query ? 1 : 0); this.tabs.search = state; ctx.actions.requestRender(); if (query) await this.loadNextPage(ctx, "search"); @@ -566,8 +547,8 @@ export class EvenHubStoreLayer implements Layer { update.latest ? { kind: "app", app: update.latest, update } : { kind: "orphan", update }, ); state.rows = rows; - state.selectedIndex = 0; - state.scrollRow = 0; + state.menu.setItems(rows, 0); + state.menu.scrollTop = 0; state.status = ""; state.exhausted = true; } catch (error) { @@ -643,7 +624,7 @@ export class EvenHubStoreLayer implements Layer { state.rows = state.rows.filter((row) => row.kind === "search-query" ? true : row.kind === "app" ? row.app.packageId !== packageId : row.update.installed.packageId !== packageId, ); - state.selectedIndex = clamp(state.selectedIndex, 0, Math.max(0, state.rows.length - 1)); + state.menu.setItems(state.rows); } // ---- login and phone editors -------------------------------------------- @@ -755,6 +736,42 @@ export class EvenHubStoreLayer implements Layer { } } +/** A list row's title (with its shade) and dim detail line. */ +function rowText(row: StoreRow): { title: string; detail: string; titleValue: number } { + switch (row.kind) { + case "search-query": { + const query = evenHubSearchQuerySetting.get(); + return { + title: query ? `Search: ${query}` : "Search: (enter a query)", + detail: "Click to type on the phone, or use voice input.", + titleValue: 200, + }; + } + case "orphan": + return { + title: row.update.installed.name, + detail: row.update.error + ? `Package missing · store lookup failed: ${row.update.error}` + : "Package missing · not in the store · click to forget", + titleValue: 170, + }; + case "app": { + const { app, update } = row; + if (!update) { + return { + title: app.name, + detail: app.tagline || `${app.creatorName} · ${formatCount(app.installCount)} installs`, + titleValue: 215, + }; + } + const detail = update.packageMissing + ? `Package missing · reinstall ${app.version ? `version ${app.version}` : ""}`.trim() + : `Version ${update.installed.version} installed · ${app.version} available`; + return { title: app.name, detail, titleValue: 215 }; + } + } +} + /** A registry entry dressed as a store record, for pages opened before the store record arrives. */ function placeholderStoreApp(installed: InstalledEvenHubApp): EvenHubStoreApp { return { diff --git a/app/apps/files/file-browser.ts b/app/apps/files/file-browser.ts index eac9645e..2227b4cc 100644 --- a/app/apps/files/file-browser.ts +++ b/app/apps/files/file-browser.ts @@ -4,7 +4,8 @@ import { GrayImage, type UiFont } from "../../graphics/image"; import { renderIcon, type IconName } from "../../graphics/icons"; import { clamp } from "../../util/numeric-util"; import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu"; -import { iconGridMinRowHeight, tightRowHeight } from "../../ui/metrics"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; +import { centeredTextY, iconGridMinRowHeight, tightRowHeight } from "../../ui/metrics"; import { ConfigSettingEnum } from "../../ui/dashboard-settings"; import { getStringSetting, setStringSetting } from "../../native/settings-store"; import { @@ -20,6 +21,8 @@ import { Layer, type LayerContext } from "../../ui/layers"; import { shell } from "../../ui/shell/shell"; const LIST_X = 20; +/** List view: the selection box extends this far left and right of the row text. */ +const LIST_HIGHLIGHT_PAD = 6; /** Header: one line holding both the title and the current path. */ function headerHeight(font: UiFont): number { @@ -133,7 +136,14 @@ export class FileBrowserLayer implements Layer { private entries: DirectoryEntry[] | null = null; private listingFailed = false; - private listIndex = 0; + /** List view. Its selected index is the flat-row index both views translate through (setViewMode). */ + private readonly listMenu = new Menu({ + wrap: false, + rowGap: 1, + highlight: { radius: 4 }, + getHeight: () => tightRowHeight(getDefaultSmallFont()), + draw: (args) => this.drawListRow(args), + }); private selectedRow = 0; private selectedCol = 0; private iconMode: IconMode = "row"; @@ -162,25 +172,20 @@ export class FileBrowserLayer implements Layer { private paintList(image: GrayImage, font: UiFont, rows: BrowserItem[], ctx: LayerContext): void { const { width, height } = ctx.stack.getBaseSize(); - this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1)); - - const rowH = tightRowHeight(font); const headerH = headerHeight(font); - const listHeight = height - headerH - 4; - const visibleRows = Math.max(1, (listHeight / rowH) | 0); - this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.listIndex, visibleRows, rows.length); + this.listMenu.setItems(rows); + // Row boxes start one pixel above the header's bottom edge. + this.listMenu.paint( + image, + { x: LIST_X - LIST_HIGHLIGHT_PAD, y: headerH - 1, width: width - 2 * LIST_X + 2 * LIST_HIGHLIGHT_PAD, height: height - headerH - 4 }, + ctx.stack.isFocused(), + ); + } - const lastVisible = Math.min(rows.length, this.scrollRow + visibleRows); - for (let index = this.scrollRow; index < lastVisible; index++) { - const row = rows[index]!; - const y = headerH + (index - this.scrollRow) * rowH; - const selected = index === this.listIndex; - if (selected) { - drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4); - } - const value = itemValue(row, selected); - image.drawText(font, LIST_X, y + 1, truncateText(font, row.label, width - 2 * LIST_X), value); - } + private drawListRow({ image, item, x, y, width, height, selected }: MenuDrawArgs): void { + const font = getDefaultSmallFont(); + const label = truncateText(font, item.label, width - 2 * LIST_HIGHLIGHT_PAD); + image.drawText(font, x + LIST_HIGHLIGHT_PAD, centeredTextY(font, y, height), label, itemValue(item, selected)); } private paintIcons(image: GrayImage, font: UiFont, rows: BrowserItem[], ctx: LayerContext): void { @@ -276,16 +281,14 @@ export class FileBrowserLayer implements Layer { } private async handleListInput(event: InputEvent, ctx: LayerContext): Promise { - const rows = this.flatRows(); + this.listMenu.setItems(this.flatRows()); switch (event.type) { case "scroll-up": - this.listIndex = Math.max(0, this.listIndex - 1); - return; case "scroll-down": - this.listIndex = Math.min(Math.max(0, rows.length - 1), this.listIndex + 1); + await this.listMenu.handleInput(event); return; case "click": { - const row = rows[clamp(this.listIndex, 0, Math.max(0, rows.length - 1))]; + const row = this.listMenu.selectedItem; if (row) await this.activateItem(row, ctx); return; } @@ -461,8 +464,7 @@ export class FileBrowserLayer implements Layer { label: isBookmarked(path) ? `Remove bookmark: ${name}` : `Bookmark: ${name}`, onSelect: (ctx) => { toggleBookmark(path); - const rows = this.flatRows(); - this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1)); + this.listMenu.setItems(this.flatRows()); ctx.stack.pop(); }, }); @@ -475,7 +477,8 @@ export class FileBrowserLayer implements Layer { const rows = this.flatRows(); if (!rows.length) return null; if (filesViewModeSetting.get() === "list") { - return rows[clamp(this.listIndex, 0, rows.length - 1)] ?? null; + this.listMenu.setItems(rows); + return this.listMenu.selectedItem; } const iconRows = buildIconRows(rows); const row = iconRows[clamp(this.selectedRow, 0, iconRows.length - 1)]; @@ -489,20 +492,23 @@ export class FileBrowserLayer implements Layer { if (filesViewModeSetting.get() === mode) return; const rows = this.flatRows(); const iconRows = buildIconRows(rows); + this.listMenu.setItems(rows); if (mode === "list") { // Carry the icon-grid selection into the flat list (clamped column when // only a row was selected). const row = iconRows[clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1))]; if (row) { - this.listIndex = - row.kind === "special" ? row.flatIndex : row.firstIndex + clamp(this.selectedCol, 0, row.items.length - 1); + this.listMenu.select( + row.kind === "special" ? row.flatIndex : row.firstIndex + clamp(this.selectedCol, 0, row.items.length - 1), + ); } } else { - this.setGridSelectionFromFlatIndex(rows, clamp(this.listIndex, 0, Math.max(0, rows.length - 1))); + this.setGridSelectionFromFlatIndex(rows, this.listMenu.selectedIndex ?? 0); this.iconMode = "row"; } filesViewModeSetting.set(mode); this.scrollRow = 0; + this.listMenu.scrollTop = 0; } private async activateItem(item: BrowserItem, ctx: LayerContext): Promise { @@ -548,7 +554,8 @@ export class FileBrowserLayer implements Layer { } private resetSelection(): void { - this.listIndex = 0; + this.listMenu.select(0); + this.listMenu.scrollTop = 0; this.selectedRow = 0; this.selectedCol = 0; this.iconMode = "row"; @@ -560,7 +567,9 @@ export class FileBrowserLayer implements Layer { const rows = this.flatRows(); const index = rows.findIndex((row) => row.kind === "entry" && row.entry.path === path); if (index < 0) return; - this.listIndex = index; + // Items first, then the selection, so the viewport scrolls minimally from the top. + this.listMenu.setItems(rows); + this.listMenu.select(index); this.setGridSelectionFromFlatIndex(rows, index); } diff --git a/app/apps/files/file-info-dialog.ts b/app/apps/files/file-info-dialog.ts index ff44fec2..5a35528b 100644 --- a/app/apps/files/file-info-dialog.ts +++ b/app/apps/files/file-info-dialog.ts @@ -4,7 +4,7 @@ import { wrapText } from "../../graphics/textwrap"; import type { DirectoryEntry } from "../../native/file-access"; import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures"; import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers"; -import { drawSelectionHighlight } from "../../ui/menu"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; const DIALOG_X = 8; @@ -25,12 +25,21 @@ export type FileInfoAction = { * double-click closes it. */ export class FileInfoDialogLayer implements Layer { - private selectedIndex = 0; + private readonly menu: Menu; constructor( private readonly entry: DirectoryEntry, private readonly actions: FileInfoAction[], - ) {} + ) { + this.menu = new Menu({ + items: actions, + wrap: true, + rowGap: 1, + highlight: { radius: 8 }, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: (args) => drawActionRow(args), + }); + } paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage { const font = getDefaultSmallFont(); @@ -69,32 +78,23 @@ export class FileInfoDialogLayer implements Layer { image.drawText(font, DIALOG_X + PADDING + 2, y + 3, `${GESTURE_DOUBLE_CLICK} close`, 110); return image; } - const focused = ctx.stack.isFocused(); - for (let index = 0; index < this.actions.length; index++) { - const rowY = y + index * rowH; - const selected = index === this.selectedIndex; - if (selected) { - drawSelectionHighlight(image, DIALOG_X + 12, rowY, DIALOG_WIDTH - 24, rowH - 1, focused, 8); - } - image.drawText(font, DIALOG_X + 22, rowY + LIST_ROW_TEXT_INSET, this.actions[index]!.label, selected ? 255 : 200); - } + // The rows fill the rest of the dialog (and scroll if a clamped dialog is too short). + this.menu.paint( + image, + { x: DIALOG_X + 12, y, width: DIALOG_WIDTH - 24, height: Math.max(0, DIALOG_Y + height - PADDING - y) }, + ctx.stack.isFocused(), + ); return image; } async handleInput(event: InputEvent, ctx: LayerContext): Promise { switch (event.type) { case "scroll-up": - if (this.actions.length) { - this.selectedIndex = (this.selectedIndex + this.actions.length - 1) % this.actions.length; - } - return; case "scroll-down": - if (this.actions.length) { - this.selectedIndex = (this.selectedIndex + 1) % this.actions.length; - } + await this.menu.handleInput(event); return; case "click": - await this.actions[this.selectedIndex]?.onSelect(ctx); + await this.menu.selectedItem?.onSelect(ctx); return; case "double-click": ctx.stack.pop(); @@ -105,6 +105,10 @@ export class FileInfoDialogLayer implements Layer { } } +function drawActionRow({ image, item, x, y, selected }: MenuDrawArgs): void { + image.drawText(getDefaultSmallFont(), x + 10, y + LIST_ROW_TEXT_INSET, item.label, selected ? 255 : 200); +} + function formatSize(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; diff --git a/app/apps/glanceboard/glanceboard-app.ts b/app/apps/glanceboard/glanceboard-app.ts index a0e2b236..dd10e848 100644 --- a/app/apps/glanceboard/glanceboard-app.ts +++ b/app/apps/glanceboard/glanceboard-app.ts @@ -3,9 +3,10 @@ import { truncateText, wrapText } from "../../graphics/textwrap"; import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { enumSettingMenuItem, onAnySettingChanged, toggleSettingMenuItem } from "../../ui/dashboard-settings"; import { type InputEvent } from "../../ui/gestures"; -import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers"; -import { drawSelectionHighlight, MenuLayer, openModalMenu, type MenuItem } from "../../ui/menu"; -import { LIST_ROW_TEXT_INSET, lineStep } from "../../ui/metrics"; +import { type Layer, type LayerContext } from "../../ui/layers"; +import { drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, type MenuItem } from "../../ui/menu"; +import { Menu } from "../../ui/menu-core"; +import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window"; import { shell } from "../../ui/shell/shell"; import { GlanceBoard } from "./board"; @@ -35,6 +36,15 @@ const PARAGRAPH_X = 24; const PREVIEW_MARGIN = 8; const PREVIEW_MIN_LINE_VALUE = 20; const PREVIEW_LINE_VALUE = 100; +/** The entry menu's row boxes: left inset, gap below the paragraph, and inset from the page's bottom. */ +const HOME_MENU_X = 20; +const HOME_MENU_TOP_GAP = 12; +const HOME_MENU_BOTTOM_MARGIN = 8; +/** Horizontal inset of row text (and custom row content) from its selection box. */ +const HOME_ROW_TEXT_X = 10; +// A throwaway menu to satisfy MenuItem.onSelect's second parameter; the +// entry page's items never use it (they act via ctx only). +const NO_MENU = new MenuLayer(null, []); const INTRO = "Your Glanceboard is a display for things you want to look at quickly. Starting " + @@ -55,25 +65,21 @@ function pageMenuLayout(width: number) { * a double-tap returns focus to the menu. */ class GlanceboardHomeLayer implements Layer { - private menu: MenuLayer | null = null; - private menuTop = 0; - private menuHeight = 0; + private readonly menu: Menu; private focus: "menu" | "preview" = "menu"; private selectedSlot = 0; + /** The context of the paint in progress, handed to item render callbacks. */ + private paintCtx: LayerContext | null = null; - constructor(private readonly setPreviewVisible: (visible: boolean) => void) {} - - private currentMenu(ctx: LayerContext, menuTop: number): MenuLayer { - const { width, height } = ctx.stack.getBaseSize(); - if (!this.menu || this.menuTop !== menuTop || this.menuHeight !== height) { - const half = (width / 2) | 0; - const items: MenuItem[] = [ + constructor(private readonly setPreviewVisible: (visible: boolean) => void) { + this.menu = new Menu({ + items: [ toggleSettingMenuItem(glanceboardEnabledSetting), { label: "Preview", - onSelect: (menuCtx) => { - menuCtx.stack.push(new GlancePreviewLayer( - () => menuCtx.actions.requestRender(), + onSelect: (ctx) => { + ctx.stack.push(new GlancePreviewLayer( + () => ctx.actions.requestRender(), () => this.setPreviewVisible(false), )); this.setPreviewVisible(true); @@ -87,17 +93,32 @@ class GlanceboardHomeLayer implements Layer { }, { label: "Settings", - onSelect: (menuCtx) => menuCtx.stack.push(new GlanceSettingsLayer()), + onSelect: openGlanceSettings, }, - ]; - this.menuTop = menuTop; - this.menuHeight = height; - this.menu = new MenuLayer(null, items, { - x: 8, y: menuTop, width: half - 16, - showBorder: false, minHeight: 0, maxHeight: height - menuTop, - }); - } - return this.menu; + ], + wrap: true, + rowGap: 1, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: ({ image, item, x, y, width, height, selected }) => { + const disabled = isMenuItemDisabled(item); + if (item.render) { + item.render({ + image, + x: x + HOME_ROW_TEXT_X, + y, + width: width - 2 * HOME_ROW_TEXT_X, + height: height - 2, + selected, + disabled, + text: item.label, + ctx: this.paintCtx!, + }); + } else { + image.drawText(getDefaultSmallFont(), x + HOME_ROW_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label, + disabled ? 70 : selected ? 255 : 200); + } + }, + }); } /** Where the scaled board sits: the right half, board aspect, vertically centred. */ @@ -128,13 +149,19 @@ class GlanceboardHomeLayer implements Layer { image.drawText(font, PARAGRAPH_X, y, line, 160); y += step; } - // The menu paints onto this page below the paragraph (its fill is raster, - // so the deferred paragraph glyphs above stay untouched either way). - // While the preview has focus the menu keeps its outline-only selection. - const menu = this.currentMenu(ctx, y + 4); - const menuFocused = ctx.stack.isFocused() && this.focus === "menu"; - const menuCtx: LayerContext = { ...ctx, stack: Object.assign(Object.create(ctx.stack), { isFocused: () => menuFocused }) }; - menu.paint(menuCtx, () => image); + // The menu sits below the paragraph in the left half. While the preview + // has focus the menu keeps its outline-only selection. + const menuTop = y + HOME_MENU_TOP_GAP; + const menuWidth = half - 2 * HOME_MENU_X; + const menuHeight = Math.max(0, height - menuTop - HOME_MENU_BOTTOM_MARGIN); + this.paintCtx = ctx; + try { + this.menu.paint(image, { x: HOME_MENU_X, y: menuTop, width: menuWidth, height: menuHeight }, + ctx.stack.isFocused() && this.focus === "menu"); + } finally { + this.paintCtx = null; + } + this.menu.drawScrollbar(image, HOME_MENU_X + menuWidth + 5, menuTop, menuHeight - 4); this.selectedSlot = Math.min(this.selectedSlot, glanceLayout().slots.length - 1); const preview = this.previewRect(width, height); @@ -173,7 +200,12 @@ class GlanceboardHomeLayer implements Layer { shell.yieldFocusToSidebar(); return; } - await this.currentMenu(ctx, this.menuTop).handleInput(event, ctx); + if (event.type === "click") { + const item = this.menu.selectedItem; + if (item && !isMenuItemDisabled(item)) await item.onSelect(ctx, NO_MENU); + return; + } + await this.menu.handleInput(event); } } @@ -266,31 +298,15 @@ function openSlotPicker(ctx: LayerContext, slotIndex: number): void { } /** Settings: layout, sleep gestures, duration, and slot lines. */ -class GlanceSettingsLayer implements Layer { - private menu: MenuLayer | null = null; - - private currentMenu(ctx: LayerContext): MenuLayer { - if (!this.menu) { - const { width } = ctx.stack.getBaseSize(); - const items: MenuItem[] = [ - enumSettingMenuItem(glanceLayoutSetting), - enumSettingMenuItem(glanceTapDurationSetting), - toggleSettingMenuItem(glanceShowOnLongPressSetting), - toggleSettingMenuItem(glanceShowOnHeadTiltSetting), - toggleSettingMenuItem(glanceShowLinesSetting), - ]; - this.menu = new MenuLayer("Glanceboard settings", items, pageMenuLayout(width)); - } - return this.menu; - } - - paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage { - return this.currentMenu(ctx).paint(ctx, paintBelow); - } - - async handleInput(event: InputEvent, ctx: LayerContext): Promise { - await this.currentMenu(ctx).handleInput(event, ctx); - } +function openGlanceSettings(ctx: LayerContext): void { + const items: MenuItem[] = [ + enumSettingMenuItem(glanceLayoutSetting), + enumSettingMenuItem(glanceTapDurationSetting), + toggleSettingMenuItem(glanceShowOnLongPressSetting), + toggleSettingMenuItem(glanceShowOnHeadTiltSetting), + toggleSettingMenuItem(glanceShowLinesSetting), + ]; + ctx.stack.push(new MenuLayer("Glanceboard settings", items, pageMenuLayout(ctx.stack.getBaseSize().width))); } /** The live board in the window; any click or double-click returns to the list. */ diff --git a/app/apps/music/media-browse.ts b/app/apps/music/media-browse.ts index 51e50d9a..3876c67e 100644 --- a/app/apps/music/media-browse.ts +++ b/app/apps/music/media-browse.ts @@ -1,15 +1,9 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage, type UiFont } from "../../graphics/image"; -import { clamp } from "../../util/numeric-util"; import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures"; -import { - MenuLayer, - drawListScrollbar, - drawSelectionHighlight, - drawSubmenuIndicator, - scrollToKeepSelectionVisible, -} from "../../ui/menu"; -import { lineStep, tightRowHeight } from "../../ui/metrics"; +import { MenuLayer, drawSubmenuIndicator } from "../../ui/menu"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; +import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics"; import { mediaBrowserBridge, type MediaBrowseItem, @@ -22,6 +16,8 @@ function headerHeight(font: UiFont): number { return 8 + lineStep(font) + font.lineHeight; } const LIST_X = 20; +/** The selection box extends this far left and right of the row text. */ +const LIST_HIGHLIGHT_PAD = 6; export type MediaBrowseOptions = { app: MediaBrowserApp; @@ -37,8 +33,8 @@ type BrowseLevel = { /** null while the listing is loading. */ items: MediaBrowseItem[] | null; error: string; - selectedIndex: number; - scrollRow: number; + /** Holds the loaded items; keeps this level's selection and scroll while a child level is open. */ + menu: Menu; }; type BrowsePhase = "idle" | "connecting" | "ready" | "failed"; @@ -97,50 +93,16 @@ export class MediaBrowseLayer implements Layer { return image; } - level.selectedIndex = clamp(level.selectedIndex, 0, items.length - 1); - const listHeight = height - headerHeight(font) - font.lineHeight - 10; - const rowH = tightRowHeight(font); - const visibleRows = Math.max(1, (listHeight / rowH) | 0); - level.scrollRow = scrollToKeepSelectionVisible(level.scrollRow, level.selectedIndex, visibleRows, items.length); - - const rowWidth = width - 2 * LIST_X; - const lastVisible = Math.min(items.length, level.scrollRow + visibleRows); - for (let index = level.scrollRow; index < lastVisible; index++) { - const item = items[index]!; - const y = headerHeight(font) + (index - level.scrollRow) * rowH; - const selected = index === level.selectedIndex; - const highlightX = LIST_X - 6; - const highlightY = y - 1; - const highlightWidth = rowWidth + 12; - const highlightHeight = rowH - 1; - if (selected) { - drawSelectionHighlight(image, highlightX, highlightY, highlightWidth, highlightHeight, ctx.stack.isFocused(), 4); - } - const value = selected ? 255 : 200; - const title = truncateRight(font, item.title || "(untitled)", rowWidth - 16); - image.drawText(font, LIST_X, y + 1, title, value); - if (item.subtitle) { - const titleWidth = font.measureText(title); - const subtitleWidth = font.measureText(item.subtitle); - if (titleWidth + subtitleWidth + 24 <= rowWidth - 16) { - image.drawText(font, LIST_X + rowWidth - 16 - subtitleWidth, y + 1, item.subtitle, 110); - } - } - if (item.browsable) { - drawSubmenuIndicator(image, font, highlightX, highlightY, highlightWidth, highlightHeight, selected ? value : 110); - } - } - if (items.length > visibleRows) { - drawListScrollbar( - image, - width - 12, - headerHeight(font), - visibleRows * rowH - 4, - level.scrollRow, - visibleRows, - items.length, - ); - } + const listTop = headerHeight(font); + const listHeight = height - listTop - font.lineHeight - 10; + const visibleRows = Math.max(1, (listHeight / tightRowHeight(font)) | 0); + // Row boxes start one pixel above the header's bottom edge. + level.menu.paint( + image, + { x: LIST_X - LIST_HIGHLIGHT_PAD, y: listTop - 1, width: width - 2 * LIST_X + 2 * LIST_HIGHLIGHT_PAD, height: listHeight }, + ctx.stack.isFocused(), + ); + level.menu.drawScrollbar(image, width - 12, listTop, visibleRows * tightRowHeight(font) - 4); image.drawText( font, @@ -175,13 +137,11 @@ export class MediaBrowseLayer implements Layer { if (!level || !items || !items.length) return; switch (event.type) { case "scroll-up": - level.selectedIndex = Math.max(0, level.selectedIndex - 1); - return; case "scroll-down": - level.selectedIndex = Math.min(items.length - 1, level.selectedIndex + 1); + await level.menu.handleInput(event); return; case "click": { - const item = items[clamp(level.selectedIndex, 0, items.length - 1)]; + const item = level.menu.selectedItem; if (!item) return; if (item.browsable && item.playable) { ctx.stack.push( @@ -233,18 +193,46 @@ export class MediaBrowseLayer implements Layer { } private descendInto(ctx: LayerContext, item: MediaBrowseItem): void { - const level: BrowseLevel = { - parentId: item.mediaId, - title: item.title || "(untitled)", - items: null, - error: "", - selectedIndex: 0, - scrollRow: 0, - }; + const level = this.createLevel(item.mediaId, item.title || "(untitled)"); this.levels.push(level); this.loadLevel(ctx, level); } + private createLevel(parentId: string, title: string): BrowseLevel { + return { + parentId, + title, + items: null, + error: "", + menu: new Menu({ + wrap: false, + rowGap: 1, + highlight: { radius: 4 }, + getHeight: () => tightRowHeight(getDefaultSmallFont()), + draw: (args) => this.drawItem(args), + }), + }; + } + + private drawItem({ image, item, x, y, width, height, selected }: MenuDrawArgs): void { + const font = getDefaultSmallFont(); + const value = selected ? 255 : 200; + const textWidth = width - 2 * LIST_HIGHLIGHT_PAD - 16; + const textY = centeredTextY(font, y, height); + const title = truncateRight(font, item.title || "(untitled)", textWidth); + image.drawText(font, x + LIST_HIGHLIGHT_PAD, textY, title, value); + if (item.subtitle) { + const titleWidth = font.measureText(title); + const subtitleWidth = font.measureText(item.subtitle); + if (titleWidth + subtitleWidth + 24 <= textWidth) { + image.drawText(font, x + LIST_HIGHLIGHT_PAD + textWidth - subtitleWidth, textY, item.subtitle, 110); + } + } + if (item.browsable) { + drawSubmenuIndicator(image, font, x, y, width, height, selected ? value : 110); + } + } + private startConnect(ctx: LayerContext): void { this.phase = "connecting"; mediaBrowserBridge @@ -252,14 +240,7 @@ export class MediaBrowseLayer implements Layer { .then((rootId) => { if (this.removed) return; this.phase = "ready"; - const root: BrowseLevel = { - parentId: rootId, - title: "Library", - items: null, - error: "", - selectedIndex: 0, - scrollRow: 0, - }; + const root = this.createLevel(rootId, "Library"); this.levels = [root]; this.loadLevel(ctx, root); ctx.actions.requestRender(); @@ -278,6 +259,7 @@ export class MediaBrowseLayer implements Layer { .then((items) => { if (this.removed) return; level.items = items; + level.menu.setItems(items, 0); ctx.actions.requestRender(); }) .catch((error) => { diff --git a/app/apps/music/music-app.ts b/app/apps/music/music-app.ts index 0996ad82..7c08867a 100644 --- a/app/apps/music/music-app.ts +++ b/app/apps/music/music-app.ts @@ -5,7 +5,7 @@ import { clamp } from "../../util/numeric-util"; import { directionalFallback, GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL_DOWN, GESTURE_SCROLL_UP, type InputEvent, isDirectionalInput } from "../../ui/gestures"; import { MenuLayer, drawSubmenuIndicator } from "../../ui/menu"; import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; -import { lineStep, tightRowHeight } from "../../ui/metrics"; +import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics"; import { mediaControllerBridge, type MediaControllerState, type MediaQueueItem } from "../../native/media-controller"; import { mediaBrowserBridge, type MediaBrowserApp } from "../../native/media-browser"; import { MediaBrowseLayer } from "./media-browse"; @@ -139,7 +139,7 @@ class MusicAppLayer implements Layer { this.reconcileSelection(actions, queue); const listHeight = height - LIST_TOP - LIST_BOTTOM_MARGIN; const focused = ctx.stack.isFocused(); - // Row boxes start one pixel above LIST_TOP so the text lands at LIST_TOP + 1. + // Row boxes start one pixel above LIST_TOP, level with the column divider. this.actionsMenu.paint( image, { x: ACTION_X - LIST_TEXT_INSET, y: LIST_TOP - 1, width: ACTION_WIDTH + 2 * LIST_TEXT_INSET - 4, height: listHeight }, @@ -165,16 +165,16 @@ class MusicAppLayer implements Layer { private drawAction({ image, item: action, x, y, width, height, selected }: MenuDrawArgs): void { const font = getDefaultSmallFont(); const value = !action.enabled ? (selected ? 130 : 90) : selected ? 255 : 200; - image.drawText(font, x + LIST_TEXT_INSET, y + 2, truncateText(font, action.label, ACTION_WIDTH - 16), value); + image.drawText(font, x + LIST_TEXT_INSET, centeredTextY(font, y, height), truncateText(font, action.label, ACTION_WIDTH - 16), value); if ((action.kind === "playlist" || action.kind === "browse") && action.enabled) { drawSubmenuIndicator(image, font, x, y, width, height, value); } } - private drawQueueItem({ image, item, x, y, width, selected }: MenuDrawArgs): void { + private drawQueueItem({ image, item, x, y, width, height, selected }: MenuDrawArgs): void { const font = getDefaultSmallFont(); const label = `${item.active ? "> " : " "}${item.title || "(untitled)"}`; - image.drawText(font, x + LIST_TEXT_INSET, y + 2, truncateText(font, label, width - 2 * LIST_TEXT_INSET), selected ? 255 : 200); + image.drawText(font, x + LIST_TEXT_INSET, centeredTextY(font, y, height), truncateText(font, label, width - 2 * LIST_TEXT_INSET), selected ? 255 : 200); } async handleInput(event: InputEvent, ctx: LayerContext): Promise { diff --git a/app/apps/music/music-settings.ts b/app/apps/music/music-settings.ts index 52dac95d..c4c45207 100644 --- a/app/apps/music/music-settings.ts +++ b/app/apps/music/music-settings.ts @@ -10,39 +10,45 @@ import { drawToggleMenuItem, MenuLayer, type MenuItem } from "../../ui/menu"; /** Discovered apps stay visible even when ignored or no longer publishing a session. */ export class MusicSettingsLayer implements Layer { private menu: MenuLayer | null = null; - private signature = ""; - private selectedPackage = ""; + private menuWidth = 0; + /** The package behind each current row, parallel to the menu's items. */ + private packages: string[] = []; constructor() { // Refresh installed browser services, remembering ignored services too. mediaBrowserBridge.listBrowsableApps(true); } + /** Refresh the rows from the remembered apps, keeping the selection on the same package. */ private currentMenu(ctx: LayerContext): MenuLayer { const apps = readMediaApps().sort((a, b) => a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName)); + const items: MenuItem[] = apps.map((app) => ({ + label: app.appName, + onSelect: () => setMediaAppEnabled(app, !isMediaAppEnabled(app.packageName)), + render: ({ image, x, y, width, selected }) => { + const font = getDefaultSmallFont(); + const duplicateName = apps.some((other) => other !== app && other.appName === app.appName); + const label = duplicateName ? `${app.appName} (${app.packageName})` : app.appName; + drawToggleMenuItem(image, font, x, y, width, truncateText(font, label, width - 48), + isMediaAppEnabled(app.packageName), selected); + }, + })); + if (!items.length) items.push({ label: "No media apps discovered yet.", disabled: true, onSelect: () => {} }); + const selectedPackage = this.menu?.selectedIndex != null ? this.packages[this.menu.selectedIndex] : undefined; + const index = apps.findIndex((app) => app.packageName === selectedPackage); + this.packages = apps.map((app) => app.packageName); + const width = ctx.stack.getBaseSize().width; - const signature = JSON.stringify([width, apps.map((app) => [app.packageName, app.appName])]); - if (!this.menu || signature !== this.signature) { - this.signature = signature; - const items: MenuItem[] = apps.map((app) => ({ - label: app.appName, - onSelect: () => setMediaAppEnabled(app, !isMediaAppEnabled(app.packageName)), - render: ({ image, x, y, width, selected }) => { - if (selected) this.selectedPackage = app.packageName; - const font = getDefaultSmallFont(); - const duplicateName = apps.some((other) => other !== app && other.appName === app.appName); - const label = duplicateName ? `${app.appName} (${app.packageName})` : app.appName; - drawToggleMenuItem(image, font, x, y, width, truncateText(font, label, width - 48), - isMediaAppEnabled(app.packageName), selected); - }, - })); - if (!items.length) items.push({ label: "No media apps discovered yet.", disabled: true, onSelect: () => {} }); + if (!this.menu || width !== this.menuWidth) { + this.menuWidth = width; this.menu = new MenuLayer("Music settings", items, { x: 8, y: 8, width: width - 16, opaque: true, showBorder: false, footer: "On = enabled Off = ignored", - }).selectItem(Math.max(0, apps.findIndex((app) => app.packageName === this.selectedPackage))); + }).selectItem(Math.max(0, index)); + } else { + this.menu.setItems(items, index >= 0 ? index : undefined); } return this.menu; } diff --git a/app/apps/navigate/navigate-app.worker.ts b/app/apps/navigate/navigate-app.worker.ts index 5bfa6194..14cdd830 100644 --- a/app/apps/navigate/navigate-app.worker.ts +++ b/app/apps/navigate/navigate-app.worker.ts @@ -16,14 +16,12 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import * as frameTimings from "../../native/frame-timings"; import { getActiveDisplay } from "../../native/active-display"; import { - drawListScrollbar, drawRightValueMenuItem, - drawSelectionHighlight, drawSubmenuIndicator, drawToggleMenuItem, - scrollToKeepSelectionVisible, type MenuItem, } from "../../ui/menu"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; import { LIST_ROW_TEXT_INSET, listRowHeight } from "../../ui/metrics"; import { WindowMenu, WindowMenuLayer } from "../../ui/window-menu"; import type { LayerContext } from "../../ui/layers"; @@ -205,9 +203,8 @@ type IdleEntry = | { kind: "recent"; destination: RecentDestination } | { kind: "action"; label: string; detail: string; run: () => void }; -/** Idle-page list selection (index into idleEntries()). */ -let idleSelection = 0; -let idleScrollRow = 0; +/** The idle page's list; created on first use (idleList) so module load stays free of paint dependencies. */ +let idleMenu: Menu | null = null; /** * In-progress destination edit: the phone text editor is open on `setting` @@ -948,7 +945,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] { onSelect: () => { const enabled = navigateRememberRecentSetting.toggle(); if (!enabled) clearRecentDestinations(); - clampIdleSelection(); + syncIdleList(); }, render: ({ image, x, y, width, selected }) => { drawToggleMenuItem( @@ -963,7 +960,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] { ); }, }); - const selectedEntry = phase === "idle" ? idleEntries()[idleSelection] : undefined; + const selectedEntry = phase === "idle" ? syncIdleList().selectedItem : null; if (selectedEntry?.kind === "recent") { const recent = selectedEntry.destination; items.push({ @@ -971,7 +968,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); removeRecentDestination(recent); - clampIdleSelection(); + syncIdleList(); }, }); } @@ -981,7 +978,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); clearRecentDestinations(); - clampIdleSelection(); + syncIdleList(); }, }); } @@ -1066,7 +1063,7 @@ function customDestinationMenuItems(destination: SavedDestination): MenuItem[] { onSelect: (ctx) => { closeMenusAnd(ctx, () => { removeCustomDestination(destination.id); - clampIdleSelection(); + syncIdleList(); }); }, }, @@ -1121,7 +1118,7 @@ function finishEdit(confirmed: boolean): void { if (!editing) { navigateDestinationNameDraftSetting.set(""); navigateDestinationAddressDraftSetting.set(""); - clampIdleSelection(); + syncIdleList(); render(); } } @@ -1206,9 +1203,27 @@ function idleEntries(): IdleEntry[] { return entries; } -function clampIdleSelection(): void { - const count = idleEntries().length; - idleSelection = Math.max(0, Math.min(idleSelection, count - 1)); +/** Horizontal inset of the idle list's selection boxes. */ +const IDLE_LIST_X = 20; +/** Pixels between consecutive idle rows' selection boxes. */ +const IDLE_ROW_GAP = 2; + +function idleList(): Menu { + idleMenu ??= new Menu({ + wrap: false, + rowGap: IDLE_ROW_GAP, + highlight: { radius: 6 }, + getHeight: () => listRowHeight(smallFont), + draw: drawIdleRow, + }); + return idleMenu; +} + +/** Refresh the idle list from idleEntries(); the selection keeps its index, clamped into range. */ +function syncIdleList(): Menu { + const list = idleList(); + list.setItems(idleEntries()); + return list; } function navigateToIdleEntry(entry: IdleEntry): void { @@ -1282,7 +1297,7 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void { } else if (phase === "arrived" || phase === "map") { stopNavigation(""); } else if (phase === "idle") { - const entry = idleEntries()[idleSelection]; + const entry = syncIdleList().selectedItem; if (!entry) { frameTimings.finishFrame(frameId, "discarded: navigate ignored click"); return; @@ -1301,8 +1316,7 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void { maybeRefreshMap(); renderAndSubmit(win, frameId); } else if (phase === "idle" && idleEntries().length > 1) { - const count = idleEntries().length; - idleSelection = Math.max(0, Math.min(count - 1, idleSelection + (event.type === "scroll-down" ? 1 : -1))); + syncIdleList().moveSelection(event.type === "scroll-down" ? 1 : -1); renderAndSubmit(win, frameId); } else { frameTimings.finishFrame(frameId, "discarded: navigate ignored scroll"); @@ -1392,59 +1406,33 @@ function paintIdleList(image: GrayImage, win: NavWindow, entries: IdleEntry[], t const rowHeight = listRowHeight(smallFont); const listBottom = image.height - 30; const visibleRows = Math.max(1, Math.floor((listBottom - top) / rowHeight)); - idleSelection = Math.max(0, Math.min(idleSelection, entries.length - 1)); - idleScrollRow = scrollToKeepSelectionVisible(idleScrollRow, idleSelection, visibleRows, entries.length); - const rowX = 20; const rowWidth = image.width - 40 - (entries.length > visibleRows ? 10 : 0); - const labelWidth = Math.floor(rowWidth * 0.4); - for (let row = 0; row < visibleRows; row++) { - const index = idleScrollRow + row; - const entry = entries[index]; - if (!entry) break; - const y = top + row * rowHeight; - const selected = index === idleSelection; - if (selected) drawSelectionHighlight(image, rowX, y, rowWidth, rowHeight - 2, win.focused); - const textX = rowX + 6; - const textY = y + LIST_ROW_TEXT_INSET; - if (entry.kind === "action") { - const label = truncateText(smallFont, entry.label, labelWidth); - image.drawText(smallFont, textX, textY, label, selected ? 245 : 210); - const detailX = textX + labelWidth + 8; - image.drawText( - smallFont, - detailX, - textY, - truncateText(smallFont, entry.detail, rowX + rowWidth - 6 - detailX), - selected ? 170 : 130, - ); - } else if (entry.kind === "saved") { - const label = truncateText(smallFont, entry.destination.name, labelWidth); - image.drawText(smallFont, textX, textY, label, selected ? 245 : 210); - const detailX = textX + labelWidth + 8; - image.drawText( - smallFont, - detailX, - textY, - truncateText(smallFont, entry.destination.address, rowX + rowWidth - 6 - detailX), - selected ? 170 : 130, - ); - } else { - const label = truncateText(smallFont, entry.destination.name, labelWidth); - image.drawText(smallFont, textX, textY, label, selected ? 245 : 210); - const detailX = textX + labelWidth + 8; - const detail = entry.destination.place ? `${entry.destination.place} (recent)` : "(recent)"; - image.drawText( - smallFont, - detailX, - textY, - truncateText(smallFont, detail, rowX + rowWidth - 6 - detailX), - selected ? 170 : 130, - ); - } - } - if (entries.length > visibleRows) { - drawListScrollbar(image, rowX + rowWidth + 4, top, visibleRows * rowHeight - 2, idleScrollRow, visibleRows, entries.length); + const list = idleList(); + list.setItems(entries); + list.paint(image, { x: IDLE_LIST_X, y: top, width: rowWidth, height: visibleRows * rowHeight - IDLE_ROW_GAP }, win.focused); + list.drawScrollbar(image, IDLE_LIST_X + rowWidth + 4, top, visibleRows * rowHeight - 2); +} + +/** Two columns: the entry's name, then its detail (action hint, address or place). */ +function drawIdleRow({ image, item: entry, x, y, width, selected }: MenuDrawArgs): void { + const labelWidth = Math.floor(width * 0.4); + const textX = x + 6; + const textY = y + LIST_ROW_TEXT_INSET; + let label: string; + let detail: string; + if (entry.kind === "action") { + label = entry.label; + detail = entry.detail; + } else if (entry.kind === "saved") { + label = entry.destination.name; + detail = entry.destination.address; + } else { + label = entry.destination.name; + detail = entry.destination.place ? `${entry.destination.place} (recent)` : "(recent)"; } + image.drawText(smallFont, textX, textY, truncateText(smallFont, label, labelWidth), selected ? 245 : 210); + const detailX = textX + labelWidth + 8; + image.drawText(smallFont, detailX, textY, truncateText(smallFont, detail, x + width - 6 - detailX), selected ? 170 : 130); } function paintNavigating(image: GrayImage, win: NavWindow): void { diff --git a/app/apps/teleprompter/teleprompter-app.ts b/app/apps/teleprompter/teleprompter-app.ts index bbd3be46..c615297b 100644 --- a/app/apps/teleprompter/teleprompter-app.ts +++ b/app/apps/teleprompter/teleprompter-app.ts @@ -52,10 +52,8 @@ export type TeleprompterAppOptions = InProcessAppOptions & { * over the home page. */ export function createTeleprompterAppWindow(options: TeleprompterAppOptions): InProcessWindow { - // The home menu's items are rebuilt in place whenever the recents change - // (MenuLayer reads the array each paint). - const homeItems: MenuItem[] = []; - const home = new MenuLayer("Teleprompter", homeItems, HOME_LAYOUT); + // The home menu's items are replaced (refreshHome) whenever the recents change. + const home = new MenuLayer("Teleprompter", [], HOME_LAYOUT); let created: InProcessWindow | null = null; let notice = ""; @@ -142,10 +140,8 @@ export function createTeleprompterAppWindow(options: TeleprompterAppOptions): In if (notice) { items.push({ label: notice, disabled: true, onSelect: () => {} }); } - homeItems.length = 0; - homeItems.push(...items); // Land on the most recent script (one click resumes it), else on Browse. - home.selectItem(getRecentScripts().length > 0 ? 1 : 0); + home.setItems(items, getRecentScripts().length > 0 ? 1 : 0); } refreshHome(); diff --git a/app/apps/terminal/terminal-app.worker.ts b/app/apps/terminal/terminal-app.worker.ts index 29c112ce..fd110ad5 100644 --- a/app/apps/terminal/terminal-app.worker.ts +++ b/app/apps/terminal/terminal-app.worker.ts @@ -54,7 +54,8 @@ import { clamp } from "../../util/numeric-util"; import { terminalAutoReconnectSetting, terminalLaunchPresetsSetting, terminalNewConnectionSetting, terminalWakeOnBellSetting } from "../../ui/dashboard-settings"; import { connectionDisplayName, loadConnections, parseConnectionString, saveConnections, TERMINAL_CONNECTIONS_KEY, updateConnection, type TerminalConnection } from "./connections"; import { TerminalEmulator } from "./terminal-emulator"; -import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu"; +import { type MenuItem } from "../../ui/menu"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; import { lineStep, listRowHeight } from "../../ui/metrics"; import { WindowMenu } from "../../ui/window-menu"; import { appViewportSize } from "../../ui/shell/geometry"; @@ -126,8 +127,8 @@ type HubMode = "sessions" | "connections" | "add"; type HubWindow = BaseWindow & { kind: "hub"; mode: HubMode; - selectedIndex: number; - scrollRow: number; + /** The section's item list; created on first paint or input (hubMenu). */ + list: Menu | null; /** * Session recency keys in display order, captured when the window last * became visible so the list doesn't reshuffle under the user while it's @@ -507,8 +508,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport lastSubmittedFingerprint: "", menu: null, mode: "sessions", - selectedIndex: 0, - scrollRow: 0, + list: null, sessionOrder: [], addError: "", }); @@ -1189,11 +1189,48 @@ type HubItem = { onSelect?: () => void; }; +/** Vertical offset of a row's text line from the top of its selection box. */ +const HUB_ROW_TEXT_INSET = 4; +/** Horizontal inset of the list's selection boxes from the viewport edges. */ +const HUB_LIST_X = 20; + +/** The hub window's list, created on first use so openWindow stays free of paint dependencies. */ +function hubMenu(window: HubWindow): Menu { + window.list ??= new Menu({ + wrap: false, + rowGap: 1, + getHeight: () => listRowHeight(chromeFont()), + isSelectable: (item) => Boolean(item.onSelect), + onSelect: (item) => item.onSelect?.(), + draw: drawHubRow, + }); + return window.list; +} + +function drawHubRow({ image, item, x, y, width, selected }: MenuDrawArgs): void { + const font = chromeFont(); + if (item.heading) { + image.drawText(font, x, y + HUB_ROW_TEXT_INSET, item.label, 140); + return; + } + // Activity gutter, open-window number column, then the label, truncated + // to the row (shared with the Glanceboard's Terminal widget). + drawSessionRow(image, font, { + x: x + 2, + y: y + HUB_ROW_TEXT_INSET, + width: width - 8, + label: item.label, + openGlyph: item.openGlyph ?? null, + active: Boolean(item.active), + phase: hubAnimationPhase, + value: selected ? 255 : 200, + }); +} + /** Switch the hub between its sections, resetting selection state. */ function setHubMode(window: HubWindow, mode: HubMode): void { window.mode = mode; - window.selectedIndex = 0; - window.scrollRow = 0; + window.list?.select(0); window.addError = ""; } @@ -1423,34 +1460,6 @@ function endAddConnection(window: HubWindow): void { post({ type: "end-text-setting-edit" }); } -/** Move the hub selection to the next selectable item in `direction`. */ -function moveHubSelection(window: HubWindow, items: HubItem[], direction: -1 | 1): void { - let index = window.selectedIndex + direction; - while (index >= 0 && index < items.length && !items[index]!.onSelect) { - index += direction; - } - if (index >= 0 && index < items.length) { - window.selectedIndex = index; - } -} - -/** Clamp the selection into range and off heading rows (prefer moving down). */ -function clampHubSelection(window: HubWindow, items: HubItem[]): void { - if (!items.length) { - window.selectedIndex = 0; - return; - } - let index = Math.max(0, Math.min(window.selectedIndex, items.length - 1)); - if (!items[index]!.onSelect) { - let forward = index; - while (forward < items.length && !items[forward]!.onSelect) forward++; - let backward = index; - while (backward >= 0 && !items[backward]!.onSelect) backward--; - index = forward < items.length ? forward : Math.max(0, backward); - } - window.selectedIndex = index; -} - function handleHubInput(window: HubWindow, event: InputEvent, frameId: number): void { if (window.mode === "add") { if (event.type === "click") { @@ -1461,23 +1470,18 @@ function handleHubInput(window: HubWindow, event: InputEvent, frameId: number): frameTimings.finishFrame(frameId, "discarded: terminal add-connection ignored input"); return; } - const items = hubItems(window); - clampHubSelection(window, items); + const list = hubMenu(window); + list.setItems(hubItems(window)); switch (event.type) { case "scroll-up": - moveHubSelection(window, items, -1); - renderAndSubmit(window, frameId); - return; case "scroll-down": - moveHubSelection(window, items, 1); + case "click": + // The menu's input handler is async only to await onSelect; hub item + // callbacks are synchronous, so the selection move or action has + // already applied when it returns and the frame can paint right away. + list.handleInput(event).catch((error) => console.error("terminal hub action failed", error)); renderAndSubmit(window, frameId); return; - case "click": { - const item = items[window.selectedIndex]; - item?.onSelect?.(); - renderAndSubmit(window, frameId); - return; - } default: frameTimings.finishFrame(frameId, "discarded: terminal hub ignored input"); return; @@ -1601,49 +1605,18 @@ function paintHub(window: HubWindow): GrayImage { listTop += 2 * step + 6; } - const items = hubItems(window); - clampHubSelection(window, items); - const hubRowH = listRowHeight(chromeFont()); - const visibleRowCount = Math.max(1, ((window.viewportHeight - 6 - listTop) / hubRowH) | 0); - window.scrollRow = scrollToKeepSelectionVisible(window.scrollRow, window.selectedIndex, visibleRowCount, items.length); - const lastVisibleRow = Math.min(items.length, window.scrollRow + visibleRowCount); - for (let index = window.scrollRow; index < lastVisibleRow; index++) { - const y = listTop + (index - window.scrollRow) * hubRowH; - const item = items[index]!; - if (item.heading) { - image.drawText(chromeFont(), 20, y + 2, item.label, 140); - continue; - } - const selected = index === window.selectedIndex; - if (selected) { - // Match the shell convention: fill only when this window has focus, so - // an outline-only selection signals the sidebar owns input. - drawSelectionHighlight(image, 20, y - 2, window.viewportWidth - 40, hubRowH - 1, window.focused, 8); - } - // Activity gutter, open-window number column, then the label, truncated - // to the row (shared with the Glanceboard's Terminal widget). - drawSessionRow(image, chromeFont(), { - x: 22, - y: y + 2, - width: window.viewportWidth - 22 - 26, - label: item.label, - openGlyph: item.openGlyph ?? null, - active: Boolean(item.active), - phase: hubAnimationPhase, - value: selected ? 255 : 200, - }); - } - if (items.length > visibleRowCount) { - drawListScrollbar( - image, - window.viewportWidth - 10, - listTop, - visibleRowCount * hubRowH - 4, - window.scrollRow, - visibleRowCount, - items.length, - ); - } + const list = hubMenu(window); + list.setItems(hubItems(window)); + // Selection boxes start above the text line; the menu fills the selected + // box only while this window has focus (an outline alone means the sidebar + // owns input), matching the shell convention. + const listHeight = window.viewportHeight - 6 - listTop; + list.paint( + image, + { x: HUB_LIST_X, y: listTop - 2, width: window.viewportWidth - 2 * HUB_LIST_X, height: listHeight }, + window.focused, + ); + list.drawScrollbar(image, window.viewportWidth - 10, listTop, listHeight - 4); return image; } diff --git a/app/apps/timer/timer-app.ts b/app/apps/timer/timer-app.ts index 0555aecf..af61c195 100644 --- a/app/apps/timer/timer-app.ts +++ b/app/apps/timer/timer-app.ts @@ -31,14 +31,12 @@ import { } from "../../ui/gestures"; import { type Layer, type LayerContext } from "../../ui/layers"; import { - drawListScrollbar, drawRightValueMenuItem, - drawSelectionHighlight, drawToggleMenuItem, - scrollToKeepSelectionVisible, TextPageLayer, type MenuItem, } from "../../ui/menu"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window"; import { shell } from "../../ui/shell/shell"; @@ -91,6 +89,8 @@ const LIST_SHARE = 0.4; const LIST_MIN_WIDTH = 190; const LIST_MAX_WIDTH = 240; const LIST_TOP = 6; +/** Pixels between consecutive list rows' selection boxes. */ +const LIST_ROW_GAP = 1; const STAGE_X = 10; /** Gap between the stage's right edge and the list's divider. */ const STAGE_LIST_GAP = 14; @@ -183,8 +183,22 @@ function fittingDigitFont(text: string, maxWidth: number, sizes: readonly number export class TimersLayer implements Layer { readonly acceptsDirectional = true; + /** + * The selected row's key: the source of truth for the selection, which + * survives row rebuilds and is pinned to newly ringing items. The list + * menu is re-synced from it before each paint, hit test and move. + */ private selectionKey = ""; - private scrollRow = 0; + private readonly list = new Menu({ + wrap: true, + rowGap: LIST_ROW_GAP, + highlight: { radius: 6 }, + getHeight: () => listRowHeight(smallFont()), + isSelectable: (row) => row.kind !== "header", + draw: (args) => this.drawListRow(args), + }); + /** Per-paint inputs to drawListRow. */ + private listPaint = { dim: 1, now: 0 }; private mode: Mode = { kind: "list" }; /** Which of the ringing stage's two buttons is highlighted. */ private ringButton = 0; @@ -232,7 +246,8 @@ export class TimersLayer implements Layer { let index = rows.findIndex((row) => row.key === this.selectionKey); if (index < 0) { // The row went away (a dismissed timer, a deleted alarm): stay in place. - index = clamp(this.scrollRow, 0, rows.length - 1); + const firstVisibleRow = Math.floor(this.list.scrollTop / listRowHeight(smallFont())); + index = clamp(firstVisibleRow, 0, rows.length - 1); while (index < rows.length && rows[index]!.kind === "header") index++; if (index >= rows.length) index = rows.findIndex((row) => row.kind !== "header"); this.selectionKey = rows[index]!.key; @@ -244,14 +259,16 @@ export class TimersLayer implements Layer { return rows[this.reconcileSelection(rows)]!; } - private moveSelection(rows: Row[], delta: number): void { - const count = rows.length; - let index = this.reconcileSelection(rows); - for (let step = 0; step < count; step++) { - index = (index + delta + count) % count; - if (rows[index]!.kind !== "header") break; - } - this.selectionKey = rows[index]!.key; + /** Point the list menu at these rows and the current selection. */ + private syncList(rows: Row[]): void { + this.list.setItems(rows, this.reconcileSelection(rows)); + } + + private moveSelection(rows: Row[], delta: -1 | 1): void { + this.syncList(rows); + this.list.moveSelection(delta); + const index = this.list.selectedIndex; + if (index !== null) this.selectionKey = rows[index]!.key; } /** Called on every engine change: jump to a newly ringing item. */ @@ -547,15 +564,14 @@ export class TimersLayer implements Layer { /** A mirror touch: on the list, select the row under it. */ hitTest(x: number, y: number, ctx: LayerContext): boolean { if (this.mode.kind !== "list") return false; - const { width, height } = ctx.stack.getBaseSize(); + const { width } = ctx.stack.getBaseSize(); const listX = width - listWidthFor(width); if (x < listX) return false; const rows = this.buildRows(Date.now()); - this.reconcileSelection(rows); - const rowHeight = listRowHeight(smallFont()); - const index = this.scrollRow + Math.floor((y - LIST_TOP) / rowHeight); - const row = rows[index]; - if (!row || row.kind === "header" || y < LIST_TOP || y > height) return true; + this.syncList(rows); + const index = this.list.indexAt(y); + if (index === null) return true; + const row = rows[index]!; if (this.selectionKey === row.key) { this.activateRow(row); } else { @@ -882,79 +898,78 @@ export class TimersLayer implements Layer { dim: number, now: number, ): void { - const font = smallFont(); - const rowHeight = listRowHeight(font); + const rowHeight = listRowHeight(smallFont()); const visible = Math.max(1, Math.floor((height - 2 * LIST_TOP) / rowHeight)); - this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, selectedIndex, visible, rows.length); + this.listPaint = { dim, now }; + // While a picker owns the stage the list has no live selection, so no + // highlight; drawListRow still brightens the selected row by key. + this.list.setItems(rows, dim === 1 ? selectedIndex : null); + this.list.paint(image, { x: listX, y: LIST_TOP, width: listWidth - 12, height: visible * rowHeight - LIST_ROW_GAP }, focused); + this.list.drawScrollbar(image, listX + listWidth - 7, LIST_TOP, visible * rowHeight - 4); + } + + private drawListRow({ image, item: row, x, y, width, height }: MenuDrawArgs): void { + const font = smallFont(); + const { dim, now } = this.listPaint; + const rowHeight = height + LIST_ROW_GAP; const shade = (value: number) => Math.round(value * dim); - const textX = listX + 8; - const textWidth = listWidth - 24; - const last = Math.min(rows.length, this.scrollRow + visible); - for (let index = this.scrollRow; index < last; index++) { - const row = rows[index]!; - const y = LIST_TOP + (index - this.scrollRow) * rowHeight; - const textY = y + LIST_ROW_TEXT_INSET; - if (row.kind === "header") { - image.drawText(font, textX, textY, row.title!, shade(90)); - continue; - } - const selected = index === selectedIndex; - if (selected && dim === 1) { - drawSelectionHighlight(image, listX, y, listWidth - 12, rowHeight - 1, focused, 6); - } - const bright = shade(selected ? 250 : 210); - const soft = shade(selected ? 170 : 130); - switch (row.kind) { - case "timer": { - const timer = row.timer!; - const phase = timerPhase(timer); - const digits = phase === "rung" ? "0:00" : formatCountdown(timerRemainingMs(timer, now)); - const digitsValue = phase === "rung" ? (Math.floor(now / 1000) % 2 ? bright : soft) : phase === "paused" ? soft : bright; - image.drawText(font, textX, textY, digits, digitsValue); - const digitsWidth = font.measureText(digits) + 8; - const nameWidth = textWidth - digitsWidth - (phase === "paused" ? 12 : 0); - if (nameWidth > 12) { - image.drawText(font, textX + digitsWidth, textY, truncateText(font, timerDisplayName(timer), nameWidth), soft); - } - if (phase === "paused") drawPauseMark(image, listX + listWidth - 22, y + Math.floor(rowHeight / 2) - 5, soft); - break; - } - case "new-timer": - image.drawText(font, textX, textY, "+ New timer", shade(selected ? 220 : 150)); - break; - case "stopwatch": { - const stopwatch = timerEngine.state.stopwatch; - const running = stopwatchIsRunning(stopwatch); - const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, now), false); - image.drawText(font, textX, textY, "Stopwatch", running ? bright : soft); - image.drawText(font, listX + listWidth - 16 - font.measureText(elapsed), textY, elapsed, running ? bright : soft); - break; - } - case "alarm": { - const alarm = row.alarm!; - const on = alarm.enabled; - const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour()); - image.drawText(font, textX, textY, time, on ? bright : soft); - const timeWidth = font.measureText(time) + 8; - const daysWidth = textWidth - timeWidth - 14; - if (daysWidth > 12) { - image.drawText(font, textX + timeWidth, textY, truncateText(font, alarm.label || formatDays(alarm.days), daysWidth), on ? soft : shade(80)); - } - const dotX = listX + listWidth - 22; - const dotY = y + Math.floor(rowHeight / 2) - 4; - if (alarm.ringingSinceMs !== null || on) image.fillRoundedRect(dotX, dotY, 8, 8, on ? shade(220) : shade(90), 4); - else image.drawRoundedRect(dotX, dotY, 8, 8, shade(90), 4); - break; - } - case "new-alarm": - image.drawText(font, textX, textY, "+ New alarm", shade(selected ? 220 : 150)); - break; - default: - break; - } + const textX = x + 8; + const textWidth = width - 12; + const textY = y + LIST_ROW_TEXT_INSET; + if (row.kind === "header") { + image.drawText(font, textX, textY, row.title!, shade(90)); + return; } - if (rows.length > visible) { - drawListScrollbar(image, listX + listWidth - 7, LIST_TOP, visible * rowHeight - 4, this.scrollRow, visible, rows.length); + const selected = row.key === this.selectionKey; + const bright = shade(selected ? 250 : 210); + const soft = shade(selected ? 170 : 130); + switch (row.kind) { + case "timer": { + const timer = row.timer!; + const phase = timerPhase(timer); + const digits = phase === "rung" ? "0:00" : formatCountdown(timerRemainingMs(timer, now)); + const digitsValue = phase === "rung" ? (Math.floor(now / 1000) % 2 ? bright : soft) : phase === "paused" ? soft : bright; + image.drawText(font, textX, textY, digits, digitsValue); + const digitsWidth = font.measureText(digits) + 8; + const nameWidth = textWidth - digitsWidth - (phase === "paused" ? 12 : 0); + if (nameWidth > 12) { + image.drawText(font, textX + digitsWidth, textY, truncateText(font, timerDisplayName(timer), nameWidth), soft); + } + if (phase === "paused") drawPauseMark(image, x + width - 10, y + Math.floor(rowHeight / 2) - 5, soft); + break; + } + case "new-timer": + image.drawText(font, textX, textY, "+ New timer", shade(selected ? 220 : 150)); + break; + case "stopwatch": { + const stopwatch = timerEngine.state.stopwatch; + const running = stopwatchIsRunning(stopwatch); + const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, now), false); + image.drawText(font, textX, textY, "Stopwatch", running ? bright : soft); + image.drawText(font, x + width - 4 - font.measureText(elapsed), textY, elapsed, running ? bright : soft); + break; + } + case "alarm": { + const alarm = row.alarm!; + const on = alarm.enabled; + const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour()); + image.drawText(font, textX, textY, time, on ? bright : soft); + const timeWidth = font.measureText(time) + 8; + const daysWidth = textWidth - timeWidth - 14; + if (daysWidth > 12) { + image.drawText(font, textX + timeWidth, textY, truncateText(font, alarm.label || formatDays(alarm.days), daysWidth), on ? soft : shade(80)); + } + const dotX = x + width - 10; + const dotY = y + Math.floor(rowHeight / 2) - 4; + if (alarm.ringingSinceMs !== null || on) image.fillRoundedRect(dotX, dotY, 8, 8, on ? shade(220) : shade(90), 4); + else image.drawRoundedRect(dotX, dotY, 8, 8, shade(90), 4); + break; + } + case "new-alarm": + image.drawText(font, textX, textY, "+ New alarm", shade(selected ? 220 : 150)); + break; + default: + break; } } diff --git a/app/apps/weather/weather.ts b/app/apps/weather/weather.ts index 5b16fbf8..d32d2e3f 100644 --- a/app/apps/weather/weather.ts +++ b/app/apps/weather/weather.ts @@ -1,12 +1,11 @@ import { getDefaultLargeFont, getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage, type UiFont } from "../../graphics/image"; import { wrapText, truncateText } from "../../graphics/textwrap"; -import { clamp } from "../../util/numeric-util"; import { type ForecastPeriod, type WeatherState } from "../../native/weather"; import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures"; import { type Layer, type LayerContext } from "../../ui/layers"; -import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../../ui/menu"; -import { lineStep, tightRowHeight } from "../../ui/metrics"; +import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; +import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics"; const PAGE_X = 18; const HEADER_Y = 8; @@ -18,11 +17,26 @@ const FORECAST_TOP = 124; const FORECAST_MIN_ROW_HEIGHT = 23; /** Gap between forecast columns. */ const FORECAST_COL_GAP = 14; +/** Left edge of the forecast rows' selection boxes. */ +const FORECAST_BOX_X = PAGE_X - 7; +/** Pixels between consecutive forecast rows' selection boxes. */ +const FORECAST_ROW_GAP = 2; + +/** Forecast column x offsets from the row box's left edge. */ +type ForecastColumns = { name: number; temp: number; precip: number; summary: number }; /** Weather's current-conditions summary and scrollable 12-hour forecast. */ export class WeatherLayer implements Layer { - private selectedIndex = 0; - private scrollRow = 0; + /** Forecast table rows: selection only, a click does nothing there. */ + private readonly forecastMenu = new Menu({ + wrap: false, + rowGap: FORECAST_ROW_GAP, + highlight: { radius: 5 }, + getHeight: () => forecastRowHeight(getDefaultSmallFont()), + draw: (args) => this.drawForecastRow(args), + }); + /** Column layout for drawForecastRow, set by each drawForecast. */ + private columns: ForecastColumns = { name: 0, temp: 0, precip: 0, summary: 0 }; constructor( private readonly state: () => WeatherState, @@ -81,10 +95,9 @@ export class WeatherLayer implements Layer { return; } if (!weather.forecast.length || weather.phase !== "ready") return; - if (event.type === "scroll-up") { - this.selectedIndex = Math.max(0, this.selectedIndex - 1); - } else if (event.type === "scroll-down") { - this.selectedIndex = Math.min(weather.forecast.length - 1, this.selectedIndex + 1); + if (event.type === "scroll-up" || event.type === "scroll-down") { + this.forecastMenu.setItems(weather.forecast); + void this.forecastMenu.handleInput(event); } } @@ -134,12 +147,14 @@ export class WeatherLayer implements Layer { image.drawText(font, PAGE_X, FORECAST_TOP, "No upcoming forecast periods.", 160); return; } - this.selectedIndex = clamp(this.selectedIndex, 0, forecast.length - 1); - const rowH = Math.max(FORECAST_MIN_ROW_HEIGHT, tightRowHeight(font) + 3); + const rowH = forecastRowHeight(font); // The last row only needs its text line (not a full row pitch of // clearance below), which usually fits one more row before the bottom. + // The menu only draws rows whose whole selection box fits, so the box + // holds that many rows, cut at the image's bottom edge. const visibleRows = Math.max(1, 1 + Math.floor((height - FORECAST_TOP - (font.lineHeight + 4)) / rowH)); - this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, forecast.length); + const boxTop = FORECAST_TOP - 2; + const boxHeight = Math.min(visibleRows * rowH - FORECAST_ROW_GAP, height - boxTop); // Columns are sized to the widest period name so names ("Wednesday // Night") never truncate; the summary column absorbs what's left. @@ -155,20 +170,31 @@ export class WeatherLayer implements Layer { image.drawText(font, tempX, FORECAST_HEADER_Y, "Temp", 105); image.drawText(font, precipX, FORECAST_HEADER_Y, "Rain", 105); - const last = Math.min(forecast.length, this.scrollRow + visibleRows); - for (let index = this.scrollRow; index < last; index++) { - const period = forecast[index]!; - const y = FORECAST_TOP + (index - this.scrollRow) * rowH; - const selected = index === this.selectedIndex; - if (selected) { - drawSelectionHighlight(image, PAGE_X - 7, y - 2, width - 2 * (PAGE_X - 7), rowH - 2, ctx.stack.isFocused(), 5); - } - const shade = selected ? 245 : 190; - image.drawText(font, PAGE_X, y + 2, period.name, shade); - image.drawText(font, tempX, y + 2, period.temperatureF === null ? "--" : `${Math.round(period.temperatureF)}°F`, shade); - image.drawText(font, precipX, y + 2, period.precipitationPercent === null ? "--" : `${Math.round(period.precipitationPercent)}%`, selected ? 220 : 155); - image.drawText(font, summaryX, y + 2, truncateText(font, period.shortForecast, width - summaryX - PAGE_X), selected ? 220 : 165); - } + this.columns = { + name: PAGE_X - FORECAST_BOX_X, + temp: tempX - FORECAST_BOX_X, + precip: precipX - FORECAST_BOX_X, + summary: summaryX - FORECAST_BOX_X, + }; + this.forecastMenu.setItems(forecast); + this.forecastMenu.paint( + image, + { x: FORECAST_BOX_X, y: boxTop, width: width - 2 * FORECAST_BOX_X, height: boxHeight }, + ctx.stack.isFocused(), + ); + } + + private drawForecastRow({ image, item: period, x, y, width, height, selected }: MenuDrawArgs): void { + const font = getDefaultSmallFont(); + const columns = this.columns; + const shade = selected ? 245 : 190; + const textY = centeredTextY(font, y, height); + image.drawText(font, x + columns.name, textY, period.name, shade); + image.drawText(font, x + columns.temp, textY, period.temperatureF === null ? "--" : `${Math.round(period.temperatureF)}°F`, shade); + image.drawText(font, x + columns.precip, textY, period.precipitationPercent === null ? "--" : `${Math.round(period.precipitationPercent)}%`, selected ? 220 : 155); + // The summary stops PAGE_X short of the viewport's right edge, as the name starts PAGE_X in from the left. + const summaryWidth = width - columns.summary - columns.name; + image.drawText(font, x + columns.summary, textY, truncateText(font, period.shortForecast, summaryWidth), selected ? 220 : 165); } private drawMessage( @@ -190,6 +216,11 @@ export class WeatherLayer implements Layer { } } +/** Forecast row pitch, including the gap between selection boxes. */ +function forecastRowHeight(font: UiFont): number { + return Math.max(FORECAST_MIN_ROW_HEIGHT, tightRowHeight(font) + 3); +} + function formatAge(ageMs: number): string { const minutes = Math.max(0, Math.round(ageMs / 60_000)); if (minutes < 1) return "just now"; diff --git a/app/ui/dashboard/settings-panel.ts b/app/ui/dashboard/settings-panel.ts index ec006487..1dd957df 100644 --- a/app/ui/dashboard/settings-panel.ts +++ b/app/ui/dashboard/settings-panel.ts @@ -1,10 +1,10 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage, type UiFont } from "../../graphics/image"; import { wrapText } from "../../graphics/textwrap"; -import { clamp } from "../../util/numeric-util"; import { InputEvent } from "../gestures"; import { Layer, LayerContext, PaintBelow } from "../layers"; -import { drawSelectionHighlight, isMenuItemDisabled, MenuItem, MenuLayer, openModalMenu } from "../menu"; +import { isMenuItemDisabled, MenuItem, MenuLayer, openModalMenu } from "../menu"; +import { Menu } from "../menu-core"; import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../metrics"; import { shell } from "../shell/shell"; @@ -30,6 +30,10 @@ export type SettingsSection = { const PAD = 8; const LEFT_W = 150; +/** Gap between a row's selection box and the next row. */ +const ROW_GAP = 2; +/** Horizontal inset of row text (and custom row content) from its selection box. */ +const ROW_TEXT_X = 10; const MAX_DESCRIPTION_LINES = 3; // A throwaway menu to satisfy MenuItem.onSelect's second parameter; the // settings items never use it (they act via ctx only). @@ -45,23 +49,62 @@ export class SettingsPanelLayer implements Layer { // Watch swipes map onto the two columns: right goes into a section's // items, left comes back out (and out to the sidebar from the left column). readonly acceptsDirectional = true; - private leftIndex = 0; - private rightIndex = 0; private focus: "left" | "right" = "left"; - private leftScroll = 0; - private rightScroll = 0; + private readonly leftMenu: Menu; + /** The highlighted section's items; unselected while focus is in the left column (a preview). */ + private readonly rightMenu: Menu; + /** The context of the paint in progress, handed to item render callbacks. */ + private paintCtx: LayerContext | null = null; - constructor(private readonly sections: SettingsSection[]) {} + constructor(private readonly sections: SettingsSection[]) { + this.leftMenu = new Menu({ + items: sections, + wrap: true, + rowGap: ROW_GAP, + highlight: { radius: 6 }, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: ({ image, item, x, y, selected }) => { + image.drawText(getDefaultSmallFont(), x + ROW_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label, selected ? 255 : 200); + }, + }); + this.rightMenu = new Menu({ + items: this.section().items, + selectedIndex: null, + wrap: true, + rowGap: ROW_GAP, + highlight: { radius: 6 }, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: ({ image, item, x, y, width, height, selected }) => { + const disabled = isMenuItemDisabled(item); + if (item.render) { + item.render({ + image, + x: x + ROW_TEXT_X, + y, + width: width - ROW_TEXT_X - 8, + height: height - 1, + selected, + disabled, + text: item.label, + ctx: this.paintCtx!, + }); + } else { + image.drawText(getDefaultSmallFont(), x + ROW_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label, + disabled ? 70 : selected ? 255 : 200); + } + }, + }); + } private section(): SettingsSection { - return this.sections[clamp(this.leftIndex, 0, this.sections.length - 1)]!; + return this.leftMenu.selectedItem ?? this.sections[0]!; } /** Select a left-column section by label (deep link, e.g. from an app's menu). */ focusSection(label: string): void { const index = this.sections.findIndex((section) => section.label === label); if (index < 0) return; - this.leftIndex = index; + this.leftMenu.select(index); this.focus = "left"; this.resetRight(); } @@ -71,27 +114,16 @@ export class SettingsPanelLayer implements Layer { const { width, height } = ctx.stack.getBaseSize(); const image = new GrayImage(width, height, 0); const appFocused = ctx.stack.isFocused(); - - this.leftIndex = clamp(this.leftIndex, 0, this.sections.length - 1); const section = this.section(); const rightItems = section.items; - this.rightIndex = clamp(this.rightIndex, 0, Math.max(0, rightItems.length - 1)); + this.rightMenu.setItems(rightItems); - const rowH = listRowHeight(font); const top = PAD; const listBottom = height - PAD; // Left column: section labels. - const leftRows = Math.max(1, ((listBottom - top) / rowH) | 0); - this.leftScroll = clampScroll(this.leftIndex, this.leftScroll, leftRows, this.sections.length); - for (let i = this.leftScroll; i < Math.min(this.sections.length, this.leftScroll + leftRows); i++) { - const rowY = top + (i - this.leftScroll) * rowH; - const selected = i === this.leftIndex; - if (selected) { - drawSelectionHighlight(image, PAD - 2, rowY, LEFT_W, rowH - 2, appFocused && this.focus === "left", 6); - } - image.drawText(font, PAD + 8, rowY + LIST_ROW_TEXT_INSET, this.sections[i]!.label, selected ? 255 : 200); - } + this.leftMenu.paint(image, { x: PAD - 2, y: top, width: LEFT_W, height: listBottom - top }, + appFocused && this.focus === "left"); // Column divider (a light rule, not a full border). const divX = PAD + LEFT_W + 6; @@ -108,38 +140,15 @@ export class SettingsPanelLayer implements Layer { if (rightItems.length && rightTop < listBottom) { // Once focus is in the right column, the selected item's extended // description (when it has one) is drawn over the bottom of the pane by - // the companion SettingsDescriptionOverlayLayer. The row list keeps the - // full column height — rows the description band covers are drawn and - // partially occluded by the overlay's plane — but the scroll clamp uses - // the shrunk height so the selected row always stays clear of it. - const descriptionH = this.descriptionHeight(font, rightW); - const clampRows = Math.max(1, ((listBottom - descriptionH - rightTop) / rowH) | 0); - const rightRows = Math.max(1, ((listBottom - rightTop) / rowH) | 0); - this.rightScroll = clampScroll(this.rightIndex, this.rightScroll, clampRows, rightItems.length); - for (let i = this.rightScroll; i < Math.min(rightItems.length, this.rightScroll + rightRows); i++) { - const item = rightItems[i]!; - const rowY = rightTop + (i - this.rightScroll) * rowH; - // A selection only appears once focus is in the right column; before - // that the pane is a preview of what tapping would open. - const selected = this.focus === "right" && i === this.rightIndex; - const disabled = isMenuItemDisabled(item); - if (selected) { - drawSelectionHighlight(image, rightX - 2, rowY, rightW + 2, rowH - 2, appFocused, 6); - } - if (item.render) { - item.render({ - image, - x: rightX + 8, - y: rowY, - width: rightW - 16, - height: rowH - 3, - selected, - disabled, - text: item.label, - ctx, - }); - } else { - image.drawText(font, rightX + 8, rowY + LIST_ROW_TEXT_INSET, item.label, disabled ? 70 : selected ? 255 : 200); + // the companion SettingsDescriptionOverlayLayer. The list stops above + // that band, so the selected row always stays clear of it. + const listHeight = listBottom - this.descriptionHeight(font, rightW) - rightTop; + if (listHeight > 0) { + this.paintCtx = ctx; + try { + this.rightMenu.paint(image, { x: rightX - 2, y: rightTop, width: rightW + 2, height: listHeight }, appFocused); + } finally { + this.paintCtx = null; } } } @@ -150,8 +159,7 @@ export class SettingsPanelLayer implements Layer { /** The selected item's wrapped help text, or [] when none applies. */ private descriptionLines(font: UiFont, rightW: number): string[] { if (this.focus !== "right") return []; - const items = this.section().items; - const item = items[clamp(this.rightIndex, 0, Math.max(0, items.length - 1))]; + const item = this.rightMenu.selectedItem; if (!item?.description) return []; return wrapText(font, item.description, rightW - 4).slice(0, MAX_DESCRIPTION_LINES); } @@ -164,9 +172,8 @@ export class SettingsPanelLayer implements Layer { /** * Draw the selected item's help text band (separator + text on an opaque * background) at the bottom of the right column. Called by the companion - * overlay layer with the overlay's own canvas: as a separate plane its - * raster covers the row list's glyphs, so it can partially occlude a row — - * which raster drawn into the panel's own image cannot do. + * overlay layer with the overlay's own canvas, so the band stays above + * whatever the panel paints (including a section's detail content). */ paintDescriptionOverlay(image: GrayImage, ctx: LayerContext): void { const font = getDefaultSmallFont(); @@ -186,18 +193,15 @@ export class SettingsPanelLayer implements Layer { } async handleInput(event: InputEvent, ctx: LayerContext): Promise { + const scroll = scrollEventFor(event); if (this.focus === "left") { + if (scroll) { + const before = this.leftMenu.selectedIndex; + await this.leftMenu.handleInput(scroll); + if (this.leftMenu.selectedIndex !== before) this.resetRight(); + return; + } switch (event.type) { - case "scroll-up": - case "swipe-up": - this.leftIndex = (this.leftIndex + this.sections.length - 1) % this.sections.length; - this.resetRight(); - return; - case "scroll-down": - case "swipe-down": - this.leftIndex = (this.leftIndex + 1) % this.sections.length; - this.resetRight(); - return; case "click": case "swipe-right": // Only enter sections that have something interactive on the right. @@ -215,38 +219,42 @@ export class SettingsPanelLayer implements Layer { } } - const items = this.section().items; + if (scroll) { + await this.rightMenu.handleInput(scroll); + return; + } switch (event.type) { - case "scroll-up": - case "swipe-up": - if (items.length) this.rightIndex = (this.rightIndex + items.length - 1) % items.length; - return; - case "scroll-down": - case "swipe-down": - if (items.length) this.rightIndex = (this.rightIndex + 1) % items.length; - return; case "click": - case "swipe-right": - if (items.length) { - const item = items[clamp(this.rightIndex, 0, items.length - 1)]!; - if (!isMenuItemDisabled(item)) await item.onSelect(ctx, NO_MENU); - } + case "swipe-right": { + const item = this.rightMenu.selectedItem; + if (item && !isMenuItemDisabled(item)) await item.onSelect(ctx, NO_MENU); return; + } case "double-click": case "swipe-left": + // Back to a preview: the right column keeps its scroll but shows no selection. this.focus = "left"; + this.rightMenu.select(null); return; default: return; } } + /** Show the highlighted section's items from the top, selected on the first only when focus is there. */ private resetRight(): void { - this.rightIndex = 0; - this.rightScroll = 0; + this.rightMenu.setItems(this.section().items, this.focus === "right" ? 0 : null); + this.rightMenu.scrollTop = 0; } } +/** Scroll and watch swipe-up/down both move a column's selection. */ +function scrollEventFor(event: InputEvent): InputEvent | null { + if (event.type === "scroll-up" || event.type === "swipe-up") return { ...event, type: "scroll-up" } as InputEvent; + if (event.type === "scroll-down" || event.type === "swipe-down") return { ...event, type: "scroll-down" } as InputEvent; + return null; +} + /** * Companion layer for SettingsPanelLayer, sitting permanently above it in the * settings app's stack: paints the selected item's help text as its own plane @@ -276,12 +284,3 @@ export class SettingsDescriptionOverlayLayer implements Layer { export function openSettingsSubMenu(ctx: LayerContext, title: string, items: MenuItem[]): void { openModalMenu(ctx, title, items); } - -function clampScroll(selected: number, scroll: number, visible: number, count: number): number { - if (selected < scroll) { - scroll = selected; - } else if (selected >= scroll + visible) { - scroll = selected - visible + 1; - } - return clamp(scroll, 0, Math.max(0, count - visible)); -} diff --git a/app/ui/font-picker.ts b/app/ui/font-picker.ts index 70b113ca..ba06b1b6 100644 --- a/app/ui/font-picker.ts +++ b/app/ui/font-picker.ts @@ -23,7 +23,8 @@ import { type UiFontSelection, } from "../graphics/ui-fonts"; import { GESTURE_DOUBLE_CLICK, type InputEvent } from "./gestures"; -import { drawRightValueMenuItem, drawSelectionHighlight, openModalMenu, type MenuItem } from "./menu"; +import { drawRightValueMenuItem, openModalMenu, type MenuItem } from "./menu"; +import { Menu, type MenuDrawArgs } from "./menu-core"; import { LIST_ROW_TEXT_INSET, listRowHeight } from "./metrics"; import type { Layer, LayerContext } from "./layers"; @@ -62,7 +63,14 @@ type RowId = (typeof ROWS)[number]; export class FontPickerLayer implements Layer { private readonly families: FontFamily[]; private draft: Draft; - private selectedRow = 0; + private readonly menu = new Menu({ + items: ROWS, + wrap: true, + rowGap: 2, + highlight: { radius: 8 }, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: (args) => this.drawRow(args), + }); constructor(private readonly options: FontPickerOptions) { this.families = collectFamilies(options.monospaceOnly); @@ -111,26 +119,7 @@ export class FontPickerLayer implements Layer { const rowWidth = width - 2 * rowX; const rowHeight = listRowHeight(font); const rowsTop = 24 + font.lineHeight; - for (let index = 0; index < ROWS.length; index++) { - const row = ROWS[index]!; - const y = rowsTop + index * rowHeight; - const disabled = this.rowDisabled(row); - if (index === this.selectedRow) { - drawSelectionHighlight(image, rowX - 10, y, rowWidth + 20, rowHeight - 2, focused, 8); - } - if (row === "save") { - image.drawText(font, rowX, y + LIST_ROW_TEXT_INSET, "Save", index === this.selectedRow ? 255 : 200); - continue; - } - const label = row === "face" ? "Font" : row === "weight" ? "Weight" : "Size"; - const value = this.rowValue(row); - if (disabled) { - image.drawText(font, rowX, y + LIST_ROW_TEXT_INSET, label, 70); - image.drawText(font, rowX + rowWidth - font.measureText(value) - 2, y + LIST_ROW_TEXT_INSET, value, 70); - } else { - drawRightValueMenuItem(image, font, rowX, y, rowWidth, label, value); - } - } + this.menu.paint(image, { x: rowX - 10, y: rowsTop, width: rowWidth + 20, height: ROWS.length * rowHeight }, focused); // Preview: a separator, then the sample line in the draft font. const previewTop = rowsTop + ROWS.length * rowHeight + 10; @@ -145,6 +134,25 @@ export class FontPickerLayer implements Layer { return image; } + /** Row box = highlight box; text sits 10px in from its left edge and 10px from its right. */ + private drawRow({ image, item: row, x, y, width, selected }: MenuDrawArgs): void { + const font = getDefaultSmallFont(); + const textX = x + 10; + const textWidth = width - 20; + if (row === "save") { + image.drawText(font, textX, y + LIST_ROW_TEXT_INSET, "Save", selected ? 255 : 200); + return; + } + const label = row === "face" ? "Font" : row === "weight" ? "Weight" : "Size"; + const value = this.rowValue(row); + if (this.rowDisabled(row)) { + image.drawText(font, textX, y + LIST_ROW_TEXT_INSET, label, 70); + image.drawText(font, textX + textWidth - font.measureText(value) - 2, y + LIST_ROW_TEXT_INSET, value, 70); + } else { + drawRightValueMenuItem(image, font, textX, y, textWidth, label, value); + } + } + private rowDisabled(row: RowId): boolean { return (row === "weight" || row === "size") && this.draft.kind === "bitmap"; } @@ -165,14 +173,12 @@ export class FontPickerLayer implements Layer { handleInput(event: InputEvent, ctx: LayerContext): void { switch (event.type) { case "scroll-up": - this.selectedRow = (this.selectedRow + ROWS.length - 1) % ROWS.length; - return; case "scroll-down": - this.selectedRow = (this.selectedRow + 1) % ROWS.length; + void this.menu.handleInput(event); return; case "click": { - const row = ROWS[this.selectedRow]!; - if (this.rowDisabled(row)) return; + const row = this.menu.selectedItem; + if (!row || this.rowDisabled(row)) return; if (row === "face") this.openFaceMenu(ctx); else if (row === "weight") this.openWeightMenu(ctx); else if (row === "size") this.openSizeMenu(ctx); diff --git a/app/ui/menu-core.ts b/app/ui/menu-core.ts index 121ceb5d..108e07b3 100644 --- a/app/ui/menu-core.ts +++ b/app/ui/menu-core.ts @@ -80,15 +80,20 @@ type MenuLayout = { tops: number[]; heights: number[]; total: number }; export class Menu { private itemList: readonly T[]; private selected: number | null; + /** + * The caller asked for no selection. Otherwise a null selection only means + * nothing was selectable, and the first selectable item is chosen as soon + * as one exists (a menu created empty and filled later starts on it). + */ + private deselected: boolean; private scrollY = 0; private lastBox: MenuBox | null = null; private readonly motion = new MenuHighlightMotion(); constructor(private readonly options: MenuOptions) { this.itemList = options.items ?? []; - this.selected = options.selectedIndex === undefined - ? this.nextSelectable(null, 1) - : this.resolve(options.selectedIndex); + this.deselected = options.selectedIndex === null; + this.selected = this.settle(options.selectedIndex ?? null); } get items(): readonly T[] { @@ -110,6 +115,11 @@ export class Menu { return this.scrollY; } + /** Move the viewport's top edge; the next paint clamps it and scrolls the selection back into view. */ + set scrollTop(value: number) { + this.scrollY = Math.max(0, value | 0); + } + /** True when the content did not fit the box given to the last paint. */ get overflows(): boolean { if (!this.lastBox) return false; @@ -119,8 +129,8 @@ export class Menu { /** * Replace the items. `selectedIndex` names the new selection (null for * none); left out, the selection stays at the same index, clamped into - * range. The viewport keeps the selected row at the same on-screen - * position when it can. + * range, or lands on the first selectable item if there was none. The + * viewport keeps the selected row at the same on-screen position when it can. */ setItems(items: readonly T[], selectedIndex?: number | null): void { const width = this.lastBox?.width; @@ -128,15 +138,21 @@ export class Menu { ? this.layout(width).tops[this.selected]! - this.scrollY : null; this.itemList = items; - this.selected = this.resolve(selectedIndex === undefined ? this.selected : selectedIndex); + if (selectedIndex !== undefined) this.deselected = selectedIndex === null; + this.selected = this.settle(selectedIndex === undefined ? this.selected : selectedIndex); if (before !== null && this.selected !== null && width !== undefined) { this.scrollY = Math.max(0, this.layout(width).tops[this.selected]! - before); } } - /** Move the selection; a non-selectable or out-of-range index lands on the nearest selectable one. */ + /** + * Move the selection; a non-selectable or out-of-range index lands on the + * nearest selectable one. null clears it until the user scrolls or a + * number is selected. + */ select(index: number | null): void { - this.selected = this.resolve(index); + this.deselected = index === null; + this.selected = this.settle(index); } /** Step the selection by one selectable row; handles wrap and the exit callbacks. */ @@ -147,6 +163,7 @@ export class Menu { if (next !== null) { if (from !== null) this.motion.navigate(from, false); this.selected = next; + this.deselected = false; return; } if (from === null && this.scrollContent(delta)) return; @@ -155,6 +172,7 @@ export class Menu { if (wrapped !== null && wrapped !== from) { if (from !== null) this.motion.navigate(from, true); this.selected = wrapped; + this.deselected = false; } else if (from === null && this.lastBox) { this.scrollY = delta > 0 ? 0 : this.maxScroll(this.layout(this.lastBox.width), this.lastBox.height); } @@ -258,9 +276,15 @@ export class Menu { return null; } + /** Resolve a stored selection: null stays null only when the caller deselected. */ + private settle(index: number | null): number | null { + if (index === null) return this.deselected ? null : this.nextSelectable(null, 1); + return this.resolve(index); + } + /** Clamp an index into range and onto a selectable row (nearest below, else nearest above). */ - private resolve(index: number | null): number | null { - if (index === null || !this.itemList.length) return null; + private resolve(index: number): number | null { + if (!this.itemList.length) return null; const clamped = Math.max(0, Math.min(this.itemList.length - 1, index | 0)); if (this.isSelectable(clamped)) return clamped; return this.nextSelectable(clamped, 1) ?? this.nextSelectable(clamped, -1); @@ -268,7 +292,7 @@ export class Menu { /** Re-validate the selection against the current items (they may have been edited in place). */ private reconcile(): void { - this.selected = this.resolve(this.selected); + this.selected = this.settle(this.selected); } private layout(width: number): MenuLayout { @@ -312,6 +336,15 @@ export class Menu { } } } + // Never scroll past the end (setItems can leave the viewport there when + // rows are removed or inserted above the selection): pull back to the + // first row top that still shows the last row, so no partial row starts + // the list. The selected row stays visible, since it ends by the list's end. + const maxScroll = this.maxScroll(layout, viewportHeight); + if (target > maxScroll) { + const aligned = layout.tops.find((rowTop) => rowTop >= maxScroll); + target = aligned !== undefined && aligned <= target ? aligned : maxScroll; + } this.scrollY = Math.max(0, target); } diff --git a/app/ui/menu-highlight-motion.ts b/app/ui/menu-highlight-motion.ts index 8d63b91d..e7c09121 100644 --- a/app/ui/menu-highlight-motion.ts +++ b/app/ui/menu-highlight-motion.ts @@ -1,4 +1,4 @@ -export const MENU_HIGHLIGHT_DURATION_MS = 300; +export const MENU_HIGHLIGHT_DURATION_MS = 240; export type MenuHighlightAnimation = { dx: number; dy: number; startedAt: number; token: number; durationMs: number }; let nextToken = 1; diff --git a/app/ui/menu.ts b/app/ui/menu.ts index f3f4b8ad..39af0a14 100644 --- a/app/ui/menu.ts +++ b/app/ui/menu.ts @@ -6,7 +6,7 @@ import { Layer, LayerContext, PaintBelow } from "./layers"; import { Menu, MENU_HIGHLIGHT_FILL, MENU_HIGHLIGHT_STROKE } from "./menu-core"; import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures"; -import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight, menuTitleHeight } from "./metrics"; +import { LIST_ROW_TEXT_INSET, centeredTextY, lineStep, listRowHeight, menuTitleHeight } from "./metrics"; const DEFAULT_MENU_X = 8; const DEFAULT_MENU_Y = 8; const DEFAULT_MENU_WIDTH = 272; @@ -148,7 +148,7 @@ export function drawSubmenuIndicator( ): void { const arrow = ">"; const x = highlightX + highlightWidth - font.measureText(arrow) - 4; - const y = highlightY + (((highlightHeight - font.lineHeight) / 2) | 0); + const y = centeredTextY(font, highlightY, highlightHeight); image.drawText(font, x, y, arrow, value); } @@ -206,7 +206,7 @@ export class MenuLayer implements Layer { constructor( private readonly title: string | null, - private readonly items: MenuItem[], + private items: MenuItem[], private readonly layout: MenuLayout = { x: DEFAULT_MENU_X, y: DEFAULT_MENU_Y, @@ -248,6 +248,25 @@ export class MenuLayer implements Layer { return this; } + /** The selected row's index, or null when nothing is selectable. */ + get selectedIndex(): number | null { + return this.menu.selectedIndex; + } + + get selectedItem(): MenuItem | null { + return this.menu.selectedItem; + } + + /** + * Replace the rows in place, keeping scroll and highlight state. The + * selection follows Menu.setItems: pass the new index of the previously + * selected row, or leave it out to keep the same index, clamped. + */ + setItems(items: MenuItem[], selectedIndex?: number | null): void { + this.items = items; + this.menu.setItems(items, selectedIndex); + } + paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage { const font = getDefaultSmallFont(); const rowHeight = listRowHeight(font); diff --git a/app/ui/metrics.ts b/app/ui/metrics.ts index 4c99f4d6..3cdb2397 100644 --- a/app/ui/metrics.ts +++ b/app/ui/metrics.ts @@ -8,6 +8,8 @@ * * The formulas reproduce the pre-TTF constants exactly at the 12px default: * listRowHeight 20, tightRowHeight 16, lineStep 14, menuTitleHeight 16. + * tightRowHeight follows the measured ink rather than the line box, which + * for Terminus is the same thing. */ import type { UiFont } from "../graphics/image"; @@ -20,13 +22,71 @@ export function listRowHeight(font: UiFont): number { export const LIST_ROW_TEXT_INSET = 4; /** - * Height of one row in dense lists (file browser, track lists). Grows at - * half the lineHeight's rate above the 12px anchor: TTF line heights carry - * internal leading that already reads as row spacing, so full-rate growth - * made large-font rows feel too tall. + * Characters whose ink bounds a font's text rows: accented capitals (the + * highest Latin marks), descenders, brackets, and digits. + */ +const INK_SAMPLE = "ÅÉÎÖÇÑbdfhklgjpqy()[]{}|/_0123456789"; + +export type TextInkBounds = { + /** First inked row, relative to the drawText y (the line top); may be negative. */ + top: number; + /** One past the last inked row, relative to the line top; may exceed lineHeight. */ + bottom: number; +}; + +const inkBoundsCache = new WeakMap(); + +/** + * The vertical extent of a font's ink over a representative sample, measured + * from the rendered glyphs. Bitmap faces fill their line box exactly; TTF + * faces may leave internal leading inside it or overshoot it with marks. + * Falls back to the line box when the font renders no sample ink. + */ +export function textInkBounds(font: UiFont): TextInkBounds { + const cached = inkBoundsCache.get(font); + if (cached) return cached; + let top = Infinity; + let bottom = -Infinity; + if (typeof font.getGlyph === "function") { + for (const char of INK_SAMPLE) { + const glyph = font.getGlyph(char.codePointAt(0)!); + if (!glyph || glyph.bbxHeight <= 0) continue; + // Same placement as rasterizeGlyph: baseline at y + ascent, bbxY up from it. + const glyphTop = font.ascent - (glyph.bbxHeight + glyph.bbxY); + top = Math.min(top, glyphTop); + bottom = Math.max(bottom, glyphTop + glyph.bbxHeight); + } + } + const bounds = top < bottom ? { top, bottom } : { top: 0, bottom: font.lineHeight }; + inkBoundsCache.set(font, bounds); + return bounds; +} + +/** Height of a font's ink extent (see textInkBounds). */ +export function textInkHeight(font: UiFont): number { + const { top, bottom } = textInkBounds(font); + return bottom - top; +} + +/** + * The drawText y that centers a font's ink vertically in a box, rounding the + * spare pixel to the bottom. Pair with row heights derived from + * textInkHeight so the ink fits whatever the face's internal leading. + */ +export function centeredTextY(font: UiFont, boxTop: number, boxHeight: number): number { + const { top } = textInkBounds(font); + return boxTop + Math.floor((boxHeight - textInkHeight(font)) / 2) - top; +} + +/** + * Row pitch in dense lists (file browser, track lists): the font's ink height + * plus 4px, so a selection box one pixel shorter than the pitch keeps at + * least a pixel of clearance around the ink. Draw the text with + * centeredTextY; a fixed offset from the row top can overflow faces whose + * ink starts below their line top. */ export function tightRowHeight(font: UiFont): number { - return font.lineHeight + 4 - Math.floor(Math.max(0, font.lineHeight - 12) / 2); + return textInkHeight(font) + 4; } /** Step between consecutive lines of body/paragraph text. */ diff --git a/app/ui/notification-filter.ts b/app/ui/notification-filter.ts index 93bb9144..123f5d9e 100644 --- a/app/ui/notification-filter.ts +++ b/app/ui/notification-filter.ts @@ -7,35 +7,41 @@ import { type InputEvent } from "./gestures"; import { type Layer, type LayerContext, type PaintBelow } from "./layers"; import { drawToggleMenuItem, MenuLayer, type MenuItem } from "./menu"; -/** Rebuild rows when new sources arrive, keeping the current selection by package. */ +/** Refresh rows as new sources arrive, keeping the current selection by package. */ export class NotificationFilterLayer implements Layer { private menu: MenuLayer | null = null; - private packages = ""; - private selectedPackage = ""; + private menuWidth = 0; + /** The package behind each current row, parallel to the menu's items. */ + private packages: string[] = []; private currentMenu(ctx: LayerContext): MenuLayer { readActiveNotifications(ALL_NOTIFICATIONS); const sources = readNotificationSources().sort((a, b) => a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName)); - const signature = JSON.stringify([ctx.stack.getBaseSize().width, sources.map((source) => [source.packageName, source.appName])]); - if (!this.menu || signature !== this.packages) { - this.packages = signature; - const items: MenuItem[] = sources.map((source) => ({ - label: source.appName, - onSelect: () => setNotificationSourceEnabled(source, !shouldShowNotificationOnGlasses(source.packageName)), - render: ({ image, x, y, width, selected }) => { - if (selected) this.selectedPackage = source.packageName; - const font = getDefaultSmallFont(); - drawToggleMenuItem(image, font, x, y, width, truncateText(font, source.appName, width - 48), - shouldShowNotificationOnGlasses(source.packageName), selected); - }, - })); - if (!items.length) items.push({ label: "No notification sources discovered yet.", disabled: true, onSelect: () => {} }); + const items: MenuItem[] = sources.map((source) => ({ + label: source.appName, + onSelect: () => setNotificationSourceEnabled(source, !shouldShowNotificationOnGlasses(source.packageName)), + render: ({ image, x, y, width, selected }) => { + const font = getDefaultSmallFont(); + drawToggleMenuItem(image, font, x, y, width, truncateText(font, source.appName, width - 48), + shouldShowNotificationOnGlasses(source.packageName), selected); + }, + })); + if (!items.length) items.push({ label: "No notification sources discovered yet.", disabled: true, onSelect: () => {} }); + const selectedPackage = this.menu?.selectedIndex != null ? this.packages[this.menu.selectedIndex] : undefined; + const index = sources.findIndex((source) => source.packageName === selectedPackage); + this.packages = sources.map((source) => source.packageName); + + const width = ctx.stack.getBaseSize().width; + if (!this.menu || width !== this.menuWidth) { + this.menuWidth = width; this.menu = new MenuLayer("Notification filter", items, { - x: 8, y: 8, width: ctx.stack.getBaseSize().width - 16, + x: 8, y: 8, width: width - 16, opaque: true, showBorder: false, footer: "On = show popups on glasses", - }).selectItem(Math.max(0, sources.findIndex((source) => source.packageName === this.selectedPackage))); + }).selectItem(Math.max(0, index)); + } else { + this.menu.setItems(items, index >= 0 ? index : undefined); } return this.menu; } diff --git a/app/ui/notifications.ts b/app/ui/notifications.ts index 3b9ad386..e52adfaa 100644 --- a/app/ui/notifications.ts +++ b/app/ui/notifications.ts @@ -4,7 +4,7 @@ import { getDefaultSmallFont } from "../graphics/ui-fonts"; import { truncateText } from "../graphics/textwrap"; import { GrayImage, type UiFont } from "../graphics/image"; import { wrapText } from "../graphics/textwrap"; -import { lineStep, listRowHeight } from "./metrics"; +import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "./metrics"; import { ALL_NOTIFICATIONS, dismissNotification, @@ -19,7 +19,7 @@ import { notificationEmptyMessage } from "../native/notification-access"; import { noteStaleDataUsed, renderPassAllowsStaleData } from "../util/render-freshness"; import { type InputEvent } from "./gestures"; import { type Layer, type LayerContext, type PaintBelow } from "./layers"; -import { MenuLayer } from "./menu"; +import { Menu, type MenuBox } from "./menu-core"; const PAGE_X = 12; const PAGE_Y = 12; @@ -35,7 +35,19 @@ const CARD_GAP = 6; const MAX_NOTIFICATIONS = 50; // Right-hand action menu of the detail view. const DETAIL_MENU_WIDTH = 148; +/** Top of the action menu's first row box, and the space kept below its last. */ +const DETAIL_MENU_TOP = 22; +const DETAIL_MENU_BOTTOM_MARGIN = 17; +const DETAIL_MENU_ROW_GAP = 3; +/** Row text inset from the row box: horizontal, then vertical. */ +const DETAIL_MENU_TEXT_X = 8; +const DETAIL_MENU_TEXT_Y = 4; const DETAIL_CONTENT_X = 24; +// Disable-source confirmation: actions on top, the explanation below them. +const CONFIRM_X = 24; +const CONFIRM_Y = 8; +const CONFIRM_TEXT_X = 10; +const CONFIRM_PROMPT_GAP = 16; /** Icon for a paint pass: allow-stale, reporting staleness to the render loop. */ function iconForNotification(key: string): GrayImage | null { @@ -58,6 +70,8 @@ type DetailMenuItem = | { kind: "dismiss"; label: string } | { kind: "disable-source"; label: string }; +type ConfirmationItem = { label: string; run: (ctx: LayerContext) => void }; + export type SingleNotificationLayerOrigin = "notifications-list" | "new-notification-modal"; type SingleNotificationLayerOptions = { @@ -168,8 +182,24 @@ export class NotificationsListLayer implements Layer { * new-notification modal. */ export class SingleNotificationLayer implements Layer { - private selectedMenuIndex = 0; - private confirmation: { source: AndroidNotification; menu: MenuLayer } | null = null; + /** The action column; its items are rebuilt from the live notification on every paint and input. */ + private readonly detailMenu = new Menu({ + wrap: false, + rowGap: DETAIL_MENU_ROW_GAP, + highlight: { radius: 6 }, + getHeight: (item, width) => { + const font = getDefaultSmallFont(); + return detailMenuRowLines(font, item, width).length * lineStep(font) + 8; + }, + draw: ({ image, item, x, y, width, selected }) => { + const font = getDefaultSmallFont(); + const lines = detailMenuRowLines(font, item, width); + for (let line = 0; line < lines.length; line++) { + image.drawText(font, x + DETAIL_MENU_TEXT_X, y + DETAIL_MENU_TEXT_Y + line * lineStep(font), lines[line]!, selected ? 255 : 185); + } + }, + }); + private confirmation: { source: AndroidNotification; menu: Menu } | null = null; constructor( private readonly notificationKey: string, @@ -187,17 +217,18 @@ export class SingleNotificationLayer implements Layer { return this.closeUnavailableNotification(ctx, paintBelow); } - const menu = buildDetailMenu(notification, this.options.origin); - this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, Math.max(0, menu.length - 1)); + this.detailMenu.setItems(buildDetailMenu(notification, this.options.origin)); drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height); - drawDetailMenu(image, font, menu, this.selectedMenuIndex, width); + this.detailMenu.paint(image, detailMenuBox(width, height), ctx.stack.isFocused()); return image; } async handleInput(event: InputEvent, ctx: LayerContext): Promise { if (this.confirmation) { + const { menu } = this.confirmation; if (event.type === "double-click") this.close(ctx); - else await this.confirmation.menu.handleInput(event, ctx); + else if (event.type === "click") menu.selectedItem?.run(ctx); + else await menu.handleInput(event); return; } const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey); @@ -205,24 +236,21 @@ export class SingleNotificationLayer implements Layer { this.closeUnavailableNotification(ctx); return; } - const menu = buildDetailMenu(notification, this.options.origin); - this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, menu.length - 1); + this.detailMenu.setItems(buildDetailMenu(notification, this.options.origin)); if (event.type === "double-click") { this.close(ctx); return; } - if (event.type === "scroll-up") { - this.selectedMenuIndex = Math.max(0, this.selectedMenuIndex - 1); - return; - } - if (event.type === "scroll-down") { - this.selectedMenuIndex = Math.min(menu.length - 1, this.selectedMenuIndex + 1); + if (event.type === "scroll-up" || event.type === "scroll-down") { + await this.detailMenu.handleInput(event); return; } if (event.type !== "click") return; - const item = menu[this.selectedMenuIndex]!; + // "(unavailable)" actions stay clickable: Android decides whether they do anything. + const item = this.detailMenu.selectedItem; + if (!item) return; if (item.kind === "back") { this.close(ctx); } else if (item.kind === "action") { @@ -237,13 +265,21 @@ export class SingleNotificationLayer implements Layer { // Keep the modal alive for confirmation even after Android removes the notification. this.confirmation = { source: notification, - menu: new MenuLayer(null, [ - { label: "Cancel", onSelect: () => this.close(ctx) }, - { label: "Turn off popups", onSelect: () => { - setNotificationSourceEnabled(notification, false); - this.close(ctx); - } }, - ], { x: 12, y: 0, width: ctx.stack.getBaseSize().width - 24, minHeight: 0, showBorder: false }), + menu: new Menu({ + items: [ + { label: "Cancel", run: (runCtx) => this.close(runCtx) }, + { label: "Turn off popups", run: (runCtx) => { + setNotificationSourceEnabled(notification, false); + this.close(runCtx); + } }, + ], + wrap: true, + rowGap: 1, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: ({ image, item, x, y, selected }) => { + image.drawText(getDefaultSmallFont(), x + CONFIRM_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label, selected ? 255 : 200); + }, + }), }; dismissNotification(this.notificationKey); } @@ -255,15 +291,21 @@ export class SingleNotificationLayer implements Layer { const { width, height } = ctx.stack.getBaseSize(); const image = new GrayImage(width, height, 0); // Put actions first so they remain reachable even with a large UI font. - menu.paint(ctx, () => image); - const top = 24 + 2 * listRowHeight(font); + const menuBox: MenuBox = { + x: CONFIRM_X, + y: CONFIRM_Y, + width: width - 2 * CONFIRM_X, + height: Math.min(menu.items.length * listRowHeight(font), height - CONFIRM_Y), + }; + menu.paint(image, menuBox, ctx.stack.isFocused()); + const top = menuBox.y + menuBox.height + CONFIRM_PROMPT_GAP; const prompt = `Turn off notification popups from ${source.appName || source.packageName}? You can turn them back on in the Notifications app's Notification filter.`; - const lines = wrapText(font, prompt, width - 48); + const lines = wrapText(font, prompt, width - 2 * CONFIRM_X); const maxLines = Math.max(1, Math.floor((height - top - 12) / lineStep(font))); for (let index = 0; index < Math.min(lines.length, maxLines); index++) { const text = index === maxLines - 1 && lines.length > maxLines - ? truncateText(font, lines[index] + "...", width - 48) : lines[index]!; - image.drawText(font, 24, top + index * lineStep(font), text, 210); + ? truncateText(font, lines[index] + "...", width - 2 * CONFIRM_X) : lines[index]!; + image.drawText(font, CONFIRM_X, top + index * lineStep(font), text, 210); } return image; } @@ -404,35 +446,20 @@ function drawDetailContent( } } -function drawDetailMenu(image: GrayImage, font: UiFont, menu: DetailMenuItem[], selectedIndex: number, width: number): void { - const menuX = width - DETAIL_MENU_WIDTH - 24; - const menuY = 24; - const rows = menu.map((item) => { - const lines = item.kind === "disable-source" - ? wrapText(font, item.label, DETAIL_MENU_WIDTH - 16) - : [truncateText(font, item.label, DETAIL_MENU_WIDTH - 16)]; - return { lines, height: lines.length * lineStep(font) + 8 }; - }); - const selectedBottom = rows.slice(0, selectedIndex + 1).reduce((sum, row) => sum + row.height, 0); - const scrollY = Math.max(0, selectedBottom - (image.height - menuY - 12)); - let y = menuY - scrollY; - for (let index = 0; index < menu.length; index++) { - const row = rows[index]!; - if (y < menuY) { - y += row.height; - continue; - } - if (y + row.height > image.height - 12) break; - const selected = index === selectedIndex; - if (selected) { - image.fillRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, row.height - 3, 18, 6); - image.drawRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, row.height - 3, 60, 6); - } - for (let line = 0; line < row.lines.length; line++) { - image.drawText(font, menuX, y + 2 + line * lineStep(font), row.lines[line]!, selected ? 255 : 185); - } - y += row.height; - } +/** The action column's row boxes: right of the content, from DETAIL_MENU_TOP to the bottom margin. */ +function detailMenuBox(width: number, height: number): MenuBox { + return { + x: width - DETAIL_MENU_WIDTH - 32, + y: DETAIL_MENU_TOP, + width: DETAIL_MENU_WIDTH, + height: height - DETAIL_MENU_TOP - DETAIL_MENU_BOTTOM_MARGIN, + }; +} + +/** An action row's text lines: the disable-source row wraps, the rest truncate to one line. */ +function detailMenuRowLines(font: UiFont, item: DetailMenuItem, rowWidth: number): string[] { + const textWidth = rowWidth - 2 * DETAIL_MENU_TEXT_X; + return item.kind === "disable-source" ? wrapText(font, item.label, textWidth) : [truncateText(font, item.label, textWidth)]; } function buildDetailMenu(notification: AndroidNotification, origin: SingleNotificationLayerOrigin): DetailMenuItem[] { diff --git a/app/ui/shell/assistant.ts b/app/ui/shell/assistant.ts index 05f5b0ec..1df039d7 100644 --- a/app/ui/shell/assistant.ts +++ b/app/ui/shell/assistant.ts @@ -1,26 +1,13 @@ -import { G2_LENS_WIDTH, GrayImage } from "../../graphics/image"; -import { type BdfFont } from "../../graphics/bdffont"; -import { getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { type GrayImage } from "../../graphics/image"; import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../gestures"; -import { drawSelectionHighlight } from "../menu"; -import { listRowHeight } from "../metrics"; import { Layer, type LayerActions, type LayerContext } from "../layers"; -import { wrapText, truncateText } from "../../graphics/textwrap"; -import { MIN_WINDOW_HEIGHT, minWindowTop } from "./geometry"; +import { createInputDialogMenu, paintInputDialog, type InputDialogRow } from "./input-dialog"; -const DIALOG_X = 40; -const DIALOG_W = G2_LENS_WIDTH - 80; -// The dialog fits inside the min-height window band (like the other shell -// overlays), wherever the vertical position setting puts it. -const DIALOG_MARGIN_Y = 28; -const DIALOG_H = MIN_WINDOW_HEIGHT - 2 * DIALOG_MARGIN_Y; -const TEXT_MAX_WIDTH = DIALOG_W - 32; -const MENU_ROWS = 2; - -/** Dialog top edge; band-relative, so computed per paint. */ -function dialogY(): number { - return minWindowTop() + DIALOG_MARGIN_Y; -} +const FOLLOW_UP_ROW = 0; +const MENU_ROWS: readonly InputDialogRow[] = [ + { label: "Follow-up", dim: false }, + { label: "Done", dim: false }, +]; /** thinking: turn running; done/error: finished, showing the Follow-up/Done menu. */ type AssistantPhase = "thinking" | "done" | "error"; @@ -46,7 +33,7 @@ export class AssistantLayer implements Layer { private phase: AssistantPhase = "thinking"; private replyText = ""; private status = "Thinking..."; - private menuIndex = 0; + private readonly menu = createInputDialogMenu(MENU_ROWS); constructor( private readonly actions: LayerActions, @@ -58,7 +45,7 @@ export class AssistantLayer implements Layer { this.phase = "thinking"; this.replyText = ""; this.status = "Thinking..."; - this.menuIndex = 0; + this.menu.select(0); this.actions.requestRender(); } @@ -76,61 +63,28 @@ export class AssistantLayer implements Layer { onTurnDone(): void { this.phase = "done"; this.status = this.replyText.trim() ? "" : "(no reply)"; - this.menuIndex = 0; + this.menu.select(0); this.actions.requestRender(); } onError(message: string): void { this.phase = "error"; this.status = message; - this.menuIndex = 0; + this.menu.select(0); this.actions.requestRender(); } paint(_ctx: LayerContext, paintBelow: () => GrayImage): GrayImage { - const font = getDefaultSmallFont(); - const menuRowH = listRowHeight(font); const image = paintBelow(); - const top = dialogY(); - - // Solid dialog box (fill 1, matching the voice dialog: opaque after 4bpp - // quantization, but not the color-key transparent 0). - image.fillRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 1); - image.drawRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 90); - - const left = DIALOG_X + 16; - image.drawText(font, left, top + 12, this.phase === "thinking" ? "Assistant ●" : "Assistant", 220); - if (this.status) { - const statusValue = this.phase === "error" ? 200 : 130; - image.drawText(font, left, top + 30, truncateText(font, this.status, TEXT_MAX_WIDTH), statusValue); - } - const inMenu = this.phase !== "thinking"; - const textBottom = inMenu ? top + DIALOG_H - MENU_ROWS * menuRowH - 8 : top + DIALOG_H - 8; - const textTop = top + 56; - const maxLines = Math.max(1, ((textBottom - textTop) / 16) | 0); - - const wrapped = wrapText(font, this.replyText, TEXT_MAX_WIDTH); - // Keep the tail visible as text streams past the bottom. - const firstLine = Math.max(0, wrapped.length - maxLines); - for (let index = firstLine; index < wrapped.length; index++) { - image.drawText(font, left, textTop + (index - firstLine) * 16, wrapped[index]!, 235); - } - - if (inMenu) { - const rows = ["Follow-up", "Done"]; - const menuTop = top + DIALOG_H - MENU_ROWS * menuRowH - 2; - for (let i = 0; i < rows.length; i++) { - const rowY = menuTop + i * menuRowH; - const selected = i === this.menuIndex; - if (selected) { - drawSelectionHighlight(image, left - 4, rowY - 2, DIALOG_W - 24, menuRowH - 2, true, 6); - } - image.drawText(font, left + 4, rowY + 2, rows[i]!, selected ? 255 : 200); - } - } else { - image.drawText(font, left, top + DIALOG_H - 14, `${GESTURE_DOUBLE_CLICK} cancel`, 110 - font.lineHeight); - } + paintInputDialog(image, { + title: this.phase === "thinking" ? "Assistant ●" : "Assistant", + status: this.status, + statusValue: this.phase === "error" ? 200 : 130, + text: this.replyText, + menu: inMenu ? this.menu : null, + hint: inMenu ? undefined : `${GESTURE_DOUBLE_CLICK} cancel`, + }); return image; } @@ -140,7 +94,7 @@ export class AssistantLayer implements Layer { this.callbacks.onCancel(); this.phase = "done"; this.status = "Cancelled"; - this.menuIndex = 0; + this.menu.select(0); this.actions.requestRender(); } return; @@ -148,15 +102,12 @@ export class AssistantLayer implements Layer { // done / error: the Follow-up / Done menu. switch (event.type) { case "scroll-up": - this.menuIndex = (this.menuIndex + MENU_ROWS - 1) % MENU_ROWS; - this.actions.requestRender(); - return; case "scroll-down": - this.menuIndex = (this.menuIndex + 1) % MENU_ROWS; + void this.menu.handleInput(event); this.actions.requestRender(); return; case "click": - if (this.menuIndex === 0) { + if (this.menu.selectedIndex === FOLLOW_UP_ROW) { this.callbacks.onFollowUp(); } else { this.callbacks.onClose(); diff --git a/app/ui/shell/input-dialog.ts b/app/ui/shell/input-dialog.ts index 17d89fed..ef4956c2 100644 --- a/app/ui/shell/input-dialog.ts +++ b/app/ui/shell/input-dialog.ts @@ -1,13 +1,13 @@ import { G2_LENS_WIDTH, type GrayImage } from "../../graphics/image"; import { wrapText, truncateText } from "../../graphics/textwrap"; import { getDefaultSmallFont } from "../../graphics/ui-fonts"; -import { drawSelectionHighlight } from "../menu"; +import { Menu, type MenuDrawArgs } from "../menu-core"; import { listRowHeight } from "../metrics"; import { MIN_WINDOW_HEIGHT, minWindowTop } from "./geometry"; /** - * The shared look of the shell's text-entry dialogs (voice input and phone - * keyboard input): a solid box over whatever is on screen with a title line, + * The shared look of the shell's text dialogs (voice input, phone keyboard + * input, and the assistant's reply): a solid box over whatever is on screen with a title line, * a status line, the message so far, and either a menu of destinations at * the bottom or a gesture hint. */ @@ -19,6 +19,14 @@ const DIALOG_W = G2_LENS_WIDTH - 80; const DIALOG_MARGIN_Y = 28; const DIALOG_H = MIN_WINDOW_HEIGHT - 2 * DIALOG_MARGIN_Y; const TEXT_MAX_WIDTH = DIALOG_W - 32; +const TEXT_LEFT = DIALOG_X + 16; +// Menu row boxes: 4px left of the text column, 2px shorter than the row +// pitch, with each row's label inset 8px / 4px into its box. +const MENU_X = TEXT_LEFT - 4; +const MENU_W = DIALOG_W - 24; +const MENU_ROW_GAP = 2; +const MENU_LABEL_INSET_X = 8; +const MENU_LABEL_INSET_Y = 4; /** Dialog top edge; band-relative, so computed per paint. */ function dialogY(): number { @@ -31,20 +39,47 @@ export type InputDialogRow = { dim: boolean; }; -export type InputDialogContent = { +export type InputDialogContent = { title: string; status: string; + /** Gray level of the status line. Default 130. */ + statusValue?: number; /** The message body (a placeholder when nothing has been captured yet). */ text: string; - /** Menu rows along the bottom edge; empty for no menu. */ - rows: readonly InputDialogRow[]; - selectedRow: number; + /** + * Menu along the bottom edge (see createInputDialogMenu), or null for none. + * Height is reserved for every item. + */ + menu: Menu | null; /** Gesture hint drawn along the bottom edge when there is no menu. */ hint?: string; }; +/** + * A wrapping menu of dialog rows, laid out and drawn the way paintInputDialog + * expects. The owning layer keeps it across paints (so the selection sticks), + * refreshes its rows with setItems, forwards scroll events to it, and hands + * it to paintInputDialog while the menu is showing. + */ +export function createInputDialogMenu(items: readonly T[] = [], selectedIndex = 0): Menu { + return new Menu({ + items, + selectedIndex, + wrap: true, + rowGap: MENU_ROW_GAP, + highlight: { radius: 6 }, + getHeight: () => listRowHeight(getDefaultSmallFont()), + draw: drawMenuRow, + }); +} + +function drawMenuRow({ image, item, x, y, selected }: MenuDrawArgs): void { + const value = item.dim ? 90 : selected ? 255 : 200; + image.drawText(getDefaultSmallFont(), x + MENU_LABEL_INSET_X, y + MENU_LABEL_INSET_Y, item.label, value); +} + /** Paint the dialog onto `image` (an already-painted canvas of the layers below). */ -export function paintInputDialog(image: GrayImage, content: InputDialogContent): void { +export function paintInputDialog(image: GrayImage, content: InputDialogContent): void { const font = getDefaultSmallFont(); const menuRowH = listRowHeight(font); const top = dialogY(); @@ -54,14 +89,14 @@ export function paintInputDialog(image: GrayImage, content: InputDialogContent): image.fillRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 1); image.drawRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 90); - const left = DIALOG_X + 16; + const left = TEXT_LEFT; image.drawText(font, left, top + 12, content.title, 220); - image.drawText(font, left, top + 30, truncateText(font, content.status, TEXT_MAX_WIDTH), 130); + image.drawText(font, left, top + 30, truncateText(font, content.status, TEXT_MAX_WIDTH), content.statusValue ?? 130); - const rows = content.rows; - const hasMenu = rows.length > 0; + const menu = content.menu; + const rowCount = menu?.items.length ?? 0; // Reserve space for the actual number of rows this menu has. - const textBottom = hasMenu ? top + DIALOG_H - rows.length * menuRowH - 8 : top + DIALOG_H - 8; + const textBottom = rowCount > 0 ? top + DIALOG_H - rowCount * menuRowH - 8 : top + DIALOG_H - 8; const textTop = top + 56; const maxLines = Math.max(1, ((textBottom - textTop) / 16) | 0); @@ -73,17 +108,10 @@ export function paintInputDialog(image: GrayImage, content: InputDialogContent): image.drawText(font, left, textTop + (index - firstLine) * 16, wrapped[index]!, 235); } - if (hasMenu) { - const menuTop = top + DIALOG_H - rows.length * menuRowH - 2; - for (let i = 0; i < rows.length; i++) { - const rowY = menuTop + i * menuRowH; - const selected = i === content.selectedRow; - if (selected) { - drawSelectionHighlight(image, left - 4, rowY - 2, DIALOG_W - 24, menuRowH - 2, true, 6); - } - const row = rows[i]!; - image.drawText(font, left + 4, rowY + 2, row.label, row.dim ? 90 : selected ? 255 : 200); - } + if (menu && rowCount > 0) { + // Row boxes are one pitch apart, the last ending 6px above the dialog's bottom edge. + const menuTop = top + DIALOG_H - rowCount * menuRowH - 4; + menu.paint(image, { x: MENU_X, y: menuTop, width: MENU_W, height: rowCount * menuRowH - MENU_ROW_GAP }, true); } else if (content.hint) { image.drawText(font, left, top + DIALOG_H - 14, content.hint, 110 - font.lineHeight); } diff --git a/app/ui/shell/keyboard-input.ts b/app/ui/shell/keyboard-input.ts index 22f51014..b8952070 100644 --- a/app/ui/shell/keyboard-input.ts +++ b/app/ui/shell/keyboard-input.ts @@ -1,9 +1,13 @@ import { type GrayImage } from "../../graphics/image"; import { type InputEvent } from "../gestures"; import { Layer, type LayerActions, type LayerContext } from "../layers"; -import { paintInputDialog } from "./input-dialog"; +import { type Menu } from "../menu-core"; +import { createInputDialogMenu, paintInputDialog, type InputDialogRow } from "./input-dialog"; import { type VoiceSendTarget } from "./voice-input"; +/** A menu row: a send target, or Discard (no target). */ +type KeyboardMenuRow = InputDialogRow & { target?: VoiceSendTarget }; + /** * The phone side's handle on an open keyboard-input dialog: the phone types * into it and picks where the text goes. The layer itself implements this; @@ -46,7 +50,7 @@ export type KeyboardInputLayerOptions = { */ export class KeyboardInputLayer implements Layer, KeyboardInputSession { private text = ""; - private menuIndex: number; + private readonly menu: Menu; private closed = false; private readonly actions: LayerActions; @@ -62,7 +66,7 @@ export class KeyboardInputLayer implements Layer, KeyboardInputSession { this.sendTargets = options.sendTargets; const defaultIndex = options.defaultTargetIndex ?? 0; this.defaultTargetIndex = Math.min(Math.max(0, defaultIndex), Math.max(0, this.sendTargets.length - 1)); - this.menuIndex = this.defaultTargetIndex; + this.menu = createInputDialogMenu(this.menuRows(), this.defaultTargetIndex); } get targets(): ReadonlyArray<{ id: string; label: string }> { @@ -76,8 +80,7 @@ export class KeyboardInputLayer implements Layer, KeyboardInputSession { } send(): void { - const row = this.menuRows()[this.menuIndex]; - const target = row?.target ?? this.sendTargets[this.defaultTargetIndex]; + const target = this.menu.selectedItem?.target ?? this.sendTargets[this.defaultTargetIndex]; if (target) this.sendToTarget(target); } @@ -101,9 +104,9 @@ export class KeyboardInputLayer implements Layer, KeyboardInputSession { } /** The menu rows: one per send target, then Discard. */ - private menuRows(): Array<{ label: string; dim: boolean; target?: VoiceSendTarget }> { + private menuRows(): KeyboardMenuRow[] { const hasText = this.text.trim().length > 0; - const rows: Array<{ label: string; dim: boolean; target?: VoiceSendTarget }> = []; + const rows: KeyboardMenuRow[] = []; for (const target of this.sendTargets) { rows.push({ label: target.label, dim: !hasText, target }); } @@ -113,29 +116,26 @@ export class KeyboardInputLayer implements Layer, KeyboardInputSession { paint(_ctx: LayerContext, paintBelow: () => GrayImage): GrayImage { const image = paintBelow(); + this.menu.setItems(this.menuRows()); paintInputDialog(image, { title: "Keyboard", status: "Type on the phone", text: this.text || "(nothing typed yet)", - rows: this.menuRows(), - selectedRow: this.menuIndex, + menu: this.menu, }); return image; } handleInput(event: InputEvent, _ctx: LayerContext): void { - const rowCount = this.menuRows().length; + this.menu.setItems(this.menuRows()); switch (event.type) { case "scroll-up": - this.menuIndex = (this.menuIndex + rowCount - 1) % rowCount; - this.actions.requestRender(); - return; case "scroll-down": - this.menuIndex = (this.menuIndex + 1) % rowCount; + void this.menu.handleInput(event); this.actions.requestRender(); return; case "click": { - const row = this.menuRows()[this.menuIndex]; + const row = this.menu.selectedItem; if (!row) return; if (row.target) { this.sendToTarget(row.target); diff --git a/app/ui/shell/voice-input.ts b/app/ui/shell/voice-input.ts index 2e8832fe..e96bc8ee 100644 --- a/app/ui/shell/voice-input.ts +++ b/app/ui/shell/voice-input.ts @@ -4,7 +4,8 @@ import { refineDictation, type AnthropicStreamHandle } from "../../native/anthro import { anthropicApiKeySetting } from "../dashboard-settings"; import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, gestureHints, type InputEvent } from "../gestures"; import { Layer, type LayerActions, type LayerContext } from "../layers"; -import { paintInputDialog } from "./input-dialog"; +import { type Menu } from "../menu-core"; +import { createInputDialogMenu, paintInputDialog, type InputDialogRow } from "./input-dialog"; // After native recognition finishes, a cloud final can still trail in. const FOLLOWUP_FINALIZE_TIMEOUT_MS = 1200; @@ -16,6 +17,9 @@ const FOLLOWUP_FINALIZE_TIMEOUT_MS = 1200; */ type VoicePhase = "capturing" | "menu" | "continuing" | "refining"; +/** A menu row; dim rows still take clicks, and onSelect decides what they do. */ +type VoiceMenuRow = InputDialogRow & { onSelect: () => void }; + /** * A destination the captured text can be sent to. The shell supplies these per * entry point: "Send to Assistant" (hand off to the voice assistant) and/or @@ -84,7 +88,8 @@ export class VoiceInputLayer implements Layer { private stopGeneration = 0; private acceptingTranscript = true; private refineHandle: AnthropicStreamHandle | null = null; - private menuIndex = 0; + /** The send / Continue / Discard menu; its rows are rebuilt on every paint and input. */ + private readonly menu: Menu; /** Auto-send (wakeword skip-confirmation) is waiting to fire. */ private pendingAutoSend = false; private autoSendTimer: ReturnType | null = null; @@ -111,7 +116,7 @@ export class VoiceInputLayer implements Layer { this.autoSend = options.autoSend ?? false; const defaultIndex = options.defaultTargetIndex ?? 0; this.defaultTargetIndex = Math.min(Math.max(0, defaultIndex), Math.max(0, this.sendTargets.length - 1)); - this.menuIndex = this.defaultTargetIndex; + this.menu = createInputDialogMenu(this.menuRows(), this.defaultTargetIndex); } startCapture(): void { @@ -221,11 +226,11 @@ export class VoiceInputLayer implements Layer { } /** The menu rows: one per send target, then Continue, then Discard. */ - private menuRows(): Array<{ label: string; dim: boolean; onSelect: () => void }> { + private menuRows(): VoiceMenuRow[] { const text = this.displayText().trim(); const hasText = text.length > 0 && !this.stoppingCapture; const hasLlmKey = anthropicApiKeySetting.get().trim().length > 0; - const rows: Array<{ label: string; dim: boolean; onSelect: () => void }> = []; + const rows: VoiceMenuRow[] = []; for (const target of this.sendTargets) { rows.push({ label: target.label, @@ -251,12 +256,12 @@ export class VoiceInputLayer implements Layer { paint(_ctx: LayerContext, paintBelow: () => GrayImage): GrayImage { const image = paintBelow(); const inMenu = this.phase === "menu"; + if (inMenu) this.menu.setItems(this.menuRows()); paintInputDialog(image, { title: this.capturing && this.listening ? "Voice ●" : "Voice", status: this.stoppingCapture ? "Finishing transcription..." : this.status, text: this.displayText() || this.placeholderText(), - rows: inMenu ? this.menuRows() : [], - selectedRow: this.menuIndex, + menu: inMenu ? this.menu : null, hint: inMenu ? undefined : this.hintText(), }); return image; @@ -290,21 +295,16 @@ export class VoiceInputLayer implements Layer { } private handleMenuInput(event: InputEvent): void { - const rowCount = this.menuRows().length; + this.menu.setItems(this.menuRows()); switch (event.type) { case "scroll-up": - this.menuIndex = (this.menuIndex + rowCount - 1) % rowCount; - this.actions.requestRender(); - return; case "scroll-down": - this.menuIndex = (this.menuIndex + 1) % rowCount; + void this.menu.handleInput(event); this.actions.requestRender(); return; - case "click": { - const row = this.menuRows()[this.menuIndex]; - row?.onSelect(); + case "click": + this.menu.selectedItem?.onSelect(); return; - } case "double-click": this.dismiss(); return; @@ -397,7 +397,7 @@ export class VoiceInputLayer implements Layer { this.finalizedText = text; this.liveText = ""; this.phase = "menu"; - this.menuIndex = 0; + this.menu.select(0); this.status = status; this.actions.requestRender(); } diff --git a/tests/evenhub-install-performance.test.cjs b/tests/evenhub-install-performance.test.cjs index 7422183e..c01e53e0 100644 --- a/tests/evenhub-install-performance.test.cjs +++ b/tests/evenhub-install-performance.test.cjs @@ -44,7 +44,7 @@ test('store install releases serialized input before download and permission app const download = new Promise(resolve => { completeDownload = resolve; }); const manifest = { name: 'Test', packageId: 'test', permissions: [{ name: 'network' }], privacyPolicyUrl: '' }; const load = loader({}, { - '../../graphics/ui-fonts': {}, '../../graphics/image': {}, '../../graphics/textwrap': {}, '../../ui/menu': {}, '../files/text-viewer': {}, '../../ui/metrics': {}, + '../../graphics/ui-fonts': {}, '../../graphics/image': {}, '../../graphics/textwrap': {}, '../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'), '../files/text-viewer': {}, '../../ui/metrics': {}, './even-api': { evenHubApi: { getStoreAppDetail: async () => null, downloadApp: () => download } }, './installed-apps': { getInstalledEvenHubApp: () => null, readEvenHubPackageManifestBytes: () => manifest, readEvenHubPackageManifest: () => null, installedEvenHubPackagePath: () => '', installedEvenHubAppId: id => id, diff --git a/tests/evenhub-signin.test.cjs b/tests/evenhub-signin.test.cjs index 6350a6fe..55b19801 100644 --- a/tests/evenhub-signin.test.cjs +++ b/tests/evenhub-signin.test.cjs @@ -26,7 +26,8 @@ const loadStoreLayer = () => { '../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => [text] }, '../../util/numeric-util': { clamp: (v, lo, hi) => Math.min(hi, Math.max(lo, v)) }, '../../ui/gestures': { GESTURE_CLICK: 'click' }, - '../../ui/menu': { drawListScrollbar() {}, drawSelectionHighlight() {}, scrollToKeepSelectionVisible() {} }, + '../../ui/menu': { drawSelectionHighlight() {} }, + '../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'), '../../ui/shell/shell': { shell: { yieldFocusToSidebar() {} } }, '../../ui/metrics': { lineStep: () => 12 }, '../../ui/dashboard-settings': { diff --git a/tests/ios-terminal-input.test.cjs b/tests/ios-terminal-input.test.cjs index e58e02ce..df6e1138 100644 --- a/tests/ios-terminal-input.test.cjs +++ b/tests/ios-terminal-input.test.cjs @@ -3,6 +3,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const vm = require('node:vm'); const ts = require('typescript'); +const { Menu } = require('../.test-build/app/ui/menu-core.js'); function load(file, context) { const sandbox = { exports: {}, ...context }; vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), { @@ -23,7 +24,9 @@ test('iOS Type Into App submits UTF-8 terminal text and delays Enter at the byte client.handleMessage(JSON.stringify({ type: 'connect', command: 'test' })); const { VoiceInputLayer } = load('app/ui/shell/voice-input.ts', { require: id => id.includes('voice-control') ? { voiceControlBridge: { stop() {} } } - : id.includes('dashboard-settings') ? { anthropicApiKeySetting: { get: () => '' } } : {}, + : id.includes('dashboard-settings') ? { anthropicApiKeySetting: { get: () => '' } } + : id.includes('input-dialog') ? { createInputDialogMenu: (items, selectedIndex) => + new Menu({ items, selectedIndex, wrap: true, getHeight: () => 1, draw() {} }) } : {}, global: { isIOS: true }, }); for (const text of ['hello terminal', 'café π 🔋', 'line one\n第二行', '']) { diff --git a/tests/menu-core.test.cjs b/tests/menu-core.test.cjs index 01b4cc24..ce64f813 100644 --- a/tests/menu-core.test.cjs +++ b/tests/menu-core.test.cjs @@ -238,3 +238,51 @@ test('the scrollbar tracks the pixel scroll fraction', () => { short.menu.drawScrollbar(short.image, 95, 5, 60); assert.equal(short.image.getPixel(95, 5), 0, 'no scrollbar when the content fits'); }); + +test('a menu created empty starts on the first selectable item once items arrive', () => { + const { menu } = stringMenu({ items: [], isSelectable: (item) => !item.startsWith('Group') }); + assert.equal(menu.selectedIndex, null); + menu.setItems(['Group', 'a', 'b']); + assert.equal(menu.selectedIndex, 1, 'skips a leading heading'); + menu.setItems([]); + assert.equal(menu.selectedIndex, null); + menu.setItems(['x', 'y']); + assert.equal(menu.selectedIndex, 0, 'emptying and refilling starts over at the top'); +}); + +test('an explicit deselection survives setItems until the user or caller selects', async () => { + const { menu } = stringMenu({ items: [] , selectedIndex: null }); + menu.setItems(['a', 'b']); + assert.equal(menu.selectedIndex, null, 'constructed with no selection'); + menu.select(1); + menu.setItems(['a', 'b', 'c'], null); + menu.setItems(['a', 'b', 'c', 'd']); + assert.equal(menu.selectedIndex, null, 'setItems without an index keeps the deselection'); + await menu.handleInput({ type: 'scroll-down' }); + assert.equal(menu.selectedIndex, 0); + menu.setItems([]); + menu.setItems(['p', 'q']); + assert.equal(menu.selectedIndex, 0, 'scrolling ended the deselection'); +}); + +test('setItems never leaves the viewport scrolled past the end of the list', () => { + // Box 60px, rows 20px: a 3-row list fits, so it must sit at the top. + const { menu, paint } = stringMenu({ items: ['b', 'c', 'd'] }); + menu.select(2); + paint(); + assert.equal(menu.scrollTop, 0); + menu.setItems(['a', 'b', 'c'], 2); + assert.deepEqual(paint().map((r) => r.item), ['a', 'b', 'c'], 'a row sorted in above stays visible'); + assert.equal(menu.scrollTop, 0); + // The selected row at the top of a scrolled viewport loses the rows below it: + // keeping its on-screen position would leave a gap, so pull back to show the end. + const long = stringMenu({ items: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] }); + long.menu.select(6); + long.paint(); + long.menu.select(4); + long.paint(); + assert.equal(long.menu.scrollTop, 80, 'e is the top row'); + long.menu.setItems(['a', 'b', 'c', 'd', 'e'], 4); + assert.deepEqual(long.paint().map((r) => r.item), ['c', 'd', 'e']); + assert.equal(long.menu.scrollTop, 40); +}); diff --git a/tests/menu-highlight-motion.test.cjs b/tests/menu-highlight-motion.test.cjs index ca561f4b..0684b5d0 100644 --- a/tests/menu-highlight-motion.test.cjs +++ b/tests/menu-highlight-motion.test.cjs @@ -5,16 +5,17 @@ const { GrayImage } = require('../.test-build/app/graphics/image.js'); const { encodePresentation, readPresentation, paintPresentation } = require('../.test-build/app/graphics/presentation-wire.js'); test('highlight animates only navigation that preserves the scroll window', () => { + const D = MENU_HIGHLIGHT_DURATION_MS; const motion = new MenuHighlightMotion(); assert.equal(motion.paint(0, 0, 10, 20, 100, 20, 0), undefined); motion.navigate(0, false); const moved = motion.paint(1, 0, 10, 40, 100, 20, 100); assert.equal(moved.dx, 0); assert.equal(moved.dy, -20); - assert.equal(moved.durationMs, 300); - assert.equal(motion.paint(1, 0, 10, 40, 100, 20, 250).token, moved.token); + assert.equal(moved.durationMs, D); + assert.equal(motion.paint(1, 0, 10, 40, 100, 20, 100 + D / 4).token, moved.token); motion.navigate(1, false); - const next = motion.paint(2, 0, 10, 60, 100, 20, 250); + const next = motion.paint(2, 0, 10, 60, 100, 20, 100 + D / 2); assert.equal(next.dy, -30, 'continue from the halfway position'); motion.navigate(2, false); assert.equal(motion.paint(3, 1, 10, 60, 100, 20, 400), undefined, 'scroll snaps'); @@ -22,8 +23,8 @@ test('highlight animates only navigation that preserves the scroll window', () = assert.equal(motion.paint(0, 0, 10, 20, 100, 20, 500), undefined, 'wrap snaps'); motion.navigate(0, false); motion.paint(1, 0, 10, 40, 100, 20, 600); - assert.ok(motion.paint(1, 0, 10, 40, 100, 20, 899)); - assert.equal(motion.paint(1, 0, 10, 40, 100, 20, 900), undefined, 'finished after 300 ms'); + assert.ok(motion.paint(1, 0, 10, 40, 100, 20, 600 + D - 1)); + assert.equal(motion.paint(1, 0, 10, 40, 100, 20, 600 + D), undefined, `finished after ${D} ms`); assert.equal(motion.paint(2, 0, 10, 60, 100, 20, 1200), undefined, 'programmatic changes snap'); }); diff --git a/tests/navigate-worker.test.cjs b/tests/navigate-worker.test.cjs index 319234da..2cd297c9 100644 --- a/tests/navigate-worker.test.cjs +++ b/tests/navigate-worker.test.cjs @@ -31,6 +31,7 @@ function fixture() { '../compass/calibration': { calibrateHeading: value => value + 5, normalizeHeading: value => (value + 360) % 360 }, '../../native/frame-timings': { startFrame: () => 1, finishFrame() {}, logFrame() {}, span: (_id, _name, fn) => fn(), runWithFrame: (_id, fn) => fn() }, '../../native/active-display': { getActiveDisplay: () => null }, + '../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'), '../../ui/window-menu': { WindowMenu: class { paint() { return []; } isOpen() { return false; } resize() {} } }, '../../graphics/plane': { planesFingerprint: () => 'frame' }, '../../native/mapbox': { diff --git a/tests/row-metrics.test.cjs b/tests/row-metrics.test.cjs new file mode 100644 index 00000000..7a2adc81 --- /dev/null +++ b/tests/row-metrics.test.cjs @@ -0,0 +1,87 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { GrayImage } = require('../.test-build/app/graphics/image.js'); +const { textInkBounds, textInkHeight, centeredTextY, tightRowHeight } = require('../.test-build/app/ui/metrics.js'); +const { Menu } = require('../.test-build/app/ui/menu-core.js'); + +function load(file) { + const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8'); + const context = { exports: {}, require: () => ({}) }; + vm.runInNewContext(ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText, context); + return context.exports; +} +const { BdfFont } = load('app/graphics/bdffont.ts'); +const terminus = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8')); +const SIZES = [12, 14, 16, 18, 20, 22, 24]; + +/** A font whose glyphs sit `leading` px below the line top and end `trim` px above its bottom. */ +function leadingFont(lineHeight, leading, trim) { + const ascent = lineHeight - 3; + const inkHeight = lineHeight - leading - trim; + return { + lineHeight, ascent, descent: 3, + // bbxY is the ink bottom's height above the baseline (negative below it). + getGlyph: () => ({ bbxHeight: inkHeight, bbxY: ascent - leading - inkHeight, bbxWidth: 1, bbxX: 0 }), + }; +} + +test('Terminus ink fills its line box, so the compact row keeps its 12px pitch of 16', () => { + for (const size of SIZES) { + const font = terminus(size); + assert.deepEqual(textInkBounds(font), { top: 0, bottom: font.lineHeight }, `ter-u${size}n`); + assert.equal(tightRowHeight(font), font.lineHeight + 4); + } + assert.equal(tightRowHeight(terminus(12)), 16); +}); + +test('ink bounds follow the rendered glyphs, not the line box', () => { + const font = leadingFont(21, 4, 1); + assert.deepEqual(textInkBounds(font), { top: 4, bottom: 20 }); + assert.equal(textInkHeight(font), 16); + assert.equal(tightRowHeight(font), 20); + // Centered in a 19px box: 3 spare pixels, 1 above; the line top sits 3 above the box to put ink at +1. + assert.equal(centeredTextY(font, 100, 19), 100 + 1 - 4); +}); + +test('fonts without glyph access fall back to the line box', () => { + const font = { lineHeight: 14, ascent: 11, descent: 3 }; + assert.deepEqual(textInkBounds(font), { top: 0, bottom: 14 }); + assert.equal(centeredTextY(font, 10, 20), 13); +}); + +test('centered text keeps at least a pixel of clearance inside a compact selection box', () => { + for (const font of [...SIZES.map(terminus), leadingFont(21, 4, 1), leadingFont(17, 0, 2)]) { + const box = tightRowHeight(font) - 1; + const offset = centeredTextY(font, 0, box); + const { top, bottom } = textInkBounds(font); + assert.ok(offset + top >= 1, `top clearance at lineHeight ${font.lineHeight}`); + assert.ok(offset + bottom <= box - 1, `bottom clearance at lineHeight ${font.lineHeight}`); + } +}); + +test('a selected compact row keeps every inked pixel of its text', () => { + const label = 'Jgpqy (É|Å) 0189'; + const inked = (image) => image.withDrawsBaked().pixels.reduce((n, v) => n + (v !== 0 ? 1 : 0), 0); + for (const size of SIZES) { + const font = terminus(size); + const reference = new GrayImage(400, 80); + reference.drawText(font, 0, 20, label, 255); + const menu = new Menu({ + items: [label], + rowGap: 1, + getHeight: () => tightRowHeight(font), + draw: ({ image, item, x, y, height }) => image.drawText(font, x + 6, centeredTextY(font, y, height), item, 255), + }); + const page = new GrayImage(420, 120); + menu.paint(page, { x: 4, y: 4, width: 400, height: 100 }, true); + const selection = page.draws.find((draw) => draw.presentation); + assert.ok(selection, `ter-u${size}n selection`); + assert.equal(inked(selection.source), inked(reference), `ter-u${size}n keeps all ink`); + } +}); diff --git a/tests/settings-panel.test.cjs b/tests/settings-panel.test.cjs new file mode 100644 index 00000000..dcfbabac --- /dev/null +++ b/tests/settings-panel.test.cjs @@ -0,0 +1,112 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +function load(file, modules) { + const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8'); + const context = { exports: {}, console, require(name) { assert.ok(name in modules, name); return modules[name]; } }; + vm.runInNewContext(ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText, context); + return context.exports; +} + +const graphics = require('../.test-build/app/graphics/image.js'); +const metrics = require('../.test-build/app/ui/metrics.js'); +const menuCore = require('../.test-build/app/ui/menu-core.js'); +const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} }); +const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/terminus/ter-u12n.bdf'), 'utf8')); +const textwrap = load('app/graphics/textwrap.ts', {}); +const fonts = { getDefaultSmallFont: () => font }; +const menu = load('app/ui/menu.ts', { + '../graphics/image': graphics, '../graphics/textwrap': textwrap, '../graphics/ui-fonts': fonts, + '../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) }, './gestures': {}, + './metrics': metrics, './menu-core': menuCore, +}); +let yields = 0; +const { SettingsPanelLayer } = load('app/ui/dashboard/settings-panel.ts', { + '../../graphics/ui-fonts': fonts, '../../graphics/image': graphics, '../../graphics/textwrap': textwrap, + '../gestures': {}, '../layers': {}, '../menu': menu, '../menu-core': menuCore, '../metrics': metrics, + '../shell/shell': { shell: { yieldFocusToSidebar: () => yields++ } }, +}); + +/** A panel over three sections; records which item callbacks fire. */ +function panel() { + const selected = []; + const item = (label, extra = {}) => ({ label, onSelect: () => selected.push(label), ...extra }); + const layer = new SettingsPanelLayer([ + { label: 'Display', items: [item('Brightness'), item('Font'), item('Off', { disabled: true })] }, + { label: 'Voice', items: Array.from({ length: 20 }, (_, i) => item(`Voice ${i}`, { description: 'Help text for this option.' })) }, + { label: 'About', items: [], renderDetail: () => {} }, + ]); + const ctx = { stack: { getBaseSize: () => ({ width: 576, height: 260 }), isFocused: () => true } }; + const input = (type) => layer.handleInput({ type, timestampMs: 0 }, ctx); + return { layer, input, paint: () => layer.paint(ctx), selected }; +} + +const selections = (image) => image.draws.filter((d) => d.kind === 'image' && d.presentation); + +test('the right column previews the section without a selection until focus enters it', async () => { + const p = panel(); + assert.equal(selections(p.paint()).length, 1, 'only the left column is highlighted'); + await p.input('click'); + const both = selections(p.paint()); + assert.equal(both.length, 2); + assert.equal(both[0].presentation.background, 0, 'left column shows an outline once focus moves right'); + assert.ok(both[1].x > 150, 'the right highlight lands in the right column'); + await p.input('click'); + assert.deepEqual(p.selected, ['Brightness']); + await p.input('double-click'); + assert.equal(selections(p.paint()).length, 1, 'back to a preview'); + const before = yields; + await p.input('double-click'); + assert.equal(yields, before + 1, 'double-click from the left column yields to the sidebar'); +}); + +test('moving between sections resets the right column to its top, unselected', async () => { + const p = panel(); + await p.input('scroll-down'); + await p.input('click'); + for (let i = 0; i < 15; i++) await p.input('scroll-down'); + p.paint(); + await p.input('double-click'); + await p.input('scroll-up'); + await p.input('scroll-down'); + assert.equal(selections(p.paint()).length, 1); + await p.input('click'); + await p.input('click'); + assert.deepEqual(p.selected, ['Voice 0'], 'entering starts at the first item'); +}); + +test('watch swipes move within a column, wrap, and skip disabled activation', async () => { + const p = panel(); + await p.input('swipe-up'); + await p.input('click'); + assert.deepEqual(p.selected, [], 'About has no items, so focus stays in the left column'); + await p.input('swipe-down'); + await p.input('swipe-right'); + await p.input('swipe-up'); + await p.input('swipe-right'); + assert.deepEqual(p.selected, [], 'the wrapped-to item is disabled'); + await p.input('swipe-up'); + await p.input('swipe-right'); + assert.deepEqual(p.selected, ['Font']); +}); + +test('the selected row stays clear of its description band', async () => { + const p = panel(); + await p.input('scroll-down'); + await p.input('click'); + await p.input('scroll-up'); + const row = selections(p.paint())[1]; + const overlay = new graphics.GrayImage(576, 260); + p.layer.paintDescriptionOverlay(overlay, { stack: { getBaseSize: () => ({ width: 576, height: 260 }) } }); + let bandTop = -1; + for (let y = 0; y < 260 && bandTop < 0; y++) if (overlay.getPixel(300, y) !== 0) bandTop = y; + assert.ok(bandTop > 0, 'the band is drawn'); + assert.ok(row.y + row.source.height <= bandTop, `row ends at ${row.y + row.source.height}, band starts at ${bandTop}`); + assert.ok(row.y + row.source.height > bandTop - 30, 'the last item scrolled down to just above the band'); +}); diff --git a/tests/voice-finalization.test.cjs b/tests/voice-finalization.test.cjs index c656a94f..2d4e638a 100644 --- a/tests/voice-finalization.test.cjs +++ b/tests/voice-finalization.test.cjs @@ -4,6 +4,7 @@ const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); const ts = require('typescript'); +const { Menu } = require('../.test-build/app/ui/menu-core.js'); function load(file, deps, globals = {}) { const exports = {}; @@ -27,7 +28,10 @@ function dialog({ autoSend = false, deferred = true, synchronousFinal, isIOS = f '../../native/anthropic': { refineDictation(options) { refinements.push(options); return { cancel() {} }; } }, '../dashboard-settings': { anthropicApiKeySetting: { get: () => 'key' } }, '../gestures': { gestureHints: () => '' }, - './input-dialog': { paintInputDialog(_image, options) { frame = options; } }, + './input-dialog': { + paintInputDialog(_image, options) { frame = options; }, + createInputDialogMenu: (items, selectedIndex) => new Menu({ items, selectedIndex, wrap: true, getHeight: () => 1, draw() {} }), + }, }, { global: { isIOS }, setTimeout(cb) { const id = ++timerId; timers.set(id, cb); return id; },