UNPKG

@teaui/core

Version:

A high-level terminal UI library for Node

68 lines 2.1 kB
import { AbstractLegend, } from './AbstractLegend.js'; import { HotKey } from './HotKey.js'; import { hotKeyToString } from '../events/index.js'; import { Size } from '../geometry.js'; /** * A Legend that automatically shows keyboard shortcuts based on: * - The currently focused view's `legendItems()` method * - Registered HotKey components that have a `label` prop * * Subscribes to focusChange events on the screen and updates when focus changes. */ export class AutoLegend extends AbstractLegend { #unsubscribe; #cachedItems; constructor(props = {}) { super(props); } didMount(screen) { super.didMount(screen); this.#unsubscribe?.(); this.#unsubscribe = screen.on('focusChange', () => { this.#cachedItems = undefined; this.invalidateSize(); }); } didUnmount(screen) { this.#unsubscribe?.(); this.#unsubscribe = undefined; super.didUnmount(screen); } collectItems() { if (!this.#cachedItems) { this.#cachedItems = this.#updateItems(this.screen?.currentFocusView); } return this.#cachedItems; } naturalSize(available) { const size = super.naturalSize(available); if (size.height === 0) { return new Size(0, 1); } return size; } #updateItems(focused) { const screen = this.screen; let items; // Collect items from the focused view if (focused) { items = focused.legendItems(); } else { items = []; } // Collect items from registered HotKey components with labels if (screen) { for (const [view] of screen.hotKeyViews) { if (view instanceof HotKey && view.label) { items.push({ key: hotKeyToString(view.hotKey), label: view.label, }); } } } return this.computeItems(items); } } //# sourceMappingURL=AutoLegend.js.map