diff --git a/docs/changes/0038-add-embeddable-grid-components.md b/docs/changes/0038-add-embeddable-grid-components.md index f7aa19a..cd1b62b 100644 --- a/docs/changes/0038-add-embeddable-grid-components.md +++ b/docs/changes/0038-add-embeddable-grid-components.md @@ -5,7 +5,7 @@ Expose the grid as two components a plugin renders inside its own render session: `Grid`, the printed lines as an element laid out for a given width, and `SelectGrid`, the driven grid over the dialogs' embeddable `Select`. `print` and `select` stay as they are. **Spec:** [Grid](../specs/grid/) -**Status:** draft +**Status:** complete **Depends On:** 0029, 0030, 0036 ## Motivation @@ -78,13 +78,13 @@ Skipping or weakening any of these rules to land the PR MUST be treated as a bug - [x] `test/plugin-consumer.test.ts`: the consumer fixture types `Grid` through the published contract; `test/plugin-boundary.test.ts` keeps passing - [x] [`docs/manual/plugins.md`](../manual/plugins.md#use-the-bundled-grid-capability): document `Grid` - [x] [Grid](../specs/grid/) spec: mark [Embeddable Grid](../specs/grid/index.md#embeddable-grid) implemented and add a changelog row -- [ ] Add the embeddable `SelectGrid` component (after [Change 0036](./0036-add-embeddable-dialog-components.md)) - - [ ] `plugins/grid/contract.ts`: `SelectGridProps` importing `EmbeddedProps` type-only from `@fx/tx/dialogs`, and the `SelectGrid` member - - [ ] `plugins/grid/index.ts` and `plugins/grid/select.ts`: the component over the dialogs' `Select`, mapping the request on mount and the answer on submit - - [ ] `test/grid-embedded.test.ts`: every scenario in [Grid: Embeddable Selection](../specs/grid/index.md#embeddable-selection) — acting on a row, cancelling, and the absent dialogs provider — plus `isActive`, `height`, and a row offering no actions - - [ ] `test/plugin-consumer.test.ts`: the consumer fixture types `SelectGrid`, resolving the grid contract through the dialogs contract in the packed tarball - - [ ] [`docs/manual/plugins.md`](../manual/plugins.md#use-the-bundled-grid-capability): document `SelectGrid` - - [ ] [Grid](../specs/grid/) spec: mark [Embeddable Selection](../specs/grid/index.md#embeddable-selection) implemented and add a changelog row; set this change `complete` in `docs/index.yml` and `docs/index.md` +- [x] Add the embeddable `SelectGrid` component (after [Change 0036](./0036-add-embeddable-dialog-components.md)) (PR #89) + - [x] `plugins/grid/contract.ts`: `SelectGridProps` importing `EmbeddedProps` type-only from `@fx/tx/dialogs`, and the `SelectGrid` member + - [x] `plugins/grid/index.ts` and `plugins/grid/select.ts`: the component over the dialogs' `Select`, mapping the request on mount and the answer on submit + - [x] `test/grid-embedded.test.ts`: every scenario in [Grid: Embeddable Selection](../specs/grid/index.md#embeddable-selection) — acting on a row, cancelling, and the absent dialogs provider — plus `isActive`, `height`, and a row offering no actions + - [x] `test/plugin-consumer.test.ts`: the consumer fixture types `SelectGrid`, resolving the grid contract through the dialogs contract in the packed tarball + - [x] [`docs/manual/plugins.md`](../manual/plugins.md#use-the-bundled-grid-capability): document `SelectGrid` + - [x] [Grid](../specs/grid/) spec: mark [Embeddable Selection](../specs/grid/index.md#embeddable-selection) implemented and add a changelog row; set this change `complete` in `docs/index.yml` and `docs/index.md` ## References diff --git a/docs/index.md b/docs/index.md index c2d4380..6cd7155 100644 --- a/docs/index.md +++ b/docs/index.md @@ -53,4 +53,4 @@ | 0035 | [Production React and Cached Text Widths](changes/0035-production-react-and-cached-widths.md) | [Architecture](specs/architecture/) | complete | 0033 | | 0036 | [Add Embeddable Dialog Components](changes/0036-add-embeddable-dialog-components.md) | [Dialogs](specs/dialogs/) | complete | 0017, 0023, 0031, 0033 | | 0037 | [Add Multi-Select](changes/0037-add-multi-select.md) | [Dialogs](specs/dialogs/) | draft | 0027, 0036 | -| 0038 | [Add Embeddable Grid Components](changes/0038-add-embeddable-grid-components.md) | [Grid](specs/grid/) | draft | 0029, 0030, 0036 | +| 0038 | [Add Embeddable Grid Components](changes/0038-add-embeddable-grid-components.md) | [Grid](specs/grid/) | complete | 0029, 0030, 0036 | diff --git a/docs/index.yml b/docs/index.yml index 934a25d..8061d0f 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -337,7 +337,7 @@ changes: path: changes/0038-add-embeddable-grid-components.md description: Expose the grid as a Grid component drawing the printed lines for a given width and a SelectGrid component driving rows over the dialogs' embeddable Select, leaving print and select unchanged. spec: grid - status: draft + status: complete depends_on: - "0029" - "0030" diff --git a/docs/manual/plugins.md b/docs/manual/plugins.md index d927c54..4704792 100644 --- a/docs/manual/plugins.md +++ b/docs/manual/plugins.md @@ -646,10 +646,11 @@ import type { GridSelectRow, OutputStream, Row, + SelectGridProps, } from "@fx/tx/grid"; ``` -`Grid` is what the key carries: `print(request)` writing a `GridRequest` — a `stream`, an optional `layout` of `"table"` or `"flow"`, optional `headers`, the `rows`, an optional `empty` message, and an optional `summary` — and `select(request)` driving a `GridSelectRequest` of a `message`, optional `headers`, and `GridSelectRow`s, each carrying its `cells`, the `value` identifying it, and the `GridAction`s it offers, resolving to a `GridSelection` of the chosen `value` and `action` or to `undefined`. It also carries `Grid`, the printed grid as a component taking `GridProps`, described below. A `Row` is a list of `Cell`s or bare strings, and an `OutputStream` is anything that can be written to and may report its `columns` and `isTTY`. +`Grid` is what the key carries: `print(request)` writing a `GridRequest` — a `stream`, an optional `layout` of `"table"` or `"flow"`, optional `headers`, the `rows`, an optional `empty` message, and an optional `summary` — and `select(request)` driving a `GridSelectRequest` of a `message`, optional `headers`, and `GridSelectRow`s, each carrying its `cells`, the `value` identifying it, and the `GridAction`s it offers, resolving to a `GridSelection` of the chosen `value` and `action` or to `undefined`. It also carries `Grid`, the printed grid as a component taking `GridProps`, and `SelectGrid`, the driven grid as a component taking `SelectGridProps`, both described below. A `Row` is a list of `Cell`s or bare strings, and an `OutputStream` is anything that can be written to and may report its `columns` and `isTTY`. A consumer reads `registrations("@fx/tx/grid")` inside its command action, after initialization has committed every provider. The contract is types only, and it declares a cell's `variable` as [Theming](#use-the-bundled-theme-capability)'s own `ThemeVariable` by importing `@fx/tx/theme` rather than restating that vocabulary, so a variable renamed there is renamed in every cell that can name one. The grid resolves a theme for the stream it is printing to through the theme capability above, so a `tx` composed without exactly one theme provider fails the call with an error naming the count rather than choosing an appearance of its own. It uses the injected React and Ink instances and never reaches for the process's own streams. @@ -766,6 +767,45 @@ const plugin: Plugin = ({ command, context, dependencies, registrations }) => { }; ``` +`SelectGrid` is `select` as a component, for the same plugin. It takes `SelectGridProps`: the `GridSelectRequest` you would pass to `select` as its `request`, and the `width`, `height`, `isActive`, `onSubmit`, and `onCancel` every embeddable component that takes keys shares — the `EmbeddedProps` of [Embed a dialog in your own interface](#embed-a-dialog-in-your-own-interface), which the grid contract imports from `@fx/tx/dialogs` rather than restating, so they mean exactly what they mean for `dialogs.Select`. It draws its request as that embedded `Select`, given your `width`, `height`, and `isActive`, so every rule above about selecting — the padded rows, the dropped `variable` and `align`, a row's actions as the column it opens, a row with no actions taken on its own — holds for it, and so does every rule that section states for an embedded `Select`: it is one-shot, it reads your callbacks on every call, it presents the request it was mounted with, and it answers keys only while it is active. `onSubmit` receives exactly the `GridSelection` `select` would resolve with, its `action` key absent where the row offered none, and `onCancel` is called where `select` would resolve `undefined`. + +It reads the dialogs capability when it mounts, while your command runs, and fails that render — which your session's error handling sees like any other render failure — with an error naming the count where a `tx` is composed without exactly one dialogs provider, rather than falling back to anything. It writes to no stream and needs no interactive one, so the handover guarantee above is `select`'s alone: a process you start after `onSubmit` inherits a terminal your session holds, and handing it over is yours. Every read of the capability yields the same `SelectGrid`. Cast it where you hand it to `createElement`, exactly as `Grid`: + +```ts +import type { Grid, GridSelection, SelectGridProps } from "@fx/tx/grid"; +import type { ReactNode } from "react"; + +// Inside your command action, with `grid`, `react`, and `ink` in hand. +const ServicePicker = grid.SelectGrid as ( + props: SelectGridProps, +) => ReactNode; + +function Picker({ onPicked }: { + readonly onPicked: (chosen?: GridSelection) => void; +}) { + const { columns, rows } = ink.useWindowSize(); + return react.createElement(ServicePicker, { + request: { + message: "Pick a service", + headers: ["SERVICE", "STATE"], + rows: services.map((service) => ({ + cells: [service.name, service.state], + value: service, + actions: [ + { label: "connect", value: "connect" as const }, + { label: "open logs", value: "logs" as const }, + ], + })), + }, + width: columns, + height: rows - 1, + isActive: true, + onSubmit: (chosen) => onPicked(chosen), + onCancel: () => onPicked(undefined), + }); +} +``` + Sorting, grouping, filtering, and paginating the supplied rows are out of scope, as are machine-readable output, borders and box drawing, spanning and wrapped cells, caller-specified widths, multi-row selection, in-place cell editing, column reordering, and value formatting of every kind — a duration, a timestamp, and a byte count are the consumer's to render into a string before it hands one over. ## One namespace per plugin diff --git a/docs/specs/grid/index.md b/docs/specs/grid/index.md index c0746aa..a332e0f 100644 --- a/docs/specs/grid/index.md +++ b/docs/specs/grid/index.md @@ -6,9 +6,9 @@ The grid capability lays text out in aligned cells and either prints it once or A grid is not only a table. A table — a header row over columns of equal meaning — is one layout; a flow, where a list of short items fills as many columns as the terminal affords, is another. Both are the same cells measured the same way, so both belong to one capability. -[Change 0030](../../changes/0030-publish-bundled-capability-contracts.md) publishes this contract at `@fx/tx/grid` and renames the capability's registry key to that same specifier, so a consumer imports the contract rather than restating it, under [Plugin System: Published Capability Contracts](../plugin-system/index.md#published-capability-contracts). That change has landed, so every requirement below describes current behavior except those the next paragraph names. +[Change 0030](../../changes/0030-publish-bundled-capability-contracts.md) publishes this contract at `@fx/tx/grid` and renames the capability's registry key to that same specifier, so a consumer imports the contract rather than restating it, under [Plugin System: Published Capability Contracts](../plugin-system/index.md#published-capability-contracts). That change has landed. -[Change 0038](../../changes/0038-add-embeddable-grid-components.md) specifies [Embeddable Grid](#embeddable-grid) and [Embeddable Selection](#embeddable-selection) — a printed grid and a driven one rendered inside a plugin's own render session — together with the members they add to [Grid Capability](#grid-capability). [Embeddable Grid](#embeddable-grid) and the `Grid` member it adds are implemented. [Embeddable Selection](#embeddable-selection) and the `SelectGrid` member it adds are planned and not yet implemented: today the capability exposes `print`, `select`, and `Grid`. +[Change 0038](../../changes/0038-add-embeddable-grid-components.md) adds [Embeddable Grid](#embeddable-grid) and [Embeddable Selection](#embeddable-selection) — a printed grid and a driven one rendered inside a plugin's own render session — together with the `Grid` and `SelectGrid` members they add to [Grid Capability](#grid-capability). That change has landed too, so every requirement below describes current behavior: the capability exposes `print`, `select`, `Grid`, and `SelectGrid`. ## Background @@ -436,3 +436,4 @@ They share every measurement decision and differ only in what drives them. Split | 2026-09-06 | Required the grid contract to be published at `@fx/tx/grid` as a types-only import, replacing the local structural copy every consumer maintained | [0030-publish-bundled-capability-contracts](../../changes/0030-publish-bundled-capability-contracts.md) | | 2026-10-18 | Desired embeddable `Grid` and `SelectGrid` components, sized by their host under the props Dialogs defines for every embeddable component | [0038-add-embeddable-grid-components](../../changes/0038-add-embeddable-grid-components.md) | | 2026-10-18 | Implemented the embeddable `Grid` component: the lines `print` would write, laid out against the host's `width` rather than a stream's, themed for the injected standard error, and handed to the host's session whole, a cell's own trailing spaces included | [0038-add-embeddable-grid-components](../../changes/0038-add-embeddable-grid-components.md) | +| 2026-10-18 | Implemented the embeddable `SelectGrid` component: the request `select` presents, drawn as the dialogs' embeddable `Select` in the host's `width`, `height`, and focus, mapped once on mount and answered through `onSubmit` with exactly the selection `select` resolves with, reading the dialogs capability when it mounts and failing that render naming the count when there is not exactly one provider | [0038-add-embeddable-grid-components](../../changes/0038-add-embeddable-grid-components.md) | diff --git a/plugins/grid/contract.ts b/plugins/grid/contract.ts index 6aa9f4a..d3637be 100644 --- a/plugins/grid/contract.ts +++ b/plugins/grid/contract.ts @@ -8,7 +8,7 @@ * restating it learns about a contract that moved when it builds rather than * when its command reaches for a member that is no longer there. * - * It declares types alone — one type-only import, no statements, nothing that + * It declares types alone — type-only imports, no statements, nothing that * survives compilation — which is what lets it be published under a `types` * condition with no runtime condition beside it. The capability's value comes * from the registry and must keep coming from there: nothing here prints, @@ -20,9 +20,13 @@ * one runtime module graph; the published path shares no graph at all, since * it is erased. It is the mechanism `@fx/tx/plugin` already uses between the * same two directories, and it means a variable renamed in one place is - * renamed everywhere a cell can name one. + * renamed everywhere a cell can name one. The props every embeddable component + * taking keys shares arrive through `@fx/tx/dialogs` for the same reason, so a + * host learns them once and the selecting grid cannot drift from the select it + * is drawn as. */ +import type { EmbeddedProps } from "@fx/tx/dialogs"; import type { ThemeVariable } from "@fx/tx/theme"; /** One cell of a grid. `variable` and `align` describe a *printed* cell; the @@ -136,6 +140,21 @@ export type GridProps = { readonly width: number; }; +/** What a host hands the embeddable `SelectGrid`: the selecting request it + * would pass to `select`, the props every embeddable component taking keys + * shares, and the rows it may draw in. + * + * `onSubmit` receives exactly the selection `select` resolves with, and + * `onCancel` is called where `select` resolves with nothing. The request is the + * one the component was mounted with: a host presenting different rows mounts + * a new component, keyed differently, rather than passing a new request. */ +export type SelectGridProps = EmbeddedProps> & { + readonly request: GridSelectRequest; + /** The terminal rows the grid may draw in, as the select it is drawn as + * reads them. */ + readonly height: number; +}; + /** The value registered under `@fx/tx/grid`: cells printed once, or driven. A * grid is one or the other in a call, never both. */ export type Grid = { @@ -151,4 +170,12 @@ export type Grid = { * React type: a host casts it where it passes it to `createElement`. The * same value on every read of the capability. */ readonly Grid: (props: GridProps) => unknown; + /** The driven grid as a component a host renders inside a session it owns: + * the request `select` would present, drawn as the dialogs' embeddable + * `Select` in the host's `width` and `height` and answering keys only while + * `isActive`. It writes to no stream and needs no interactive one. It reads + * the dialogs capability when it mounts, and fails that render when it finds + * other than exactly one provider. Typed as returning `unknown` for the + * reason `Grid` is; the same value on every read of the capability. */ + readonly SelectGrid: (props: SelectGridProps) => unknown; }; diff --git a/plugins/grid/index.ts b/plugins/grid/index.ts index 72bc7b5..d7bd516 100644 --- a/plugins/grid/index.ts +++ b/plugins/grid/index.ts @@ -7,7 +7,7 @@ import type { } from "./contract.ts"; import { requireDialogsCapability } from "./dialogs.ts"; import { embeddedGrid, printGrid } from "./render.ts"; -import { selection, selectRequest } from "./select.ts"; +import { embeddedSelectGrid, selection, selectRequest } from "./select.ts"; import { requireThemeCapability } from "./theme.ts"; /** @@ -56,6 +56,15 @@ const definition: PluginDefinition = Object.freeze({ requireThemeCapability(registrations).theme(context.stderr), ); + // Created once for the same reason. The dialogs capability is read when + // it mounts rather than here, for the reasons `select` reads it while + // the command runs: a plugin reading during its own initialization sees + // only what committed before it, and the provider is composed ahead of + // its consumers. + const SelectGrid = embeddedSelectGrid(react, () => + requireDialogsCapability(registrations), + ); + // Frozen, like every value a capability hands out: a consumer holds the // same object every other consumer in the process holds. const grid: Grid = Object.freeze({ @@ -108,6 +117,7 @@ const definition: PluginDefinition = Object.freeze({ }, Grid, + SelectGrid, }); register(gridKey, grid); diff --git a/plugins/grid/select.ts b/plugins/grid/select.ts index ec07489..127bee0 100644 --- a/plugins/grid/select.ts +++ b/plugins/grid/select.ts @@ -1,7 +1,11 @@ import type { SelectOption as DialogOption, SelectRequest as DialogRequest, + Dialogs, + SelectProps, + SelectResult, } from "@fx/tx/dialogs"; +import type { CoreDependencies } from "@fx/tx/plugin"; import { columnCount, headerCells, @@ -14,6 +18,7 @@ import type { GridSelection, GridSelectRequest, GridSelectRow, + SelectGridProps, } from "./contract.ts"; /** @@ -148,3 +153,63 @@ export function selection( const action = actions[choice.action] as GridAction; return { value: row.value, action: action.value }; } + +/** What the injected React's `createElement` returns: the type a host casts + * an embeddable component's `unknown` to, and the cast made here for the + * dialogs' `Select`, which the published contract types the same way. */ +type Rendered = ReturnType; + +/** + * The embeddable selecting grid: the request `select` presents, drawn as the + * dialogs' embeddable `Select` inside a session its host owns. + * + * It is the same composition `select` performs over the dialogs function, + * performed over the dialogs component instead, so it adds no selection rule + * of its own: the host's `width`, `height`, and `isActive` pass straight + * through, cancelling is the select's, and a submitted choice is mapped back to + * the row and the action exactly as `select` maps it. + * + * Its first render reads the dialogs capability through `resolveDialogs` and + * maps the request, both once per mount. The read happens while the host's + * command runs, after every provider has committed, and it throws when it does + * not find exactly one provider — failing the host's render rather than + * falling back to anything. The request is held from then on, as the select it + * is drawn as holds its own: a host presenting other rows mounts another + * component, and the answer is mapped against the rows it was given. + */ +export function embeddedSelectGrid( + react: CoreDependencies["react"], + resolveDialogs: () => Dialogs, +): (props: SelectGridProps) => unknown { + return function SelectGrid({ + request, + width, + height, + isActive, + onSubmit, + onCancel, + }: SelectGridProps) { + const [mounted] = react.useState(() => ({ + Select: resolveDialogs().Select as ( + props: SelectProps, + ) => Rendered, + request, + choices: selectRequest(request), + })); + /** Read through a ref, so a host passing fresh callbacks on every render + * is called back with the ones of its latest render. */ + const callbacks = react.useRef({ onSubmit, onCancel }); + callbacks.current = { onSubmit, onCancel }; + return react.createElement(mounted.Select, { + request: mounted.choices, + width, + height, + isActive, + // Only the choice is read: a select result's other fields describe what + // the select collected, and a grid's rows collect nothing. + onSubmit: (result: SelectResult) => + callbacks.current.onSubmit(selection(mounted.request, result.value)), + onCancel: () => callbacks.current.onCancel(), + }); + }; +} diff --git a/test/demo-scenarios.test.ts b/test/demo-scenarios.test.ts index b00111e..c5aa3f0 100644 --- a/test/demo-scenarios.test.ts +++ b/test/demo-scenarios.test.ts @@ -180,8 +180,9 @@ function recordingSurfaces(): { : { value: first.value, action: action.value } ) as GridSelection; }, - // The demo embeds nothing, so the component is never rendered here. + // The demo embeds nothing, so neither component is ever rendered here. Grid: () => null, + SelectGrid: () => null, }; return { inputs, diff --git a/test/demo.test.ts b/test/demo.test.ts index 2bd005c..1c5562f 100644 --- a/test/demo.test.ts +++ b/test/demo.test.ts @@ -103,8 +103,9 @@ function stubGrid(asked: Asked[]): PluginDefinition { }); return firstSelection(request); }, - // The demo embeds nothing, so the component is never rendered here. + // The demo embeds nothing, so neither component is ever rendered here. Grid: () => null, + SelectGrid: () => null, }); }, }; diff --git a/test/grid-embedded.test.ts b/test/grid-embedded.test.ts index cd65b68..e590cc7 100644 --- a/test/grid-embedded.test.ts +++ b/test/grid-embedded.test.ts @@ -1,7 +1,17 @@ import { describe, expect, test } from "bun:test"; import { PassThrough } from "node:stream"; -import type { Grid, GridProps, GridRequest, OutputStream } from "@fx/tx/grid"; +import type { + Grid, + GridProps, + GridRequest, + GridSelection, + GridSelectRequest, + OutputStream, + SelectGridProps, +} from "@fx/tx/grid"; import type { ReactNode } from "react"; +import { animationInterval } from "../plugins/dialogs/animation.ts"; +import dialogsPlugin from "../plugins/dialogs/index.ts"; import gridPlugin from "../plugins/grid/index.ts"; import themePlugin from "../plugins/theme/index.ts"; import { main } from "../src/cli.ts"; @@ -518,3 +528,445 @@ describe("the embeddable grid", () => { ]); }); }); + +/** + * The selecting half, driven the same way: a host session on a terminal of its + * own — a keyboard the test types into and a screen it reads — rendering + * `grid.SelectGrid` read from the registry. The command's own streams stay + * captured beside it, so a component that wrote anywhere but through its + * host's session, or that reached for the command's interactive streams, + * would show up there. + */ + +const ESCAPE = String.fromCharCode(27); +const CARRIAGE_RETURN = "\r"; +const DOWN = `${ESCAPE}[B`; + +/** The host's keyboard: a terminal input the renderer can put into raw mode + * and a test can type into. */ +class Keyboard extends PassThrough { + readonly isTTY = true; + isRaw = false; + + setRawMode(enabled: boolean): this { + this.isRaw = enabled; + return this; + } + + ref(): this { + return this; + } + + unref(): this { + return this; + } +} + +async function pause(milliseconds: number): Promise { + await new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +/** Generous, as the function form's own tests are: nothing waited behind here + * is an animation, and a loaded runner can be slow to draw a first frame. */ +const BUDGET = animationInterval * 20; + +async function until(predicate: () => boolean): Promise { + const deadline = performance.now() + BUDGET; + for (;;) { + if (predicate()) return; + if (performance.now() >= deadline) { + throw new Error("timed out waiting for the host session"); + } + await pause(1); + } +} + +/** The grid capability read from a `tx` composing the dialogs provider a + * selecting grid is drawn through, unless a test composes others. */ +async function readSelectingGrid( + plugins: readonly PluginDefinition[] = [dialogsPlugin], +): Promise<{ readonly grid: Grid; readonly tx: CapturedContext }> { + const { reads, tx } = await obtainGrid({ plugins }); + return { grid: reads[0] as Grid, tx }; +} + +/** The host's cast for the selecting component, as for `Grid`. */ +function selectingComponent( + grid: Grid, +): (props: SelectGridProps) => ReactNode { + return grid.SelectGrid as (props: SelectGridProps) => ReactNode; +} + +/** Every call the component made back to its host, in order. */ +type Answer = + | { readonly type: "submit"; readonly selection: GridSelection } + | { readonly type: "cancel" }; + +function answers() { + const calls: Answer[] = []; + return { + calls, + onSubmit: (selection: GridSelection) => + calls.push({ type: "submit", selection }), + onCancel: () => calls.push({ type: "cancel" }), + }; +} + +/** The line a selecting host draws above the grid, which also opens every + * frame it draws, so the latest frame is what follows its last occurrence. */ +const selectingTitle = "selecting host"; + +/** + * A host session drawing `View` beneath its title, on a keyboard and screen + * of its own. Debug mode writes every frame whole and in turn, so the latest + * frame is whatever follows the title's last occurrence. + */ +function hostSession(view: () => ReactNode) { + const { react, ink } = coreDependencies; + const View = () => + react.createElement( + ink.Box, + { flexDirection: "column" }, + react.createElement(ink.Text, null, selectingTitle), + view(), + ); + const keyboard = new Keyboard(); + const screen = new Screen(); + const instance = ink.render(react.createElement(View), { + stdout: screen, + stdin: keyboard, + stderr: screen, + debug: true, + interactive: true, + exitOnCtrlC: false, + patchConsole: false, + }); + let exited = false; + const exit = instance.waitUntilExit().then( + () => { + exited = true; + }, + (reason: unknown) => { + exited = true; + throw reason; + }, + ); + return { + screen, + exit, + exited: () => exited, + /** The latest frame's lines beneath the host's title, every sequence and + * every line's trailing whitespace removed. */ + rows(): readonly string[] { + const text = screen.text(); + const found = text.lastIndexOf(selectingTitle); + if (found < 0) return []; + return comparable(text.slice(found + selectingTitle.length)).slice(1); + }, + /** Types one chunk and lets the session answer it. */ + async press(chunk: string): Promise { + keyboard.write(chunk); + await pause(5); + }, + async close(): Promise { + instance.unmount(); + await exit; + }, + }; +} + +/** A host widget answering keys of its own, as whichever of a host's panels + * has focus does. It keeps the session reading its keyboard while the grid is + * inactive, so a key typed then is answered then rather than held for later. */ +function hostKeys(seen: string[]): ReactNode { + const { react, ink } = coreDependencies; + const Keys = () => { + ink.useInput((input) => { + seen.push(input); + }); + return null; + }; + return react.createElement(Keys); +} + +const services: GridSelectRequest = { + message: "Services", + headers: ["NAME", "STATE"], + rows: [ + { + cells: ["alpha", "up"], + value: "alpha", + actions: [ + { label: "connect", value: "connect" }, + { label: "open logs", value: "logs" }, + ], + }, + { + cells: ["bravo", "down"], + value: "bravo", + actions: [ + { label: "connect", value: "connect" }, + { label: "open logs", value: "logs" }, + ], + }, + ], +}; + +function shows( + session: ReturnType, + text: string, +): () => boolean { + return () => session.rows().some((row) => row.includes(text)); +} + +describe("the embeddable selecting grid", () => { + test("is the same component on every read of the capability", async () => { + const { reads } = await obtainGrid({ plugins: [dialogsPlugin] }); + const [first, second] = reads as [Grid, Grid]; + + expect(typeof first.SelectGrid).toBe("function"); + expect(second.SelectGrid).toBe(first.SelectGrid); + }); + + test("calls the host back once with the row and the action it acted on", async () => { + const { grid, tx } = await readSelectingGrid(); + const SelectGrid = selectingComponent(grid); + const calls = answers(); + const session = hostSession(() => + coreDependencies.react.createElement(SelectGrid, { + request: services, + width: 60, + height: 12, + isActive: true, + ...calls, + }), + ); + + await until(shows(session, "bravo")); + expect(session.rows().some((row) => /NAME\s+STATE/u.test(row))).toBe(true); + await session.press(DOWN); + await session.press(CARRIAGE_RETURN); + await until(shows(session, "open logs")); + await session.press(CARRIAGE_RETURN); + await until(() => calls.calls.length > 0); + // Nothing more arrives: the component is one-shot. + await pause(animationInterval); + + expect(calls.calls).toEqual([ + { type: "submit", selection: { value: "bravo", action: "connect" } }, + ]); + // The host's session is the host's: the grid settling ends nothing. + expect(session.exited()).toBe(false); + await session.close(); + expect(tx.stdoutText()).toBe(""); + expect(tx.stderrText()).toBe(""); + }); + + test("calls the host back with the row alone where it offers no actions", async () => { + const { grid } = await readSelectingGrid(); + const SelectGrid = selectingComponent(grid); + const calls = answers(); + const session = hostSession(() => + coreDependencies.react.createElement(SelectGrid, { + request: { + message: "Services", + rows: [ + { + cells: ["alpha"], + value: "alpha", + actions: [{ label: "connect", value: "connect" }], + }, + // Computed actions, of which this row has none. + { cells: ["bravo"], value: "bravo", actions: [] }, + ], + }, + width: 60, + height: 12, + isActive: true, + ...calls, + }), + ); + + await until(shows(session, "bravo")); + await session.press(DOWN); + await session.press(CARRIAGE_RETURN); + await until(() => calls.calls.length > 0); + await session.close(); + + expect(calls.calls).toEqual([ + { type: "submit", selection: { value: "bravo" } }, + ]); + const [call] = calls.calls as [Answer]; + expect( + "action" in + (call as { selection: GridSelection }).selection, + ).toBe(false); + }); + + test("calls the host back once on Escape and writes to no stream", async () => { + const { grid, tx } = await readSelectingGrid(); + const SelectGrid = selectingComponent(grid); + const calls = answers(); + const session = hostSession(() => + coreDependencies.react.createElement(SelectGrid, { + request: services, + width: 60, + height: 12, + isActive: true, + ...calls, + }), + ); + + await until(shows(session, "bravo")); + await session.press(ESCAPE); + await until(() => calls.calls.length > 0); + await session.press(ESCAPE); + await pause(animationInterval); + + expect(calls.calls).toEqual([{ type: "cancel" }]); + expect(session.exited()).toBe(false); + await session.close(); + expect(tx.stdoutText()).toBe(""); + expect(tx.stderrText()).toBe(""); + }); + + test("takes no keys while inactive, and answers the first once active", async () => { + const { grid } = await readSelectingGrid(); + const { react } = coreDependencies; + const SelectGrid = selectingComponent(grid); + const calls = answers(); + const seen: string[] = []; + let activate: (() => void) | undefined; + const session = hostSession(() => { + const [isActive, setActive] = react.useState(false); + activate = () => setActive(true); + return react.createElement( + react.Fragment, + null, + hostKeys(seen), + react.createElement(SelectGrid, { + request: { + message: "Services", + rows: [ + { cells: ["alpha"], value: "alpha" }, + { cells: ["bravo"], value: "bravo" }, + ], + }, + width: 60, + height: 12, + isActive, + ...calls, + }), + ); + }); + + await until(shows(session, "bravo")); + await session.press(DOWN); + await session.press(CARRIAGE_RETURN); + await until(() => seen.length >= 2); + await pause(animationInterval / 5); + expect(calls.calls).toEqual([]); + + (activate as () => void)(); + await pause(5); + await session.press(CARRIAGE_RETURN); + await until(() => calls.calls.length > 0); + await session.close(); + + // The cursor never moved while the grid was inactive. + expect(calls.calls).toEqual([ + { type: "submit", selection: { value: "alpha" } }, + ]); + }); + + test("draws within the host's height and width", async () => { + const { grid } = await readSelectingGrid(); + const SelectGrid = selectingComponent(grid); + const session = hostSession(() => + coreDependencies.react.createElement(SelectGrid, { + request: { + message: "Rows", + rows: Array.from({ length: 30 }, (_, index) => ({ + cells: [`row ${String(index + 1).padStart(2, "0")}`], + value: index + 1, + })), + }, + width: 50, + height: 9, + isActive: true, + ...answers(), + }), + ); + + await until(shows(session, "row 01")); + const rows = session.rows(); + await session.close(); + + // Nine rows in all: two edges, six rows of the grid, and the hint line. + expect(rows).toHaveLength(9); + expect(rows.filter((row) => row.includes("row "))).toHaveLength(6); + for (const row of rows) expect(row.length).toBeLessThanOrEqual(50); + }); + + test("fails the host's render naming the count when no dialogs provider is composed", async () => { + const { grid } = await readSelectingGrid([]); + const SelectGrid = selectingComponent(grid); + const calls = answers(); + const session = hostSession(() => + coreDependencies.react.createElement(SelectGrid, { + request: services, + width: 60, + height: 12, + isActive: true, + ...calls, + }), + ); + + let failure: unknown; + try { + await session.exit; + } catch (error) { + failure = error; + } + + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toBe( + "Expected exactly one dialogs capability, but found 0", + ); + expect(session.screen.text()).not.toContain("alpha"); + expect(calls.calls).toEqual([]); + }); + + test("fails the host's render when the dialogs provider is repeated", async () => { + const another: PluginDefinition = { + identity: { name: "more-dialogs" }, + load: + () => + ({ register }) => { + register("@fx/tx/dialogs", {}); + }, + }; + const { grid } = await readSelectingGrid([dialogsPlugin, another]); + const SelectGrid = selectingComponent(grid); + const session = hostSession(() => + coreDependencies.react.createElement(SelectGrid, { + request: services, + width: 60, + height: 12, + isActive: true, + ...answers(), + }), + ); + + let failure: unknown; + try { + await session.exit; + } catch (error) { + failure = error; + } + + expect((failure as Error).message).toBe( + "Expected exactly one dialogs capability, but found 2", + ); + }); +}); diff --git a/test/plugin-boundary.test.ts b/test/plugin-boundary.test.ts index 805e2c0..e698bcd 100644 --- a/test/plugin-boundary.test.ts +++ b/test/plugin-boundary.test.ts @@ -707,6 +707,7 @@ test("no capability contract type is declared outside the contract that owns it" "InputRequest", "OutputStream", "Row", + "SelectGridProps", "SelectOption", "SelectProps", "SelectRequest", diff --git a/test/plugin-consumer.test.ts b/test/plugin-consumer.test.ts index 24b2332..0c1b28a 100644 --- a/test/plugin-consumer.test.ts +++ b/test/plugin-consumer.test.ts @@ -96,6 +96,10 @@ import type { Grid, GridProps, GridSelectRow, Row } from "@fx/tx/grid"; import type { ReactNode } from "react"; import type { Appearance, Hue, Theme, ThemeVariable, Theming } from "@fx/tx/theme"; import type { ThemeOverride } from "@fx/tx/theme-override"; +// The selecting grid's props are declared over the dialogs' shared embedded +// props, so typing them makes the consumer resolve the grid contract through +// the dialogs contract, as a cell resolves it through the theme's. +import type { SelectGridProps } from "@fx/tx/grid"; interface Greeter { greet(name?: string): string; @@ -156,6 +160,17 @@ const row: GridSelectRow = { // The props of the embeddable grid, typed by the contract: the request a // consumer would print, its stream left out, and the columns to lay it out in. const embedded: GridProps = { request: { rows: [cells] }, width: 40 }; +// The props of the embeddable selecting grid: the request \`select\` takes, +// sized and focused by the host, and called back with what \`select\` would +// have resolved. +const embeddedRows: SelectGridProps = { + request: { message: "Greet which?", rows: [row] }, + width: 40, + height: 10, + isActive: true, + onSubmit: (chosen) => void [chosen.value.toUpperCase(), chosen.action], + onCancel: () => undefined, +}; const plugin: Plugin = ({ command, @@ -202,6 +217,15 @@ const plugin: Plugin = ({ ink.renderToString(react.createElement(Table, embedded)), ); } + // The selecting grid, cast the same way. Only built here, not mounted, + // because a host renders it inside a session of its own. + if (grid) { + const { react } = dependencies; + const Rows = grid.SelectGrid as ( + props: SelectGridProps, + ) => ReactNode; + void react.createElement(Rows, embeddedRows); + } // The config capability, read and typed the same way. Its contract is // reachable on its own: nothing behind this import is a store, a path, // or the marketplace plugin that used to be the only place the shape