summaryrefslogtreecommitdiff
path: root/packages/cli/src/ui/components/shared/multiline-editor.tsx
blob: bd49efcbee57c790e370915e5142040283385dff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { useTextBuffer } from './text-buffer.js';
import chalk from 'chalk';
import { Box, Text, useInput, useStdin, Key } from 'ink';
import React from 'react';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import { Colors } from '../../colors.js';

export interface MultilineTextEditorProps {
  // Initial contents.
  readonly initialText?: string;

  // Placeholder text.
  readonly placeholder?: string;

  // Visible width.
  readonly width?: number;

  // Visible height.
  readonly height?: number;

  // Called when the user submits (plain <Enter> key).
  readonly onSubmit?: (text: string) => void;

  // Capture keyboard input.
  readonly focus?: boolean;

  // Called when the internal text buffer updates.
  readonly onChange?: (text: string) => void;

  // Called when the user attempts to navigate past the start of the editor
  // with the up arrow.
  readonly navigateUp?: () => void;

  // Called when the user attempts to navigate past the end of the editor
  // with the down arrow.
  readonly navigateDown?: () => void;

  // Called on all key events to allow the caller. Returns true if the
  // event was handled and should not be passed to the editor.
  readonly inputPreprocessor?: (input: string, key: Key) => boolean;

  // Optional initial cursor position (character offset)
  readonly initialCursorOffset?: number;

  readonly widthUsedByParent: number;

  readonly widthFraction?: number;
}

export const MultilineTextEditor = ({
  initialText = '',
  placeholder = '',
  width,
  height = 10,
  onSubmit,
  focus = true,
  onChange,
  initialCursorOffset,
  widthUsedByParent,
  widthFraction = 1,
  navigateUp,
  navigateDown,
  inputPreprocessor,
}: MultilineTextEditorProps): React.ReactElement => {
  const terminalSize = useTerminalSize();
  const effectiveWidth = Math.max(
    20,
    width ??
      Math.round(terminalSize.columns * widthFraction) - widthUsedByParent,
  );

  const { stdin, setRawMode } = useStdin();

  const buffer = useTextBuffer({
    initialText,
    initialCursorOffset,
    viewport: { height, width: effectiveWidth },
    stdin,
    setRawMode,
    onChange, // Pass onChange to the hook
  });

  useInput(
    (input, key) => {
      if (!focus) {
        return;
      }

      if (inputPreprocessor?.(input, key) === true) {
        return;
      }

      const isCtrlX =
        (key.ctrl && (input === 'x' || input === '\x18')) || input === '\x18';
      const isCtrlE =
        (key.ctrl && (input === 'e' || input === '\x05')) ||
        input === '\x05' ||
        (!key.ctrl &&
          input === 'e' &&
          input.length === 1 &&
          input.charCodeAt(0) === 5);
      if (isCtrlX || isCtrlE) {
        buffer.openInExternalEditor();
        return;
      }

      if (
        process.env['TEXTBUFFER_DEBUG'] === '1' ||
        process.env['TEXTBUFFER_DEBUG'] === 'true'
      ) {
        console.log('[MultilineTextEditor] event', { input, key });
      }

      if (input.startsWith('[') && input.endsWith('u')) {
        const m = input.match(/^\[([0-9]+);([0-9]+)u$/);
        if (m && m[1] === '13') {
          const mod = Number(m[2]);
          const hasCtrl = Math.floor(mod / 4) % 2 === 1;
          if (hasCtrl) {
            if (onSubmit) {
              onSubmit(buffer.text);
            }
          } else {
            buffer.newline();
          }
          return;
        }
      }

      if (input.startsWith('[27;') && input.endsWith('~')) {
        const m = input.match(/^\[27;([0-9]+);13~$/);
        if (m) {
          const mod = Number(m[1]);
          const hasCtrl = Math.floor(mod / 4) % 2 === 1;
          if (hasCtrl) {
            if (onSubmit) {
              onSubmit(buffer.text);
            }
          } else {
            buffer.newline();
          }
          return;
        }
      }

      if (input === '\n') {
        buffer.newline();
        return;
      }

      if (input === '\r') {
        if (onSubmit) {
          onSubmit(buffer.text);
        }
        return;
      }

      if (key.upArrow) {
        if (buffer.cursor[0] === 0 && navigateUp) {
          navigateUp();
          return;
        }
      }

      if (key.downArrow) {
        if (buffer.cursor[0] === buffer.lines.length - 1 && navigateDown) {
          navigateDown();
          return;
        }
      }

      buffer.handleInput(input, key as Record<string, boolean>);
    },
    { isActive: focus },
  );

  const visibleLines = buffer.visibleLines;
  const [cursorRow, cursorCol] = buffer.cursor;
  const [scrollRow, scrollCol] = buffer.scroll;

  return (
    <Box flexDirection="column">
      {buffer.text.length === 0 && placeholder ? (
        <Text color={Colors.SubtleComment}>{placeholder}</Text>
      ) : (
        visibleLines.map((lineText, idx) => {
          const absoluteRow = scrollRow + idx;
          let display = lineText.slice(scrollCol, scrollCol + effectiveWidth);
          if (display.length < effectiveWidth) {
            display = display.padEnd(effectiveWidth, ' ');
          }

          if (absoluteRow === cursorRow) {
            const relativeCol = cursorCol - scrollCol;
            const highlightCol = relativeCol;

            if (highlightCol >= 0 && highlightCol < effectiveWidth) {
              const charToHighlight = display[highlightCol] || ' ';
              const highlighted = chalk.inverse(charToHighlight);
              display =
                display.slice(0, highlightCol) +
                highlighted +
                display.slice(highlightCol + 1);
            } else if (relativeCol === effectiveWidth) {
              display =
                display.slice(0, effectiveWidth - 1) + chalk.inverse(' ');
            }
          }
          return <Text key={idx}>{display}</Text>;
        })
      )}
    </Box>
  );
};