Use animated menus in a bunch more places

This commit is contained in:
James Babcock committed 2026-09-23 23:57:50 -07:00
1 parent 123c1142d6
commit 71c1971992
37 files changed
+1457 -1005

No files matched your search

+41 -30
View File
@@ -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<ConfigRow>({
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<ConfigRow>): 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<void> {
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;
+25 -24
View File
@@ -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<void> {
* sequencer message lands as the previous phrase finishes.
*/
export class BuzzerDemoLayer implements Layer {
private selectedIndex = 0;
private scrollRow = 0;
private readonly menu = new Menu<SoundEffect>({
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<void> {
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<SoundEffect>): 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);
}
+23 -16
View File
@@ -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<string, string> = {
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<ConsentAction>({
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<ConsentAction>): void {
image.drawText(getDefaultSmallFont(), x + 10, y + 3, item, selected ? 255 : 200);
}
+32 -22
View File
@@ -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> | 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<DetailAction>({
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<void> | 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;
}
+84 -67
View File
@@ -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<StoreRow>;
/** 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<StoreRow>({
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<StoreRow> {
if (tab.menu.items !== tab.rows) tab.menu.setItems(tab.rows);
return tab.menu;
}
export type EvenHubStoreLayerOptions = {
launchApp: (appId: string) => Promise<void> | 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<void> {
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 {
+41 -32
View File
@@ -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<BrowserItem>({
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<BrowserItem>): 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<void> {
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<void> {
@@ -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);
}
+24 -20
View File
@@ -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<FileInfoAction>;
constructor(
private readonly entry: DirectoryEntry,
private readonly actions: FileInfoAction[],
) {}
) {
this.menu = new Menu<FileInfoAction>({
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<void> {
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<FileInfoAction>): 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`;
+75 -59
View File
@@ -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<MenuItem>;
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<MenuItem>({
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<void> {
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. */
+57 -75
View File
@@ -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<MediaBrowseItem>;
};
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<MediaBrowseItem>({
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<MediaBrowseItem>): 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) => {
+5 -5
View File
@@ -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<MusicAction>): 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<MediaQueueItem>): void {
private drawQueueItem({ image, item, x, y, width, height, selected }: MenuDrawArgs<MediaQueueItem>): 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<void> {
+25 -19
View File
@@ -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;
}
+57 -69
View File
@@ -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<IdleEntry> | 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<IdleEntry> {
idleMenu ??= new Menu<IdleEntry>({
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<IdleEntry> {
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<IdleEntry>): 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 {
+3 -7
View File
@@ -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();
+63 -90
View File
@@ -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<HubItem> | 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<HubItem> {
window.list ??= new Menu<HubItem>({
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<HubItem>): 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;
}
+104 -89
View File
@@ -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<Row>({
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<Row>): 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;
}
}
+57 -26
View File
@@ -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<ForecastPeriod>({
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<ForecastPeriod>): 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";