app-input-pane.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import type { TextareaRenderable } from "@mbears/opentui-core";
  2. import type { TuiCopy } from "@zcode/i18n";
  3. import React from "react";
  4. import { DEFAULT_TUI_COPY } from "./app-locale.js";
  5. import { palette } from "./app-model.js";
  6. import { InputComposerStatus } from "./app-input-status.js";
  7. import { wordWrappedLineCount } from "./app-terminal-width.js";
  8. const h = React.createElement as (
  9. type: React.ElementType | string,
  10. props?: Record<string, unknown> | null,
  11. ...children: React.ReactNode[]
  12. ) => React.ReactElement;
  13. export const INPUT_DEFAULT_EDITOR_ROWS = 2;
  14. export const INPUT_MIN_EDITOR_ROWS = INPUT_DEFAULT_EDITOR_ROWS;
  15. export const INPUT_MAX_EDITOR_ROWS = 6;
  16. const INPUT_FRAME_CHROME_ROWS = 3;
  17. export const INPUT_PANE_STATUS_ROWS = 1;
  18. const INPUT_CHROME_ROWS = INPUT_FRAME_CHROME_ROWS + INPUT_PANE_STATUS_ROWS;
  19. const INPUT_CONTENT_FALLBACK_WIDTH = 80;
  20. const INPUT_MIN_CONTENT_WIDTH = 8;
  21. const INPUT_PANE_HORIZONTAL_CHROME_WIDTH = 4;
  22. export const INPUT_PANE_MIN_HEIGHT = INPUT_MIN_EDITOR_ROWS + INPUT_CHROME_ROWS;
  23. export const INPUT_PANE_MAX_HEIGHT = INPUT_MAX_EDITOR_ROWS + INPUT_CHROME_ROWS;
  24. export const INPUT_PANE_BORDER = true;
  25. export const INPUT_PANE_BORDER_STYLE = "rounded";
  26. export const INPUT_PANE_STATUS_SPACER_STYLE = {
  27. flexGrow: 1,
  28. minHeight: 0,
  29. } as const;
  30. export const PROMPT_TEXTAREA_KEY_BINDINGS = [
  31. { name: "return", action: "submit" },
  32. { name: "linefeed", action: "submit" },
  33. { name: "return", shift: true, action: "newline" },
  34. { name: "linefeed", shift: true, action: "newline" },
  35. ] as const;
  36. export type PromptInputEditor = Pick<
  37. TextareaRenderable,
  38. | "cursorOffset"
  39. | "deleteRange"
  40. | "focus"
  41. | "focused"
  42. | "gotoBufferEnd"
  43. | "insertText"
  44. | "logicalCursor"
  45. | "plainText"
  46. | "setText"
  47. >;
  48. type DraftTextarea = Pick<PromptInputEditor, "gotoBufferEnd" | "plainText" | "setText">;
  49. export function InputPane({
  50. busy,
  51. contentWidth,
  52. copy = DEFAULT_TUI_COPY,
  53. focused,
  54. mode,
  55. model,
  56. onInput,
  57. onSubmit,
  58. editorRef,
  59. resetCursorToEndVersion,
  60. thoughtLevel,
  61. value,
  62. }: {
  63. busy: boolean;
  64. contentWidth?: number;
  65. copy?: TuiCopy;
  66. editorRef?: React.MutableRefObject<PromptInputEditor | null>;
  67. focused: boolean;
  68. mode?: string;
  69. model: string;
  70. onInput: (value: string) => void;
  71. onSubmit: (value: string) => void;
  72. resetCursorToEndVersion: number;
  73. thoughtLevel: string;
  74. value: string;
  75. }): React.ReactElement {
  76. const textareaRef = React.useRef<TextareaRenderable | null>(null);
  77. const appliedCursorToEndVersionRef = React.useRef(0);
  78. const syncingValueRef = React.useRef(false);
  79. const editorRows = inputPaneEditorRows(value, contentWidth);
  80. const setTextareaRef = React.useCallback(
  81. (textarea: TextareaRenderable | null) => {
  82. textareaRef.current = textarea;
  83. if (editorRef) {
  84. // OpenTUI destroys the previous EditorView during keyed remounts; keep
  85. // the shared prompt editor ref aligned with the live textarea instance.
  86. editorRef.current = textarea;
  87. }
  88. },
  89. [editorRef],
  90. );
  91. React.useLayoutEffect(() => {
  92. if (!editorRef) return undefined;
  93. editorRef.current = textareaRef.current;
  94. return () => {
  95. editorRef.current = null;
  96. };
  97. }, [editorRef]);
  98. React.useLayoutEffect(() => {
  99. const textarea = textareaRef.current;
  100. if (!textarea) return;
  101. syncingValueRef.current = true;
  102. try {
  103. syncTextareaValue(textarea, value);
  104. } finally {
  105. syncingValueRef.current = false;
  106. }
  107. }, [value]);
  108. React.useLayoutEffect(() => {
  109. if (resetCursorToEndVersion <= 0) return;
  110. if (appliedCursorToEndVersionRef.current === resetCursorToEndVersion) return;
  111. appliedCursorToEndVersionRef.current = resetCursorToEndVersion;
  112. const textarea = textareaRef.current;
  113. if (textarea) moveInputCursorToEnd(textarea);
  114. }, [resetCursorToEndVersion, value]);
  115. const handleContentChange = React.useCallback(() => {
  116. if (syncingValueRef.current) return;
  117. const textarea = textareaRef.current;
  118. if (!textarea) return;
  119. // OpenTUI can echo a controlled setText as content-change after
  120. // sync finishes; treating that as user input exits history navigation.
  121. if (!shouldEmitTextareaInput(value, textarea.plainText)) return;
  122. onInput(textarea.plainText);
  123. }, [onInput, value]);
  124. const handleSubmit = React.useCallback(() => {
  125. onSubmit(textareaRef.current?.plainText ?? value);
  126. }, [onSubmit, value]);
  127. const title = inputPaneTitle(copy, mode);
  128. return h(
  129. "box",
  130. {
  131. title,
  132. style: inputPaneContainerStyle(focused, editorRows),
  133. },
  134. h("textarea", {
  135. focused,
  136. initialValue: value,
  137. keyBindings: PROMPT_TEXTAREA_KEY_BINDINGS,
  138. onContentChange: handleContentChange,
  139. onSubmit: handleSubmit,
  140. placeholder: inputPanePlaceholder(copy, busy),
  141. ref: setTextareaRef,
  142. style: inputPaneTextareaStyle(editorRows),
  143. }),
  144. h("box", { style: INPUT_PANE_STATUS_SPACER_STYLE }),
  145. h(InputComposerStatus, {
  146. contentWidth: inputPaneStatusContentWidth(contentWidth),
  147. model,
  148. thoughtLevel,
  149. }),
  150. );
  151. }
  152. export function inputPaneTitle(copy: TuiCopy, mode?: string): string {
  153. const title = mode ? formatInputModeLabel(mode) : copy.input.title;
  154. return ` ${title} `;
  155. }
  156. export function inputPanePlaceholder(copy: TuiCopy, busy: boolean): string {
  157. return busy ? copy.input.busyPlaceholder : copy.input.placeholder;
  158. }
  159. export function inputPaneEditorRows(value: string, contentWidth?: number): number {
  160. const contentRows = wordWrappedLineCount(value, normalizeInputContentWidth(contentWidth));
  161. return normalizeEditorRows(contentRows);
  162. }
  163. export function inputPaneHeight(editorRows: number): number {
  164. return normalizeEditorRows(editorRows) + INPUT_CHROME_ROWS;
  165. }
  166. export function inputPaneContainerStyle(
  167. focused: boolean,
  168. editorRows = INPUT_MIN_EDITOR_ROWS,
  169. ): Record<string, unknown> {
  170. const height = inputPaneHeight(editorRows);
  171. return {
  172. backgroundColor: palette.panel,
  173. border: INPUT_PANE_BORDER,
  174. borderColor: focused ? palette.accent : palette.border,
  175. borderStyle: INPUT_PANE_BORDER_STYLE,
  176. flexDirection: "column",
  177. height,
  178. maxHeight: INPUT_PANE_MAX_HEIGHT,
  179. minHeight: INPUT_PANE_MIN_HEIGHT,
  180. paddingLeft: 1,
  181. paddingRight: 1,
  182. };
  183. }
  184. export function inputPaneTextareaStyle(editorRows: number): Record<string, unknown> {
  185. return {
  186. focusedBackgroundColor: palette.panel,
  187. focusedTextColor: palette.text,
  188. height: normalizeEditorRows(editorRows),
  189. maxHeight: INPUT_MAX_EDITOR_ROWS,
  190. minHeight: INPUT_MIN_EDITOR_ROWS,
  191. placeholderColor: palette.muted,
  192. textColor: palette.text,
  193. width: "100%",
  194. wrapMode: "word",
  195. };
  196. }
  197. export function syncTextareaValue(textarea: DraftTextarea, value: string): boolean {
  198. if (textarea.plainText === value) return false;
  199. textarea.setText(value);
  200. moveInputCursorToEnd(textarea);
  201. return true;
  202. }
  203. export function shouldEmitTextareaInput(controlledValue: string, editorValue: string): boolean {
  204. return editorValue !== controlledValue;
  205. }
  206. export function moveInputCursorToEnd(input: Pick<TextareaRenderable, "gotoBufferEnd">): void {
  207. // OpenTUI controlled value updates can leave the previous cursor viewport in
  208. // place after history recall; gotoBufferEnd refreshes both cursor and scroll.
  209. input.gotoBufferEnd();
  210. }
  211. function normalizeInputContentWidth(contentWidth?: number): number {
  212. if (contentWidth === undefined || !Number.isFinite(contentWidth)) {
  213. return INPUT_CONTENT_FALLBACK_WIDTH;
  214. }
  215. return Math.max(INPUT_MIN_CONTENT_WIDTH, Math.floor(contentWidth));
  216. }
  217. function inputPaneStatusContentWidth(contentWidth?: number): number | undefined {
  218. if (contentWidth === undefined || !Number.isFinite(contentWidth)) return undefined;
  219. return Math.max(
  220. INPUT_MIN_CONTENT_WIDTH,
  221. Math.floor(contentWidth) - INPUT_PANE_HORIZONTAL_CHROME_WIDTH,
  222. );
  223. }
  224. function normalizeEditorRows(rows: number): number {
  225. return Math.min(INPUT_MAX_EDITOR_ROWS, Math.max(INPUT_MIN_EDITOR_ROWS, Math.floor(rows)));
  226. }
  227. function formatInputModeLabel(mode: string): string {
  228. if (mode.length === 0) return mode;
  229. return `${mode.slice(0, 1).toUpperCase()}${mode.slice(1)}`;
  230. }