@ftrdotdev/pi-inquiry 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Felix NordΓ©n
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,161 @@
1
+ # pi-inquiry
2
+
3
+ Interactive questions for the [pi coding agent](https://pi.dev). Registers a
4
+ single `question` tool that asks the user one or more multiple-choice
5
+ questions: a selectable option list for a single question, a tabbed form with
6
+ a submit tab for several. Every question keeps an open "Type something." path,
7
+ so the user can type a custom answer when the listed options do not fit.
8
+
9
+ Package: `@ftrdotdev/pi-inquiry` Β· [MIT](LICENSE)
10
+
11
+ ## What it is
12
+
13
+ `inquiry` is a pi extension. It is a package named `@ftrdotdev/pi-inquiry` and
14
+ registers exactly one tool: `question`.
15
+
16
+ The `question` tool asks the user to decide: pick between options, or confirm
17
+ a decision. It renders as a selectable list (single question) or a tabbed form
18
+ (multiple questions). Use it instead of ending a reply with a question in
19
+ plain text β€” the model guidance is contributed through `promptSnippet` and
20
+ `promptGuidelines` at tool registration, so the agent knows when to call it
21
+ and how to present questions.
22
+
23
+ The tool renders in pi's TUI. Outside TUI mode it returns an error instead of
24
+ showing a question.
25
+
26
+ ## Installation
27
+
28
+ Install from npm:
29
+
30
+ ```bash
31
+ pi install npm:@ftrdotdev/pi-inquiry
32
+ ```
33
+
34
+ From git or a local checkout:
35
+
36
+ ```bash
37
+ pi install git:github.com/felixnorden/pi-mono
38
+ pi install ./path/to/pi-mono/packages/inquiry
39
+ ```
40
+
41
+ To try the package without installing it, use `-e` (temporary, current run
42
+ only):
43
+
44
+ ```bash
45
+ pi -e npm:@ftrdotdev/pi-inquiry
46
+ ```
47
+
48
+ Registration lives in `package.json` under the `pi` field:
49
+
50
+ ```json
51
+ "pi": {
52
+ "extensions": ["./src/tool/question.ts"]
53
+ }
54
+ ```
55
+
56
+ The extension entry is `src/tool/question.ts`. It wires the tool definition
57
+ (name, JSON Schema parameters, prompt contributions, renderers) to pi's
58
+ `ExtensionAPI`. The core logic lives in pure Effect modules under `src/core/`,
59
+ with pi-specific adapters under `src/sdk/`.
60
+
61
+ ## Using the `question` tool
62
+
63
+ The model calls `question` whenever it needs the user to decide something,
64
+ pick between options, or confirm a decision. Ask all open questions in one
65
+ `question` call, with one entry per question in `questions[]`.
66
+
67
+ ### Parameters
68
+
69
+ ```json
70
+ {
71
+ "questions": [
72
+ {
73
+ "prompt": "The full question text to display",
74
+ "options": [{ "label": "Short label", "description": "Optional one-line description" }],
75
+ "id": "optional-unique-id", // defaults to q1, q2, ...
76
+ "label": "Scope", // short tab-bar label, defaults to Q1, Q2
77
+ "allowOther": true // defaults to true; false forces the listed options
78
+ }
79
+ ]
80
+ }
81
+ ```
82
+
83
+ - `questions` β€” one or more questions. A single question shows a simple
84
+ option list; multiple questions show a tabbed interface with a submit tab.
85
+ - `options` β€” 2–5 short options per question, each a `label` plus an optional
86
+ one-line `description`.
87
+ - `allowOther` β€” when `true` (default), the user can also type a free-text
88
+ answer ("Type something."). Set it to `false` only when one of the listed
89
+ options is required.
90
+
91
+ ### Result
92
+
93
+ The tool returns its answers both as human-readable content and in
94
+ `details`:
95
+
96
+ ```ts
97
+ {
98
+ questions: [...], // the normalized questions asked
99
+ answers: [
100
+ {
101
+ id: "q1",
102
+ label: "the chosen option or typed answer",
103
+ wasCustom: false, // true when the user typed a free-text answer
104
+ index: 2 // option index, absent for custom answers
105
+ }
106
+ ],
107
+ cancelled: false // true when the user dismissed the form
108
+ }
109
+ ```
110
+
111
+ Treat a cancelled result as the user declining to answer. Do not re-ask
112
+ unless the answer is essential; then ask once more in a different form.
113
+
114
+ ## Pairing with the tracker
115
+
116
+ `question` is a decision tool, not a tracker. Pair it with pi's `tracker`
117
+ tool when a session spans several pieces of work. Keep one tracker list per
118
+ piece of work, and use `question` when you need the user to steer the session:
119
+
120
+ - which task list to work on next, when several pieces of work are open
121
+ - which option or approach to take for the current item
122
+ - whether to change scope, reprioritize, or drop an item
123
+ - confirm a decision instead of guessing
124
+
125
+ Group related decisions into one `question` call with multiple entries in
126
+ `questions[]`. They render as a single tabbed form with a submit tab, so the
127
+ user resolves several open points in one pass.
128
+
129
+ ## Architecture
130
+
131
+ The core is a pure Effect toolkit with zero pi imports; all pi interaction
132
+ lives on the fringe.
133
+
134
+ - `src/core/` β€” pure Effect, no pi imports
135
+ - `domain.ts` β€” Effect Schema wire contract. The single source of truth:
136
+ the tool's `parameters` JSON Schema is generated from it, and `decodeParams`
137
+ validates every call.
138
+ - `machine.ts` β€” pure reducer `step(state, key)`. Exhaustive tests pin the
139
+ legacy UX contract (tab navigation, editor mode, cancel semantics).
140
+ - `flow.ts` β€” the interaction program: keyboard events in, machine steps,
141
+ result out, via the `Keyboard` and `Renderer` services.
142
+ - `keyboard.ts`, `editor.ts`, `scene.ts`, `text.ts` β€” key event model,
143
+ code-point editor, style-token scene model, width-aware wrapping.
144
+ - `src/sdk/` β€” the pi fringe (all pi imports live here)
145
+ - `pi-ui.ts` β€” `ctx.ui.custom` bridge: key events via a queue, scene painting
146
+ at the current width, result completion.
147
+ - `keys.ts` β€” raw pi key data to core `KeyEvent`s.
148
+ - `painter.ts` β€” scene style tokens to pi theme ANSI.
149
+ - `schema.test.ts` β€” pins pi's runtime validation against the generated schema.
150
+ - `src/tool/question.ts` β€” tool registration: discovery content
151
+ (`promptSnippet`/`promptGuidelines`), the legacy `prepareArguments` shim,
152
+ renderers.
153
+
154
+ ## Development
155
+
156
+ ```bash
157
+ bun install
158
+ bun run test # vitest (pure tests + @effect/vitest flow tests)
159
+ bun run lint # oxlint
160
+ bunx tsc --noEmit # typecheck
161
+ ```
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@ftrdotdev/pi-inquiry",
3
+ "version": "0.2.0",
4
+ "description": "Interactive questions for the pi coding agent: a single `question` tool renders option lists, tabbed forms, and free-text answers",
5
+ "keywords": [
6
+ "effect",
7
+ "extension",
8
+ "interactive",
9
+ "pi",
10
+ "pi-coding-agent",
11
+ "pi-package",
12
+ "question",
13
+ "tui"
14
+ ],
15
+ "homepage": "https://github.com/felixnorden/pi-mono#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/felixnorden/pi-mono/issues"
18
+ },
19
+ "license": "MIT",
20
+ "author": "Felix NordΓ©n <felixnorden@gmail.com>",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/felixnorden/pi-mono.git",
24
+ "directory": "packages/inquiry"
25
+ },
26
+ "files": [
27
+ "src",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "type": "module",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "prepare": "bun effect-tsgo patch --typescript --oxlint",
37
+ "test": "vitest run",
38
+ "test:watch": "vitest",
39
+ "lint": "oxlint && oxlint --type-aware -A all -D typescript/unbound-method",
40
+ "lint:fix": "oxlint --fix",
41
+ "fmt": "oxfmt -c oxfmt.config.ts"
42
+ },
43
+ "dependencies": {
44
+ "@ftrdotdev/pi-tui": "^0.2.0",
45
+ "effect": "4.0.0-rc.108"
46
+ },
47
+ "devDependencies": {
48
+ "@earendil-works/pi-ai": "0.84.2",
49
+ "@effect/tsgo": "0.36.4",
50
+ "@effect/vitest": "4.0.0-rc.108",
51
+ "@types/bun": "latest",
52
+ "oxfmt": "^0.63.0",
53
+ "oxlint": "1.77.0",
54
+ "oxlint-tsgolint": "7.0.2001",
55
+ "typescript": "7.0.2",
56
+ "vitest": "^4.1.10"
57
+ },
58
+ "peerDependencies": {
59
+ "@earendil-works/pi-coding-agent": "*",
60
+ "@earendil-works/pi-tui": "*",
61
+ "typebox": "*"
62
+ },
63
+ "pi": {
64
+ "extensions": [
65
+ "./src/tool/question.ts"
66
+ ]
67
+ }
68
+ }
@@ -0,0 +1,154 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { Schema } from "effect";
3
+ import {
4
+ QuestionListParamsJsonSchema,
5
+ decodeParams,
6
+ normalizeQuestions,
7
+ prepareQuestionArgs,
8
+ } from "./domain.ts";
9
+
10
+ describe("decodeParams", () => {
11
+ it("decodes valid params", () => {
12
+ const params = decodeParams({
13
+ questions: [{ prompt: "Pick one?", options: [{ label: "Yes" }] }],
14
+ });
15
+ expect(params.questions).toHaveLength(1);
16
+ expect(params.questions[0]?.prompt).toBe("Pick one?");
17
+ });
18
+
19
+ it("decodes optional fields", () => {
20
+ const params = decodeParams({
21
+ questions: [
22
+ {
23
+ id: "scope",
24
+ label: "Scope",
25
+ prompt: "Pick one?",
26
+ options: [{ label: "Yes", description: "Go ahead" }],
27
+ allowOther: false,
28
+ },
29
+ ],
30
+ });
31
+ expect(params.questions[0]?.id).toBe("scope");
32
+ expect(params.questions[0]?.label).toBe("Scope");
33
+ expect(params.questions[0]?.allowOther).toBe(false);
34
+ expect(params.questions[0]?.options[0]?.description).toBe("Go ahead");
35
+ });
36
+
37
+ it("rejects invalid input with a SchemaError", () => {
38
+ expect(() => decodeParams({ questions: [{ prompt: "p", options: [{ label: 42 }] }] })).toThrow(
39
+ Schema.SchemaError,
40
+ );
41
+ });
42
+
43
+ it("rejects a missing questions array", () => {
44
+ expect(() => decodeParams({})).toThrow(Schema.SchemaError);
45
+ });
46
+
47
+ it("ignores legacy extra option fields such as value", () => {
48
+ const params = decodeParams({
49
+ questions: [{ prompt: "p", options: [{ value: "yes", label: "Yes" }] }],
50
+ });
51
+ expect(params.questions[0]?.options[0]?.label).toBe("Yes");
52
+ });
53
+ });
54
+
55
+ describe("prepareQuestionArgs", () => {
56
+ it("shims legacy question-tool args into the questions array", () => {
57
+ const prepared = prepareQuestionArgs({ question: "Go?", options: [{ label: "Yes" }] });
58
+ expect(prepared).toEqual({ questions: [{ prompt: "Go?", options: [{ label: "Yes" }] }] });
59
+ });
60
+
61
+ it("shims legacy args without options", () => {
62
+ expect(prepareQuestionArgs({ question: "Go?" })).toEqual({
63
+ questions: [{ prompt: "Go?", options: [] }],
64
+ });
65
+ });
66
+
67
+ it("passes the current questionnaire shape through unchanged", () => {
68
+ const args = { questions: [{ prompt: "p", options: [{ label: "a" }] }] };
69
+ expect(prepareQuestionArgs(args)).toBe(args);
70
+ });
71
+
72
+ it("passes non-objects through unchanged", () => {
73
+ expect(prepareQuestionArgs(undefined)).toBeUndefined();
74
+ expect(prepareQuestionArgs(null)).toBeNull();
75
+ expect(prepareQuestionArgs("nope")).toBe("nope");
76
+ });
77
+ });
78
+
79
+ describe("QuestionListParamsJsonSchema", () => {
80
+ const schema = QuestionListParamsJsonSchema as Record<string, any>;
81
+
82
+ it("is an object schema requiring questions", () => {
83
+ expect(schema.type).toBe("object");
84
+ expect(schema.required).toEqual(["questions"]);
85
+ expect(schema.properties.questions.type).toBe("array");
86
+ });
87
+
88
+ it("tolerates additional properties at every level (legacy contract)", () => {
89
+ expect(schema.additionalProperties).toBe(true);
90
+ const question = schema.properties.questions.items;
91
+ expect(question.additionalProperties).toBe(true);
92
+ const option = question.properties.options.items;
93
+ expect(option.additionalProperties).toBe(true);
94
+ expect(option.required).toEqual(["label"]);
95
+ });
96
+
97
+ it("carries the field descriptions the LLM sees", () => {
98
+ expect(schema.properties.questions.description).toContain(
99
+ "single question shows a simple option list",
100
+ );
101
+ const q = schema.properties.questions.items.properties;
102
+ expect(q.prompt.description).toBe("The full question text to display");
103
+ expect(q.options.description).toBe("Available options to choose from");
104
+ expect(q.label.description).toContain("Short contextual label for tab bar");
105
+ expect(q.allowOther.description).toContain("default: true");
106
+ expect(q.options.items.properties.label.description).toBe("Display label for the option");
107
+ });
108
+ });
109
+
110
+ describe("normalizeQuestions", () => {
111
+ it("applies id, label and allowOther defaults", () => {
112
+ const questions = normalizeQuestions(
113
+ decodeParams({ questions: [{ prompt: "p", options: [{ label: "a" }] }] }),
114
+ );
115
+ expect(questions).toHaveLength(1);
116
+ expect(questions[0]?.id).toBe("q1");
117
+ expect(questions[0]?.label).toBe("Q1");
118
+ expect(questions[0]?.allowOther).toBe(true);
119
+ });
120
+
121
+ it("numbers multiple questions", () => {
122
+ const questions = normalizeQuestions(
123
+ decodeParams({
124
+ questions: [
125
+ { prompt: "p1", options: [{ label: "a" }] },
126
+ { prompt: "p2", options: [{ label: "b" }] },
127
+ ],
128
+ }),
129
+ );
130
+ expect(questions.map((q) => q.id)).toEqual(["q1", "q2"]);
131
+ expect(questions.map((q) => q.label)).toEqual(["Q1", "Q2"]);
132
+ });
133
+
134
+ it("preserves explicit values", () => {
135
+ const questions = normalizeQuestions(
136
+ decodeParams({
137
+ questions: [
138
+ { id: "x", label: "Scope", prompt: "p", options: [{ label: "a" }], allowOther: false },
139
+ ],
140
+ }),
141
+ );
142
+ expect(questions[0]?.id).toBe("x");
143
+ expect(questions[0]?.label).toBe("Scope");
144
+ expect(questions[0]?.allowOther).toBe(false);
145
+ });
146
+
147
+ it("maps option labels and descriptions", () => {
148
+ const questions = normalizeQuestions(
149
+ decodeParams({ questions: [{ prompt: "p", options: [{ label: "a", description: "d" }] }] }),
150
+ );
151
+ expect(questions[0]?.options[0]?.label).toBe("a");
152
+ expect(questions[0]?.options[0]?.description).toBe("d");
153
+ });
154
+ });
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Domain model for the question toolkit, defined with Effect Schema.
3
+ *
4
+ * The wire schemas (`QuestionListParamsSchema`) describe the tool parameters
5
+ * as the LLM sends them. The domain classes (`Option`, `Question`, `Answer`,
6
+ * `QuestionResult`) are the validated internal representation.
7
+ */
8
+
9
+ import { Schema } from "effect";
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Wire schemas (tool parameters) β€” the single source of truth. The tool's
13
+ // `parameters` JSON schema is generated from these via `toJsonSchemaDocument`
14
+ // (see `QuestionListParamsJsonSchema` below), so field descriptions written
15
+ // here are exactly what the LLM sees.
16
+ // ---------------------------------------------------------------------------
17
+
18
+ export const OptionParamsSchema = Schema.Struct({
19
+ label: Schema.String.annotate({ description: "Display label for the option" }),
20
+ description: Schema.optionalKey(
21
+ Schema.String.annotate({ description: "Optional description shown below label" }),
22
+ ),
23
+ });
24
+
25
+ export type OptionParams = typeof OptionParamsSchema.Type;
26
+
27
+ export const QuestionParamsSchema = Schema.Struct({
28
+ prompt: Schema.String.annotate({ description: "The full question text to display" }),
29
+ options: Schema.Array(OptionParamsSchema).annotate({
30
+ description: "Available options to choose from",
31
+ }),
32
+ id: Schema.optionalKey(
33
+ Schema.String.annotate({
34
+ description: "Unique identifier for this question (defaults to q1, q2, ...)",
35
+ }),
36
+ ),
37
+ label: Schema.optionalKey(
38
+ Schema.String.annotate({
39
+ description:
40
+ "Short contextual label for tab bar, e.g. 'Scope', 'Priority' (defaults to Q1, Q2)",
41
+ }),
42
+ ),
43
+ allowOther: Schema.optionalKey(
44
+ Schema.Boolean.annotate({ description: "Allow 'Type something' option (default: true)" }),
45
+ ),
46
+ });
47
+
48
+ export type QuestionParams = typeof QuestionParamsSchema.Type;
49
+
50
+ export const QuestionListParamsSchema = Schema.Struct({
51
+ questions: Schema.Array(QuestionParamsSchema).annotate({
52
+ description:
53
+ "Questions to ask the user (1 or more). A single question shows a simple option list; multiple questions show a tabbed interface with a submit tab.",
54
+ }),
55
+ });
56
+
57
+ export type QuestionListParams = typeof QuestionListParamsSchema.Type;
58
+
59
+ /**
60
+ * JSON Schema form of the wire params, passed to pi as the tool's
61
+ * `parameters`. `additionalProperties: true` mirrors the legacy typebox
62
+ * contract (unknown keys such as the old `value` field are tolerated) and
63
+ * matches Effect's own struct decoding, which ignores unknown keys.
64
+ */
65
+ export const QuestionListParamsJsonSchema = Schema.toJsonSchemaDocument(QuestionListParamsSchema, {
66
+ additionalProperties: true,
67
+ }).schema;
68
+
69
+ /** Decode raw tool arguments into validated params. Throws `Schema.SchemaError` on invalid input. */
70
+ export const decodeParams = (input: unknown): QuestionListParams =>
71
+ Schema.decodeUnknownSync(QuestionListParamsSchema)(input);
72
+
73
+ /**
74
+ * Shim legacy tool arguments into the current wire shape.
75
+ *
76
+ * Old `question` tool calls used `{ question, options }`; old `questionnaire`
77
+ * calls already used `{ questions }` and pass through unchanged. Called by
78
+ * the tool's `prepareArguments` before schema validation.
79
+ */
80
+ export const prepareQuestionArgs = (args: unknown): unknown => {
81
+ if (args && typeof args === "object") {
82
+ const legacy = args as { question?: unknown; options?: unknown; questions?: unknown };
83
+ if (!Array.isArray(legacy.questions) && typeof legacy.question === "string") {
84
+ return {
85
+ questions: [
86
+ {
87
+ prompt: legacy.question,
88
+ options: Array.isArray(legacy.options) ? legacy.options : [],
89
+ },
90
+ ],
91
+ };
92
+ }
93
+ }
94
+ return args;
95
+ };
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Domain model
99
+ // ---------------------------------------------------------------------------
100
+
101
+ export class Option extends Schema.Class<Option>("inquiry/core/domain/Option")({
102
+ label: Schema.String,
103
+ description: Schema.optionalKey(Schema.String),
104
+ }) {}
105
+
106
+ export class Question extends Schema.Class<Question>("inquiry/core/domain/Question")({
107
+ id: Schema.String,
108
+ label: Schema.String,
109
+ prompt: Schema.String,
110
+ options: Schema.Array(Option),
111
+ allowOther: Schema.Boolean,
112
+ }) {}
113
+
114
+ export class Answer extends Schema.Class<Answer>("inquiry/core/domain/Answer")({
115
+ id: Schema.String,
116
+ label: Schema.String,
117
+ wasCustom: Schema.Boolean,
118
+ index: Schema.optionalKey(Schema.Int),
119
+ }) {}
120
+
121
+ export class QuestionResult extends Schema.Class<QuestionResult>(
122
+ "inquiry/core/domain/QuestionResult",
123
+ )({
124
+ questions: Schema.Array(Question),
125
+ answers: Schema.Array(Answer),
126
+ cancelled: Schema.Boolean,
127
+ }) {}
128
+
129
+ /**
130
+ * Normalize wire params into domain questions.
131
+ *
132
+ * Applies the defaults: `id` falls back to `q{n}`, `label` to `Q{n}`,
133
+ * `allowOther` defaults to `true`.
134
+ */
135
+ export const normalizeQuestions = (params: QuestionListParams): readonly Question[] =>
136
+ params.questions.map(
137
+ (q, i) =>
138
+ new Question({
139
+ id: q.id ?? `q${i + 1}`,
140
+ label: q.label ?? `Q${i + 1}`,
141
+ prompt: q.prompt,
142
+ options: q.options.map((o) =>
143
+ o.description === undefined
144
+ ? new Option({ label: o.label })
145
+ : new Option({ label: o.label, description: o.description }),
146
+ ),
147
+ allowOther: q.allowOther !== false,
148
+ }),
149
+ );
@@ -0,0 +1,124 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ editorBackspace,
4
+ editorDelete,
5
+ editorFromText,
6
+ editorInsert,
7
+ editorMoveEnd,
8
+ editorMoveHome,
9
+ editorMoveLeft,
10
+ editorMoveRight,
11
+ emptyEditor,
12
+ sanitizePaste,
13
+ } from "./editor.ts";
14
+
15
+ describe("editorFromText", () => {
16
+ it("places the cursor at the end of the text", () => {
17
+ expect(editorFromText("hey")).toEqual({ text: "hey", cursor: 3 });
18
+ expect(editorFromText("a\nb")).toEqual({ text: "a\nb", cursor: 3 });
19
+ });
20
+
21
+ it("counts code points, not UTF-16 units", () => {
22
+ expect(editorFromText("πŸ˜€").cursor).toBe(1);
23
+ });
24
+ });
25
+
26
+ describe("editorInsert", () => {
27
+ it("inserts into an empty editor", () => {
28
+ const s = editorInsert(emptyEditor(), "ab");
29
+ expect(s.text).toBe("ab");
30
+ expect(s.cursor).toBe(2);
31
+ });
32
+
33
+ it("inserts at the cursor position", () => {
34
+ const s = editorInsert(editorInsert(emptyEditor(), "ab"), "X");
35
+ expect(s.text).toBe("abX");
36
+ const moved = editorMoveLeft(editorInsert(emptyEditor(), "ab"));
37
+ const inserted = editorInsert(moved, "X");
38
+ expect(inserted.text).toBe("aXb");
39
+ expect(inserted.cursor).toBe(2);
40
+ });
41
+
42
+ it("treats surrogate pairs as single characters", () => {
43
+ const s = editorInsert(emptyEditor(), "πŸ˜€");
44
+ expect(s.cursor).toBe(1);
45
+ expect(s.text).toBe("πŸ˜€");
46
+ });
47
+ });
48
+
49
+ describe("editorBackspace", () => {
50
+ it("deletes the character before the cursor", () => {
51
+ const s = editorBackspace(editorInsert(emptyEditor(), "abc"));
52
+ expect(s.text).toBe("ab");
53
+ expect(s.cursor).toBe(2);
54
+ });
55
+
56
+ it("is a no-op at the start", () => {
57
+ const s = editorBackspace(emptyEditor());
58
+ expect(s).toEqual(emptyEditor());
59
+ });
60
+
61
+ it("deletes whole code points", () => {
62
+ // insert "πŸ˜€a", move left of the trailing "a", then backspace deletes the emoji
63
+ const base = editorInsert(emptyEditor(), "πŸ˜€a");
64
+ const s = editorBackspace(editorMoveLeft(base));
65
+ expect(s.text).toBe("a");
66
+ expect(s.cursor).toBe(0);
67
+ });
68
+ });
69
+
70
+ describe("editorDelete", () => {
71
+ it("deletes the character at the cursor", () => {
72
+ const s = editorDelete(editorMoveHome(editorInsert(emptyEditor(), "abc")));
73
+ expect(s.text).toBe("bc");
74
+ expect(s.cursor).toBe(0);
75
+ });
76
+
77
+ it("is a no-op at the end", () => {
78
+ const s = editorDelete({ text: "ab", cursor: 2 });
79
+ expect(s.text).toBe("ab");
80
+ });
81
+ });
82
+
83
+ describe("editor movement", () => {
84
+ it("moves left and right", () => {
85
+ const base = editorInsert(emptyEditor(), "abc");
86
+ expect(editorMoveLeft(base).cursor).toBe(2);
87
+ expect(editorMoveRight(emptyEditor()).cursor).toBe(0);
88
+ });
89
+
90
+ it("clamps at the boundaries", () => {
91
+ expect(editorMoveLeft(emptyEditor()).cursor).toBe(0);
92
+ expect(editorMoveRight({ text: "ab", cursor: 2 }).cursor).toBe(2);
93
+ });
94
+
95
+ it("moves by code points", () => {
96
+ const base = editorInsert(emptyEditor(), "πŸ˜€a");
97
+ expect(editorMoveLeft(base).cursor).toBe(1);
98
+ expect(editorMoveRight(editorMoveLeft(base)).cursor).toBe(2);
99
+ });
100
+
101
+ it("jumps home and end", () => {
102
+ const base = { text: "abc", cursor: 1 };
103
+ expect(editorMoveHome(base).cursor).toBe(0);
104
+ expect(editorMoveEnd(base).cursor).toBe(3);
105
+ });
106
+ });
107
+
108
+ describe("sanitizePaste", () => {
109
+ it("normalizes line endings to newlines", () => {
110
+ expect(sanitizePaste("a\r\nb\rc")).toBe("a\nb\nc");
111
+ });
112
+
113
+ it("expands tabs to four spaces", () => {
114
+ expect(sanitizePaste("a\tb")).toBe("a b");
115
+ });
116
+
117
+ it("keeps newlines and printable characters", () => {
118
+ expect(sanitizePaste("line1\nline2 πŸ˜€")).toBe("line1\nline2 πŸ˜€");
119
+ });
120
+
121
+ it("drops other control characters", () => {
122
+ expect(sanitizePaste("\x03a\x07\x1bb")).toBe("ab");
123
+ });
124
+ });