From dee45e578e2ca425383239f40bfc9397758c7733 Mon Sep 17 00:00:00 2001 From: Corbin Crutchley Date: Mon, 10 Aug 2026 22:40:19 -0700 Subject: [PATCH] Refactor keymap (#52) * fix: initial keymap refactor * chore: migrate to `[Ctrl+C]` syntax instead of `[Ctrl]c` * docs: initial migrate to v4 docs * chore: remove backcompat * docs: improve v3 migration guide * chore: test keyboard OS portability * ci: apply automated fixes and generate docs --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- .changeset/tidy-dingos-type.md | 4 +- .github/workflows/ci.yml | 8 +- .github/workflows/keyboard-portability.yml | 34 +++ .github/workflows/pr.yml | 7 + docs/differences.md | 8 +- docs/introduction.md | 1 + docs/migrating-from-v3-to-v4.md | 116 +++++++ docs/reference/index.md | 2 + docs/reference/interfaces/keyboardKey.md | 4 +- .../reference/type-aliases/keyboardOptions.md | 36 +++ docs/reference/variables/defaultKeyMap.md | 19 ++ docs/user-event.md | 52 +++- packages/cli-testing-library/package.json | 1 + .../src/user-event/index.ts | 3 +- .../src/user-event/keyboard/getNextKeyDef.ts | 101 ++++++- .../src/user-event/keyboard/index.ts | 1 + .../src/user-event/keyboard/keyMap.ts | 285 +++++------------- .../keyboard/keyboardImplementation.ts | 18 +- .../src/user-event/keyboard/types.ts | 4 +- .../tests/execute-scripts/readline-keys.js | 41 +++ .../tests/execute-scripts/stdin-bytes.js | 28 ++ .../tests/keyboard-map.spec.ts | 123 ++++++++ .../tests/keyboard-portability.spec.ts | 172 +++++++++++ .../tests/user-keyboard.spec.ts | 2 +- website/astro.config.mjs | 4 + 25 files changed, 818 insertions(+), 256 deletions(-) create mode 100644 .github/workflows/keyboard-portability.yml create mode 100644 docs/migrating-from-v3-to-v4.md create mode 100644 docs/reference/type-aliases/keyboardOptions.md create mode 100644 docs/reference/variables/defaultKeyMap.md create mode 100644 packages/cli-testing-library/tests/execute-scripts/readline-keys.js create mode 100644 packages/cli-testing-library/tests/execute-scripts/stdin-bytes.js create mode 100644 packages/cli-testing-library/tests/keyboard-map.spec.ts create mode 100644 packages/cli-testing-library/tests/keyboard-portability.spec.ts diff --git a/.changeset/tidy-dingos-type.md b/.changeset/tidy-dingos-type.md index 4bf4784..ad633eb 100644 --- a/.changeset/tidy-dingos-type.md +++ b/.changeset/tidy-dingos-type.md @@ -2,4 +2,6 @@ "cli-testing-library": patch --- -Support forward slashes, backslashes, and Ctrl+C in `userEvent.keyboard`. +Write printable and Unicode text without manual key-map entries, support Ctrl +chords through descriptors such as `[Ctrl+C]`, and add common terminal keys to +`userEvent.keyboard`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4832359..861a01b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,10 +28,16 @@ jobs: - name: Run Tests run: pnpm run test:ci --parallel=3 + keyboard-portability: + name: Keyboard portability + permissions: + contents: read + uses: ./.github/workflows/keyboard-portability.yml + release: name: Release if: github.repository == 'crutchcorn/cli-testing-library' && github.ref_name == 'main' - needs: test + needs: [test, keyboard-portability] runs-on: ubuntu-latest permissions: contents: write diff --git a/.github/workflows/keyboard-portability.yml b/.github/workflows/keyboard-portability.yml new file mode 100644 index 0000000..eaa8427 --- /dev/null +++ b/.github/workflows/keyboard-portability.yml @@ -0,0 +1,34 @@ +name: keyboard-portability + +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + name: Test (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Setup pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + node-version-file: .nvmrc + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Test keyboard portability + run: pnpm --filter cli-testing-library test:keyboard:portability diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 0ba6049..dfd3ade 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -27,6 +27,13 @@ jobs: uses: tanstack/config/.github/setup@0b5996988cf0938ae77119e0164f9738a453d7c8 # main - name: Run Checks run: pnpm run test:pr --parallel=3 + + keyboard-portability: + name: Keyboard portability + permissions: + contents: read + uses: ./.github/workflows/keyboard-portability.yml + preview: name: Preview runs-on: ubuntu-latest diff --git a/docs/differences.md b/docs/differences.md index a24d863..fff9597 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -76,10 +76,10 @@ However, there are a few differences here as well: 1. `userEvent` can be bound to the `render` output. This is due to limitations of not having a `screen` API. It's unclear how this would work in practice, due to a lack of the `window` API. -2. `userEvent.keyboard` does not support modifier keys. It's only key-presses, - no holding. This is because of API differences that would require us to - figure out a manual binding system for every single key using ANSI AFAIK. -3. Relatedly, we've remove the `{` syntax support, since there is no standard +2. `userEvent.keyboard` supports atomic Ctrl chords such as `[Ctrl+C]`, but it + does not model arbitrary modifier-key state or held keys. Shift, Alt, and + Meta chords are not currently supported. +3. Relatedly, we've removed the `{` syntax support, since there is no standard keybinding for the CLI, [like there is for the DOM](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code). Instead, we only support `[` and `]` syntax. diff --git a/docs/introduction.md b/docs/introduction.md index b6613e5..c90e044 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -51,6 +51,7 @@ will work when a real user uses it. # Further Reading +- [Migrating from v3 to v4](./migrating-from-v3-to-v4.md) - [API reference for `render` and friends](./api.md) - [Jest and Vitest matchers](./matchers.md) - [Mock user input](./user-event.md) diff --git a/docs/migrating-from-v3-to-v4.md b/docs/migrating-from-v3-to-v4.md new file mode 100644 index 0000000..ec27f92 --- /dev/null +++ b/docs/migrating-from-v3-to-v4.md @@ -0,0 +1,116 @@ +--- +title: "Migrating from v3 to v4" +--- + +This guide covers the keyboard-input changes that may affect tests when +upgrading from CLI Testing Library v3 to v4. It does not cover unrelated v4 +changes. + +## Summary + +Version 4 of CLI Testing Library moves the library to ESM rather than CJS. This means that the minimum Node version required to use this tool is now 22.18.0, and the library must be imported with `import` rather than `require`. + +This version also changes `userEvent.keyboard` from a manually enumerated character +map into a text-and-terminal-key encoder: + +- Printable text and Unicode are written directly to stdin. +- Ctrl chords use an atomic descriptor such as `[Ctrl+C]`. +- Named terminal keys remain in `defaultKeyMap`. +- `defaultKeyMap` is exported so custom descriptors can extend it. + +These changes remove the need to add every printable character to the key map, +but they also change a few observable behaviors described below. + +## Migration checklist + +- Migrate away from CJS instance of library +- Replace Ctrl workarounds with `[Ctrl+]` descriptors. +- Update assertions that expected `Unknown` for printable or Unicode input. +- Remove printable-character entries from custom keyboard maps. +- Verify terminal-specific custom keys on every operating system in your test + matrix. + +## Use atomic Ctrl chord descriptors + +Version 3 did not include built-in Ctrl chord support. Tests commonly used +`fireEvent.write` as a workaround: + +```js +fireEvent.write(instance, { value: "\x03" }); +``` + +In version 4, use a single chord descriptor: + +```js +userEvent.keyboard("[Ctrl+C]"); +userEvent.keyboard("[Ctrl+D]"); +userEvent.keyboard("[Ctrl+Space]"); +``` + +`[Control+C]` is also accepted. Named operands can be used when punctuation is +hard to read or conflicts with descriptor syntax: + +```js +userEvent.keyboard("[Ctrl+KeyC]"); +userEvent.keyboard("[Ctrl+BracketLeft]"); +userEvent.keyboard("[Ctrl+Backslash]"); +``` + +Do not use `[CtrlC]`. Without the `+`, it is interpreted as a named key called +`CtrlC`, not as a chord. + +See [Chording](./user-event.md#chording) for the complete chord behavior and +timing semantics. + +## Printable text no longer needs map entries + +In version 3, a printable character missing from the manual map was written as +`Unknown`. Version 4 writes printable and Unicode text directly: + +```js +userEvent.keyboard('/test-dir\\name?filter="active"'); +userEvent.keyboard("Grüße 👋"); +``` + +This is intentionally observable. Update tests that asserted `Unknown` for +previously unsupported punctuation or Unicode to assert the actual input. + +The opening bracket still begins a named descriptor. Double it to type a +literal opening bracket: + +```js +userEvent.keyboard("[[value]"); // types: [value] +``` + +## Custom keyboard maps + +Custom maps should now describe named terminal keys or application-specific +actions, rather than enumerate printable text. Extend the exported default map +when adding a descriptor: + +```js +import { defaultKeyMap } from "cli-testing-library"; + +userEvent.keyboard("[Confirm]", { + keyboardMap: [ + { code: "Confirm", hex: "\r" }, + ...defaultKeyMap, + ], +}); +``` + +The first matching descriptor wins, so put overrides before +`...defaultKeyMap`. + +`Ctrl` and `Control` are modifier names on the left side of `+` inside a chord +descriptor. They are not standalone named keys. + +## Named key additions + +Version 4 adds names for Tab, Shift+Tab, Insert, common punctuation keys, and +F1 through F12. Existing Enter, Escape, Backspace, arrow, Home, End, Delete, +Page Up, and Page Down descriptors retain their previous byte sequences. + +The default sequences target Node `readline` and xterm-compatible input. CLI +programs that require a real TTY or a different terminal protocol may still +need a custom map or direct `fireEvent.write` calls. diff --git a/docs/reference/index.md b/docs/reference/index.md index ed34aab..5208e4d 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -38,6 +38,7 @@ title: cli-testing-library - [GetByError](type-aliases/GetByError.md) - [GetByText](type-aliases/GetByText.md) - [GetErrorFunction](type-aliases/GetErrorFunction.md) +- [keyboardOptions](type-aliases/keyboardOptions.md) - [Match](type-aliases/Match.md) - [Matcher](type-aliases/Matcher.md) - [MatcherFunction](type-aliases/MatcherFunction.md) @@ -51,6 +52,7 @@ title: cli-testing-library ## Variables +- [defaultKeyMap](variables/defaultKeyMap.md) - [fireEvent](variables/fireEvent.md) ## Functions diff --git a/docs/reference/interfaces/keyboardKey.md b/docs/reference/interfaces/keyboardKey.md index 2720a84..f89470b 100644 --- a/docs/reference/interfaces/keyboardKey.md +++ b/docs/reference/interfaces/keyboardKey.md @@ -17,7 +17,7 @@ optional code?: string; Defined in: [user-event/keyboard/types.ts:10](https://github.com/crutchcorn/cli-testing-library/blob/main/packages/cli-testing-library/src/user-event/keyboard/types.ts#L10) -Physical location on a keyboard +Named key descriptor, such as `Enter` or `ArrowLeft` *** @@ -29,4 +29,4 @@ optional hex?: string; Defined in: [user-event/keyboard/types.ts:12](https://github.com/crutchcorn/cli-testing-library/blob/main/packages/cli-testing-library/src/user-event/keyboard/types.ts#L12) -Character or functional key hex code +String written to stdin (historically named `hex`) diff --git a/docs/reference/type-aliases/keyboardOptions.md b/docs/reference/type-aliases/keyboardOptions.md new file mode 100644 index 0000000..7305db3 --- /dev/null +++ b/docs/reference/type-aliases/keyboardOptions.md @@ -0,0 +1,36 @@ +--- +id: keyboardOptions +title: keyboardOptions +--- + +# Type Alias: keyboardOptions + +```ts +type keyboardOptions = object; +``` + +Defined in: [user-event/keyboard/types.ts:1](https://github.com/crutchcorn/cli-testing-library/blob/main/packages/cli-testing-library/src/user-event/keyboard/types.ts#L1) + +## Properties + +### delay + +```ts +delay: number; +``` + +Defined in: [user-event/keyboard/types.ts:3](https://github.com/crutchcorn/cli-testing-library/blob/main/packages/cli-testing-library/src/user-event/keyboard/types.ts#L3) + +Delay between keystrokes + +*** + +### keyboardMap + +```ts +keyboardMap: keyboardKey[]; +``` + +Defined in: [user-event/keyboard/types.ts:5](https://github.com/crutchcorn/cli-testing-library/blob/main/packages/cli-testing-library/src/user-event/keyboard/types.ts#L5) + +Keyboard layout to use diff --git a/docs/reference/variables/defaultKeyMap.md b/docs/reference/variables/defaultKeyMap.md new file mode 100644 index 0000000..7e0df16 --- /dev/null +++ b/docs/reference/variables/defaultKeyMap.md @@ -0,0 +1,19 @@ +--- +id: defaultKeyMap +title: defaultKeyMap +--- + +# Variable: defaultKeyMap + +```ts +const defaultKeyMap: keyboardKey[]; +``` + +Defined in: [user-event/keyboard/keyMap.ts:34](https://github.com/crutchcorn/cli-testing-library/blob/main/packages/cli-testing-library/src/user-event/keyboard/keyMap.ts#L34) + +Named key descriptors supported by the default terminal keyboard. + +Printable text is written directly to stdin and deliberately does not need +an entry here. This map is reserved for named physical keys and terminal +escape sequences. The generated digit and letter entries preserve support +for descriptors such as `[Digit1]`, `[KeyA]`, and `[KeyLowerA]`. diff --git a/docs/user-event.md b/docs/user-event.md index a79248c..ee5bfff 100644 --- a/docs/user-event.md +++ b/docs/user-event.md @@ -5,6 +5,10 @@ title: "User Event" [`user-event`][gh] is a helper that provides more advanced simulation of CLI interactions than the [`fireEvent`](./fire-event.md) method. +> Upgrading from v3? See the +> [v3 to v4 migration guide](./migrating-from-v3-to-v4.md) for keyboard-input +> changes. + ## Import `userEvent` can be used either as a global import or as returned from `render`: @@ -58,8 +62,12 @@ Keystrokes can be described: ```js userEvent.keyboard("foo"); // translates to: f, o, o userEvent.keyboard("/test-dir\\"); // forward and backslashes are typed literally + userEvent.keyboard("Grüße 👋"); // Unicode text is typed literally too ``` + Printable text is written directly to the process. It does not need to be + added to the keyboard map. + The bracket `[` is used as a special character and can be referenced by doubling it. @@ -71,22 +79,43 @@ Keystrokes can be described: symbol ```js - userEvent.keyboard("[ArrowLeft][KeyF][KeyO][KeyO]"); // translates to: Left Arrow, f, o, o + userEvent.keyboard("[ArrowLeft][KeyF][KeyO][KeyO]"); // translates to: Left Arrow, F, O, O ``` - This does not keep any key pressed. So `Shift` will be lifted before pressing - `f`. +Named special keys are resolved through the +[default terminal key map](../packages/cli-testing-library/src/user-event/keyboard/keyMap.ts). +You can provide your own mapping to replace it, or extend the default map with +application-specific descriptors. -The mapping of special character strings are performed by a -[default key map](../packages/cli-testing-library/src/user-event/keyboard/keyMap.ts) portraying a "default" -US-keyboard. You can provide your own local keyboard mapping per option. +The default map targets Node `readline` and xterm-compatible input over a piped +stdin. Its raw bytes and decoded Node keypress events are tested on Linux, +macOS, and Windows. This does not emulate a real PTY; programs that require a +TTY or another terminal protocol may need a custom map or direct `fireEvent` +calls. ```js -userEvent.keyboard("?", { keyboardMap: myOwnLocaleKeyboardMap }); +import { defaultKeyMap } from "cli-testing-library"; + +userEvent.keyboard("[Confirm]", { + keyboardMap: [ + { code: "Confirm", hex: "\r" }, + ...defaultKeyMap, + ], +}); ``` +#### Chording + +Chords use `+` inside a single descriptor. For example, `[Ctrl+C]` sends the +Ctrl+C control character and `[Ctrl+D]` sends Ctrl+D. Sequential forms such as +`[Ctrl]c` are not supported because Ctrl has no standalone terminal input. + +A chord emits one control character. For example, `[Ctrl+C]` writes only +`0x03`. When `options.delay` is set, the delay applies between the chord and +surrounding keys, not between `Ctrl` and `C`. + #### Special characters We support inputting many special character strings with the `[` syntax @@ -98,14 +127,21 @@ mentioned previously. Here are some of the ones that are supported: | `[Space]` | `' '` | | `[Escape]` | Escape | | `[Backspace]` | Backspace | -| `[Ctrl]` | Ctrl+C | +| `[Ctrl+C]` | Ctrl+C | +| `[Ctrl+D]` | Ctrl+D | +| `[Tab]` | Tab | +| `[ShiftTab]` | Shift+Tab | | `[Delete]` | Delete | +| `[Insert]` | Insert | | `[ArrowLeft]` | Left Arrow | | `[ArrowRight]` | Right Arrow | | `[ArrowUp]` | Up Arrow | | `[ArrowDown]` | Down Arrow | | `[Home]` | Home | | `[End]` | End | +| `[PageUp]` | Page Up | +| `[PageDown]` | Page Down | +| `[F1]`–`[F12]` | Function keys | A full list of supported special characters that can be input can be found [in our key mapping file](../packages/cli-testing-library/src/user-event/keyboard/keyMap.ts). diff --git a/packages/cli-testing-library/package.json b/packages/cli-testing-library/package.json index afb38f3..3a1066c 100644 --- a/packages/cli-testing-library/package.json +++ b/packages/cli-testing-library/package.json @@ -43,6 +43,7 @@ "test:types:latest": "tsc", "test:lib": "vitest", "test:lib:dev": "pnpm run test:lib --watch", + "test:keyboard:portability": "vitest run tests/keyboard-portability.spec.ts --coverage.enabled=false", "test:build": "publint --strict", "build": "tsdown" }, diff --git a/packages/cli-testing-library/src/user-event/index.ts b/packages/cli-testing-library/src/user-event/index.ts index 1604b15..84d5796 100644 --- a/packages/cli-testing-library/src/user-event/index.ts +++ b/packages/cli-testing-library/src/user-event/index.ts @@ -6,4 +6,5 @@ const userEvent = { export default userEvent; -export type { keyboardKey } from "./keyboard/index"; +export { defaultKeyMap } from "./keyboard/index"; +export type { keyboardKey, keyboardOptions } from "./keyboard/index"; diff --git a/packages/cli-testing-library/src/user-event/keyboard/getNextKeyDef.ts b/packages/cli-testing-library/src/user-event/keyboard/getNextKeyDef.ts index 298a210..f2e5de2 100644 --- a/packages/cli-testing-library/src/user-event/keyboard/getNextKeyDef.ts +++ b/packages/cli-testing-library/src/user-event/keyboard/getNextKeyDef.ts @@ -7,9 +7,10 @@ enum bracketDict { /** * Get the next key from keyMap * - * Keys can be referenced by `{key}` or `{special}` as well as physical locations per `[code]`. + * Named keys can be referenced by physical locations per `[code]`. * Everything else will be interpreted as a typed character - e.g. `a`. - * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * The opening bracket `[` can be escaped by doubling it - e.g. `foo[[bar` + * translates to `foo[bar`. */ export function getNextKeyDef( text: string, @@ -18,24 +19,101 @@ export function getNextKeyDef( keyDef: keyboardKey; consumedLength: number; } { - const { type, descriptor, consumedLength } = readNextDescriptor(text); + const descriptor = readNextDescriptor(text); + const controlChord = readInlineControlChord(descriptor, options); - const keyDef: keyboardKey = options.keyboardMap.find((def) => { + if (controlChord) return controlChord; + + return { + keyDef: resolveKeyDef(descriptor, options), + consumedLength: descriptor.consumedLength, + }; +} + +type KeyDescriptor = ReturnType; + +function resolveKeyDef( + { type, descriptor }: KeyDescriptor, + options: keyboardOptions, +): keyboardKey { + const mappedKey = options.keyboardMap.find((def) => { if (type === "[") { return def.code?.toLowerCase() === descriptor.toLowerCase(); } return def.hex === descriptor; - }) ?? { + }); + + if (mappedKey) return mappedKey; + + if (type === "") { + return { + code: descriptor, + hex: descriptor, + }; + } + + return { code: descriptor, hex: "Unknown", }; +} + +function readInlineControlChord( + descriptor: KeyDescriptor, + options: keyboardOptions, +): { keyDef: keyboardKey; consumedLength: number } | undefined { + if (descriptor.type !== "[") return undefined; + + const chordParts = descriptor.descriptor.split("+"); + if (chordParts.length !== 2) return undefined; + + const [modifier, keyDescriptor] = chordParts; + if ( + !modifier || + !keyDescriptor || + !["control", "ctrl"].includes(modifier.toLowerCase()) + ) { + return undefined; + } + + const mappedKey = options.keyboardMap.find( + (key) => key.code?.toLowerCase() === keyDescriptor.toLowerCase(), + ); + const key = + mappedKey ?? + (Array.from(keyDescriptor).length === 1 + ? { code: keyDescriptor, hex: keyDescriptor } + : undefined); + const controlCharacter = toControlCharacter(key?.hex); + + if (controlCharacter === undefined) return undefined; return { - keyDef, - consumedLength, + keyDef: { + code: `${modifier}+${keyDescriptor}`, + hex: controlCharacter, + }, + consumedLength: descriptor.consumedLength, }; } +function toControlCharacter(value: string | undefined): string | undefined { + if (!value) return undefined; + + const characters = Array.from(value); + if (characters.length !== 1) return undefined; + + const codePoint = characters[0]!.toUpperCase().codePointAt(0)!; + + if (codePoint === 0x20) return "\x00"; + if (codePoint >= 0x40 && codePoint <= 0x5f) { + return String.fromCharCode(codePoint & 0x1f); + } + if (codePoint === 0x3f) return "\x7f"; + + return undefined; +} + function readNextDescriptor(text: string) { let pos = 0; const startBracket = @@ -43,8 +121,7 @@ function readNextDescriptor(text: string) { pos += startBracket.length; - // `foo[[bar` is an escaped char at position 3, - // but `foo[[[>5}bar` should be treated as `{` pressed down for 5 keydowns. + // `foo[[bar` is an escaped opening bracket at position 3. const startBracketRepeated = startBracket ? (text.match(new RegExp(`^\\${startBracket}+`)) as RegExpMatchArray)[0] .length @@ -60,7 +137,9 @@ function readNextDescriptor(text: string) { } function readPrintableChar(text: string, pos: number) { - const descriptor = text[pos]; + const codePoint = text.codePointAt(pos); + const descriptor = + codePoint === undefined ? undefined : String.fromCodePoint(codePoint); assertDescriptor(descriptor, text, pos); @@ -80,7 +159,7 @@ function readTag( pos: number, startBracket: keyof typeof bracketDict, ) { - const descriptor = text.slice(pos).match(/^\w+/)?.[0]; + const descriptor = text.slice(pos).match(/^[^\]]+/)?.[0]; assertDescriptor(descriptor, text, pos); diff --git a/packages/cli-testing-library/src/user-event/keyboard/index.ts b/packages/cli-testing-library/src/user-event/keyboard/index.ts index 3ac9e2b..498fada 100644 --- a/packages/cli-testing-library/src/user-event/keyboard/index.ts +++ b/packages/cli-testing-library/src/user-event/keyboard/index.ts @@ -4,6 +4,7 @@ import type { TestInstance } from "../../types"; import type { keyboardKey, keyboardOptions } from "./types"; export type { keyboardOptions, keyboardKey }; +export { defaultKeyMap } from "./keyMap"; export function keyboard( instance: TestInstance, diff --git a/packages/cli-testing-library/src/user-event/keyboard/keyMap.ts b/packages/cli-testing-library/src/user-event/keyboard/keyMap.ts index 6867e3b..3693a96 100644 --- a/packages/cli-testing-library/src/user-event/keyboard/keyMap.ts +++ b/packages/cli-testing-library/src/user-event/keyboard/keyMap.ts @@ -1,227 +1,84 @@ import type { keyboardKey } from "./types"; +const digitKeys: Array = Array.from( + { length: 10 }, + (_, digit) => ({ + code: `Digit${digit}`, + hex: String(digit), + }), +); + +const letterKeys: Array = Array.from( + { length: 26 }, + (_, offset) => { + const uppercaseLetter = String.fromCharCode("A".charCodeAt(0) + offset); + + return [ + { code: `Key${uppercaseLetter}`, hex: uppercaseLetter }, + { + code: `KeyLower${uppercaseLetter}`, + hex: uppercaseLetter.toLowerCase(), + }, + ]; + }, +).flat(); + /** - * Mapping for a default US-104-QWERTY keyboard + * Named key descriptors supported by the default terminal keyboard. * - * These use ANSI-C quoting, which seems to work for Linux, macOS, and Windows alike - * @see https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#ANSI_002dC-Quoting - * @see https://stackoverflow.com/questions/35429671/detecting-key-press-within-bash-scripts - * @see https://gist.github.com/crutchcorn/2811db78a7b924cf54f4507198427fd2 + * Printable text is written directly to stdin and deliberately does not need + * an entry here. This map is reserved for named physical keys and terminal + * escape sequences. The generated digit and letter entries preserve support + * for descriptors such as `[Digit1]`, `[KeyA]`, and `[KeyLowerA]`. */ export const defaultKeyMap: Array = [ - // alphanumeric keys - { code: "Digit!", hex: "\x21" }, - { code: 'Digit"', hex: "\x22" }, - { code: "Digit#", hex: "\x23" }, - { code: "Digit$", hex: "\x24" }, - { code: "Digit%", hex: "\x25" }, - { code: "Digit&", hex: "\x26" }, - { code: "Digit'", hex: "\x27" }, - { code: "Digit(", hex: "\x28" }, - { code: "Digit)", hex: "\x29" }, - { code: "Digit*", hex: "\x2a" }, - { code: "Digit+", hex: "\x2b" }, - { code: "Digit,", hex: "\x2c" }, - { code: "Digit-", hex: "\x2d" }, - { code: "Digit.", hex: "\x2e" }, - { code: "Digit/", hex: "\x2f" }, - { code: "Digit:", hex: "\x3a" }, - { code: "Digit;", hex: "\x3b" }, - { code: "Digit<", hex: "\x3c" }, - { code: "Digit=", hex: "\x3d" }, - { code: "Digit>", hex: "\x3e" }, - { code: "Digit?", hex: "\x3f" }, - { code: "Digit@", hex: "\x40" }, - { code: "Digit[", hex: "\x5b" }, - { code: "Digit]", hex: "\x5d" }, - { code: "Digit^", hex: "\x5e" }, - { code: "Digit_", hex: "\x5f" }, - { code: "Digit`", hex: "\x60" }, - { code: "Digit{", hex: "\x7b" }, - { code: "Digit|", hex: "\x7c" }, - { code: "Digit}", hex: "\x7d" }, - { code: "Digit~", hex: "\x7e" }, - { code: "Digit0", hex: "\x30" }, - { code: "Digit1", hex: "\x31" }, - { code: "Digit2", hex: "\x32" }, - { code: "Digit3", hex: "\x33" }, - { code: "Digit4", hex: "\x34" }, - { code: "Digit5", hex: "\x35" }, - { code: "Digit6", hex: "\x36" }, - { code: "Digit7", hex: "\x37" }, - { code: "Digit8", hex: "\x38" }, - { code: "Digit9", hex: "\x39" }, - { code: "KeyA", hex: "\x41" }, - { code: "KeyB", hex: "\x42" }, - { code: "KeyC", hex: "\x43" }, - { code: "KeyD", hex: "\x44" }, - { code: "KeyE", hex: "\x45" }, - { code: "KeyF", hex: "\x46" }, - { code: "KeyG", hex: "\x47" }, - { code: "KeyH", hex: "\x48" }, - { code: "KeyI", hex: "\x49" }, - { code: "KeyJ", hex: "\x4a" }, - { code: "KeyK", hex: "\x4b" }, - { code: "KeyL", hex: "\x4c" }, - { code: "KeyM", hex: "\x4d" }, - { code: "KeyN", hex: "\x4e" }, - { code: "KeyO", hex: "\x4f" }, - { code: "KeyP", hex: "\x50" }, - { code: "KeyQ", hex: "\x51" }, - { code: "KeyR", hex: "\x52" }, - { code: "KeyS", hex: "\x53" }, - { code: "KeyT", hex: "\x54" }, - { code: "KeyU", hex: "\x55" }, - { code: "KeyV", hex: "\x56" }, - { code: "KeyW", hex: "\x57" }, - { code: "KeyX", hex: "\x58" }, - { code: "KeyY", hex: "\x59" }, - { code: "KeyZ", hex: "\x5a" }, - { code: "Backslash", hex: "\x5c" }, - { code: "Digit_", hex: "\x5f" }, - { code: "KeyLowerA", hex: "\x61" }, - { code: "KeyLowerB", hex: "\x62" }, - { code: "KeyLowerC", hex: "\x63" }, - { code: "KeyLowerD", hex: "\x64" }, - { code: "KeyLowerE", hex: "\x65" }, - { code: "KeyLowerF", hex: "\x66" }, - { code: "KeyLowerG", hex: "\x67" }, - { code: "KeyLowerH", hex: "\x68" }, - { code: "KeyLowerI", hex: "\x69" }, - { code: "KeyLowerJ", hex: "\x6a" }, - { code: "KeyLowerK", hex: "\x6b" }, - { code: "KeyLowerL", hex: "\x6c" }, - { code: "KeyLowerM", hex: "\x6d" }, - { code: "KeyLowerN", hex: "\x6e" }, - { code: "KeyLowerO", hex: "\x6f" }, - { code: "KeyLowerP", hex: "\x70" }, - { code: "KeyLowerQ", hex: "\x71" }, - { code: "KeyLowerR", hex: "\x72" }, - { code: "KeyLowerS", hex: "\x73" }, - { code: "KeyLowerT", hex: "\x74" }, - { code: "KeyLowerU", hex: "\x75" }, - { code: "KeyLowerV", hex: "\x76" }, - { code: "KeyLowerW", hex: "\x77" }, - { code: "KeyLowerX", hex: "\x78" }, - { code: "KeyLowerY", hex: "\x79" }, - { code: "KeyLowerZ", hex: "\x7a" }, + ...digitKeys, + ...letterKeys, - { code: "Digit¡", hex: "\xa1" }, - { code: "Digit¢", hex: "\xa2" }, - { code: "Digit£", hex: "\xa3" }, - { code: "Digit¤", hex: "\xa4" }, - { code: "Digit¥", hex: "\xa5" }, - { code: "Digit¦", hex: "\xa6" }, - { code: "Digit§", hex: "\xa7" }, - { code: "Digit¨", hex: "\xa8" }, - { code: "Digit©", hex: "\xa9" }, - { code: "Digitª", hex: "\xaa" }, - { code: "Digit«", hex: "\xab" }, - { code: "Digit¬", hex: "\xac" }, - { code: "Digit®", hex: "\xae" }, - { code: "Digit¯", hex: "\xaf" }, - { code: "Digit°", hex: "\xb0" }, - { code: "Digit±", hex: "\xb1" }, - { code: "Digit²", hex: "\xb2" }, - { code: "Digit³", hex: "\xb3" }, - { code: "Digit´", hex: "\xb4" }, - { code: "Digitµ", hex: "\xb5" }, - { code: "Digit¶", hex: "\xb6" }, - { code: "Digit·", hex: "\xb7" }, - { code: "Digit¸", hex: "\xb8" }, - { code: "Digit¹", hex: "\xb9" }, - { code: "Digitº", hex: "\xba" }, - { code: "Digit»", hex: "\xbb" }, - { code: "Digit¼", hex: "\xbc" }, - { code: "Digit½", hex: "\xbd" }, - { code: "Digit¾", hex: "\xbe" }, - { code: "Digit¿", hex: "\xbf" }, - { code: "DigitÀ", hex: "\xc0" }, - { code: "DigitÁ", hex: "\xc1" }, - { code: "DigitÂ", hex: "\xc2" }, - { code: "DigitÃ", hex: "\xc3" }, - { code: "DigitÄ", hex: "\xc4" }, - { code: "DigitÅ", hex: "\xc5" }, - { code: "DigitÆ", hex: "\xc6" }, - { code: "DigitÇ", hex: "\xc7" }, - { code: "DigitÈ", hex: "\xc8" }, - { code: "DigitÉ", hex: "\xc9" }, - { code: "DigitÊ", hex: "\xca" }, - { code: "DigitË", hex: "\xcb" }, - { code: "DigitÌ", hex: "\xcc" }, - { code: "DigitÍ", hex: "\xcd" }, - { code: "DigitÎ", hex: "\xce" }, - { code: "DigitÏ", hex: "\xcf" }, - { code: "DigitÐ", hex: "\xd0" }, - { code: "DigitÑ", hex: "\xd1" }, - { code: "DigitÒ", hex: "\xd2" }, - { code: "DigitÓ", hex: "\xd3" }, - { code: "DigitÔ", hex: "\xd4" }, - { code: "DigitÕ", hex: "\xd5" }, - { code: "DigitÖ", hex: "\xd6" }, - { code: "Digit×", hex: "\xd7" }, - { code: "DigitØ", hex: "\xd8" }, - { code: "DigitÙ", hex: "\xd9" }, - { code: "DigitÚ", hex: "\xda" }, - { code: "DigitÛ", hex: "\xdb" }, - { code: "DigitÜ", hex: "\xdc" }, - { code: "DigitÝ", hex: "\xdd" }, - { code: "DigitÞ", hex: "\xde" }, - { code: "Digitß", hex: "\xdf" }, - { code: "Digità", hex: "\xe0" }, - { code: "Digitá", hex: "\xe1" }, - { code: "Digitâ", hex: "\xe2" }, - { code: "Digitã", hex: "\xe3" }, - { code: "Digitä", hex: "\xe4" }, - { code: "Digitå", hex: "\xe5" }, - { code: "Digitæ", hex: "\xe6" }, - { code: "Digitç", hex: "\xe7" }, - { code: "Digitè", hex: "\xe8" }, - { code: "Digité", hex: "\xe9" }, - { code: "Digitê", hex: "\xea" }, - { code: "Digitë", hex: "\xeb" }, - { code: "Digitì", hex: "\xec" }, - { code: "Digití", hex: "\xed" }, - { code: "Digitî", hex: "\xee" }, - { code: "Digitï", hex: "\xef" }, - { code: "Digitð", hex: "\xf0" }, - { code: "Digitñ", hex: "\xf1" }, - { code: "Digitò", hex: "\xf2" }, - { code: "Digitó", hex: "\xf3" }, - { code: "Digitô", hex: "\xf4" }, - { code: "Digitõ", hex: "\xf5" }, - { code: "Digitö", hex: "\xf6" }, - { code: "Digit÷", hex: "\xf7" }, - { code: "Digitø", hex: "\xf8" }, - { code: "Digitù", hex: "\xf9" }, - { code: "Digitú", hex: "\xfa" }, - { code: "Digitû", hex: "\xfb" }, - { code: "Digitü", hex: "\xfc" }, - { code: "Digitý", hex: "\xfd" }, - { code: "Digitþ", hex: "\xfe" }, - { code: "Digitÿ", hex: "\xff" }, + // Named printable physical keys + { code: "Space", hex: " " }, + { code: "Backquote", hex: "`" }, + { code: "Minus", hex: "-" }, + { code: "Equal", hex: "=" }, + { code: "BracketLeft", hex: "[" }, + { code: "BracketRight", hex: "]" }, + { code: "Backslash", hex: "\\" }, + { code: "Semicolon", hex: ";" }, + { code: "Quote", hex: "'" }, + { code: "Comma", hex: "," }, + { code: "Period", hex: "." }, + { code: "Slash", hex: "/" }, - // alphanumeric block - functional - { code: "Space", hex: "\x20" }, + // Editing and control keys + { code: "Tab", hex: "\x09" }, { code: "Backspace", hex: "\x08" }, - { code: "Enter", hex: "\x0D" }, - { code: "Ctrl", hex: "\x03" }, - - // function + { code: "Enter", hex: "\x0d" }, { code: "Escape", hex: "\x1b" }, + { code: "ShiftTab", hex: "\x1b[Z" }, - // arrows - { code: "ArrowUp", hex: "\x1b\x5b\x41" }, - { code: "ArrowDown", hex: "\x1B\x5B\x42" }, - { code: "ArrowLeft", hex: "\x1b\x5b\x44" }, - { code: "ArrowRight", hex: "\x1b\x5b\x43" }, - - // control pad - { code: "Home", hex: "\x1b\x4f\x48" }, - { code: "End", hex: "\x1b\x4f\x46" }, - { code: "Delete", hex: "\x1b\x5b\x33\x7e" }, - { code: "PageUp", hex: "\x1b\x5b\x35\x7e" }, - { code: "PageDown", hex: "\x1b\x5b\x36\x7e" }, + // Navigation keys + { code: "ArrowUp", hex: "\x1b[A" }, + { code: "ArrowDown", hex: "\x1b[B" }, + { code: "ArrowRight", hex: "\x1b[C" }, + { code: "ArrowLeft", hex: "\x1b[D" }, + { code: "Home", hex: "\x1bOH" }, + { code: "End", hex: "\x1bOF" }, + { code: "Insert", hex: "\x1b[2~" }, + { code: "Delete", hex: "\x1b[3~" }, + { code: "PageUp", hex: "\x1b[5~" }, + { code: "PageDown", hex: "\x1b[6~" }, - // TODO: add mappings + // Function keys (common xterm-compatible sequences) + { code: "F1", hex: "\x1bOP" }, + { code: "F2", hex: "\x1bOQ" }, + { code: "F3", hex: "\x1bOR" }, + { code: "F4", hex: "\x1bOS" }, + { code: "F5", hex: "\x1b[15~" }, + { code: "F6", hex: "\x1b[17~" }, + { code: "F7", hex: "\x1b[18~" }, + { code: "F8", hex: "\x1b[19~" }, + { code: "F9", hex: "\x1b[20~" }, + { code: "F10", hex: "\x1b[21~" }, + { code: "F11", hex: "\x1b[23~" }, + { code: "F12", hex: "\x1b[24~" }, ]; diff --git a/packages/cli-testing-library/src/user-event/keyboard/keyboardImplementation.ts b/packages/cli-testing-library/src/user-event/keyboard/keyboardImplementation.ts index 0666a07..d5fdb33 100644 --- a/packages/cli-testing-library/src/user-event/keyboard/keyboardImplementation.ts +++ b/packages/cli-testing-library/src/user-event/keyboard/keyboardImplementation.ts @@ -9,22 +9,18 @@ export async function keyboardImplementation( text: string, options: keyboardOptions, ): Promise { - const { keyDef, consumedLength } = getNextKeyDef(text, options); + let remainingText = text; - keypress(keyDef, instance); + while (remainingText) { + const { keyDef, consumedLength } = getNextKeyDef(remainingText, options); - if (text.length > consumedLength) { - if (options.delay > 0) { + keypress(keyDef, instance); + remainingText = remainingText.slice(consumedLength); + + if (remainingText && options.delay > 0) { await wait(options.delay); } - - return keyboardImplementation( - instance, - text.slice(consumedLength), - options, - ); } - return void undefined; } function keypress(keyDef: keyboardKey, instance: TestInstance) { diff --git a/packages/cli-testing-library/src/user-event/keyboard/types.ts b/packages/cli-testing-library/src/user-event/keyboard/types.ts index c97ca87..8b4d337 100644 --- a/packages/cli-testing-library/src/user-event/keyboard/types.ts +++ b/packages/cli-testing-library/src/user-event/keyboard/types.ts @@ -6,8 +6,8 @@ export type keyboardOptions = { }; export interface keyboardKey { - /** Physical location on a keyboard */ + /** Named key descriptor, such as `Enter` or `ArrowLeft` */ code?: string; - /** Character or functional key hex code */ + /** String written to stdin (historically named `hex`) */ hex?: string; } diff --git a/packages/cli-testing-library/tests/execute-scripts/readline-keys.js b/packages/cli-testing-library/tests/execute-scripts/readline-keys.js new file mode 100644 index 0000000..bf5ed11 --- /dev/null +++ b/packages/cli-testing-library/tests/execute-scripts/readline-keys.js @@ -0,0 +1,41 @@ +import { emitKeypressEvents } from "node:readline"; + +const expectedEventCount = Number.parseInt(process.argv[2] ?? "", 10); + +if (!Number.isSafeInteger(expectedEventCount) || expectedEventCount < 1) { + throw new TypeError("Expected a positive keypress event count"); +} + +/** + * @type {Array<{ + * code: string | null; + * ctrl: boolean; + * input: string | null; + * meta: boolean; + * name: string | null; + * sequenceHex: string; + * shift: boolean; + * }>} + */ +const events = []; + +emitKeypressEvents(process.stdin); +process.stdin.on("keypress", (input, key = {}) => { + events.push({ + code: key.code ?? null, + ctrl: key.ctrl ?? false, + input: input ?? null, + meta: key.meta ?? false, + name: key.name ?? null, + sequenceHex: Buffer.from(key.sequence ?? "").toString("hex"), + shift: key.shift ?? false, + }); + + if (events.length < expectedEventCount) return; + + process.stdout.write(`KEYS:${JSON.stringify(events)}\n`, () => + process.exit(0), + ); +}); + +process.stdout.write("READY\n"); diff --git a/packages/cli-testing-library/tests/execute-scripts/stdin-bytes.js b/packages/cli-testing-library/tests/execute-scripts/stdin-bytes.js new file mode 100644 index 0000000..c4dafcb --- /dev/null +++ b/packages/cli-testing-library/tests/execute-scripts/stdin-bytes.js @@ -0,0 +1,28 @@ +const expectedLength = Number.parseInt(process.argv[2] ?? "", 10); + +if (!Number.isSafeInteger(expectedLength) || expectedLength < 0) { + throw new TypeError("Expected a non-negative stdin byte length"); +} + +/** @type {Array} */ +const chunks = []; +let receivedLength = 0; + +process.stdin.on("data", (chunk) => { + const buffer = Buffer.from(chunk); + chunks.push(buffer); + receivedLength += buffer.length; + + if (receivedLength < expectedLength) return; + + const bytes = Buffer.concat(chunks); + process.stdout.write( + `BYTES:${JSON.stringify({ + hex: bytes.toString("hex"), + length: bytes.length, + })}\n`, + () => process.exit(receivedLength === expectedLength ? 0 : 1), + ); +}); + +process.stdout.write("READY\n"); diff --git a/packages/cli-testing-library/tests/keyboard-map.spec.ts b/packages/cli-testing-library/tests/keyboard-map.spec.ts new file mode 100644 index 0000000..0b05205 --- /dev/null +++ b/packages/cli-testing-library/tests/keyboard-map.spec.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { getNextKeyDef } from "../src/user-event/keyboard/getNextKeyDef"; +import { defaultKeyMap } from "../src/user-event/keyboard/keyMap"; +import { keyboardImplementation } from "../src/user-event/keyboard/keyboardImplementation"; +import type { TestInstance } from "../src/types"; + +const options = { delay: 0, keyboardMap: defaultKeyMap }; + +afterEach(() => { + vi.useRealTimers(); +}); + +function encodeKeyboardInput(text: string): string { + let remainingText = text; + let output = ""; + + while (remainingText) { + const { keyDef, consumedLength } = getNextKeyDef(remainingText, options); + output += keyDef.hex; + remainingText = remainingText.slice(consumedLength); + } + + return output; +} + +describe("printable input", () => { + test("writes every printable ASCII character without a map entry", () => { + for (let codePoint = 0x20; codePoint <= 0x7e; codePoint++) { + const character = String.fromCodePoint(codePoint); + const input = character === "[" ? "[[" : character; + + expect(encodeKeyboardInput(input)).toBe(character); + } + }); + + test.each(["é", "Ж", "漢", "👋", "👩🏽‍💻"])( + "writes the Unicode text %s without a map entry", + (text) => { + expect(encodeKeyboardInput(text)).toBe(text); + }, + ); +}); + +describe("named keys", () => { + test("preserves generated digit and letter descriptors", () => { + expect(encodeKeyboardInput("[Digit1][KeyA][KeyLowerB]")).toBe("1Ab"); + }); + + test("supports common editing, navigation, and function keys", () => { + expect(encodeKeyboardInput("[Tab][ShiftTab][Insert][F1][F12]")).toBe( + "\x09\x1b[Z\x1b[2~\x1bOP\x1b[24~", + ); + }); + + test("keeps the existing Unknown result for an unknown descriptor", () => { + expect(encodeKeyboardInput("[NotAKey]")).toBe("Unknown"); + }); +}); + +describe("Ctrl chords", () => { + test("does not define standalone Ctrl descriptors", () => { + expect( + defaultKeyMap.some((key) => + ["ctrl", "control"].includes(key.code?.toLowerCase() ?? ""), + ), + ).toBe(false); + }); + + test.each([ + ["[Ctrl+C]", "\x03"], + ["[Control+D]", "\x04"], + ["[Ctrl+BracketLeft]", "\x1b"], + ["[Ctrl+Backslash]", "\x1c"], + ["[Ctrl+BracketRight]", "\x1d"], + ["[Ctrl+^]", "\x1e"], + ["[Ctrl+_]", "\x1f"], + ["[Ctrl+?]", "\x7f"], + ["[Ctrl+Space]", "\x00"], + ["[Ctrl+KeyC]", "\x03"], + ])("encodes %s", (input, expected) => { + expect(encodeKeyboardInput(input)).toBe(expected); + }); + + test("does not interpret sequential descriptors as a chord", () => { + expect(encodeKeyboardInput("[Ctrl]c")).toBe("Unknownc"); + }); +}); + +describe("keyboard implementation", () => { + function createInstance() { + const write = vi.fn(() => true); + const instance = { + process: { stdin: { write } }, + } as unknown as TestInstance; + + return { instance, write }; + } + + test("handles long text iteratively", async () => { + const { instance, write } = createInstance(); + const text = "a".repeat(20_000); + + await keyboardImplementation(instance, text, options); + + expect(write).toHaveBeenCalledTimes(text.length); + }); + + test("delays between encoded keys", async () => { + vi.useFakeTimers(); + const { instance, write } = createInstance(); + + const typing = keyboardImplementation(instance, "ab", { + ...options, + delay: 10, + }); + + expect(write).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(10); + await typing; + + expect(write).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/cli-testing-library/tests/keyboard-portability.spec.ts b/packages/cli-testing-library/tests/keyboard-portability.spec.ts new file mode 100644 index 0000000..777e6e1 --- /dev/null +++ b/packages/cli-testing-library/tests/keyboard-portability.spec.ts @@ -0,0 +1,172 @@ +import { resolve } from "node:path"; +import { afterEach, describe, expect, test } from "vitest"; +import { cleanup, render } from "../src/pure"; +import { waitFor } from "../src/wait-for"; +import { defaultKeyMap } from "../src/user-event/keyboard/keyMap"; + +const fixtureDirectory = resolve(__dirname, "./execute-scripts"); + +type DecodedKey = { + code: string | null; + ctrl: boolean; + input: string | null; + meta: boolean; + name: string | null; + sequenceHex: string; + shift: boolean; +}; + +afterEach(async () => { + await cleanup(); +}); + +async function waitForExit(instance: Awaited>) { + await waitFor( + () => expect(instance.hasExit()).toMatchObject({ exitCode: 0 }), + { instance, timeout: 2_000 }, + ); +} + +function readFixtureResult(output: string, prefix: string): T { + const resultLine = output + .split(/\r?\n/) + .find((line) => line.startsWith(prefix)); + + if (!resultLine) throw new Error(`Fixture did not output ${prefix}`); + + return JSON.parse(resultLine.slice(prefix.length)) as T; +} + +async function captureStdinBytes(input: string, expectedValue: string) { + const expectedBytes = Buffer.from(expectedValue); + const instance = await render(process.execPath, [ + resolve(fixtureDirectory, "stdin-bytes.js"), + String(expectedBytes.length), + ]); + + await instance.findByText("READY"); + instance.userEvent.keyboard(input); + await instance.findByText("BYTES:"); + await waitForExit(instance); + + return readFixtureResult<{ hex: string; length: number }>( + instance.getStdallStr(), + "BYTES:", + ); +} + +async function decodeKeys(input: string, expectedEventCount = 1) { + const instance = await render(process.execPath, [ + resolve(fixtureDirectory, "readline-keys.js"), + String(expectedEventCount), + ]); + + await instance.findByText("READY"); + instance.userEvent.keyboard(input); + await instance.findByText("KEYS:", undefined, { timeout: 2_000 }); + await waitForExit(instance); + + return readFixtureResult>(instance.getStdallStr(), "KEYS:"); +} + +describe("stdin byte transport", () => { + test("preserves printable ASCII and Unicode as UTF-8", async () => { + const expected = `${Array.from({ length: 95 }, (_, index) => + String.fromCodePoint(0x20 + index), + ).join("")} Grüße Ж 漢 👩🏽‍💻`; + const input = expected.replaceAll("[", "[["); + + expect(await captureStdinBytes(input, expected)).toEqual({ + hex: Buffer.from(expected).toString("hex"), + length: Buffer.byteLength(expected), + }); + }); + + test("preserves every default named key sequence", async () => { + const input = defaultKeyMap.map(({ code }) => `[${code}]`).join(""); + const expected = defaultKeyMap.map(({ hex }) => hex).join(""); + + expect(await captureStdinBytes(input, expected)).toEqual({ + hex: Buffer.from(expected).toString("hex"), + length: Buffer.byteLength(expected), + }); + }); + + test("preserves generated Ctrl chord bytes", async () => { + const chords = [ + ["[Ctrl+Space]", "\x00"], + ["[Ctrl+C]", "\x03"], + ["[Control+D]", "\x04"], + ["[Ctrl+BracketLeft]", "\x1b"], + ["[Ctrl+Backslash]", "\x1c"], + ["[Ctrl+BracketRight]", "\x1d"], + ["[Ctrl+^]", "\x1e"], + ["[Ctrl+_]", "\x1f"], + ["[Ctrl+?]", "\x7f"], + ] as const; + const input = chords.map(([descriptor]) => descriptor).join(""); + const expected = chords.map(([, value]) => value).join(""); + + expect(await captureStdinBytes(input, expected)).toEqual({ + hex: Buffer.from(expected).toString("hex"), + length: Buffer.byteLength(expected), + }); + }); +}); + +const readlineKeyCases = [ + ["Tab", "tab", false, false], + ["Backspace", "backspace", false, false], + ["Enter", "return", false, false], + ["Escape", "escape", true, false], + ["ShiftTab", "tab", false, true], + ["ArrowUp", "up", false, false], + ["ArrowDown", "down", false, false], + ["ArrowRight", "right", false, false], + ["ArrowLeft", "left", false, false], + ["Home", "home", false, false], + ["End", "end", false, false], + ["Insert", "insert", false, false], + ["Delete", "delete", false, false], + ["PageUp", "pageup", false, false], + ["PageDown", "pagedown", false, false], + ...Array.from( + { length: 12 }, + (_, index) => [`F${index + 1}`, `f${index + 1}`, false, false] as const, + ), +] as const; + +describe("Node readline decoding", () => { + test.each(readlineKeyCases)( + "decodes [%s] consistently", + async (descriptor, expectedName, expectedMeta, expectedShift) => { + const keyMapEntry = defaultKeyMap.find(({ code }) => code === descriptor); + expect(keyMapEntry?.hex).toBeDefined(); + + const [event] = await decodeKeys(`[${descriptor}]`); + + expect(event).toMatchObject({ + ctrl: false, + meta: expectedMeta, + name: expectedName, + sequenceHex: Buffer.from(keyMapEntry!.hex!).toString("hex"), + shift: expectedShift, + }); + }, + ); + + test.each([ + ["[Ctrl+C]", "c", "03"], + ["[Control+D]", "d", "04"], + ])("decodes %s as a Ctrl keypress", async (descriptor, name, sequenceHex) => { + const [event] = await decodeKeys(descriptor); + + expect(event).toMatchObject({ + ctrl: true, + meta: false, + name, + sequenceHex, + shift: false, + }); + }); +}); diff --git a/packages/cli-testing-library/tests/user-keyboard.spec.ts b/packages/cli-testing-library/tests/user-keyboard.spec.ts index e160592..c145362 100644 --- a/packages/cli-testing-library/tests/user-keyboard.spec.ts +++ b/packages/cli-testing-library/tests/user-keyboard.spec.ts @@ -40,7 +40,7 @@ test("Should cancel a process with Ctrl", async () => { const instance = await findByText("What is your name?"); - userEventLocal.keyboard("[Ctrl]c"); + userEventLocal.keyboard("[Ctrl+C]"); await waitFor(() => expect(instance.hasExit()).toBeTruthy()); }); diff --git a/website/astro.config.mjs b/website/astro.config.mjs index c845c58..8667a6d 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -37,6 +37,10 @@ export default defineConfig({ label: "Guides", items: [ { label: "Introduction", slug: "guides/introduction" }, + { + label: "Migrating from v3 to v4", + slug: "guides/migrating-from-v3-to-v4", + }, { label: "API", slug: "guides/api" }, { label: "Configuration Options", slug: "guides/configure" }, { label: "Debug", slug: "guides/debug" }, -- knotmirror 0.0.1