Files
faceclaw/app/ui/window-menu.ts
T

203 lines
7.7 KiB
TypeScript

import { swapMenuGesturesSetting } from "./dashboard-settings";
import { GrayImage } from "../graphics/image";
import { singlePlane, type Plane } from "../graphics/plane";
import { GESTURE_LONG_PRESS, GESTURE_SHORT_THEN_LONG_PRESS, gestureHints, type InputEvent } from "./gestures";
import { type Layer, type LayerActions, LayerStack, noopLayerActions } from "./layers";
import { CONTEXT_MENU_DIM, MenuLayer, type MenuItem, type MenuLayout } from "./menu";
import type { WorkerAppReply } from "./shell/worker-window";
/**
* The window context menu, opened by tap-then-hold by default: an app's own menu,
* holding its app-specific actions. The menu gesture preference can swap
* these bindings unless the app owns long-press. The shell's system menu
* carries the entries every window shares — Focus app switcher, Voice input,
* Close window — so an app with nothing of its own to offer has no menu of
* its own: tap-then-hold then opens the system menu in its place, so both
* gestures land on the same menu. The system menu is also the safety net:
* shell-owned, so an unresponsive app can always be closed (a window that
* claims long-press for a move of its own reaches it by holding the press).
*/
/** Centered over the viewport; visually matches the shell's system menu position. */
export const WINDOW_MENU_LAYOUT: MenuLayout = {
x: "center",
y: 8,
width: 272,
minHeight: 150,
footer: gestureHints([[GESTURE_LONG_PRESS, "system menu"]]),
dimUnderneath: CONTEXT_MENU_DIM,
depth: 4,
};
export class WindowMenuLayer extends MenuLayer {
constructor(title: string | null, items: MenuItem[], holdToTalk = false, claimsLongPress = false) {
super(title, items, (holdToTalk || (swapMenuGesturesSetting.get() && !claimsLongPress))
? { ...WINDOW_MENU_LAYOUT, footer: gestureHints([[GESTURE_SHORT_THEN_LONG_PRESS, "system menu"]]) }
: WINDOW_MENU_LAYOUT);
}
/**
* A window submenu (Settings, Spotify, ...) opens in place of the window
* menu it came from, which it would mostly cover anyway: the window content
* shows beneath it, dimmed once, rather than the parent menu dimming it a
* second time and costing a plane of its own.
*/
replacesLayerBelow(below: Layer): boolean {
return below instanceof WindowMenuLayer;
}
}
export type WindowMenuOptions = {
windowId: string;
post: (reply: WorkerAppReply) => void;
/** Menu title: the window's title, read at open time. */
title: () => string;
/**
* The app's menu entries, built at open time so they reflect current
* state. Empty means the window has no context menu right now: open()
* asks the shell for the system menu instead.
*/
items: () => MenuItem[];
/**
* True while the app gives long-press a meaning of its own (a game move).
* The shell then forwards long-presses to the window instead of opening
* the system menu on them; holding the press past the escape threshold
* still reaches the system menu. Default: never.
*/
claimsLongPress?: () => boolean;
/** Paint the window content the menu draws over (a fresh, mutable image). */
paintBase: () => GrayImage;
size: { width: number; height: number };
isFocused: () => boolean;
};
/**
* Menu host for worker apps, which paint pixels directly rather than through
* a persistent LayerStack. Wraps a short-lived stack so MenuLayer (and the
* ctx.stack.pop() convention in item callbacks) works unchanged.
*
* Usage: answer tap-then-hold with open(); route input to handleInput while
* isOpen(); paint every frame through paint(), which returns the window
* content with the menu drawn over it and keeps the shell told about the
* window's gesture bindings (whether it has a menu, whether it claims
* long-press).
*
* Text-setting rows (textSettingMenuItem) work here too: the phone editor
* opens through the shell, and the app repaints the edit page as the setting
* changes. Call close() when the window closes so an open edit is ended.
*/
export class WindowMenu {
private stack: LayerStack | null = null;
private reported: { hasAppMenu: boolean; claimsLongPress: boolean } | null = null;
/** A text-setting row opened the phone editor and nothing has closed it yet. */
private textEditOpen = false;
constructor(private readonly options: WindowMenuOptions) {}
resize(size: { width: number; height: number }): void {
this.options.size = size;
this.stack?.setBaseSize(size);
}
isOpen(): boolean {
return this.stack !== null;
}
/** True when tap-then-hold currently opens this menu with something in it. */
isAvailable(): boolean {
return this.options.items().length > 0;
}
/**
* Open the menu, or the shell's system menu when this window has no
* entries. `items` (and optionally `title`) override the window's own for
* an app that reuses this host for another list (a per-row action menu),
* and `selectedIndex` starts a picker on its current value.
*/
open(items: MenuItem[] = this.options.items(), title: string = this.options.title(), selectedIndex?: number): void {
if (this.stack) return;
if (!items.length) {
this.options.post({ type: "open-system-menu", windowId: this.options.windowId });
return;
}
const base: Layer = {
paint: () => this.options.paintBase(),
handleInput: () => {},
};
const stack = new LayerStack(base, this.layerActions(), this.options.size, this.options.isFocused);
const layer = new WindowMenuLayer(title, items, false, this.options.claimsLongPress?.() ?? false);
if (selectedIndex !== undefined) layer.selectItem(selectedIndex);
stack.push(layer);
this.stack = stack;
}
/** Close the menu outright (the window is closing), ending any phone edit. */
close(): void {
this.stack?.clearToBase();
this.stack = null;
this.endTextEdit();
}
/**
* No-ops apart from the phone text editor, which the shell owns: a worker
* can only ask for it by setting id.
*/
private layerActions(): LayerActions {
return {
...noopLayerActions,
startTextSettingEdit: (setting) => {
this.textEditOpen = true;
this.options.post({ type: "start-text-setting-edit", settingId: setting.id });
},
endTextSettingEdit: () => this.endTextEdit(),
};
}
private endTextEdit(): void {
if (!this.textEditOpen) return;
this.textEditOpen = false;
this.options.post({ type: "end-text-setting-edit" });
}
/**
* Paint the window content with the menu over it. `content` paints the
* closed-state content (default: paintBase alone), for windows whose
* ordinary frame has more planes than the menu needs beneath it.
*/
paint(content?: () => Plane[]): Plane[] {
this.syncGestures();
if (this.stack) return this.stack.paint();
return content ? content() : singlePlane(this.options.paintBase());
}
/** Tell the shell when this window's gesture bindings change. */
private syncGestures(): void {
const hasAppMenu = this.isAvailable();
const claimsLongPress = this.options.claimsLongPress?.() ?? false;
if (this.reported?.hasAppMenu === hasAppMenu && this.reported.claimsLongPress === claimsLongPress) return;
this.reported = { hasAppMenu, claimsLongPress };
this.options.post({
type: "set-window-gestures",
windowId: this.options.windowId,
hasAppMenu,
claimsLongPress,
});
}
/** Route an input event to the menu; the menu closes by popping itself. */
async handleInput(event: InputEvent): Promise<void> {
const stack = this.stack;
if (!stack) return;
// The shell opened its system menu over this window; close ours so the
// two context menus never stack.
if (event.type === "system-menu-opened") {
this.close();
return;
}
await stack.handleInput(event);
if (stack.isAtBase()) {
this.stack = null;
}
}
}