@dxos/react-ui-terminal 0.0.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.
Files changed (69) hide show
  1. package/dist/lib/chunk-cli.mjs +500 -0
  2. package/dist/lib/chunk-cli.mjs.map +1 -0
  3. package/dist/lib/cli.mjs +2 -0
  4. package/dist/lib/index.mjs +157 -0
  5. package/dist/lib/index.mjs.map +1 -0
  6. package/dist/lib/testing.mjs +41 -0
  7. package/dist/lib/testing.mjs.map +1 -0
  8. package/dist/types/src/cli/bridge.d.ts +42 -0
  9. package/dist/types/src/cli/bridge.d.ts.map +1 -0
  10. package/dist/types/src/cli/console.d.ts +16 -0
  11. package/dist/types/src/cli/console.d.ts.map +1 -0
  12. package/dist/types/src/cli/console.test.d.ts +2 -0
  13. package/dist/types/src/cli/console.test.d.ts.map +1 -0
  14. package/dist/types/src/cli/context.d.ts +17 -0
  15. package/dist/types/src/cli/context.d.ts.map +1 -0
  16. package/dist/types/src/cli/index.d.ts +9 -0
  17. package/dist/types/src/cli/index.d.ts.map +1 -0
  18. package/dist/types/src/cli/input.d.ts +14 -0
  19. package/dist/types/src/cli/input.d.ts.map +1 -0
  20. package/dist/types/src/cli/input.test.d.ts +2 -0
  21. package/dist/types/src/cli/input.test.d.ts.map +1 -0
  22. package/dist/types/src/cli/line-editor.d.ts +35 -0
  23. package/dist/types/src/cli/line-editor.d.ts.map +1 -0
  24. package/dist/types/src/cli/line-editor.test.d.ts +2 -0
  25. package/dist/types/src/cli/line-editor.test.d.ts.map +1 -0
  26. package/dist/types/src/cli/shell.d.ts +30 -0
  27. package/dist/types/src/cli/shell.d.ts.map +1 -0
  28. package/dist/types/src/cli/terminal.d.ts +12 -0
  29. package/dist/types/src/cli/terminal.d.ts.map +1 -0
  30. package/dist/types/src/cli/testing.d.ts +20 -0
  31. package/dist/types/src/cli/testing.d.ts.map +1 -0
  32. package/dist/types/src/cli/tokenize.d.ts +12 -0
  33. package/dist/types/src/cli/tokenize.d.ts.map +1 -0
  34. package/dist/types/src/components/Terminal/Terminal.d.ts +30 -0
  35. package/dist/types/src/components/Terminal/Terminal.d.ts.map +1 -0
  36. package/dist/types/src/components/Terminal/Terminal.stories.d.ts +18 -0
  37. package/dist/types/src/components/Terminal/Terminal.stories.d.ts.map +1 -0
  38. package/dist/types/src/components/Terminal/index.d.ts +2 -0
  39. package/dist/types/src/components/Terminal/index.d.ts.map +1 -0
  40. package/dist/types/src/components/Terminal/theme.d.ts +7 -0
  41. package/dist/types/src/components/Terminal/theme.d.ts.map +1 -0
  42. package/dist/types/src/components/index.d.ts +2 -0
  43. package/dist/types/src/components/index.d.ts.map +1 -0
  44. package/dist/types/src/index.d.ts +2 -0
  45. package/dist/types/src/index.d.ts.map +1 -0
  46. package/dist/types/src/testing.d.ts +23 -0
  47. package/dist/types/src/testing.d.ts.map +1 -0
  48. package/dist/types/tsconfig.tsbuildinfo +1 -0
  49. package/package.json +65 -0
  50. package/src/cli/bridge.ts +102 -0
  51. package/src/cli/console.test.ts +73 -0
  52. package/src/cli/console.ts +91 -0
  53. package/src/cli/context.ts +26 -0
  54. package/src/cli/index.ts +13 -0
  55. package/src/cli/input.test.ts +109 -0
  56. package/src/cli/input.ts +132 -0
  57. package/src/cli/line-editor.test.ts +141 -0
  58. package/src/cli/line-editor.ts +199 -0
  59. package/src/cli/shell.ts +103 -0
  60. package/src/cli/terminal.ts +43 -0
  61. package/src/cli/testing.ts +51 -0
  62. package/src/cli/tokenize.ts +35 -0
  63. package/src/components/Terminal/Terminal.stories.tsx +114 -0
  64. package/src/components/Terminal/Terminal.tsx +118 -0
  65. package/src/components/Terminal/index.ts +5 -0
  66. package/src/components/Terminal/theme.ts +87 -0
  67. package/src/components/index.ts +5 -0
  68. package/src/index.ts +5 -0
  69. package/src/testing.ts +56 -0
