/** * Interaction tests for OpenTUI components on `TestHost`, without a native * renderer. Extends `Play.Play` with terminal input and focus assertions. * * Focus follows `focused` props at commit, `OpenTuiCommand.focus` and * `blur`, and uncancelled left clicks. The `input`, `textarea`, `select`, * `tabSelect` and `scrollbox` elements are focusable by default; the * `focusable` style overrides that default. Moving focus between elements * sends `blur` to the previous element, then `focus` to the next. * * Keys reach global `OpenTuiSubscription` listeners before the focused * element's `keydown` handler. Cancelling a key stops delivery to the * element. Mouse events reach the nearest handler on the target or its * ancestors; other events reach only the target. * * Widget key behavior, such as arrow navigation in a select, is not * simulated. Use `select` to change an option, `fire` to send a widget * event, or `OpenTuiTest` to test the native widgets. * * Provide `TestHost.layer()` and any services the component needs. * `make` and `fromCase` supply terminal events and `OpenTui.Host`, reusing * `TestOpenTuiEvents.layer` when provided so external events reach the * component and commands are recorded. * * **Example** (Typing a name) * * ```ts import.meta.vitest * import { UiSchema } from "effect/ui" * import { Locator, TestHost } from "effect/ui/testing" * import { OpenTui } from "@effect/ui-opentui" * import { OpenTuiPlay } from "@effect/ui-opentui/testing" * import { Effect, Schema } from "effect" * * const Message = UiSchema.TaggedEnum({ * ChangedName: { value: Schema.String }, * Cleared: {} * }) * * const Greeter = OpenTui.component({ * name: "Greeter", * model: Schema.Struct({ name: Schema.String }), * message: Message * }).make({ * init: () => ({ name: "" }), * update: { * ChangedName: ($, { value }) => $.evolve({ name: value }), * Cleared: ($) => $.evolve({ name: "" }) * }, * view: (h, model) => * h.box.children( * h.input.value(model.name).on( * "input", * ({ value }) => Message.ChangedName({ value }) * ), * h.box.on("mousedown", Message.Cleared()).children(h.text("clear")), * h.text(`Hello, ${model.name}`) * ) * }) * * Effect.gen(function*() { * const play = yield* OpenTuiPlay.make(Greeter, {}) * yield* play.click(Locator.tag("input")) * yield* play.type("Ada") * yield* play.expect(Locator.tag("input")).toHaveValue("Ada") * yield* play.expect(Locator.text("Hello, Ada")).toExist() * yield* play.click("clear") * yield* play.expect(Locator.tag("input")).toHaveValue("") * }).pipe(Effect.scoped, Effect.provide(TestHost.layer()), Effect.runPromise) * ``` * * @stability experimental * @since 4.2.0 */ import type * as OT from "@opentui/core" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Option from "effect/Option" import type * as Scope from "effect/Scope" import type * as Component from "effect/ui/Component" import * as Renderer from "effect/ui/Renderer" import type * as Case from "effect/ui/testing/Case" import * as Locator from "effect/ui/testing/Locator" import * as Play from "effect/ui/testing/Play" import * as TestHost from "effect/ui/testing/TestHost" import type * as View from "effect/ui/View" import { observe } from "../internal/heard.ts" import * as OpenTui from "../OpenTui.ts" import type * as OpenTuiHost from "../OpenTuiHost.ts" import * as OpenTuiSubscription from "../OpenTuiSubscription.ts" import * as TestOpenTuiEvents from "./TestOpenTuiEvents.ts" /** * Extends Play assertions with field values, selection and focus. * * @stability experimental * @category models * @since 4.2.0 */ export interface Expect extends Play.Expect { /** Asserts the value of the `input` or `textarea`: what the view set, or what was typed into it. */ toHaveValue(value: string): Effect.Effect /** Asserts the selected option's index in the `select` or `tabSelect`. */ toHaveSelectedIndex(index: number): Effect.Effect /** Asserts that the element has focus, or hasn't with `false`. */ toBeFocused(focused?: boolean): Effect.Effect } /** * The fields of a key a step sends, besides its name. Each defaults to * `false`, `sequence` to the key, `eventType` to `"press"`, and * `editable` to whether an `input` or `textarea` has focus. * * @stability experimental * @category models * @since 4.2.0 */ export type KeyDetails = Partial> /** * A Play cursor with terminal interactions on `TestHost`. * * @stability experimental * @category models * @since 4.2.0 */ export interface OpenTuiPlay extends Play.Play { /** * Sends `mousedown`, applies focus, then sends `mouseup`. If a press or * focus handler produces a message, settles before release. If the target * was removed, releases on its nearest ancestor still in the tree. * An uncancelled left press focuses the nearest focusable element, * including the target. A string target means `Locator.text(target)`. * Defaults to the left button at the origin with no modifiers. * Throws when neither event reaches a handler and focus does not move. */ click( target: string | Locator.Locator, details?: Partial ): Effect.Effect /** * Presses `key`, named as `OpenTuiKeyboard` names keys, such as `"a"`, * `"return"` or `"down"`. The global `keypress` listeners get it first, * then the focused element's `keydown`, unless a listener cancelled it. * Throws when no listener heard it and the focused element, if any, has no * `keydown` handler. */ pressKey( key: string, details?: KeyDetails ): Effect.Effect /** * Types `text` into the focused `input` or `textarea`, one character at a * time. Each character goes through the listeners as `pressKey` sends it, * then, unless one cancelled it, is added to the field's value and sent as * `input`. The tree settles after each character, so a field the Model * controls drops a character it refused before the next one. Throws when * nothing has focus, or the focused element isn't a field. */ type(text: string): Effect.Effect /** * Pastes `text`: the global `paste` listeners get it first, then the * focused element's `paste`, unless a listener cancelled it. A focused * `input` or `textarea` then adds it to its value and sends `input`, * unless something cancelled the paste. */ paste(text: string): Effect.Effect /** Resizes the terminal: sends `resize` to the global listeners. Throws when none listens. */ resize(width: number, height: number): Effect.Effect /** * Turns the mouse wheel over the one element `locator` matches: sends * `mousescroll` with `direction` and `delta`, `1` by default. */ scroll( locator: Locator.Locator, direction: OpenTui.MouseScrollInfo["direction"], delta?: number ): Effect.Effect /** * Selects the option at `index` in the one `select` or `tabSelect` * `locator` matches: writes `selectedIndex`, then sends * `selectionChanged` with the option. A `selectedIndex` the Model * controls goes back to the Model's once the step settles, unless the * Model took the change. Send `itemSelected` with `fire`. */ select( locator: Locator.Locator, index: number ): Effect.Effect /** Asserts on the elements `locator` matches, once the tree has settled. */ expect(locator: Locator.Locator): Expect } const mouseEvents: ReadonlySet = new Set([ "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "mousescroll" ]) const focusableTags: ReadonlySet = new Set([ "input", "textarea", "select", "tabSelect", "scrollbox" ]) const fields: ReadonlySet = new Set(["input", "textarea"]) const selects: ReadonlySet = new Set(["select", "tabSelect"]) const isFocusable = (element: TestHost.TestElement): boolean => { const style = element.props.focusable return style === undefined ? focusableTags.has(element.tag) : style === true } const ancestors = ( node: TestHost.TestElement ): ReadonlyArray => { const out: Array = [] for (let at: TestHost.TestElement | undefined = node; at; at = at.parent) { out.push(at) } return out } /** In a tree a root renders, not removed. */ const isAttached = (element: TestHost.TestElement): boolean => { let at = element while (at.parent !== undefined) at = at.parent return at.tag === "#root" } const pointer: OpenTui.MousePayload = { x: 0, y: 0, button: 0, shift: false, alt: false, ctrl: false } const describe = (element: TestHost.TestElement): string => `<${element.tag}>` type Send = (element: TestHost.TestElement, event: string) => void const direct: Send = (element, event) => { if (Object.hasOwn(element.handlers, event)) { element.dispatch?.(event, element.handlers[event]!, {}) } } class Focus { private current: TestHost.TestElement | undefined readonly pending = new Map() get(): TestHost.TestElement | undefined { if (this.current !== undefined && !isAttached(this.current)) { this.current = undefined } return this.current } /** Moves focus to `element` if it can take it. Returns whether it moved. */ focus(element: TestHost.TestElement, send: Send = direct): boolean { const previous = this.get() if (previous === element || !isFocusable(element) || !isAttached(element)) { return false } this.current = element if (previous !== undefined) send(previous, "blur") send(element, "focus") return true } blur(element: TestHost.TestElement, send: Send = direct): void { if (this.get() !== element) return this.current = undefined send(element, "blur") } /** Applies the `focused` props the flush set, blurs first, as `OpenTuiHost` does. */ commit(): void { for (const [element, focused] of this.pending) { if (!focused) this.blur(element) } for (const [element, focused] of this.pending) { if (focused) this.focus(element) } this.pending.clear() } } const terminalHost = ( base: Renderer.Host, focus: Focus, selected: WeakMap ): Renderer.Host => ({ ...base, controlled: new Set([...base.controlled, "selectedIndex", "focused"]), setProp(node, name, value) { const element = node as TestHost.TestElement if (name === "focused") focus.pending.set(element, Boolean(value)) else if (name === "selectedIndex") { if (value === undefined) selected.delete(element) else selected.set(element, value) } base.setProp(node, name, value) }, commit() { base.commit?.() focus.commit() } }) const keyPayload = ( key: string, details: KeyDetails | undefined, focused: TestHost.TestElement | undefined ): OpenTui.KeyPayload => ({ key, sequence: details?.sequence ?? key, ctrl: details?.ctrl ?? false, shift: details?.shift ?? false, meta: details?.meta ?? false, option: details?.option ?? false, repeat: details?.repeat ?? false, eventType: details?.eventType ?? "press", editable: details?.editable ?? (focused !== undefined && fields.has(focused.tag)) }) const nothingFocused = "nothing has focus: click it, or render it with focused(true)" const valueOf = (element: Locator.Node): string => { const value = element.props?.value return value === undefined ? "" : String(value) } const one = ( check: (node: Locator.Node) => string | undefined ): Play.Matcher => (nodes) => nodes.length === 1 ? check(nodes[0]!) : `${nodes.length} elements match` interface Terminal { readonly events: TestOpenTuiEvents.TestOpenTuiEvents readonly focus: Focus readonly selected: WeakMap } const terminalSteps = ( driver: Play.Driver, { events, focus, selected }: Terminal ) => { const route = ( action: Play.Action, event: "keydown" | "paste", fire: () => boolean, payload: unknown ) => { const focused = focus.get() const [cancelled, global] = observe(fire) if (global.heard) action.heard(global.handled) const sent = cancelled || focused === undefined ? undefined : action.send(focused, event, payload) return { focused, prevented: cancelled || sent?.prevented === true, heard: global.heard || sent !== undefined } } const pressKey = (action: Play.Action, key: string, details?: KeyDetails) => { const payload = keyPayload(key, details, focus.get()) return route( action, "keydown", () => events.pressKey(key, payload), payload ) } const edit = ( action: Play.Action, field: TestHost.TestElement, text: string ): boolean => { const value = valueOf(field) + text field.props.value = value return action.send(field, "input", { value }) !== undefined } const focusedField = (step: string): TestHost.TestElement => { const field = focus.get() if (field === undefined) { throw new Error(`OpenTuiPlay.${step}: ${nothingFocused}`) } if (!fields.has(field.tag)) { throw new Error( `OpenTuiPlay.${step}: the focused ${describe(field)} isn't an input or textarea` ) } return field } const matchers = { toHaveValue: (expected: string) => one((node) => { const value = valueOf(node) return value === expected ? undefined : `its value is ${JSON.stringify(value)}` }), toHaveSelectedIndex: (expected: number) => one((node) => { if (node.tag === undefined || !selects.has(node.tag)) { return `it is a <${node.tag}>, not a select or tabSelect` } const index = (node.props?.selectedIndex as number | undefined) ?? 0 return index === expected ? undefined : `its selected index is ${index}` }), toBeFocused: (expected = true) => one((node) => { const focused = focus.get() if ((focused === node) === expected) return undefined return focused === undefined ? "nothing has focus" : focused === node ? "it has focus" : `${describe(focused)} has focus` }) } return { click( target: string | Locator.Locator, details?: Partial ): Effect.Effect { const locator = typeof target === "string" ? Locator.text(target) : target const payload: OpenTui.MousePayload = { ...pointer, ...details } return driver.step("click", function*(action) { const node = action.find(locator) const path = ancestors(node) const down = action.send(node, "mousedown", payload) let handled = down?.handled === true let moved = false if (payload.button === 0 && down?.prevented !== true) { const into = path.find(isFocusable) moved = into !== undefined && focus.focus(into, (element, event) => { if (action.send(element, event, {})?.handled === true) { handled = true } }) if (moved) action.heard(true) } // A message from the press or the focus it moved can change the tree before the release. if (handled) yield // The terminal sends the release to what is under the pointer by then. const under = path.find(isAttached) const up = under && action.send(under, "mouseup", payload) if (down === undefined && up === undefined && !moved) { throw new Error( `OpenTuiPlay.click: nothing handles "mousedown" or "mouseup" at ${locator.description}, and nothing focusable holds it` ) } }) }, pressKey( key: string, details?: KeyDetails ): Effect.Effect { return driver.step("pressKey", (action) => { const { focused, heard } = pressKey(action, key, details) if (!heard) { throw new Error( `OpenTuiPlay.pressKey: nothing listens for "${key}": no key listener heard it, and ${ focused === undefined ? nothingFocused : `the focused ${describe(focused)} has no keydown handler${ fields.has(focused.tag) ? "; type(text) types into it" : selects.has(focused.tag) ? "; select(locator, index) picks an option" : "" }` }` ) } }) }, type(text: string): Effect.Effect { return driver.step("type", function*(action) { let reached = false for (const character of text) { const field = focusedField("type") const key = character === " " ? "space" : character.toLowerCase() const routed = pressKey(action, key, { sequence: character, shift: character !== character.toLowerCase() }) reached ||= routed.heard if (!routed.prevented) { reached = edit(action, field, character) || reached } yield } if (text.length === 0) focusedField("type") if (!reached) { throw new Error( `OpenTuiPlay.type: nothing handles typing into the focused ${ describe(focus.get()!) }: it has no input or keydown handler, and no key listener heard it` ) } }) }, paste(text: string): Effect.Effect { return driver.step("paste", (action) => { const routed = route( action, "paste", () => events.paste(text), { text } ) const field = routed.focused const edited = !routed.prevented && field !== undefined && fields.has(field.tag) && edit(action, field, text) if (!routed.heard && !edited) { throw new Error( `OpenTuiPlay.paste: nothing listens for "paste": no paste listener heard it, and ${ field === undefined ? nothingFocused : `the focused ${describe(field)} has no paste handler` }` ) } }) }, resize( width: number, height: number ): Effect.Effect { return driver.step("resize", (action) => { const [, global] = observe(() => events.resize(width, height)) if (!global.heard) { throw new Error(`OpenTuiPlay.resize: nothing listens for "resize"`) } action.heard(global.handled) }) }, scroll( locator: Locator.Locator, direction: OpenTui.MouseScrollInfo["direction"], delta = 1 ): Effect.Effect { return driver.step("scroll", (action) => { action.send( action.find(locator), "mousescroll", { ...pointer, scroll: { direction, delta } } ) }) }, select( locator: Locator.Locator, index: number ): Effect.Effect { return driver.step("select", function*(action) { const node = action.find(locator) if (!selects.has(node.tag)) { throw new Error( `OpenTuiPlay.select: ${locator.description} is a ${describe(node)}, not a select or tabSelect` ) } const options = (node.props.options as ReadonlyArray | undefined) ?? [] if (!Number.isInteger(index) || index < 0 || index >= options.length) { throw new Error( `OpenTuiPlay.select: ${locator.description} has no option ${index}: it has ${options.length}` ) } node.props.selectedIndex = index action.send(node, "selectionChanged", { index, option: options[index]! }) yield if (selected.has(node)) node.props.selectedIndex = selected.get(node) }) }, expect(locator: Locator.Locator): Expect { return driver.expect(locator, matchers) } } } const Run = Context.Service( "@effect/ui-opentui/testing/OpenTuiPlay/Run" ) const start = (start: Play.Start, caller: Function) => Play.custom({ module: "OpenTuiPlay", caller, start, bubbles: (event) => mouseEvents.has(event), steps: (driver) => Effect.map( Effect.service(Run), (terminal) => terminalSteps(driver, terminal) ), around: Effect.fnUntraced(function*( run: Effect.Effect ) { const { host } = yield* TestHost.TestHost const upstream = yield* OpenTuiSubscription.GlobalEvents const shared = Option.getOrUndefined( yield* Effect.serviceOption(TestOpenTuiEvents.TestOpenTuiEvents) ) const recorder = Option.getOrElse( yield* Effect.serviceOption(OpenTui.Host), () => TestOpenTuiEvents.makeHostRecorder() ) const own = shared === undefined ? TestOpenTuiEvents.make() : undefined const terminal: Terminal = { events: own ?? shared!, focus: new Focus(), selected: new WeakMap() } // `TestOpenTuiEvents.layer` makes its events the global ones. Otherwise a // listener goes to `upstream` too, so the events a test fires there still arrive. const source: OpenTuiSubscription.GlobalEvents = own === undefined ? upstream : { listen: (event, listener) => { const offUpstream = upstream.listen(event, listener) const offOwn = own.listen(event, listener) return () => { offOwn() offUpstream() } } } return yield* run.pipe( Effect.provideService(Run, terminal), Effect.provideService(Renderer.Renderer, { host: terminalHost(host, terminal.focus, terminal.selected) }), Effect.provideService(OpenTuiSubscription.GlobalEvents, source), Effect.provideService(OpenTui.Host, { ...recorder, focus: (node) => { terminal.focus.focus(node as unknown as TestHost.TestElement) recorder.focus(node) }, blur: (node) => { terminal.focus.blur(node as unknown as TestHost.TestElement) recorder.blur(node) } }) ) }) }) /** * Mounts `component` on `TestHost` with `props`, settles, and returns an * OpenTUI cursor over it. It takes what `Play.make` takes, and runs the * same end check when the scope closes. * * @stability experimental * @category constructors * @since 4.2.0 */ export const make = < Name extends string, Props, Model, Msg, Events, R, V extends View.Elements, RP = never >( component: & Component.Members & OpenTuiHost.OpenTuiRoot, props: Component.PropsInput ): Effect.Effect< OpenTuiPlay, Play.StepError, Exclude | TestHost.TestHost | Scope.Scope > => start({ component, props }, make) as any /** * Mounts a `Case` on `TestHost`, sends its messages, settles, and returns * an `OpenTuiPlay` cursor over it, as `Play.fromCase` does. * * @stability experimental * @category constructors * @since 4.2.0 */ export const fromCase = ( c: Case.Case ): Effect.Effect< OpenTuiPlay< Component.Model, Component.Message, Component.Events >, Play.StepError, Exclude | TestHost.TestHost | Scope.Scope > => start(c, fromCase) as any