@@ -0,0 +1,141 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Fiber from 'effect/Fiber';
7
+ import { describe, expect, test } from 'vitest';
8
+
9
+ import { EffectEx } from '@dxos/effect';
10
+
11
+ import { type LineResult, readLineResult } from './line-editor';
12
+ import { TestBridge } from './testing';
13
+
14
+ /**
15
+ * Starts a read, feeds the given data, and resolves with the result. The read subscribes
16
+ * synchronously up to its first suspension, so the data is delivered to a live subscriber.
17
+ */
18
+ const readWith = async (
19
+ data: string,
20
+ options?: { prompt?: string; history?: string[] },
21
+ ): Promise<{ bridge: TestBridge; result: LineResult }> => {
22
+ const bridge = new TestBridge();
23
+ const fiber = Effect.runFork(readLineResult(bridge, options));
24
+ bridge.send(data);
25
+ return { bridge, result: await EffectEx.runPromise(Fiber.join(fiber)) };
26
+ };
27
+
28
+ describe('readLineResult', () => {
29
+ test('returns the typed line on return', async () => {
30
+ const { result } = await readWith('space list\r');
31
+ expect(result).to.deep.eq({ type: 'line', value: 'space list' });
32
+ });
33
+
34
+ test('returns an empty line for a bare return', async () => {
35
+ const { result } = await readWith('\r');
36
+ expect(result).to.deep.eq({ type: 'line', value: '' });
37
+ });
38
+
39
+ test('backspace removes the previous character', async () => {
40
+ const { result } = await readWith('lists\x7f\r');
41
+ expect(result).to.deep.eq({ type: 'line', value: 'list' });
42
+ });
43
+
44
+ test('backspace at the start is a no-op', async () => {
45
+ const { result } = await readWith('\x7f\x7fok\r');
46
+ expect(result).to.deep.eq({ type: 'line', value: 'ok' });
47
+ });
48
+
49
+ test('left arrow moves the insertion point', async () => {
50
+ const { result } = await readWith('ac\x1b[Db\r');
51
+ expect(result).to.deep.eq({ type: 'line', value: 'abc' });
52
+ });
53
+
54
+ test('right arrow moves back toward the end', async () => {
55
+ const { result } = await readWith('ac\x1b[D\x1b[Cd\r');
56
+ expect(result).to.deep.eq({ type: 'line', value: 'acd' });
57
+ });
58
+
59
+ test('delete removes the character under the cursor', async () => {
60
+ const { result } = await readWith('abc\x1b[D\x1b[3~\r');
61
+ expect(result).to.deep.eq({ type: 'line', value: 'ab' });
62
+ });
63
+
64
+ test('home and end jump to the buffer edges', async () => {
65
+ const { result } = await readWith('bc\x1b[Ha\x1b[Fd\r');
66
+ expect(result).to.deep.eq({ type: 'line', value: 'abcd' });
67
+ });
68
+
69
+ test('ctrl-a and ctrl-e jump to the buffer edges', async () => {
70
+ const { result } = await readWith('bc\x01a\x05d\r');
71
+ expect(result).to.deep.eq({ type: 'line', value: 'abcd' });
72
+ });
73
+
74
+ test('ctrl-u clears to the start and ctrl-k clears to the end', async () => {
75
+ expect((await readWith('drop\x15keep\r')).result).to.deep.eq({ type: 'line', value: 'keep' });
76
+ expect((await readWith('keep\x1b[D\x0b\r')).result).to.deep.eq({ type: 'line', value: 'kee' });
77
+ });
78
+
79
+ test('ctrl-c cancels without returning a line', async () => {
80
+ const { result } = await readWith('half typed\x03');
81
+ expect(result).to.deep.eq({ type: 'cancelled' });
82
+ });
83
+
84
+ test('ctrl-d on an empty buffer signals end of input', async () => {
85
+ const { result } = await readWith('\x04');
86
+ expect(result).to.deep.eq({ type: 'eof' });
87
+ });
88
+
89
+ test('ctrl-d with content is ignored', async () => {
90
+ const { result } = await readWith('keep\x04\r');
91
+ expect(result).to.deep.eq({ type: 'line', value: 'keep' });
92
+ });
93
+
94
+ test('up recalls the previous entry', async () => {
95
+ const { result } = await readWith('\x1b[A\r', { history: ['space list', 'database query'] });
96
+ expect(result).to.deep.eq({ type: 'line', value: 'database query' });
97
+ });
98
+
99
+ test('up twice reaches further back', async () => {
100
+ const { result } = await readWith('\x1b[A\x1b[A\r', { history: ['space list', 'database query'] });
101
+ expect(result).to.deep.eq({ type: 'line', value: 'space list' });
102
+ });
103
+
104
+ test('up past the oldest entry stays put', async () => {
105
+ const { result } = await readWith('\x1b[A\x1b[A\x1b[A\r', { history: ['only'] });
106
+ expect(result).to.deep.eq({ type: 'line', value: 'only' });
107
+ });
108
+
109
+ test('down returns to the in-progress draft', async () => {
110
+ const { result } = await readWith('draft\x1b[A\x1b[B\r', { history: ['recalled'] });
111
+ expect(result).to.deep.eq({ type: 'line', value: 'draft' });
112
+ });
113
+
114
+ test('a pasted chunk is inserted verbatim', async () => {
115
+ const { result } = await readWith('space join abc-123-xyz\r');
116
+ expect(result).to.deep.eq({ type: 'line', value: 'space join abc-123-xyz' });
117
+ });
118
+
119
+ test('echoes the prompt and buffer', async () => {
120
+ const { bridge } = await readWith('hi\r', { prompt: 'dx> ' });
121
+ expect(bridge.rendered).to.contain('dx> hi');
122
+ });
123
+
124
+ test('leaves the cursor on a fresh line after return', async () => {
125
+ const { bridge } = await readWith('hi\r');
126
+ expect(bridge.atLineStart).to.be.true;
127
+ });
128
+
129
+ test('ctrl-l clears the screen and repaints', async () => {
130
+ const { bridge, result } = await readWith('keep\x0c\r');
131
+ expect(bridge.writes).to.contain('<clear>');
132
+ expect(result).to.deep.eq({ type: 'line', value: 'keep' });
133
+ });
134
+
135
+ test('unsubscribes once the line is read', async () => {
136
+ const { bridge } = await readWith('done\r');
137
+ const before = bridge.writes.length;
138
+ bridge.send('ignored');
139
+ expect(bridge.writes.length).to.eq(before);
140
+ });
141
+ });
@@ -0,0 +1,199 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Terminal from '@effect/platform/Terminal';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Option from 'effect/Option';
8
+
9
+ import type { TerminalBridge } from './bridge';
10
+
11
+ export type LineResult =
12
+ | { readonly type: 'line'; readonly value: string }
13
+ | { readonly type: 'cancelled' }
14
+ | { readonly type: 'eof' };
15
+
16
+ export type ReadLineOptions = {
17
+ /**
18
+ * Rendered before the editable buffer and redrawn on every keystroke.
19
+ */
20
+ prompt?: string;
21
+ /**
22
+ * Previously entered lines, oldest first. Mutated by the caller between reads; the editor only
23
+ * reads it.
24
+ */
25
+ history?: ReadonlyArray<string>;
26
+ };
27
+
28
+ /**
29
+ * Reads a single line, echoing keystrokes and supporting inline editing, history recall, and the
30
+ * common readline control chords.
31
+ *
32
+ * Distinguishes cancellation (Ctrl-C) from end-of-input (Ctrl-D on an empty buffer) so a shell can
33
+ * abandon the current line without exiting.
34
+ */
35
+ export const readLineResult = (bridge: TerminalBridge, options: ReadLineOptions = {}): Effect.Effect<LineResult> =>
36
+ Effect.async<LineResult>((resume) => {
37
+ const { prompt = '', history = [] } = options;
38
+
39
+ let buffer = '';
40
+ let cursor = 0;
41
+ let historyIndex = history.length;
42
+ let draft = '';
43
+
44
+ // Redraws the whole row; a buffer long enough to wrap will not repaint correctly.
45
+ const render = () => {
46
+ const trailing = buffer.length - cursor;
47
+ bridge.write(`\r\x1b[K${prompt}${buffer}${trailing > 0 ? `\x1b[${trailing}D` : ''}`);
48
+ };
49
+
50
+ const finish = (result: LineResult) => {
51
+ unsubscribe();
52
+ resume(Effect.succeed(result));
53
+ };
54
+
55
+ const recall = (index: number) => {
56
+ if (historyIndex === history.length) {
57
+ draft = buffer;
58
+ }
59
+
60
+ historyIndex = index;
61
+ buffer = index === history.length ? draft : history[index];
62
+ cursor = buffer.length;
63
+ render();
64
+ };
65
+
66
+ const unsubscribe = bridge.subscribe((input) => {
67
+ const { key } = input;
68
+
69
+ if (key.ctrl) {
70
+ switch (key.name) {
71
+ case 'c': {
72
+ bridge.write('^C\n');
73
+ finish({ type: 'cancelled' });
74
+ return;
75
+ }
76
+ case 'd': {
77
+ if (buffer.length === 0) {
78
+ bridge.write('\n');
79
+ finish({ type: 'eof' });
80
+ }
81
+ return;
82
+ }
83
+ case 'a': {
84
+ cursor = 0;
85
+ render();
86
+ return;
87
+ }
88
+ case 'e': {
89
+ cursor = buffer.length;
90
+ render();
91
+ return;
92
+ }
93
+ case 'u': {
94
+ buffer = buffer.slice(cursor);
95
+ cursor = 0;
96
+ render();
97
+ return;
98
+ }
99
+ case 'k': {
100
+ buffer = buffer.slice(0, cursor);
101
+ render();
102
+ return;
103
+ }
104
+ case 'l': {
105
+ bridge.clear();
106
+ render();
107
+ return;
108
+ }
109
+ default:
110
+ return;
111
+ }
112
+ }
113
+
114
+ switch (key.name) {
115
+ case 'return': {
116
+ bridge.write('\n');
117
+ finish({ type: 'line', value: buffer });
118
+ return;
119
+ }
120
+ case 'backspace': {
121
+ if (cursor > 0) {
122
+ buffer = buffer.slice(0, cursor - 1) + buffer.slice(cursor);
123
+ cursor -= 1;
124
+ render();
125
+ }
126
+ return;
127
+ }
128
+ case 'delete': {
129
+ if (cursor < buffer.length) {
130
+ buffer = buffer.slice(0, cursor) + buffer.slice(cursor + 1);
131
+ render();
132
+ }
133
+ return;
134
+ }
135
+ case 'left': {
136
+ if (cursor > 0) {
137
+ cursor -= 1;
138
+ render();
139
+ }
140
+ return;
141
+ }
142
+ case 'right': {
143
+ if (cursor < buffer.length) {
144
+ cursor += 1;
145
+ render();
146
+ }
147
+ return;
148
+ }
149
+ case 'home': {
150
+ cursor = 0;
151
+ render();
152
+ return;
153
+ }
154
+ case 'end': {
155
+ cursor = buffer.length;
156
+ render();
157
+ return;
158
+ }
159
+ case 'up': {
160
+ if (historyIndex > 0) {
161
+ recall(historyIndex - 1);
162
+ }
163
+ return;
164
+ }
165
+ case 'down': {
166
+ if (historyIndex < history.length) {
167
+ recall(historyIndex + 1);
168
+ }
169
+ return;
170
+ }
171
+ case 'escape':
172
+ case 'tab':
173
+ return;
174
+ }
175
+
176
+ Option.match(input.input, {
177
+ onNone: () => {},
178
+ onSome: (char) => {
179
+ buffer = buffer.slice(0, cursor) + char + buffer.slice(cursor);
180
+ cursor += char.length;
181
+ render();
182
+ },
183
+ });
184
+ });
185
+
186
+ render();
187
+
188
+ return Effect.sync(unsubscribe);
189
+ });
190
+
191
+ /**
192
+ * The `Terminal` service contract: a line, or a `QuitException` for either interrupt.
193
+ */
194
+ export const readLine = (bridge: TerminalBridge, options: ReadLineOptions = {}) =>
195
+ readLineResult(bridge, options).pipe(
196
+ Effect.flatMap((result) =>
197
+ result.type === 'line' ? Effect.succeed(result.value) : Effect.fail(new Terminal.QuitException()),
198
+ ),
199
+ );
@@ -0,0 +1,103 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Command from '@effect/cli/Command';
6
+ import * as ValidationError from '@effect/cli/ValidationError';
7
+ import type * as FileSystem from '@effect/platform/FileSystem';
8
+ import type * as Path from '@effect/platform/Path';
9
+ import type * as Terminal from '@effect/platform/Terminal';
10
+ import * as Cause from 'effect/Cause';
11
+ import * as Console from 'effect/Console';
12
+ import * as Effect from 'effect/Effect';
13
+
14
+ import type { TerminalBridge } from './bridge';
15
+ import { readLineResult } from './line-editor';
16
+ import { rewriteHelpAliases, tokenize } from './tokenize';
17
+
18
+ const EXIT_COMMANDS = ['exit', 'quit'];
19
+
20
+ /**
21
+ * The services `Command.run` itself needs, spelled out because `@effect/cli` only exposes the
22
+ * equivalent alias inside its `CliApp` namespace.
23
+ */
24
+ export type CliEnvironment = FileSystem.FileSystem | Path.Path | Terminal.Terminal;
25
+
26
+ export type ShellOptions<Name extends string, R, E, A> = {
27
+ command: Command.Command<Name, R, E, A>;
28
+ /**
29
+ * Executable name, used in help output and as the argv[1] the Effect CLI parser skips.
30
+ */
31
+ name?: string;
32
+ version?: string;
33
+ prompt?: string;
34
+ banner?: string;
35
+ };
36
+
37
+ /**
38
+ * Runs a read-eval-print loop against an `@effect/cli` command tree.
39
+ *
40
+ * Each line is tokenized and dispatched through the same `Command.run` the binary uses, with a
41
+ * synthetic argv prefix standing in for the two leading entries the parser discards. The command
42
+ * tree and its layer are built once, so every command reuses the already-activated services.
43
+ */
44
+ export const runShell = <Name extends string, R, E, A>(
45
+ bridge: TerminalBridge,
46
+ options: ShellOptions<Name, R, E, A>,
47
+ ): Effect.Effect<void, never, R | CliEnvironment> =>
48
+ Effect.gen(function* () {
49
+ const { command, name = 'dx', version = '0.0.0', prompt = `${name}> `, banner } = options;
50
+ const run = Command.run(command, { name, version });
51
+ const history: string[] = [];
52
+
53
+ if (banner) {
54
+ bridge.write(`${banner}\n`);
55
+ }
56
+
57
+ while (true) {
58
+ if (!bridge.atLineStart) {
59
+ bridge.write('\n');
60
+ }
61
+
62
+ const result = yield* readLineResult(bridge, { prompt, history });
63
+ if (result.type === 'eof') {
64
+ break;
65
+ }
66
+ if (result.type === 'cancelled') {
67
+ continue;
68
+ }
69
+
70
+ const line = result.value.trim();
71
+ if (line.length === 0) {
72
+ continue;
73
+ }
74
+ if (EXIT_COMMANDS.includes(line)) {
75
+ break;
76
+ }
77
+
78
+ history.push(line);
79
+ const tokens = rewriteHelpAliases(tokenize(line));
80
+ if (tokens.length === 0) {
81
+ continue;
82
+ }
83
+
84
+ // Failures are reported rather than propagated so the shell survives to the next prompt.
85
+ // Validation errors are skipped because the Effect CLI has already rendered them.
86
+ yield* run([name, name, ...tokens]).pipe(
87
+ Effect.catchAllCause((cause) => {
88
+ if (Cause.isInterruptedOnly(cause)) {
89
+ return Effect.void;
90
+ }
91
+
92
+ const failure = Cause.failureOption(cause);
93
+ if (failure._tag === 'Some' && ValidationError.isValidationError(failure.value)) {
94
+ return Effect.void;
95
+ }
96
+
97
+ return Console.error(Cause.pretty(cause));
98
+ }),
99
+ );
100
+ }
101
+
102
+ bridge.write('\n');
103
+ });
@@ -0,0 +1,43 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Terminal from '@effect/platform/Terminal';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Exit from 'effect/Exit';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as Mailbox from 'effect/Mailbox';
10
+
11
+ import type { TerminalBridge } from './bridge';
12
+ import { isQuitInput } from './input';
13
+ import { readLine } from './line-editor';
14
+
15
+ /**
16
+ * A `@effect/platform` `Terminal` backed by xterm.
17
+ *
18
+ * This is the only service in `CliApp.Environment` without a browser implementation upstream;
19
+ * `Path` is already pure JS and `FileSystem` can be stubbed.
20
+ */
21
+ export const make = (bridge: TerminalBridge): Terminal.Terminal =>
22
+ Terminal.Terminal.of({
23
+ columns: Effect.sync(() => bridge.columns),
24
+ rows: Effect.sync(() => bridge.rows),
25
+ isTTY: Effect.succeed(true),
26
+ readInput: Effect.gen(function* () {
27
+ const mailbox = yield* Mailbox.make<Terminal.UserInput>();
28
+ const unsubscribe = bridge.subscribe((input) => {
29
+ mailbox.unsafeOffer(input);
30
+ if (isQuitInput(input)) {
31
+ mailbox.unsafeDone(Exit.void);
32
+ }
33
+ });
34
+
35
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
36
+ return mailbox;
37
+ }),
38
+ readLine: readLine(bridge),
39
+ display: (text) => Effect.sync(() => bridge.write(text)),
40
+ });
41
+
42
+ export const layer = (bridge: TerminalBridge): Layer.Layer<Terminal.Terminal> =>
43
+ Layer.succeed(Terminal.Terminal, make(bridge));
@@ -0,0 +1,51 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { type InputHandler, type TerminalBridge } from './bridge';
6
+ import { decodeInput } from './input';
7
+
8
+ /**
9
+ * A bridge that records writes and lets a test push keystrokes, standing in for xterm.
10
+ */
11
+ export class TestBridge implements TerminalBridge {
12
+ readonly columns = 80;
13
+ readonly rows = 24;
14
+ readonly writes: string[] = [];
15
+
16
+ #handlers: InputHandler[] = [];
17
+ #atLineStart = true;
18
+
19
+ get atLineStart(): boolean {
20
+ return this.#atLineStart;
21
+ }
22
+
23
+ get rendered(): string {
24
+ return this.writes.join('');
25
+ }
26
+
27
+ write(text: string): void {
28
+ this.writes.push(text);
29
+ this.#atLineStart = text.endsWith('\n');
30
+ }
31
+
32
+ clear(): void {
33
+ this.writes.push('<clear>');
34
+ }
35
+
36
+ subscribe(handler: InputHandler): () => void {
37
+ this.#handlers.push(handler);
38
+ return () => {
39
+ this.#handlers = this.#handlers.filter((entry) => entry !== handler);
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Feeds raw terminal data through the real decoder, so tests exercise the same path as xterm.
45
+ */
46
+ send(data: string): void {
47
+ for (const input of decodeInput(data)) {
48
+ this.#handlers.at(-1)?.(input);
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,35 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ /**
6
+ * Splits a raw input line into argv tokens. Supports single/double-quoted segments so quoted
7
+ * strings with spaces survive. Intentionally simple — anything needing real shell semantics belongs
8
+ * in a real shell.
9
+ */
10
+ export const tokenize = (input: string): string[] => {
11
+ const tokens: string[] = [];
12
+ const regex = /"([^"]*)"|'([^']*)'|(\S+)/g;
13
+ let match: RegExpExecArray | null;
14
+ while ((match = regex.exec(input)) !== null) {
15
+ tokens.push(match[1] ?? match[2] ?? match[3]);
16
+ }
17
+
18
+ return tokens;
19
+ };
20
+
21
+ /**
22
+ * Translates shell-friendly aliases to their Effect CLI equivalents. The Effect CLI uses `--help`
23
+ * rather than a `help` subcommand, but `help` and `?` are the natural things to type.
24
+ */
25
+ export const rewriteHelpAliases = (tokens: ReadonlyArray<string>): string[] => {
26
+ if (tokens.length === 0) {
27
+ return [...tokens];
28
+ }
29
+
30
+ if (tokens[0] !== 'help' && tokens[0] !== '?') {
31
+ return [...tokens];
32
+ }
33
+
34
+ return tokens.length === 1 ? ['--help'] : [...tokens.slice(1), '--help'];
35
+ };
@@ -0,0 +1,114 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Args from '@effect/cli/Args';
6
+ import * as Command from '@effect/cli/Command';
7
+ import * as Options from '@effect/cli/Options';
8
+ import * as Prompt from '@effect/cli/Prompt';
9
+ import { type Meta, type StoryObj } from '@storybook/react-vite';
10
+ import * as Console from 'effect/Console';
11
+ import * as Effect from 'effect/Effect';
12
+ import * as Layer from 'effect/Layer';
13
+ import React, { useMemo } from 'react';
14
+ import { userEvent } from 'storybook/test';
15
+
16
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
17
+
18
+ import { runCommand, waitForTerminal } from '../../testing';
19
+ import { Terminal } from './Terminal';
20
+
21
+ const BOLD = '\x1b[1m';
22
+ const DIM = '\x1b[2m';
23
+ const CYAN = '\x1b[36m';
24
+ const RESET = '\x1b[0m';
25
+
26
+ //
27
+ // A self-contained command tree. Mounting a real CLI against a DXOS client is the CliPanel story
28
+ // in plugin-devtools, which is also what ships as the devtools panel.
29
+ //
30
+
31
+ const greet = Command.make(
32
+ 'greet',
33
+ {
34
+ name: Args.text({ name: 'name' }),
35
+ loud: Options.boolean('loud', { ifPresent: true }).pipe(Options.withDescription('Shout the greeting.')),
36
+ },
37
+ ({ name, loud }) => Console.log(loud ? `HELLO, ${name.toUpperCase()}!` : `Hello, ${name}.`),
38
+ ).pipe(Command.withDescription('Greet someone by name.'));
39
+
40
+ const ask = Command.make('ask', {}, () =>
41
+ Effect.gen(function* () {
42
+ const name = yield* Prompt.text({ message: 'What is your name?' });
43
+ const color = yield* Prompt.select({
44
+ message: 'Pick a color',
45
+ choices: [
46
+ { title: 'Cyan', value: CYAN },
47
+ { title: 'Magenta', value: '\x1b[35m' },
48
+ { title: 'Yellow', value: '\x1b[33m' },
49
+ ],
50
+ });
51
+
52
+ yield* Console.log(`${color}Nice to meet you, ${name}.${RESET}`);
53
+ }),
54
+ ).pipe(Command.withDescription('Interactive prompts, driven by the terminal key stream.'));
55
+
56
+ const colors = Command.make('colors', {}, () =>
57
+ Console.log(
58
+ Array.from({ length: 8 }, (_, index) => `\x1b[3${index}m██\x1b[0m`).join('') +
59
+ `\n${BOLD}bold${RESET} ${DIM}dim${RESET} \x1b[4munderline${RESET}`,
60
+ ),
61
+ ).pipe(Command.withDescription('Show that ANSI styling renders.'));
62
+
63
+ const demo = Command.make('demo').pipe(Command.withSubcommands([greet, ask, colors]));
64
+
65
+ const DefaultStory = () => {
66
+ const command = useMemo(() => demo, []);
67
+
68
+ return (
69
+ <Terminal
70
+ command={command}
71
+ layer={Layer.empty}
72
+ name='demo'
73
+ banner={`${BOLD}Effect CLI in the browser${RESET}\n${DIM}Try: greet world --loud · ask · colors · help${RESET}`}
74
+ />
75
+ );
76
+ };
77
+
78
+ const meta = {
79
+ title: 'ui/react-ui-terminal/Terminal',
80
+ render: DefaultStory,
81
+ decorators: [withTheme(), withLayout({ layout: 'fullscreen' })],
82
+ parameters: { layout: 'fullscreen' },
83
+ } satisfies Meta<typeof DefaultStory>;
84
+
85
+ export default meta;
86
+
87
+ type Story = StoryObj<typeof meta>;
88
+
89
+ export const Default: Story = {};
90
+
91
+ /**
92
+ * Drives the shell end to end: a command is parsed, run, and its output rendered.
93
+ */
94
+ export const Spec: Story = {
95
+ play: async ({ canvasElement }) => {
96
+ const keyboard = (text: string) => userEvent.keyboard(text);
97
+ await waitForTerminal(canvasElement, 'demo>');
98
+
99
+ await runCommand(canvasElement, 'greet world', keyboard);
100
+ await waitForTerminal(canvasElement, 'Hello, world.');
101
+
102
+ // Options are parsed, not merely echoed.
103
+ await runCommand(canvasElement, 'greet ada --loud', keyboard);
104
+ await waitForTerminal(canvasElement, 'HELLO, ADA!');
105
+
106
+ // An unknown command is reported once, by the CLI itself.
107
+ await runCommand(canvasElement, 'bogus', keyboard);
108
+ await waitForTerminal(canvasElement, 'Invalid subcommand');
109
+
110
+ // The shell survives the failure and keeps accepting commands.
111
+ await runCommand(canvasElement, 'greet again', keyboard);
112
+ await waitForTerminal(canvasElement, 'Hello, again.');
113
+ },
114
+ };