Add files using upload-large-folder tool
Browse files- projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolConfirmationMessage.test.tsx +58 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx +297 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolGroupMessage.tsx +126 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolMessage.test.tsx +183 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolMessage.tsx +296 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/messages/UserMessage.tsx +43 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/messages/UserShellMessage.tsx +25 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/MaxSizedBox.test.tsx +425 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/MaxSizedBox.tsx +624 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/RadioButtonSelect.test.tsx +181 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/RadioButtonSelect.tsx +234 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/__snapshots__/RadioButtonSelect.test.tsx.snap +47 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/text-buffer.test.ts +1728 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/text-buffer.ts +2227 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/vim-buffer-actions.test.ts +1119 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/shared/vim-buffer-actions.ts +814 -0
- projects/ui/qwen-code/packages/cli/src/ui/utils/__snapshots__/MarkdownDisplay.test.tsx.snap +93 -0
- projects/ui/qwen-code/packages/core/src/code_assist/codeAssist.ts +35 -0
- projects/ui/qwen-code/packages/core/src/index.test.ts +13 -0
- projects/ui/qwen-code/packages/core/src/index.ts +107 -0
projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolConfirmationMessage.test.tsx
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect, vi } from 'vitest';
|
| 8 |
+
import { ToolConfirmationMessage } from './ToolConfirmationMessage.js';
|
| 9 |
+
import { ToolCallConfirmationDetails } from '@qwen-code/qwen-code-core';
|
| 10 |
+
import { renderWithProviders } from '../../../test-utils/render.js';
|
| 11 |
+
|
| 12 |
+
describe('ToolConfirmationMessage', () => {
|
| 13 |
+
it('should not display urls if prompt and url are the same', () => {
|
| 14 |
+
const confirmationDetails: ToolCallConfirmationDetails = {
|
| 15 |
+
type: 'info',
|
| 16 |
+
title: 'Confirm Web Fetch',
|
| 17 |
+
prompt: 'https://example.com',
|
| 18 |
+
urls: ['https://example.com'],
|
| 19 |
+
onConfirm: vi.fn(),
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
const { lastFrame } = renderWithProviders(
|
| 23 |
+
<ToolConfirmationMessage
|
| 24 |
+
confirmationDetails={confirmationDetails}
|
| 25 |
+
availableTerminalHeight={30}
|
| 26 |
+
terminalWidth={80}
|
| 27 |
+
/>,
|
| 28 |
+
);
|
| 29 |
+
|
| 30 |
+
expect(lastFrame()).not.toContain('URLs to fetch:');
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
it('should display urls if prompt and url are different', () => {
|
| 34 |
+
const confirmationDetails: ToolCallConfirmationDetails = {
|
| 35 |
+
type: 'info',
|
| 36 |
+
title: 'Confirm Web Fetch',
|
| 37 |
+
prompt:
|
| 38 |
+
'fetch https://github.com/google/gemini-react/blob/main/README.md',
|
| 39 |
+
urls: [
|
| 40 |
+
'https://raw.githubusercontent.com/google/gemini-react/main/README.md',
|
| 41 |
+
],
|
| 42 |
+
onConfirm: vi.fn(),
|
| 43 |
+
};
|
| 44 |
+
|
| 45 |
+
const { lastFrame } = renderWithProviders(
|
| 46 |
+
<ToolConfirmationMessage
|
| 47 |
+
confirmationDetails={confirmationDetails}
|
| 48 |
+
availableTerminalHeight={30}
|
| 49 |
+
terminalWidth={80}
|
| 50 |
+
/>,
|
| 51 |
+
);
|
| 52 |
+
|
| 53 |
+
expect(lastFrame()).toContain('URLs to fetch:');
|
| 54 |
+
expect(lastFrame()).toContain(
|
| 55 |
+
'- https://raw.githubusercontent.com/google/gemini-react/main/README.md',
|
| 56 |
+
);
|
| 57 |
+
});
|
| 58 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React from 'react';
|
| 8 |
+
import { Box, Text } from 'ink';
|
| 9 |
+
import { DiffRenderer } from './DiffRenderer.js';
|
| 10 |
+
import { Colors } from '../../colors.js';
|
| 11 |
+
import { RenderInline } from '../../utils/InlineMarkdownRenderer.js';
|
| 12 |
+
import {
|
| 13 |
+
ToolCallConfirmationDetails,
|
| 14 |
+
ToolConfirmationOutcome,
|
| 15 |
+
ToolExecuteConfirmationDetails,
|
| 16 |
+
ToolMcpConfirmationDetails,
|
| 17 |
+
Config,
|
| 18 |
+
} from '@qwen-code/qwen-code-core';
|
| 19 |
+
import {
|
| 20 |
+
RadioButtonSelect,
|
| 21 |
+
RadioSelectItem,
|
| 22 |
+
} from '../shared/RadioButtonSelect.js';
|
| 23 |
+
import { MaxSizedBox } from '../shared/MaxSizedBox.js';
|
| 24 |
+
import { useKeypress } from '../../hooks/useKeypress.js';
|
| 25 |
+
|
| 26 |
+
export interface ToolConfirmationMessageProps {
|
| 27 |
+
confirmationDetails: ToolCallConfirmationDetails;
|
| 28 |
+
config?: Config;
|
| 29 |
+
isFocused?: boolean;
|
| 30 |
+
availableTerminalHeight?: number;
|
| 31 |
+
terminalWidth: number;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
export const ToolConfirmationMessage: React.FC<
|
| 35 |
+
ToolConfirmationMessageProps
|
| 36 |
+
> = ({
|
| 37 |
+
confirmationDetails,
|
| 38 |
+
config,
|
| 39 |
+
isFocused = true,
|
| 40 |
+
availableTerminalHeight,
|
| 41 |
+
terminalWidth,
|
| 42 |
+
}) => {
|
| 43 |
+
const { onConfirm } = confirmationDetails;
|
| 44 |
+
const childWidth = terminalWidth - 2; // 2 for padding
|
| 45 |
+
|
| 46 |
+
const handleConfirm = async (outcome: ToolConfirmationOutcome) => {
|
| 47 |
+
if (confirmationDetails.type === 'edit') {
|
| 48 |
+
const ideClient = config?.getIdeClient();
|
| 49 |
+
if (config?.getIdeMode()) {
|
| 50 |
+
const cliOutcome =
|
| 51 |
+
outcome === ToolConfirmationOutcome.Cancel ? 'rejected' : 'accepted';
|
| 52 |
+
await ideClient?.resolveDiffFromCli(
|
| 53 |
+
confirmationDetails.filePath,
|
| 54 |
+
cliOutcome,
|
| 55 |
+
);
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
onConfirm(outcome);
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
useKeypress(
|
| 62 |
+
(key) => {
|
| 63 |
+
if (!isFocused) return;
|
| 64 |
+
if (key.name === 'escape' || (key.ctrl && key.name === 'c')) {
|
| 65 |
+
handleConfirm(ToolConfirmationOutcome.Cancel);
|
| 66 |
+
}
|
| 67 |
+
},
|
| 68 |
+
{ isActive: isFocused },
|
| 69 |
+
);
|
| 70 |
+
|
| 71 |
+
const handleSelect = (item: ToolConfirmationOutcome) => handleConfirm(item);
|
| 72 |
+
|
| 73 |
+
let bodyContent: React.ReactNode | null = null; // Removed contextDisplay here
|
| 74 |
+
let question: string;
|
| 75 |
+
|
| 76 |
+
const options: Array<RadioSelectItem<ToolConfirmationOutcome>> = new Array<
|
| 77 |
+
RadioSelectItem<ToolConfirmationOutcome>
|
| 78 |
+
>();
|
| 79 |
+
|
| 80 |
+
// Body content is now the DiffRenderer, passing filename to it
|
| 81 |
+
// The bordered box is removed from here and handled within DiffRenderer
|
| 82 |
+
|
| 83 |
+
function availableBodyContentHeight() {
|
| 84 |
+
if (options.length === 0) {
|
| 85 |
+
// This should not happen in practice as options are always added before this is called.
|
| 86 |
+
throw new Error('Options not provided for confirmation message');
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
if (availableTerminalHeight === undefined) {
|
| 90 |
+
return undefined;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// Calculate the vertical space (in lines) consumed by UI elements
|
| 94 |
+
// surrounding the main body content.
|
| 95 |
+
const PADDING_OUTER_Y = 2; // Main container has `padding={1}` (top & bottom).
|
| 96 |
+
const MARGIN_BODY_BOTTOM = 1; // margin on the body container.
|
| 97 |
+
const HEIGHT_QUESTION = 1; // The question text is one line.
|
| 98 |
+
const MARGIN_QUESTION_BOTTOM = 1; // Margin on the question container.
|
| 99 |
+
const HEIGHT_OPTIONS = options.length; // Each option in the radio select takes one line.
|
| 100 |
+
|
| 101 |
+
const surroundingElementsHeight =
|
| 102 |
+
PADDING_OUTER_Y +
|
| 103 |
+
MARGIN_BODY_BOTTOM +
|
| 104 |
+
HEIGHT_QUESTION +
|
| 105 |
+
MARGIN_QUESTION_BOTTOM +
|
| 106 |
+
HEIGHT_OPTIONS;
|
| 107 |
+
return Math.max(availableTerminalHeight - surroundingElementsHeight, 1);
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
if (confirmationDetails.type === 'edit') {
|
| 111 |
+
if (confirmationDetails.isModifying) {
|
| 112 |
+
return (
|
| 113 |
+
<Box
|
| 114 |
+
minWidth="90%"
|
| 115 |
+
borderStyle="round"
|
| 116 |
+
borderColor={Colors.Gray}
|
| 117 |
+
justifyContent="space-around"
|
| 118 |
+
padding={1}
|
| 119 |
+
overflow="hidden"
|
| 120 |
+
>
|
| 121 |
+
<Text>Modify in progress: </Text>
|
| 122 |
+
<Text color={Colors.AccentGreen}>
|
| 123 |
+
Save and close external editor to continue
|
| 124 |
+
</Text>
|
| 125 |
+
</Box>
|
| 126 |
+
);
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
question = `Apply this change?`;
|
| 130 |
+
options.push(
|
| 131 |
+
{
|
| 132 |
+
label: 'Yes, allow once',
|
| 133 |
+
value: ToolConfirmationOutcome.ProceedOnce,
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
label: 'Yes, allow always',
|
| 137 |
+
value: ToolConfirmationOutcome.ProceedAlways,
|
| 138 |
+
},
|
| 139 |
+
);
|
| 140 |
+
if (config?.getIdeMode()) {
|
| 141 |
+
options.push({
|
| 142 |
+
label: 'No (esc)',
|
| 143 |
+
value: ToolConfirmationOutcome.Cancel,
|
| 144 |
+
});
|
| 145 |
+
} else {
|
| 146 |
+
options.push({
|
| 147 |
+
label: 'Modify with external editor',
|
| 148 |
+
value: ToolConfirmationOutcome.ModifyWithEditor,
|
| 149 |
+
});
|
| 150 |
+
options.push({
|
| 151 |
+
label: 'No, suggest changes (esc)',
|
| 152 |
+
value: ToolConfirmationOutcome.Cancel,
|
| 153 |
+
});
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
bodyContent = (
|
| 157 |
+
<DiffRenderer
|
| 158 |
+
diffContent={confirmationDetails.fileDiff}
|
| 159 |
+
filename={confirmationDetails.fileName}
|
| 160 |
+
availableTerminalHeight={availableBodyContentHeight()}
|
| 161 |
+
terminalWidth={childWidth}
|
| 162 |
+
/>
|
| 163 |
+
);
|
| 164 |
+
} else if (confirmationDetails.type === 'exec') {
|
| 165 |
+
const executionProps =
|
| 166 |
+
confirmationDetails as ToolExecuteConfirmationDetails;
|
| 167 |
+
|
| 168 |
+
question = `Allow execution of: '${executionProps.rootCommand}'?`;
|
| 169 |
+
options.push(
|
| 170 |
+
{
|
| 171 |
+
label: `Yes, allow once`,
|
| 172 |
+
value: ToolConfirmationOutcome.ProceedOnce,
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
label: `Yes, allow always ...`,
|
| 176 |
+
value: ToolConfirmationOutcome.ProceedAlways,
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
label: 'No, suggest changes (esc)',
|
| 180 |
+
value: ToolConfirmationOutcome.Cancel,
|
| 181 |
+
},
|
| 182 |
+
);
|
| 183 |
+
|
| 184 |
+
let bodyContentHeight = availableBodyContentHeight();
|
| 185 |
+
if (bodyContentHeight !== undefined) {
|
| 186 |
+
bodyContentHeight -= 2; // Account for padding;
|
| 187 |
+
}
|
| 188 |
+
bodyContent = (
|
| 189 |
+
<Box flexDirection="column">
|
| 190 |
+
<Box paddingX={1} marginLeft={1}>
|
| 191 |
+
<MaxSizedBox
|
| 192 |
+
maxHeight={bodyContentHeight}
|
| 193 |
+
maxWidth={Math.max(childWidth - 4, 1)}
|
| 194 |
+
>
|
| 195 |
+
<Box>
|
| 196 |
+
<Text color={Colors.AccentCyan}>{executionProps.command}</Text>
|
| 197 |
+
</Box>
|
| 198 |
+
</MaxSizedBox>
|
| 199 |
+
</Box>
|
| 200 |
+
</Box>
|
| 201 |
+
);
|
| 202 |
+
} else if (confirmationDetails.type === 'info') {
|
| 203 |
+
const infoProps = confirmationDetails;
|
| 204 |
+
const displayUrls =
|
| 205 |
+
infoProps.urls &&
|
| 206 |
+
!(infoProps.urls.length === 1 && infoProps.urls[0] === infoProps.prompt);
|
| 207 |
+
|
| 208 |
+
question = `Do you want to proceed?`;
|
| 209 |
+
options.push(
|
| 210 |
+
{
|
| 211 |
+
label: 'Yes, allow once',
|
| 212 |
+
value: ToolConfirmationOutcome.ProceedOnce,
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
label: 'Yes, allow always',
|
| 216 |
+
value: ToolConfirmationOutcome.ProceedAlways,
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
label: 'No, suggest changes (esc)',
|
| 220 |
+
value: ToolConfirmationOutcome.Cancel,
|
| 221 |
+
},
|
| 222 |
+
);
|
| 223 |
+
|
| 224 |
+
bodyContent = (
|
| 225 |
+
<Box flexDirection="column" paddingX={1} marginLeft={1}>
|
| 226 |
+
<Text color={Colors.AccentCyan}>
|
| 227 |
+
<RenderInline text={infoProps.prompt} />
|
| 228 |
+
</Text>
|
| 229 |
+
{displayUrls && infoProps.urls && infoProps.urls.length > 0 && (
|
| 230 |
+
<Box flexDirection="column" marginTop={1}>
|
| 231 |
+
<Text>URLs to fetch:</Text>
|
| 232 |
+
{infoProps.urls.map((url) => (
|
| 233 |
+
<Text key={url}>
|
| 234 |
+
{' '}
|
| 235 |
+
- <RenderInline text={url} />
|
| 236 |
+
</Text>
|
| 237 |
+
))}
|
| 238 |
+
</Box>
|
| 239 |
+
)}
|
| 240 |
+
</Box>
|
| 241 |
+
);
|
| 242 |
+
} else {
|
| 243 |
+
// mcp tool confirmation
|
| 244 |
+
const mcpProps = confirmationDetails as ToolMcpConfirmationDetails;
|
| 245 |
+
|
| 246 |
+
bodyContent = (
|
| 247 |
+
<Box flexDirection="column" paddingX={1} marginLeft={1}>
|
| 248 |
+
<Text color={Colors.AccentCyan}>MCP Server: {mcpProps.serverName}</Text>
|
| 249 |
+
<Text color={Colors.AccentCyan}>Tool: {mcpProps.toolName}</Text>
|
| 250 |
+
</Box>
|
| 251 |
+
);
|
| 252 |
+
|
| 253 |
+
question = `Allow execution of MCP tool "${mcpProps.toolName}" from server "${mcpProps.serverName}"?`;
|
| 254 |
+
options.push(
|
| 255 |
+
{
|
| 256 |
+
label: 'Yes, allow once',
|
| 257 |
+
value: ToolConfirmationOutcome.ProceedOnce,
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
label: `Yes, always allow tool "${mcpProps.toolName}" from server "${mcpProps.serverName}"`,
|
| 261 |
+
value: ToolConfirmationOutcome.ProceedAlwaysTool, // Cast until types are updated
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
label: `Yes, always allow all tools from server "${mcpProps.serverName}"`,
|
| 265 |
+
value: ToolConfirmationOutcome.ProceedAlwaysServer,
|
| 266 |
+
},
|
| 267 |
+
{
|
| 268 |
+
label: 'No, suggest changes (esc)',
|
| 269 |
+
value: ToolConfirmationOutcome.Cancel,
|
| 270 |
+
},
|
| 271 |
+
);
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
return (
|
| 275 |
+
<Box flexDirection="column" padding={1} width={childWidth}>
|
| 276 |
+
{/* Body Content (Diff Renderer or Command Info) */}
|
| 277 |
+
{/* No separate context display here anymore for edits */}
|
| 278 |
+
<Box flexGrow={1} flexShrink={1} overflow="hidden" marginBottom={1}>
|
| 279 |
+
{bodyContent}
|
| 280 |
+
</Box>
|
| 281 |
+
|
| 282 |
+
{/* Confirmation Question */}
|
| 283 |
+
<Box marginBottom={1} flexShrink={0}>
|
| 284 |
+
<Text wrap="truncate">{question}</Text>
|
| 285 |
+
</Box>
|
| 286 |
+
|
| 287 |
+
{/* Select Input for Options */}
|
| 288 |
+
<Box flexShrink={0}>
|
| 289 |
+
<RadioButtonSelect
|
| 290 |
+
items={options}
|
| 291 |
+
onSelect={handleSelect}
|
| 292 |
+
isFocused={isFocused}
|
| 293 |
+
/>
|
| 294 |
+
</Box>
|
| 295 |
+
</Box>
|
| 296 |
+
);
|
| 297 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, { useMemo } from 'react';
|
| 8 |
+
import { Box } from 'ink';
|
| 9 |
+
import { IndividualToolCallDisplay, ToolCallStatus } from '../../types.js';
|
| 10 |
+
import { ToolMessage } from './ToolMessage.js';
|
| 11 |
+
import { ToolConfirmationMessage } from './ToolConfirmationMessage.js';
|
| 12 |
+
import { Colors } from '../../colors.js';
|
| 13 |
+
import { Config } from '@qwen-code/qwen-code-core';
|
| 14 |
+
import { SHELL_COMMAND_NAME } from '../../constants.js';
|
| 15 |
+
|
| 16 |
+
interface ToolGroupMessageProps {
|
| 17 |
+
groupId: number;
|
| 18 |
+
toolCalls: IndividualToolCallDisplay[];
|
| 19 |
+
availableTerminalHeight?: number;
|
| 20 |
+
terminalWidth: number;
|
| 21 |
+
config?: Config;
|
| 22 |
+
isFocused?: boolean;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
// Main component renders the border and maps the tools using ToolMessage
|
| 26 |
+
export const ToolGroupMessage: React.FC<ToolGroupMessageProps> = ({
|
| 27 |
+
toolCalls,
|
| 28 |
+
availableTerminalHeight,
|
| 29 |
+
terminalWidth,
|
| 30 |
+
config,
|
| 31 |
+
isFocused = true,
|
| 32 |
+
}) => {
|
| 33 |
+
const hasPending = !toolCalls.every(
|
| 34 |
+
(t) => t.status === ToolCallStatus.Success,
|
| 35 |
+
);
|
| 36 |
+
const isShellCommand = toolCalls.some((t) => t.name === SHELL_COMMAND_NAME);
|
| 37 |
+
const borderColor =
|
| 38 |
+
hasPending || isShellCommand ? Colors.AccentYellow : Colors.Gray;
|
| 39 |
+
|
| 40 |
+
const staticHeight = /* border */ 2 + /* marginBottom */ 1;
|
| 41 |
+
// This is a bit of a magic number, but it accounts for the border and
|
| 42 |
+
// marginLeft.
|
| 43 |
+
const innerWidth = terminalWidth - 4;
|
| 44 |
+
|
| 45 |
+
// only prompt for tool approval on the first 'confirming' tool in the list
|
| 46 |
+
// note, after the CTA, this automatically moves over to the next 'confirming' tool
|
| 47 |
+
const toolAwaitingApproval = useMemo(
|
| 48 |
+
() => toolCalls.find((tc) => tc.status === ToolCallStatus.Confirming),
|
| 49 |
+
[toolCalls],
|
| 50 |
+
);
|
| 51 |
+
|
| 52 |
+
let countToolCallsWithResults = 0;
|
| 53 |
+
for (const tool of toolCalls) {
|
| 54 |
+
if (tool.resultDisplay !== undefined && tool.resultDisplay !== '') {
|
| 55 |
+
countToolCallsWithResults++;
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
const countOneLineToolCalls = toolCalls.length - countToolCallsWithResults;
|
| 59 |
+
const availableTerminalHeightPerToolMessage = availableTerminalHeight
|
| 60 |
+
? Math.max(
|
| 61 |
+
Math.floor(
|
| 62 |
+
(availableTerminalHeight - staticHeight - countOneLineToolCalls) /
|
| 63 |
+
Math.max(1, countToolCallsWithResults),
|
| 64 |
+
),
|
| 65 |
+
1,
|
| 66 |
+
)
|
| 67 |
+
: undefined;
|
| 68 |
+
|
| 69 |
+
return (
|
| 70 |
+
<Box
|
| 71 |
+
flexDirection="column"
|
| 72 |
+
borderStyle="round"
|
| 73 |
+
/*
|
| 74 |
+
This width constraint is highly important and protects us from an Ink rendering bug.
|
| 75 |
+
Since the ToolGroup can typically change rendering states frequently, it can cause
|
| 76 |
+
Ink to render the border of the box incorrectly and span multiple lines and even
|
| 77 |
+
cause tearing.
|
| 78 |
+
*/
|
| 79 |
+
width="100%"
|
| 80 |
+
marginLeft={1}
|
| 81 |
+
borderDimColor={hasPending}
|
| 82 |
+
borderColor={borderColor}
|
| 83 |
+
>
|
| 84 |
+
{toolCalls.map((tool) => {
|
| 85 |
+
const isConfirming = toolAwaitingApproval?.callId === tool.callId;
|
| 86 |
+
return (
|
| 87 |
+
<Box key={tool.callId} flexDirection="column" minHeight={1}>
|
| 88 |
+
<Box flexDirection="row" alignItems="center">
|
| 89 |
+
<ToolMessage
|
| 90 |
+
callId={tool.callId}
|
| 91 |
+
name={tool.name}
|
| 92 |
+
description={tool.description}
|
| 93 |
+
resultDisplay={tool.resultDisplay}
|
| 94 |
+
status={tool.status}
|
| 95 |
+
confirmationDetails={tool.confirmationDetails}
|
| 96 |
+
availableTerminalHeight={availableTerminalHeightPerToolMessage}
|
| 97 |
+
terminalWidth={innerWidth}
|
| 98 |
+
emphasis={
|
| 99 |
+
isConfirming
|
| 100 |
+
? 'high'
|
| 101 |
+
: toolAwaitingApproval
|
| 102 |
+
? 'low'
|
| 103 |
+
: 'medium'
|
| 104 |
+
}
|
| 105 |
+
renderOutputAsMarkdown={tool.renderOutputAsMarkdown}
|
| 106 |
+
/>
|
| 107 |
+
</Box>
|
| 108 |
+
{tool.status === ToolCallStatus.Confirming &&
|
| 109 |
+
isConfirming &&
|
| 110 |
+
tool.confirmationDetails && (
|
| 111 |
+
<ToolConfirmationMessage
|
| 112 |
+
confirmationDetails={tool.confirmationDetails}
|
| 113 |
+
config={config}
|
| 114 |
+
isFocused={isFocused}
|
| 115 |
+
availableTerminalHeight={
|
| 116 |
+
availableTerminalHeightPerToolMessage
|
| 117 |
+
}
|
| 118 |
+
terminalWidth={innerWidth}
|
| 119 |
+
/>
|
| 120 |
+
)}
|
| 121 |
+
</Box>
|
| 122 |
+
);
|
| 123 |
+
})}
|
| 124 |
+
</Box>
|
| 125 |
+
);
|
| 126 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolMessage.test.tsx
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React from 'react';
|
| 8 |
+
import { render } from 'ink-testing-library';
|
| 9 |
+
import { ToolMessage, ToolMessageProps } from './ToolMessage.js';
|
| 10 |
+
import { StreamingState, ToolCallStatus } from '../../types.js';
|
| 11 |
+
import { Text } from 'ink';
|
| 12 |
+
import { StreamingContext } from '../../contexts/StreamingContext.js';
|
| 13 |
+
|
| 14 |
+
// Mock child components or utilities if they are complex or have side effects
|
| 15 |
+
vi.mock('../GeminiRespondingSpinner.js', () => ({
|
| 16 |
+
GeminiRespondingSpinner: ({
|
| 17 |
+
nonRespondingDisplay,
|
| 18 |
+
}: {
|
| 19 |
+
nonRespondingDisplay?: string;
|
| 20 |
+
}) => {
|
| 21 |
+
const streamingState = React.useContext(StreamingContext)!;
|
| 22 |
+
if (streamingState === StreamingState.Responding) {
|
| 23 |
+
return <Text>MockRespondingSpinner</Text>;
|
| 24 |
+
}
|
| 25 |
+
return nonRespondingDisplay ? <Text>{nonRespondingDisplay}</Text> : null;
|
| 26 |
+
},
|
| 27 |
+
}));
|
| 28 |
+
vi.mock('./DiffRenderer.js', () => ({
|
| 29 |
+
DiffRenderer: function MockDiffRenderer({
|
| 30 |
+
diffContent,
|
| 31 |
+
}: {
|
| 32 |
+
diffContent: string;
|
| 33 |
+
}) {
|
| 34 |
+
return <Text>MockDiff:{diffContent}</Text>;
|
| 35 |
+
},
|
| 36 |
+
}));
|
| 37 |
+
vi.mock('../../utils/MarkdownDisplay.js', () => ({
|
| 38 |
+
MarkdownDisplay: function MockMarkdownDisplay({ text }: { text: string }) {
|
| 39 |
+
return <Text>MockMarkdown:{text}</Text>;
|
| 40 |
+
},
|
| 41 |
+
}));
|
| 42 |
+
|
| 43 |
+
// Helper to render with context
|
| 44 |
+
const renderWithContext = (
|
| 45 |
+
ui: React.ReactElement,
|
| 46 |
+
streamingState: StreamingState,
|
| 47 |
+
) => {
|
| 48 |
+
const contextValue: StreamingState = streamingState;
|
| 49 |
+
return render(
|
| 50 |
+
<StreamingContext.Provider value={contextValue}>
|
| 51 |
+
{ui}
|
| 52 |
+
</StreamingContext.Provider>,
|
| 53 |
+
);
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
describe('<ToolMessage />', () => {
|
| 57 |
+
const baseProps: ToolMessageProps = {
|
| 58 |
+
callId: 'tool-123',
|
| 59 |
+
name: 'test-tool',
|
| 60 |
+
description: 'A tool for testing',
|
| 61 |
+
resultDisplay: 'Test result',
|
| 62 |
+
status: ToolCallStatus.Success,
|
| 63 |
+
terminalWidth: 80,
|
| 64 |
+
confirmationDetails: undefined,
|
| 65 |
+
emphasis: 'medium',
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
it('renders basic tool information', () => {
|
| 69 |
+
const { lastFrame } = renderWithContext(
|
| 70 |
+
<ToolMessage {...baseProps} />,
|
| 71 |
+
StreamingState.Idle,
|
| 72 |
+
);
|
| 73 |
+
const output = lastFrame();
|
| 74 |
+
expect(output).toContain('✔'); // Success indicator
|
| 75 |
+
expect(output).toContain('test-tool');
|
| 76 |
+
expect(output).toContain('A tool for testing');
|
| 77 |
+
expect(output).toContain('MockMarkdown:Test result');
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
describe('ToolStatusIndicator rendering', () => {
|
| 81 |
+
it('shows ✔ for Success status', () => {
|
| 82 |
+
const { lastFrame } = renderWithContext(
|
| 83 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Success} />,
|
| 84 |
+
StreamingState.Idle,
|
| 85 |
+
);
|
| 86 |
+
expect(lastFrame()).toContain('✔');
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('shows o for Pending status', () => {
|
| 90 |
+
const { lastFrame } = renderWithContext(
|
| 91 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Pending} />,
|
| 92 |
+
StreamingState.Idle,
|
| 93 |
+
);
|
| 94 |
+
expect(lastFrame()).toContain('o');
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
it('shows ? for Confirming status', () => {
|
| 98 |
+
const { lastFrame } = renderWithContext(
|
| 99 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Confirming} />,
|
| 100 |
+
StreamingState.Idle,
|
| 101 |
+
);
|
| 102 |
+
expect(lastFrame()).toContain('?');
|
| 103 |
+
});
|
| 104 |
+
|
| 105 |
+
it('shows - for Canceled status', () => {
|
| 106 |
+
const { lastFrame } = renderWithContext(
|
| 107 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Canceled} />,
|
| 108 |
+
StreamingState.Idle,
|
| 109 |
+
);
|
| 110 |
+
expect(lastFrame()).toContain('-');
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it('shows x for Error status', () => {
|
| 114 |
+
const { lastFrame } = renderWithContext(
|
| 115 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Error} />,
|
| 116 |
+
StreamingState.Idle,
|
| 117 |
+
);
|
| 118 |
+
expect(lastFrame()).toContain('x');
|
| 119 |
+
});
|
| 120 |
+
|
| 121 |
+
it('shows paused spinner for Executing status when streamingState is Idle', () => {
|
| 122 |
+
const { lastFrame } = renderWithContext(
|
| 123 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Executing} />,
|
| 124 |
+
StreamingState.Idle,
|
| 125 |
+
);
|
| 126 |
+
expect(lastFrame()).toContain('⊷');
|
| 127 |
+
expect(lastFrame()).not.toContain('MockRespondingSpinner');
|
| 128 |
+
expect(lastFrame()).not.toContain('✔');
|
| 129 |
+
});
|
| 130 |
+
|
| 131 |
+
it('shows paused spinner for Executing status when streamingState is WaitingForConfirmation', () => {
|
| 132 |
+
const { lastFrame } = renderWithContext(
|
| 133 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Executing} />,
|
| 134 |
+
StreamingState.WaitingForConfirmation,
|
| 135 |
+
);
|
| 136 |
+
expect(lastFrame()).toContain('⊷');
|
| 137 |
+
expect(lastFrame()).not.toContain('MockRespondingSpinner');
|
| 138 |
+
expect(lastFrame()).not.toContain('✔');
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
it('shows MockRespondingSpinner for Executing status when streamingState is Responding', () => {
|
| 142 |
+
const { lastFrame } = renderWithContext(
|
| 143 |
+
<ToolMessage {...baseProps} status={ToolCallStatus.Executing} />,
|
| 144 |
+
StreamingState.Responding, // Simulate app still responding
|
| 145 |
+
);
|
| 146 |
+
expect(lastFrame()).toContain('MockRespondingSpinner');
|
| 147 |
+
expect(lastFrame()).not.toContain('✔');
|
| 148 |
+
});
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
it('renders DiffRenderer for diff results', () => {
|
| 152 |
+
const diffResult = {
|
| 153 |
+
fileDiff: '--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new',
|
| 154 |
+
fileName: 'file.txt',
|
| 155 |
+
originalContent: 'old',
|
| 156 |
+
newContent: 'new',
|
| 157 |
+
};
|
| 158 |
+
const { lastFrame } = renderWithContext(
|
| 159 |
+
<ToolMessage {...baseProps} resultDisplay={diffResult} />,
|
| 160 |
+
StreamingState.Idle,
|
| 161 |
+
);
|
| 162 |
+
// Check that the output contains the MockDiff content as part of the whole message
|
| 163 |
+
expect(lastFrame()).toMatch(/MockDiff:--- a\/file\.txt/);
|
| 164 |
+
});
|
| 165 |
+
|
| 166 |
+
it('renders emphasis correctly', () => {
|
| 167 |
+
const { lastFrame: highEmphasisFrame } = renderWithContext(
|
| 168 |
+
<ToolMessage {...baseProps} emphasis="high" />,
|
| 169 |
+
StreamingState.Idle,
|
| 170 |
+
);
|
| 171 |
+
// Check for trailing indicator or specific color if applicable (Colors are not easily testable here)
|
| 172 |
+
expect(highEmphasisFrame()).toContain('←'); // Trailing indicator for high emphasis
|
| 173 |
+
|
| 174 |
+
const { lastFrame: lowEmphasisFrame } = renderWithContext(
|
| 175 |
+
<ToolMessage {...baseProps} emphasis="low" />,
|
| 176 |
+
StreamingState.Idle,
|
| 177 |
+
);
|
| 178 |
+
// For low emphasis, the name and description might be dimmed (check for dimColor if possible)
|
| 179 |
+
// This is harder to assert directly in text output without color checks.
|
| 180 |
+
// We can at least ensure it doesn't have the high emphasis indicator.
|
| 181 |
+
expect(lowEmphasisFrame()).not.toContain('←');
|
| 182 |
+
});
|
| 183 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/messages/ToolMessage.tsx
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React from 'react';
|
| 8 |
+
import { Box, Text } from 'ink';
|
| 9 |
+
import { IndividualToolCallDisplay, ToolCallStatus } from '../../types.js';
|
| 10 |
+
import { DiffRenderer } from './DiffRenderer.js';
|
| 11 |
+
import { Colors } from '../../colors.js';
|
| 12 |
+
import { MarkdownDisplay } from '../../utils/MarkdownDisplay.js';
|
| 13 |
+
import { GeminiRespondingSpinner } from '../GeminiRespondingSpinner.js';
|
| 14 |
+
import { MaxSizedBox } from '../shared/MaxSizedBox.js';
|
| 15 |
+
import { TodoDisplay } from '../TodoDisplay.js';
|
| 16 |
+
import { TodoResultDisplay } from '@qwen-code/qwen-code-core';
|
| 17 |
+
|
| 18 |
+
const STATIC_HEIGHT = 1;
|
| 19 |
+
const RESERVED_LINE_COUNT = 5; // for tool name, status, padding etc.
|
| 20 |
+
const STATUS_INDICATOR_WIDTH = 3;
|
| 21 |
+
const MIN_LINES_SHOWN = 2; // show at least this many lines
|
| 22 |
+
|
| 23 |
+
// Large threshold to ensure we don't cause performance issues for very large
|
| 24 |
+
// outputs that will get truncated further MaxSizedBox anyway.
|
| 25 |
+
const MAXIMUM_RESULT_DISPLAY_CHARACTERS = 1000000;
|
| 26 |
+
export type TextEmphasis = 'high' | 'medium' | 'low';
|
| 27 |
+
|
| 28 |
+
type DisplayRendererResult =
|
| 29 |
+
| { type: 'none' }
|
| 30 |
+
| { type: 'todo'; data: TodoResultDisplay }
|
| 31 |
+
| { type: 'string'; data: string }
|
| 32 |
+
| { type: 'diff'; data: { fileDiff: string; fileName: string } };
|
| 33 |
+
|
| 34 |
+
/**
|
| 35 |
+
* Custom hook to determine the type of result display and return appropriate rendering info
|
| 36 |
+
*/
|
| 37 |
+
const useResultDisplayRenderer = (
|
| 38 |
+
resultDisplay: unknown,
|
| 39 |
+
): DisplayRendererResult =>
|
| 40 |
+
React.useMemo(() => {
|
| 41 |
+
if (!resultDisplay) {
|
| 42 |
+
return { type: 'none' };
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// Check for TodoResultDisplay
|
| 46 |
+
if (
|
| 47 |
+
typeof resultDisplay === 'object' &&
|
| 48 |
+
resultDisplay !== null &&
|
| 49 |
+
'type' in resultDisplay &&
|
| 50 |
+
resultDisplay.type === 'todo_list'
|
| 51 |
+
) {
|
| 52 |
+
return {
|
| 53 |
+
type: 'todo',
|
| 54 |
+
data: resultDisplay as TodoResultDisplay,
|
| 55 |
+
};
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// Check for FileDiff
|
| 59 |
+
if (
|
| 60 |
+
typeof resultDisplay === 'object' &&
|
| 61 |
+
resultDisplay !== null &&
|
| 62 |
+
'fileDiff' in resultDisplay
|
| 63 |
+
) {
|
| 64 |
+
return {
|
| 65 |
+
type: 'diff',
|
| 66 |
+
data: resultDisplay as { fileDiff: string; fileName: string },
|
| 67 |
+
};
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
// Default to string
|
| 71 |
+
return {
|
| 72 |
+
type: 'string',
|
| 73 |
+
data: resultDisplay as string,
|
| 74 |
+
};
|
| 75 |
+
}, [resultDisplay]);
|
| 76 |
+
|
| 77 |
+
/**
|
| 78 |
+
* Component to render todo list results
|
| 79 |
+
*/
|
| 80 |
+
const TodoResultRenderer: React.FC<{ data: TodoResultDisplay }> = ({
|
| 81 |
+
data,
|
| 82 |
+
}) => <TodoDisplay todos={data.todos} />;
|
| 83 |
+
|
| 84 |
+
/**
|
| 85 |
+
* Component to render string results (markdown or plain text)
|
| 86 |
+
*/
|
| 87 |
+
const StringResultRenderer: React.FC<{
|
| 88 |
+
data: string;
|
| 89 |
+
renderAsMarkdown: boolean;
|
| 90 |
+
availableHeight?: number;
|
| 91 |
+
childWidth: number;
|
| 92 |
+
}> = ({ data, renderAsMarkdown, availableHeight, childWidth }) => {
|
| 93 |
+
let displayData = data;
|
| 94 |
+
|
| 95 |
+
// Truncate if too long
|
| 96 |
+
if (displayData.length > MAXIMUM_RESULT_DISPLAY_CHARACTERS) {
|
| 97 |
+
displayData = '...' + displayData.slice(-MAXIMUM_RESULT_DISPLAY_CHARACTERS);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
if (renderAsMarkdown) {
|
| 101 |
+
return (
|
| 102 |
+
<Box flexDirection="column">
|
| 103 |
+
<MarkdownDisplay
|
| 104 |
+
text={displayData}
|
| 105 |
+
isPending={false}
|
| 106 |
+
availableTerminalHeight={availableHeight}
|
| 107 |
+
terminalWidth={childWidth}
|
| 108 |
+
/>
|
| 109 |
+
</Box>
|
| 110 |
+
);
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
return (
|
| 114 |
+
<MaxSizedBox maxHeight={availableHeight} maxWidth={childWidth}>
|
| 115 |
+
<Box>
|
| 116 |
+
<Text wrap="wrap">{displayData}</Text>
|
| 117 |
+
</Box>
|
| 118 |
+
</MaxSizedBox>
|
| 119 |
+
);
|
| 120 |
+
};
|
| 121 |
+
|
| 122 |
+
/**
|
| 123 |
+
* Component to render diff results
|
| 124 |
+
*/
|
| 125 |
+
const DiffResultRenderer: React.FC<{
|
| 126 |
+
data: { fileDiff: string; fileName: string };
|
| 127 |
+
availableHeight?: number;
|
| 128 |
+
childWidth: number;
|
| 129 |
+
}> = ({ data, availableHeight, childWidth }) => (
|
| 130 |
+
<DiffRenderer
|
| 131 |
+
diffContent={data.fileDiff}
|
| 132 |
+
filename={data.fileName}
|
| 133 |
+
availableTerminalHeight={availableHeight}
|
| 134 |
+
terminalWidth={childWidth}
|
| 135 |
+
/>
|
| 136 |
+
);
|
| 137 |
+
|
| 138 |
+
export interface ToolMessageProps extends IndividualToolCallDisplay {
|
| 139 |
+
availableTerminalHeight?: number;
|
| 140 |
+
terminalWidth: number;
|
| 141 |
+
emphasis?: TextEmphasis;
|
| 142 |
+
renderOutputAsMarkdown?: boolean;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
export const ToolMessage: React.FC<ToolMessageProps> = ({
|
| 146 |
+
name,
|
| 147 |
+
description,
|
| 148 |
+
resultDisplay,
|
| 149 |
+
status,
|
| 150 |
+
availableTerminalHeight,
|
| 151 |
+
terminalWidth,
|
| 152 |
+
emphasis = 'medium',
|
| 153 |
+
renderOutputAsMarkdown = true,
|
| 154 |
+
}) => {
|
| 155 |
+
const availableHeight = availableTerminalHeight
|
| 156 |
+
? Math.max(
|
| 157 |
+
availableTerminalHeight - STATIC_HEIGHT - RESERVED_LINE_COUNT,
|
| 158 |
+
MIN_LINES_SHOWN + 1, // enforce minimum lines shown
|
| 159 |
+
)
|
| 160 |
+
: undefined;
|
| 161 |
+
|
| 162 |
+
// Long tool call response in MarkdownDisplay doesn't respect availableTerminalHeight properly,
|
| 163 |
+
// we're forcing it to not render as markdown when the response is too long, it will fallback
|
| 164 |
+
// to render as plain text, which is contained within the terminal using MaxSizedBox
|
| 165 |
+
if (availableHeight) {
|
| 166 |
+
renderOutputAsMarkdown = false;
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
const childWidth = terminalWidth - 3; // account for padding.
|
| 170 |
+
|
| 171 |
+
// Use the custom hook to determine the display type
|
| 172 |
+
const displayRenderer = useResultDisplayRenderer(resultDisplay);
|
| 173 |
+
|
| 174 |
+
return (
|
| 175 |
+
<Box paddingX={1} paddingY={0} flexDirection="column">
|
| 176 |
+
<Box minHeight={1}>
|
| 177 |
+
<ToolStatusIndicator status={status} />
|
| 178 |
+
<ToolInfo
|
| 179 |
+
name={name}
|
| 180 |
+
status={status}
|
| 181 |
+
description={description}
|
| 182 |
+
emphasis={emphasis}
|
| 183 |
+
/>
|
| 184 |
+
{emphasis === 'high' && <TrailingIndicator />}
|
| 185 |
+
</Box>
|
| 186 |
+
{displayRenderer.type !== 'none' && (
|
| 187 |
+
<Box paddingLeft={STATUS_INDICATOR_WIDTH} width="100%" marginTop={1}>
|
| 188 |
+
<Box flexDirection="column">
|
| 189 |
+
{displayRenderer.type === 'todo' && (
|
| 190 |
+
<TodoResultRenderer data={displayRenderer.data} />
|
| 191 |
+
)}
|
| 192 |
+
{displayRenderer.type === 'string' && (
|
| 193 |
+
<StringResultRenderer
|
| 194 |
+
data={displayRenderer.data}
|
| 195 |
+
renderAsMarkdown={renderOutputAsMarkdown}
|
| 196 |
+
availableHeight={availableHeight}
|
| 197 |
+
childWidth={childWidth}
|
| 198 |
+
/>
|
| 199 |
+
)}
|
| 200 |
+
{displayRenderer.type === 'diff' && (
|
| 201 |
+
<DiffResultRenderer
|
| 202 |
+
data={displayRenderer.data}
|
| 203 |
+
availableHeight={availableHeight}
|
| 204 |
+
childWidth={childWidth}
|
| 205 |
+
/>
|
| 206 |
+
)}
|
| 207 |
+
</Box>
|
| 208 |
+
</Box>
|
| 209 |
+
)}
|
| 210 |
+
</Box>
|
| 211 |
+
);
|
| 212 |
+
};
|
| 213 |
+
|
| 214 |
+
type ToolStatusIndicatorProps = {
|
| 215 |
+
status: ToolCallStatus;
|
| 216 |
+
};
|
| 217 |
+
|
| 218 |
+
const ToolStatusIndicator: React.FC<ToolStatusIndicatorProps> = ({
|
| 219 |
+
status,
|
| 220 |
+
}) => (
|
| 221 |
+
<Box minWidth={STATUS_INDICATOR_WIDTH}>
|
| 222 |
+
{status === ToolCallStatus.Pending && (
|
| 223 |
+
<Text color={Colors.AccentGreen}>o</Text>
|
| 224 |
+
)}
|
| 225 |
+
{status === ToolCallStatus.Executing && (
|
| 226 |
+
<GeminiRespondingSpinner
|
| 227 |
+
spinnerType="toggle"
|
| 228 |
+
nonRespondingDisplay={'⊷'}
|
| 229 |
+
/>
|
| 230 |
+
)}
|
| 231 |
+
{status === ToolCallStatus.Success && (
|
| 232 |
+
<Text color={Colors.AccentGreen}>✔</Text>
|
| 233 |
+
)}
|
| 234 |
+
{status === ToolCallStatus.Confirming && (
|
| 235 |
+
<Text color={Colors.AccentYellow}>?</Text>
|
| 236 |
+
)}
|
| 237 |
+
{status === ToolCallStatus.Canceled && (
|
| 238 |
+
<Text color={Colors.AccentYellow} bold>
|
| 239 |
+
-
|
| 240 |
+
</Text>
|
| 241 |
+
)}
|
| 242 |
+
{status === ToolCallStatus.Error && (
|
| 243 |
+
<Text color={Colors.AccentRed} bold>
|
| 244 |
+
x
|
| 245 |
+
</Text>
|
| 246 |
+
)}
|
| 247 |
+
</Box>
|
| 248 |
+
);
|
| 249 |
+
|
| 250 |
+
type ToolInfo = {
|
| 251 |
+
name: string;
|
| 252 |
+
description: string;
|
| 253 |
+
status: ToolCallStatus;
|
| 254 |
+
emphasis: TextEmphasis;
|
| 255 |
+
};
|
| 256 |
+
const ToolInfo: React.FC<ToolInfo> = ({
|
| 257 |
+
name,
|
| 258 |
+
description,
|
| 259 |
+
status,
|
| 260 |
+
emphasis,
|
| 261 |
+
}) => {
|
| 262 |
+
const nameColor = React.useMemo<string>(() => {
|
| 263 |
+
switch (emphasis) {
|
| 264 |
+
case 'high':
|
| 265 |
+
return Colors.Foreground;
|
| 266 |
+
case 'medium':
|
| 267 |
+
return Colors.Foreground;
|
| 268 |
+
case 'low':
|
| 269 |
+
return Colors.Gray;
|
| 270 |
+
default: {
|
| 271 |
+
const exhaustiveCheck: never = emphasis;
|
| 272 |
+
return exhaustiveCheck;
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
}, [emphasis]);
|
| 276 |
+
return (
|
| 277 |
+
<Box>
|
| 278 |
+
<Text
|
| 279 |
+
wrap="truncate-end"
|
| 280 |
+
strikethrough={status === ToolCallStatus.Canceled}
|
| 281 |
+
>
|
| 282 |
+
<Text color={nameColor} bold>
|
| 283 |
+
{name}
|
| 284 |
+
</Text>{' '}
|
| 285 |
+
<Text color={Colors.Gray}>{description}</Text>
|
| 286 |
+
</Text>
|
| 287 |
+
</Box>
|
| 288 |
+
);
|
| 289 |
+
};
|
| 290 |
+
|
| 291 |
+
const TrailingIndicator: React.FC = () => (
|
| 292 |
+
<Text color={Colors.Foreground} wrap="truncate">
|
| 293 |
+
{' '}
|
| 294 |
+
←
|
| 295 |
+
</Text>
|
| 296 |
+
);
|
projects/ui/qwen-code/packages/cli/src/ui/components/messages/UserMessage.tsx
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React from 'react';
|
| 8 |
+
import { Text, Box } from 'ink';
|
| 9 |
+
import { Colors } from '../../colors.js';
|
| 10 |
+
|
| 11 |
+
interface UserMessageProps {
|
| 12 |
+
text: string;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export const UserMessage: React.FC<UserMessageProps> = ({ text }) => {
|
| 16 |
+
const prefix = '> ';
|
| 17 |
+
const prefixWidth = prefix.length;
|
| 18 |
+
const isSlashCommand = text.startsWith('/');
|
| 19 |
+
|
| 20 |
+
const textColor = isSlashCommand ? Colors.AccentPurple : Colors.Gray;
|
| 21 |
+
const borderColor = isSlashCommand ? Colors.AccentPurple : Colors.Gray;
|
| 22 |
+
|
| 23 |
+
return (
|
| 24 |
+
<Box
|
| 25 |
+
borderStyle="round"
|
| 26 |
+
borderColor={borderColor}
|
| 27 |
+
flexDirection="row"
|
| 28 |
+
paddingX={2}
|
| 29 |
+
paddingY={0}
|
| 30 |
+
marginY={1}
|
| 31 |
+
alignSelf="flex-start"
|
| 32 |
+
>
|
| 33 |
+
<Box width={prefixWidth}>
|
| 34 |
+
<Text color={textColor}>{prefix}</Text>
|
| 35 |
+
</Box>
|
| 36 |
+
<Box flexGrow={1}>
|
| 37 |
+
<Text wrap="wrap" color={textColor}>
|
| 38 |
+
{text}
|
| 39 |
+
</Text>
|
| 40 |
+
</Box>
|
| 41 |
+
</Box>
|
| 42 |
+
);
|
| 43 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/components/messages/UserShellMessage.tsx
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React from 'react';
|
| 8 |
+
import { Box, Text } from 'ink';
|
| 9 |
+
import { Colors } from '../../colors.js';
|
| 10 |
+
|
| 11 |
+
interface UserShellMessageProps {
|
| 12 |
+
text: string;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export const UserShellMessage: React.FC<UserShellMessageProps> = ({ text }) => {
|
| 16 |
+
// Remove leading '!' if present, as App.tsx adds it for the processor.
|
| 17 |
+
const commandToDisplay = text.startsWith('!') ? text.substring(1) : text;
|
| 18 |
+
|
| 19 |
+
return (
|
| 20 |
+
<Box>
|
| 21 |
+
<Text color={Colors.AccentCyan}>$ </Text>
|
| 22 |
+
<Text>{commandToDisplay}</Text>
|
| 23 |
+
</Box>
|
| 24 |
+
);
|
| 25 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/MaxSizedBox.test.tsx
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { render } from 'ink-testing-library';
|
| 8 |
+
import { OverflowProvider } from '../../contexts/OverflowContext.js';
|
| 9 |
+
import { MaxSizedBox, setMaxSizedBoxDebugging } from './MaxSizedBox.js';
|
| 10 |
+
import { Box, Text } from 'ink';
|
| 11 |
+
import { describe, it, expect } from 'vitest';
|
| 12 |
+
|
| 13 |
+
describe('<MaxSizedBox />', () => {
|
| 14 |
+
// Make sure MaxSizedBox logs errors on invalid configurations.
|
| 15 |
+
// This is useful for debugging issues with the component.
|
| 16 |
+
// It should be set to false in production for performance and to avoid
|
| 17 |
+
// cluttering the console if there are ignorable issues.
|
| 18 |
+
setMaxSizedBoxDebugging(true);
|
| 19 |
+
|
| 20 |
+
it('renders children without truncation when they fit', () => {
|
| 21 |
+
const { lastFrame } = render(
|
| 22 |
+
<OverflowProvider>
|
| 23 |
+
<MaxSizedBox maxWidth={80} maxHeight={10}>
|
| 24 |
+
<Box>
|
| 25 |
+
<Text>Hello, World!</Text>
|
| 26 |
+
</Box>
|
| 27 |
+
</MaxSizedBox>
|
| 28 |
+
</OverflowProvider>,
|
| 29 |
+
);
|
| 30 |
+
expect(lastFrame()).equals('Hello, World!');
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
it('hides lines when content exceeds maxHeight', () => {
|
| 34 |
+
const { lastFrame } = render(
|
| 35 |
+
<OverflowProvider>
|
| 36 |
+
<MaxSizedBox maxWidth={80} maxHeight={2}>
|
| 37 |
+
<Box>
|
| 38 |
+
<Text>Line 1</Text>
|
| 39 |
+
</Box>
|
| 40 |
+
<Box>
|
| 41 |
+
<Text>Line 2</Text>
|
| 42 |
+
</Box>
|
| 43 |
+
<Box>
|
| 44 |
+
<Text>Line 3</Text>
|
| 45 |
+
</Box>
|
| 46 |
+
</MaxSizedBox>
|
| 47 |
+
</OverflowProvider>,
|
| 48 |
+
);
|
| 49 |
+
expect(lastFrame()).equals(`... first 2 lines hidden ...
|
| 50 |
+
Line 3`);
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it('hides lines at the end when content exceeds maxHeight and overflowDirection is bottom', () => {
|
| 54 |
+
const { lastFrame } = render(
|
| 55 |
+
<OverflowProvider>
|
| 56 |
+
<MaxSizedBox maxWidth={80} maxHeight={2} overflowDirection="bottom">
|
| 57 |
+
<Box>
|
| 58 |
+
<Text>Line 1</Text>
|
| 59 |
+
</Box>
|
| 60 |
+
<Box>
|
| 61 |
+
<Text>Line 2</Text>
|
| 62 |
+
</Box>
|
| 63 |
+
<Box>
|
| 64 |
+
<Text>Line 3</Text>
|
| 65 |
+
</Box>
|
| 66 |
+
</MaxSizedBox>
|
| 67 |
+
</OverflowProvider>,
|
| 68 |
+
);
|
| 69 |
+
expect(lastFrame()).equals(`Line 1
|
| 70 |
+
... last 2 lines hidden ...`);
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
it('wraps text that exceeds maxWidth', () => {
|
| 74 |
+
const { lastFrame } = render(
|
| 75 |
+
<OverflowProvider>
|
| 76 |
+
<MaxSizedBox maxWidth={10} maxHeight={5}>
|
| 77 |
+
<Box>
|
| 78 |
+
<Text wrap="wrap">This is a long line of text</Text>
|
| 79 |
+
</Box>
|
| 80 |
+
</MaxSizedBox>
|
| 81 |
+
</OverflowProvider>,
|
| 82 |
+
);
|
| 83 |
+
|
| 84 |
+
expect(lastFrame()).equals(`This is a
|
| 85 |
+
long line
|
| 86 |
+
of text`);
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('handles mixed wrapping and non-wrapping segments', () => {
|
| 90 |
+
const multilineText = `This part will wrap around.
|
| 91 |
+
And has a line break.
|
| 92 |
+
Leading spaces preserved.`;
|
| 93 |
+
const { lastFrame } = render(
|
| 94 |
+
<OverflowProvider>
|
| 95 |
+
<MaxSizedBox maxWidth={20} maxHeight={20}>
|
| 96 |
+
<Box>
|
| 97 |
+
<Text>Example</Text>
|
| 98 |
+
</Box>
|
| 99 |
+
<Box>
|
| 100 |
+
<Text>No Wrap: </Text>
|
| 101 |
+
<Text wrap="wrap">{multilineText}</Text>
|
| 102 |
+
</Box>
|
| 103 |
+
<Box>
|
| 104 |
+
<Text>Longer No Wrap: </Text>
|
| 105 |
+
<Text wrap="wrap">This part will wrap around.</Text>
|
| 106 |
+
</Box>
|
| 107 |
+
</MaxSizedBox>
|
| 108 |
+
</OverflowProvider>,
|
| 109 |
+
);
|
| 110 |
+
|
| 111 |
+
expect(lastFrame()).equals(
|
| 112 |
+
`Example
|
| 113 |
+
No Wrap: This part
|
| 114 |
+
will wrap
|
| 115 |
+
around.
|
| 116 |
+
And has a
|
| 117 |
+
line break.
|
| 118 |
+
Leading
|
| 119 |
+
spaces
|
| 120 |
+
preserved.
|
| 121 |
+
Longer No Wrap: This
|
| 122 |
+
part
|
| 123 |
+
will
|
| 124 |
+
wrap
|
| 125 |
+
arou
|
| 126 |
+
nd.`,
|
| 127 |
+
);
|
| 128 |
+
});
|
| 129 |
+
|
| 130 |
+
it('handles words longer than maxWidth by splitting them', () => {
|
| 131 |
+
const { lastFrame } = render(
|
| 132 |
+
<OverflowProvider>
|
| 133 |
+
<MaxSizedBox maxWidth={5} maxHeight={5}>
|
| 134 |
+
<Box>
|
| 135 |
+
<Text wrap="wrap">Supercalifragilisticexpialidocious</Text>
|
| 136 |
+
</Box>
|
| 137 |
+
</MaxSizedBox>
|
| 138 |
+
</OverflowProvider>,
|
| 139 |
+
);
|
| 140 |
+
|
| 141 |
+
expect(lastFrame()).equals(`... …
|
| 142 |
+
istic
|
| 143 |
+
expia
|
| 144 |
+
lidoc
|
| 145 |
+
ious`);
|
| 146 |
+
});
|
| 147 |
+
|
| 148 |
+
it('does not truncate when maxHeight is undefined', () => {
|
| 149 |
+
const { lastFrame } = render(
|
| 150 |
+
<OverflowProvider>
|
| 151 |
+
<MaxSizedBox maxWidth={80} maxHeight={undefined}>
|
| 152 |
+
<Box>
|
| 153 |
+
<Text>Line 1</Text>
|
| 154 |
+
</Box>
|
| 155 |
+
<Box>
|
| 156 |
+
<Text>Line 2</Text>
|
| 157 |
+
</Box>
|
| 158 |
+
</MaxSizedBox>
|
| 159 |
+
</OverflowProvider>,
|
| 160 |
+
);
|
| 161 |
+
expect(lastFrame()).equals(`Line 1
|
| 162 |
+
Line 2`);
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
+
it('shows plural "lines" when more than one line is hidden', () => {
|
| 166 |
+
const { lastFrame } = render(
|
| 167 |
+
<OverflowProvider>
|
| 168 |
+
<MaxSizedBox maxWidth={80} maxHeight={2}>
|
| 169 |
+
<Box>
|
| 170 |
+
<Text>Line 1</Text>
|
| 171 |
+
</Box>
|
| 172 |
+
<Box>
|
| 173 |
+
<Text>Line 2</Text>
|
| 174 |
+
</Box>
|
| 175 |
+
<Box>
|
| 176 |
+
<Text>Line 3</Text>
|
| 177 |
+
</Box>
|
| 178 |
+
</MaxSizedBox>
|
| 179 |
+
</OverflowProvider>,
|
| 180 |
+
);
|
| 181 |
+
expect(lastFrame()).equals(`... first 2 lines hidden ...
|
| 182 |
+
Line 3`);
|
| 183 |
+
});
|
| 184 |
+
|
| 185 |
+
it('shows plural "lines" when more than one line is hidden and overflowDirection is bottom', () => {
|
| 186 |
+
const { lastFrame } = render(
|
| 187 |
+
<OverflowProvider>
|
| 188 |
+
<MaxSizedBox maxWidth={80} maxHeight={2} overflowDirection="bottom">
|
| 189 |
+
<Box>
|
| 190 |
+
<Text>Line 1</Text>
|
| 191 |
+
</Box>
|
| 192 |
+
<Box>
|
| 193 |
+
<Text>Line 2</Text>
|
| 194 |
+
</Box>
|
| 195 |
+
<Box>
|
| 196 |
+
<Text>Line 3</Text>
|
| 197 |
+
</Box>
|
| 198 |
+
</MaxSizedBox>
|
| 199 |
+
</OverflowProvider>,
|
| 200 |
+
);
|
| 201 |
+
expect(lastFrame()).equals(`Line 1
|
| 202 |
+
... last 2 lines hidden ...`);
|
| 203 |
+
});
|
| 204 |
+
|
| 205 |
+
it('renders an empty box for empty children', () => {
|
| 206 |
+
const { lastFrame } = render(
|
| 207 |
+
<OverflowProvider>
|
| 208 |
+
<MaxSizedBox maxWidth={80} maxHeight={10}></MaxSizedBox>
|
| 209 |
+
</OverflowProvider>,
|
| 210 |
+
);
|
| 211 |
+
// Expect an empty string or a box with nothing in it.
|
| 212 |
+
// Ink renders an empty box as an empty string.
|
| 213 |
+
expect(lastFrame()).equals('');
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
it('wraps text with multi-byte unicode characters correctly', () => {
|
| 217 |
+
const { lastFrame } = render(
|
| 218 |
+
<OverflowProvider>
|
| 219 |
+
<MaxSizedBox maxWidth={5} maxHeight={5}>
|
| 220 |
+
<Box>
|
| 221 |
+
<Text wrap="wrap">你好世界</Text>
|
| 222 |
+
</Box>
|
| 223 |
+
</MaxSizedBox>
|
| 224 |
+
</OverflowProvider>,
|
| 225 |
+
);
|
| 226 |
+
|
| 227 |
+
// "你好" has a visual width of 4. "世界" has a visual width of 4.
|
| 228 |
+
// With maxWidth=5, it should wrap after the second character.
|
| 229 |
+
expect(lastFrame()).equals(`你好
|
| 230 |
+
世界`);
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
it('wraps text with multi-byte emoji characters correctly', () => {
|
| 234 |
+
const { lastFrame } = render(
|
| 235 |
+
<OverflowProvider>
|
| 236 |
+
<MaxSizedBox maxWidth={5} maxHeight={5}>
|
| 237 |
+
<Box>
|
| 238 |
+
<Text wrap="wrap">🐶🐶🐶🐶🐶</Text>
|
| 239 |
+
</Box>
|
| 240 |
+
</MaxSizedBox>
|
| 241 |
+
</OverflowProvider>,
|
| 242 |
+
);
|
| 243 |
+
|
| 244 |
+
// Each "🐶" has a visual width of 2.
|
| 245 |
+
// With maxWidth=5, it should wrap every 2 emojis.
|
| 246 |
+
expect(lastFrame()).equals(`🐶🐶
|
| 247 |
+
🐶🐶
|
| 248 |
+
🐶`);
|
| 249 |
+
});
|
| 250 |
+
|
| 251 |
+
it('falls back to an ellipsis when width is extremely small', () => {
|
| 252 |
+
const { lastFrame } = render(
|
| 253 |
+
<OverflowProvider>
|
| 254 |
+
<MaxSizedBox maxWidth={2} maxHeight={2}>
|
| 255 |
+
<Box>
|
| 256 |
+
<Text>No</Text>
|
| 257 |
+
<Text wrap="wrap">wrap</Text>
|
| 258 |
+
</Box>
|
| 259 |
+
</MaxSizedBox>
|
| 260 |
+
</OverflowProvider>,
|
| 261 |
+
);
|
| 262 |
+
|
| 263 |
+
expect(lastFrame()).equals('N…');
|
| 264 |
+
});
|
| 265 |
+
|
| 266 |
+
it('truncates long non-wrapping text with ellipsis', () => {
|
| 267 |
+
const { lastFrame } = render(
|
| 268 |
+
<OverflowProvider>
|
| 269 |
+
<MaxSizedBox maxWidth={3} maxHeight={2}>
|
| 270 |
+
<Box>
|
| 271 |
+
<Text>ABCDE</Text>
|
| 272 |
+
<Text wrap="wrap">wrap</Text>
|
| 273 |
+
</Box>
|
| 274 |
+
</MaxSizedBox>
|
| 275 |
+
</OverflowProvider>,
|
| 276 |
+
);
|
| 277 |
+
|
| 278 |
+
expect(lastFrame()).equals('AB…');
|
| 279 |
+
});
|
| 280 |
+
|
| 281 |
+
it('truncates non-wrapping text containing line breaks', () => {
|
| 282 |
+
const { lastFrame } = render(
|
| 283 |
+
<OverflowProvider>
|
| 284 |
+
<MaxSizedBox maxWidth={3} maxHeight={2}>
|
| 285 |
+
<Box>
|
| 286 |
+
<Text>{'A\nBCDE'}</Text>
|
| 287 |
+
<Text wrap="wrap">wrap</Text>
|
| 288 |
+
</Box>
|
| 289 |
+
</MaxSizedBox>
|
| 290 |
+
</OverflowProvider>,
|
| 291 |
+
);
|
| 292 |
+
|
| 293 |
+
expect(lastFrame()).equals(`A\n…`);
|
| 294 |
+
});
|
| 295 |
+
|
| 296 |
+
it('truncates emoji characters correctly with ellipsis', () => {
|
| 297 |
+
const { lastFrame } = render(
|
| 298 |
+
<OverflowProvider>
|
| 299 |
+
<MaxSizedBox maxWidth={3} maxHeight={2}>
|
| 300 |
+
<Box>
|
| 301 |
+
<Text>🐶🐶🐶</Text>
|
| 302 |
+
<Text wrap="wrap">wrap</Text>
|
| 303 |
+
</Box>
|
| 304 |
+
</MaxSizedBox>
|
| 305 |
+
</OverflowProvider>,
|
| 306 |
+
);
|
| 307 |
+
|
| 308 |
+
expect(lastFrame()).equals(`🐶…`);
|
| 309 |
+
});
|
| 310 |
+
|
| 311 |
+
it('shows ellipsis for multiple rows with long non-wrapping text', () => {
|
| 312 |
+
const { lastFrame } = render(
|
| 313 |
+
<OverflowProvider>
|
| 314 |
+
<MaxSizedBox maxWidth={3} maxHeight={3}>
|
| 315 |
+
<Box>
|
| 316 |
+
<Text>AAA</Text>
|
| 317 |
+
<Text wrap="wrap">first</Text>
|
| 318 |
+
</Box>
|
| 319 |
+
<Box>
|
| 320 |
+
<Text>BBB</Text>
|
| 321 |
+
<Text wrap="wrap">second</Text>
|
| 322 |
+
</Box>
|
| 323 |
+
<Box>
|
| 324 |
+
<Text>CCC</Text>
|
| 325 |
+
<Text wrap="wrap">third</Text>
|
| 326 |
+
</Box>
|
| 327 |
+
</MaxSizedBox>
|
| 328 |
+
</OverflowProvider>,
|
| 329 |
+
);
|
| 330 |
+
|
| 331 |
+
expect(lastFrame()).equals(`AA…\nBB…\nCC…`);
|
| 332 |
+
});
|
| 333 |
+
|
| 334 |
+
it('accounts for additionalHiddenLinesCount', () => {
|
| 335 |
+
const { lastFrame } = render(
|
| 336 |
+
<OverflowProvider>
|
| 337 |
+
<MaxSizedBox maxWidth={80} maxHeight={2} additionalHiddenLinesCount={5}>
|
| 338 |
+
<Box>
|
| 339 |
+
<Text>Line 1</Text>
|
| 340 |
+
</Box>
|
| 341 |
+
<Box>
|
| 342 |
+
<Text>Line 2</Text>
|
| 343 |
+
</Box>
|
| 344 |
+
<Box>
|
| 345 |
+
<Text>Line 3</Text>
|
| 346 |
+
</Box>
|
| 347 |
+
</MaxSizedBox>
|
| 348 |
+
</OverflowProvider>,
|
| 349 |
+
);
|
| 350 |
+
// 1 line is hidden by overflow, 5 are additionally hidden.
|
| 351 |
+
expect(lastFrame()).equals(`... first 7 lines hidden ...
|
| 352 |
+
Line 3`);
|
| 353 |
+
});
|
| 354 |
+
|
| 355 |
+
it('handles React.Fragment as a child', () => {
|
| 356 |
+
const { lastFrame } = render(
|
| 357 |
+
<OverflowProvider>
|
| 358 |
+
<MaxSizedBox maxWidth={80} maxHeight={10}>
|
| 359 |
+
<>
|
| 360 |
+
<Box>
|
| 361 |
+
<Text>Line 1 from Fragment</Text>
|
| 362 |
+
</Box>
|
| 363 |
+
<Box>
|
| 364 |
+
<Text>Line 2 from Fragment</Text>
|
| 365 |
+
</Box>
|
| 366 |
+
</>
|
| 367 |
+
<Box>
|
| 368 |
+
<Text>Line 3 direct child</Text>
|
| 369 |
+
</Box>
|
| 370 |
+
</MaxSizedBox>
|
| 371 |
+
</OverflowProvider>,
|
| 372 |
+
);
|
| 373 |
+
expect(lastFrame()).equals(`Line 1 from Fragment
|
| 374 |
+
Line 2 from Fragment
|
| 375 |
+
Line 3 direct child`);
|
| 376 |
+
});
|
| 377 |
+
|
| 378 |
+
it('clips a long single text child from the top', () => {
|
| 379 |
+
const THIRTY_LINES = Array.from(
|
| 380 |
+
{ length: 30 },
|
| 381 |
+
(_, i) => `Line ${i + 1}`,
|
| 382 |
+
).join('\n');
|
| 383 |
+
|
| 384 |
+
const { lastFrame } = render(
|
| 385 |
+
<OverflowProvider>
|
| 386 |
+
<MaxSizedBox maxWidth={80} maxHeight={10}>
|
| 387 |
+
<Box>
|
| 388 |
+
<Text>{THIRTY_LINES}</Text>
|
| 389 |
+
</Box>
|
| 390 |
+
</MaxSizedBox>
|
| 391 |
+
</OverflowProvider>,
|
| 392 |
+
);
|
| 393 |
+
|
| 394 |
+
const expected = [
|
| 395 |
+
'... first 21 lines hidden ...',
|
| 396 |
+
...Array.from({ length: 9 }, (_, i) => `Line ${22 + i}`),
|
| 397 |
+
].join('\n');
|
| 398 |
+
|
| 399 |
+
expect(lastFrame()).equals(expected);
|
| 400 |
+
});
|
| 401 |
+
|
| 402 |
+
it('clips a long single text child from the bottom', () => {
|
| 403 |
+
const THIRTY_LINES = Array.from(
|
| 404 |
+
{ length: 30 },
|
| 405 |
+
(_, i) => `Line ${i + 1}`,
|
| 406 |
+
).join('\n');
|
| 407 |
+
|
| 408 |
+
const { lastFrame } = render(
|
| 409 |
+
<OverflowProvider>
|
| 410 |
+
<MaxSizedBox maxWidth={80} maxHeight={10} overflowDirection="bottom">
|
| 411 |
+
<Box>
|
| 412 |
+
<Text>{THIRTY_LINES}</Text>
|
| 413 |
+
</Box>
|
| 414 |
+
</MaxSizedBox>
|
| 415 |
+
</OverflowProvider>,
|
| 416 |
+
);
|
| 417 |
+
|
| 418 |
+
const expected = [
|
| 419 |
+
...Array.from({ length: 9 }, (_, i) => `Line ${i + 1}`),
|
| 420 |
+
'... last 21 lines hidden ...',
|
| 421 |
+
].join('\n');
|
| 422 |
+
|
| 423 |
+
expect(lastFrame()).equals(expected);
|
| 424 |
+
});
|
| 425 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/MaxSizedBox.tsx
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, { Fragment, useEffect, useId } from 'react';
|
| 8 |
+
import { Box, Text } from 'ink';
|
| 9 |
+
import stringWidth from 'string-width';
|
| 10 |
+
import { Colors } from '../../colors.js';
|
| 11 |
+
import { toCodePoints } from '../../utils/textUtils.js';
|
| 12 |
+
import { useOverflowActions } from '../../contexts/OverflowContext.js';
|
| 13 |
+
|
| 14 |
+
let enableDebugLog = false;
|
| 15 |
+
|
| 16 |
+
/**
|
| 17 |
+
* Minimum height for the MaxSizedBox component.
|
| 18 |
+
* This ensures there is room for at least one line of content as well as the
|
| 19 |
+
* message that content was truncated.
|
| 20 |
+
*/
|
| 21 |
+
export const MINIMUM_MAX_HEIGHT = 2;
|
| 22 |
+
|
| 23 |
+
export function setMaxSizedBoxDebugging(value: boolean) {
|
| 24 |
+
enableDebugLog = value;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
function debugReportError(message: string, element: React.ReactNode) {
|
| 28 |
+
if (!enableDebugLog) return;
|
| 29 |
+
|
| 30 |
+
if (!React.isValidElement(element)) {
|
| 31 |
+
console.error(
|
| 32 |
+
message,
|
| 33 |
+
`Invalid element: '${String(element)}' typeof=${typeof element}`,
|
| 34 |
+
);
|
| 35 |
+
return;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
let sourceMessage = '<Unknown file>';
|
| 39 |
+
try {
|
| 40 |
+
const elementWithSource = element as {
|
| 41 |
+
_source?: { fileName?: string; lineNumber?: number };
|
| 42 |
+
};
|
| 43 |
+
const fileName = elementWithSource._source?.fileName;
|
| 44 |
+
const lineNumber = elementWithSource._source?.lineNumber;
|
| 45 |
+
sourceMessage = fileName ? `${fileName}:${lineNumber}` : '<Unknown file>';
|
| 46 |
+
} catch (error) {
|
| 47 |
+
console.error('Error while trying to get file name:', error);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
console.error(message, `${String(element.type)}. Source: ${sourceMessage}`);
|
| 51 |
+
}
|
| 52 |
+
interface MaxSizedBoxProps {
|
| 53 |
+
children?: React.ReactNode;
|
| 54 |
+
maxWidth?: number;
|
| 55 |
+
maxHeight: number | undefined;
|
| 56 |
+
overflowDirection?: 'top' | 'bottom';
|
| 57 |
+
additionalHiddenLinesCount?: number;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* A React component that constrains the size of its children and provides
|
| 62 |
+
* content-aware truncation when the content exceeds the specified `maxHeight`.
|
| 63 |
+
*
|
| 64 |
+
* `MaxSizedBox` requires a specific structure for its children to correctly
|
| 65 |
+
* measure and render the content:
|
| 66 |
+
*
|
| 67 |
+
* 1. **Direct children must be `<Box>` elements.** Each `<Box>` represents a
|
| 68 |
+
* single row of content.
|
| 69 |
+
* 2. **Row `<Box>` elements must contain only `<Text>` elements.** These
|
| 70 |
+
* `<Text>` elements can be nested and there are no restrictions to Text
|
| 71 |
+
* element styling other than that non-wrapping text elements must be
|
| 72 |
+
* before wrapping text elements.
|
| 73 |
+
*
|
| 74 |
+
* **Constraints:**
|
| 75 |
+
* - **Box Properties:** Custom properties on the child `<Box>` elements are
|
| 76 |
+
* ignored. In debug mode, runtime checks will report errors for any
|
| 77 |
+
* unsupported properties.
|
| 78 |
+
* - **Text Wrapping:** Within a single row, `<Text>` elements with no wrapping
|
| 79 |
+
* (e.g., headers, labels) must appear before any `<Text>` elements that wrap.
|
| 80 |
+
* - **Element Types:** Runtime checks will warn if unsupported element types
|
| 81 |
+
* are used as children.
|
| 82 |
+
*
|
| 83 |
+
* @example
|
| 84 |
+
* <MaxSizedBox maxWidth={80} maxHeight={10}>
|
| 85 |
+
* <Box>
|
| 86 |
+
* <Text>This is the first line.</Text>
|
| 87 |
+
* </Box>
|
| 88 |
+
* <Box>
|
| 89 |
+
* <Text color="cyan" wrap="truncate">Non-wrapping Header: </Text>
|
| 90 |
+
* <Text>This is the rest of the line which will wrap if it's too long.</Text>
|
| 91 |
+
* </Box>
|
| 92 |
+
* <Box>
|
| 93 |
+
* <Text>
|
| 94 |
+
* Line 3 with <Text color="yellow">nested styled text</Text> inside of it.
|
| 95 |
+
* </Text>
|
| 96 |
+
* </Box>
|
| 97 |
+
* </MaxSizedBox>
|
| 98 |
+
*/
|
| 99 |
+
export const MaxSizedBox: React.FC<MaxSizedBoxProps> = ({
|
| 100 |
+
children,
|
| 101 |
+
maxWidth,
|
| 102 |
+
maxHeight,
|
| 103 |
+
overflowDirection = 'top',
|
| 104 |
+
additionalHiddenLinesCount = 0,
|
| 105 |
+
}) => {
|
| 106 |
+
const id = useId();
|
| 107 |
+
const { addOverflowingId, removeOverflowingId } = useOverflowActions() || {};
|
| 108 |
+
|
| 109 |
+
const laidOutStyledText: StyledText[][] = [];
|
| 110 |
+
const targetMaxHeight = Math.max(
|
| 111 |
+
Math.round(maxHeight ?? Number.MAX_SAFE_INTEGER),
|
| 112 |
+
MINIMUM_MAX_HEIGHT,
|
| 113 |
+
);
|
| 114 |
+
|
| 115 |
+
if (maxWidth === undefined) {
|
| 116 |
+
throw new Error('maxWidth must be defined when maxHeight is set.');
|
| 117 |
+
}
|
| 118 |
+
function visitRows(element: React.ReactNode) {
|
| 119 |
+
if (!React.isValidElement<{ children?: React.ReactNode }>(element)) {
|
| 120 |
+
return;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
if (element.type === Fragment) {
|
| 124 |
+
React.Children.forEach(element.props.children, visitRows);
|
| 125 |
+
return;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
if (element.type === Box) {
|
| 129 |
+
layoutInkElementAsStyledText(element, maxWidth!, laidOutStyledText);
|
| 130 |
+
return;
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
debugReportError('MaxSizedBox children must be <Box> elements', element);
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
React.Children.forEach(children, visitRows);
|
| 137 |
+
|
| 138 |
+
const contentWillOverflow =
|
| 139 |
+
(targetMaxHeight !== undefined &&
|
| 140 |
+
laidOutStyledText.length > targetMaxHeight) ||
|
| 141 |
+
additionalHiddenLinesCount > 0;
|
| 142 |
+
const visibleContentHeight =
|
| 143 |
+
contentWillOverflow && targetMaxHeight !== undefined
|
| 144 |
+
? targetMaxHeight - 1
|
| 145 |
+
: targetMaxHeight;
|
| 146 |
+
|
| 147 |
+
const hiddenLinesCount =
|
| 148 |
+
visibleContentHeight !== undefined
|
| 149 |
+
? Math.max(0, laidOutStyledText.length - visibleContentHeight)
|
| 150 |
+
: 0;
|
| 151 |
+
const totalHiddenLines = hiddenLinesCount + additionalHiddenLinesCount;
|
| 152 |
+
|
| 153 |
+
useEffect(() => {
|
| 154 |
+
if (totalHiddenLines > 0) {
|
| 155 |
+
addOverflowingId?.(id);
|
| 156 |
+
} else {
|
| 157 |
+
removeOverflowingId?.(id);
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
return () => {
|
| 161 |
+
removeOverflowingId?.(id);
|
| 162 |
+
};
|
| 163 |
+
}, [id, totalHiddenLines, addOverflowingId, removeOverflowingId]);
|
| 164 |
+
|
| 165 |
+
const visibleStyledText =
|
| 166 |
+
hiddenLinesCount > 0
|
| 167 |
+
? overflowDirection === 'top'
|
| 168 |
+
? laidOutStyledText.slice(hiddenLinesCount, laidOutStyledText.length)
|
| 169 |
+
: laidOutStyledText.slice(0, visibleContentHeight)
|
| 170 |
+
: laidOutStyledText;
|
| 171 |
+
|
| 172 |
+
const visibleLines = visibleStyledText.map((line, index) => (
|
| 173 |
+
<Box key={index}>
|
| 174 |
+
{line.length > 0 ? (
|
| 175 |
+
line.map((segment, segIndex) => (
|
| 176 |
+
<Text key={segIndex} {...segment.props}>
|
| 177 |
+
{segment.text}
|
| 178 |
+
</Text>
|
| 179 |
+
))
|
| 180 |
+
) : (
|
| 181 |
+
<Text> </Text>
|
| 182 |
+
)}
|
| 183 |
+
</Box>
|
| 184 |
+
));
|
| 185 |
+
|
| 186 |
+
return (
|
| 187 |
+
<Box flexDirection="column" width={maxWidth} flexShrink={0}>
|
| 188 |
+
{totalHiddenLines > 0 && overflowDirection === 'top' && (
|
| 189 |
+
<Text color={Colors.Gray} wrap="truncate">
|
| 190 |
+
... first {totalHiddenLines} line{totalHiddenLines === 1 ? '' : 's'}{' '}
|
| 191 |
+
hidden ...
|
| 192 |
+
</Text>
|
| 193 |
+
)}
|
| 194 |
+
{visibleLines}
|
| 195 |
+
{totalHiddenLines > 0 && overflowDirection === 'bottom' && (
|
| 196 |
+
<Text color={Colors.Gray} wrap="truncate">
|
| 197 |
+
... last {totalHiddenLines} line{totalHiddenLines === 1 ? '' : 's'}{' '}
|
| 198 |
+
hidden ...
|
| 199 |
+
</Text>
|
| 200 |
+
)}
|
| 201 |
+
</Box>
|
| 202 |
+
);
|
| 203 |
+
};
|
| 204 |
+
|
| 205 |
+
// Define a type for styled text segments
|
| 206 |
+
interface StyledText {
|
| 207 |
+
text: string;
|
| 208 |
+
props: Record<string, unknown>;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/**
|
| 212 |
+
* Single row of content within the MaxSizedBox.
|
| 213 |
+
*
|
| 214 |
+
* A row can contain segments that are not wrapped, followed by segments that
|
| 215 |
+
* are. This is a minimal implementation that only supports the functionality
|
| 216 |
+
* needed today.
|
| 217 |
+
*/
|
| 218 |
+
interface Row {
|
| 219 |
+
noWrapSegments: StyledText[];
|
| 220 |
+
segments: StyledText[];
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
/**
|
| 224 |
+
* Flattens the child elements of MaxSizedBox into an array of `Row` objects.
|
| 225 |
+
*
|
| 226 |
+
* This function expects a specific child structure to function correctly:
|
| 227 |
+
* 1. The top-level child of `MaxSizedBox` should be a single `<Box>`. This
|
| 228 |
+
* outer box is primarily for structure and is not directly rendered.
|
| 229 |
+
* 2. Inside the outer `<Box>`, there should be one or more children. Each of
|
| 230 |
+
* these children must be a `<Box>` that represents a row.
|
| 231 |
+
* 3. Inside each "row" `<Box>`, the children must be `<Text>` components.
|
| 232 |
+
*
|
| 233 |
+
* The structure should look like this:
|
| 234 |
+
* <MaxSizedBox>
|
| 235 |
+
* <Box> // Row 1
|
| 236 |
+
* <Text>...</Text>
|
| 237 |
+
* <Text>...</Text>
|
| 238 |
+
* </Box>
|
| 239 |
+
* <Box> // Row 2
|
| 240 |
+
* <Text>...</Text>
|
| 241 |
+
* </Box>
|
| 242 |
+
* </MaxSizedBox>
|
| 243 |
+
*
|
| 244 |
+
* It is an error for a <Text> child without wrapping to appear after a
|
| 245 |
+
* <Text> child with wrapping within the same row Box.
|
| 246 |
+
*
|
| 247 |
+
* @param element The React node to flatten.
|
| 248 |
+
* @returns An array of `Row` objects.
|
| 249 |
+
*/
|
| 250 |
+
function visitBoxRow(element: React.ReactNode): Row {
|
| 251 |
+
if (
|
| 252 |
+
!React.isValidElement<{ children?: React.ReactNode }>(element) ||
|
| 253 |
+
element.type !== Box
|
| 254 |
+
) {
|
| 255 |
+
debugReportError(
|
| 256 |
+
`All children of MaxSizedBox must be <Box> elements`,
|
| 257 |
+
element,
|
| 258 |
+
);
|
| 259 |
+
return {
|
| 260 |
+
noWrapSegments: [{ text: '<ERROR>', props: {} }],
|
| 261 |
+
segments: [],
|
| 262 |
+
};
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
if (enableDebugLog) {
|
| 266 |
+
const boxProps = element.props as {
|
| 267 |
+
children?: React.ReactNode | undefined;
|
| 268 |
+
readonly flexDirection?:
|
| 269 |
+
| 'row'
|
| 270 |
+
| 'column'
|
| 271 |
+
| 'row-reverse'
|
| 272 |
+
| 'column-reverse'
|
| 273 |
+
| undefined;
|
| 274 |
+
};
|
| 275 |
+
// Ensure the Box has no props other than the default ones and key.
|
| 276 |
+
let maxExpectedProps = 4;
|
| 277 |
+
if (boxProps.children !== undefined) {
|
| 278 |
+
// Allow the key prop, which is automatically added by React.
|
| 279 |
+
maxExpectedProps += 1;
|
| 280 |
+
}
|
| 281 |
+
if (
|
| 282 |
+
boxProps.flexDirection !== undefined &&
|
| 283 |
+
boxProps.flexDirection !== 'row'
|
| 284 |
+
) {
|
| 285 |
+
debugReportError(
|
| 286 |
+
'MaxSizedBox children must have flexDirection="row".',
|
| 287 |
+
element,
|
| 288 |
+
);
|
| 289 |
+
}
|
| 290 |
+
if (Object.keys(boxProps).length > maxExpectedProps) {
|
| 291 |
+
debugReportError(
|
| 292 |
+
`Boxes inside MaxSizedBox must not have additional props. ${Object.keys(
|
| 293 |
+
boxProps,
|
| 294 |
+
).join(', ')}`,
|
| 295 |
+
element,
|
| 296 |
+
);
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
const row: Row = {
|
| 301 |
+
noWrapSegments: [],
|
| 302 |
+
segments: [],
|
| 303 |
+
};
|
| 304 |
+
|
| 305 |
+
let hasSeenWrapped = false;
|
| 306 |
+
|
| 307 |
+
function visitRowChild(
|
| 308 |
+
element: React.ReactNode,
|
| 309 |
+
parentProps: Record<string, unknown> | undefined,
|
| 310 |
+
) {
|
| 311 |
+
if (element === null) {
|
| 312 |
+
return;
|
| 313 |
+
}
|
| 314 |
+
if (typeof element === 'string' || typeof element === 'number') {
|
| 315 |
+
const text = String(element);
|
| 316 |
+
// Ignore empty strings as they don't need to be rendered.
|
| 317 |
+
if (!text) {
|
| 318 |
+
return;
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
const segment: StyledText = { text, props: parentProps ?? {} };
|
| 322 |
+
|
| 323 |
+
// Check the 'wrap' property from the merged props to decide the segment type.
|
| 324 |
+
if (parentProps === undefined || parentProps['wrap'] === 'wrap') {
|
| 325 |
+
hasSeenWrapped = true;
|
| 326 |
+
row.segments.push(segment);
|
| 327 |
+
} else {
|
| 328 |
+
if (!hasSeenWrapped) {
|
| 329 |
+
row.noWrapSegments.push(segment);
|
| 330 |
+
} else {
|
| 331 |
+
// put in the wrapped segment as the row is already stuck in wrapped mode.
|
| 332 |
+
row.segments.push(segment);
|
| 333 |
+
debugReportError(
|
| 334 |
+
'Text elements without wrapping cannot appear after elements with wrapping in the same row.',
|
| 335 |
+
element,
|
| 336 |
+
);
|
| 337 |
+
}
|
| 338 |
+
}
|
| 339 |
+
return;
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
if (!React.isValidElement<{ children?: React.ReactNode }>(element)) {
|
| 343 |
+
debugReportError('Invalid element.', element);
|
| 344 |
+
return;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
if (element.type === Fragment) {
|
| 348 |
+
React.Children.forEach(element.props.children, (child) =>
|
| 349 |
+
visitRowChild(child, parentProps),
|
| 350 |
+
);
|
| 351 |
+
return;
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
if (element.type !== Text) {
|
| 355 |
+
debugReportError(
|
| 356 |
+
'Children of a row Box must be <Text> elements.',
|
| 357 |
+
element,
|
| 358 |
+
);
|
| 359 |
+
return;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
// Merge props from parent <Text> elements. Child props take precedence.
|
| 363 |
+
const { children, ...currentProps } = element.props;
|
| 364 |
+
const mergedProps =
|
| 365 |
+
parentProps === undefined
|
| 366 |
+
? currentProps
|
| 367 |
+
: { ...parentProps, ...currentProps };
|
| 368 |
+
React.Children.forEach(children, (child) =>
|
| 369 |
+
visitRowChild(child, mergedProps),
|
| 370 |
+
);
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
React.Children.forEach(element.props.children, (child) =>
|
| 374 |
+
visitRowChild(child, undefined),
|
| 375 |
+
);
|
| 376 |
+
|
| 377 |
+
return row;
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
function layoutInkElementAsStyledText(
|
| 381 |
+
element: React.ReactElement,
|
| 382 |
+
maxWidth: number,
|
| 383 |
+
output: StyledText[][],
|
| 384 |
+
) {
|
| 385 |
+
const row = visitBoxRow(element);
|
| 386 |
+
if (row.segments.length === 0 && row.noWrapSegments.length === 0) {
|
| 387 |
+
// Return a single empty line if there are no segments to display
|
| 388 |
+
output.push([]);
|
| 389 |
+
return;
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
const lines: StyledText[][] = [];
|
| 393 |
+
const nonWrappingContent: StyledText[] = [];
|
| 394 |
+
let noWrappingWidth = 0;
|
| 395 |
+
|
| 396 |
+
// First, lay out the non-wrapping segments
|
| 397 |
+
row.noWrapSegments.forEach((segment) => {
|
| 398 |
+
nonWrappingContent.push(segment);
|
| 399 |
+
noWrappingWidth += stringWidth(segment.text);
|
| 400 |
+
});
|
| 401 |
+
|
| 402 |
+
if (row.segments.length === 0) {
|
| 403 |
+
// This is a bit of a special case when there are no segments that allow
|
| 404 |
+
// wrapping. It would be ideal to unify.
|
| 405 |
+
const lines: StyledText[][] = [];
|
| 406 |
+
let currentLine: StyledText[] = [];
|
| 407 |
+
nonWrappingContent.forEach((segment) => {
|
| 408 |
+
const textLines = segment.text.split('\n');
|
| 409 |
+
textLines.forEach((text, index) => {
|
| 410 |
+
if (index > 0) {
|
| 411 |
+
lines.push(currentLine);
|
| 412 |
+
currentLine = [];
|
| 413 |
+
}
|
| 414 |
+
if (text) {
|
| 415 |
+
currentLine.push({ text, props: segment.props });
|
| 416 |
+
}
|
| 417 |
+
});
|
| 418 |
+
});
|
| 419 |
+
if (
|
| 420 |
+
currentLine.length > 0 ||
|
| 421 |
+
(nonWrappingContent.length > 0 &&
|
| 422 |
+
nonWrappingContent[nonWrappingContent.length - 1].text.endsWith('\n'))
|
| 423 |
+
) {
|
| 424 |
+
lines.push(currentLine);
|
| 425 |
+
}
|
| 426 |
+
for (const line of lines) {
|
| 427 |
+
output.push(line);
|
| 428 |
+
}
|
| 429 |
+
return;
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
const availableWidth = maxWidth - noWrappingWidth;
|
| 433 |
+
|
| 434 |
+
if (availableWidth < 1) {
|
| 435 |
+
// No room to render the wrapping segments. Truncate the non-wrapping
|
| 436 |
+
// content and append an ellipsis so the line always fits within maxWidth.
|
| 437 |
+
|
| 438 |
+
// Handle line breaks in non-wrapping content when truncating
|
| 439 |
+
const lines: StyledText[][] = [];
|
| 440 |
+
let currentLine: StyledText[] = [];
|
| 441 |
+
let currentLineWidth = 0;
|
| 442 |
+
|
| 443 |
+
for (const segment of nonWrappingContent) {
|
| 444 |
+
const textLines = segment.text.split('\n');
|
| 445 |
+
textLines.forEach((text, index) => {
|
| 446 |
+
if (index > 0) {
|
| 447 |
+
// New line encountered, finish current line and start new one
|
| 448 |
+
lines.push(currentLine);
|
| 449 |
+
currentLine = [];
|
| 450 |
+
currentLineWidth = 0;
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
if (text) {
|
| 454 |
+
const textWidth = stringWidth(text);
|
| 455 |
+
|
| 456 |
+
// When there's no room for wrapping content, be very conservative
|
| 457 |
+
// For lines after the first line break, show only ellipsis if the text would be truncated
|
| 458 |
+
if (index > 0 && textWidth > 0) {
|
| 459 |
+
// This is content after a line break - just show ellipsis to indicate truncation
|
| 460 |
+
currentLine.push({ text: '…', props: {} });
|
| 461 |
+
currentLineWidth = stringWidth('…');
|
| 462 |
+
} else {
|
| 463 |
+
// This is the first line or a continuation, try to fit what we can
|
| 464 |
+
const maxContentWidth = Math.max(0, maxWidth - stringWidth('…'));
|
| 465 |
+
|
| 466 |
+
if (textWidth <= maxContentWidth && currentLineWidth === 0) {
|
| 467 |
+
// Text fits completely on this line
|
| 468 |
+
currentLine.push({ text, props: segment.props });
|
| 469 |
+
currentLineWidth += textWidth;
|
| 470 |
+
} else {
|
| 471 |
+
// Text needs truncation
|
| 472 |
+
const codePoints = toCodePoints(text);
|
| 473 |
+
let truncatedWidth = currentLineWidth;
|
| 474 |
+
let sliceEndIndex = 0;
|
| 475 |
+
|
| 476 |
+
for (const char of codePoints) {
|
| 477 |
+
const charWidth = stringWidth(char);
|
| 478 |
+
if (truncatedWidth + charWidth > maxContentWidth) {
|
| 479 |
+
break;
|
| 480 |
+
}
|
| 481 |
+
truncatedWidth += charWidth;
|
| 482 |
+
sliceEndIndex++;
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
const slice = codePoints.slice(0, sliceEndIndex).join('');
|
| 486 |
+
if (slice) {
|
| 487 |
+
currentLine.push({ text: slice, props: segment.props });
|
| 488 |
+
}
|
| 489 |
+
currentLine.push({ text: '…', props: {} });
|
| 490 |
+
currentLineWidth = truncatedWidth + stringWidth('…');
|
| 491 |
+
}
|
| 492 |
+
}
|
| 493 |
+
}
|
| 494 |
+
});
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
// Add the last line if it has content or if the last segment ended with \n
|
| 498 |
+
if (
|
| 499 |
+
currentLine.length > 0 ||
|
| 500 |
+
(nonWrappingContent.length > 0 &&
|
| 501 |
+
nonWrappingContent[nonWrappingContent.length - 1].text.endsWith('\n'))
|
| 502 |
+
) {
|
| 503 |
+
lines.push(currentLine);
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
// If we don't have any lines yet, add an ellipsis line
|
| 507 |
+
if (lines.length === 0) {
|
| 508 |
+
lines.push([{ text: '…', props: {} }]);
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
for (const line of lines) {
|
| 512 |
+
output.push(line);
|
| 513 |
+
}
|
| 514 |
+
return;
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
// Now, lay out the wrapping segments
|
| 518 |
+
let wrappingPart: StyledText[] = [];
|
| 519 |
+
let wrappingPartWidth = 0;
|
| 520 |
+
|
| 521 |
+
function addWrappingPartToLines() {
|
| 522 |
+
if (lines.length === 0) {
|
| 523 |
+
lines.push([...nonWrappingContent, ...wrappingPart]);
|
| 524 |
+
} else {
|
| 525 |
+
if (noWrappingWidth > 0) {
|
| 526 |
+
lines.push([
|
| 527 |
+
...[{ text: ' '.repeat(noWrappingWidth), props: {} }],
|
| 528 |
+
...wrappingPart,
|
| 529 |
+
]);
|
| 530 |
+
} else {
|
| 531 |
+
lines.push(wrappingPart);
|
| 532 |
+
}
|
| 533 |
+
}
|
| 534 |
+
wrappingPart = [];
|
| 535 |
+
wrappingPartWidth = 0;
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
function addToWrappingPart(text: string, props: Record<string, unknown>) {
|
| 539 |
+
if (
|
| 540 |
+
wrappingPart.length > 0 &&
|
| 541 |
+
wrappingPart[wrappingPart.length - 1].props === props
|
| 542 |
+
) {
|
| 543 |
+
wrappingPart[wrappingPart.length - 1].text += text;
|
| 544 |
+
} else {
|
| 545 |
+
wrappingPart.push({ text, props });
|
| 546 |
+
}
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
row.segments.forEach((segment) => {
|
| 550 |
+
const linesFromSegment = segment.text.split('\n');
|
| 551 |
+
|
| 552 |
+
linesFromSegment.forEach((lineText, lineIndex) => {
|
| 553 |
+
if (lineIndex > 0) {
|
| 554 |
+
addWrappingPartToLines();
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
const words = lineText.split(/(\s+)/); // Split by whitespace
|
| 558 |
+
|
| 559 |
+
words.forEach((word) => {
|
| 560 |
+
if (!word) return;
|
| 561 |
+
const wordWidth = stringWidth(word);
|
| 562 |
+
|
| 563 |
+
if (
|
| 564 |
+
wrappingPartWidth + wordWidth > availableWidth &&
|
| 565 |
+
wrappingPartWidth > 0
|
| 566 |
+
) {
|
| 567 |
+
addWrappingPartToLines();
|
| 568 |
+
if (/^\s+$/.test(word)) {
|
| 569 |
+
return;
|
| 570 |
+
}
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
if (wordWidth > availableWidth) {
|
| 574 |
+
// Word is too long, needs to be split across lines
|
| 575 |
+
const wordAsCodePoints = toCodePoints(word);
|
| 576 |
+
let remainingWordAsCodePoints = wordAsCodePoints;
|
| 577 |
+
while (remainingWordAsCodePoints.length > 0) {
|
| 578 |
+
let splitIndex = 0;
|
| 579 |
+
let currentSplitWidth = 0;
|
| 580 |
+
for (const char of remainingWordAsCodePoints) {
|
| 581 |
+
const charWidth = stringWidth(char);
|
| 582 |
+
if (
|
| 583 |
+
wrappingPartWidth + currentSplitWidth + charWidth >
|
| 584 |
+
availableWidth
|
| 585 |
+
) {
|
| 586 |
+
break;
|
| 587 |
+
}
|
| 588 |
+
currentSplitWidth += charWidth;
|
| 589 |
+
splitIndex++;
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
if (splitIndex > 0) {
|
| 593 |
+
const part = remainingWordAsCodePoints
|
| 594 |
+
.slice(0, splitIndex)
|
| 595 |
+
.join('');
|
| 596 |
+
addToWrappingPart(part, segment.props);
|
| 597 |
+
wrappingPartWidth += stringWidth(part);
|
| 598 |
+
remainingWordAsCodePoints =
|
| 599 |
+
remainingWordAsCodePoints.slice(splitIndex);
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
if (remainingWordAsCodePoints.length > 0) {
|
| 603 |
+
addWrappingPartToLines();
|
| 604 |
+
}
|
| 605 |
+
}
|
| 606 |
+
} else {
|
| 607 |
+
addToWrappingPart(word, segment.props);
|
| 608 |
+
wrappingPartWidth += wordWidth;
|
| 609 |
+
}
|
| 610 |
+
});
|
| 611 |
+
});
|
| 612 |
+
// Split omits a trailing newline, so we need to handle it here
|
| 613 |
+
if (segment.text.endsWith('\n')) {
|
| 614 |
+
addWrappingPartToLines();
|
| 615 |
+
}
|
| 616 |
+
});
|
| 617 |
+
|
| 618 |
+
if (wrappingPart.length > 0) {
|
| 619 |
+
addWrappingPartToLines();
|
| 620 |
+
}
|
| 621 |
+
for (const line of lines) {
|
| 622 |
+
output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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { renderWithProviders } from '../../../test-utils/render.js';
|
| 8 |
+
import { waitFor } from '@testing-library/react';
|
| 9 |
+
import {
|
| 10 |
+
RadioButtonSelect,
|
| 11 |
+
type RadioSelectItem,
|
| 12 |
+
} from './RadioButtonSelect.js';
|
| 13 |
+
import { describe, it, expect, vi } from 'vitest';
|
| 14 |
+
|
| 15 |
+
const ITEMS: Array<RadioSelectItem<string>> = [
|
| 16 |
+
{ label: 'Option 1', value: 'one' },
|
| 17 |
+
{ label: 'Option 2', value: 'two' },
|
| 18 |
+
{ label: 'Option 3', value: 'three', disabled: true },
|
| 19 |
+
];
|
| 20 |
+
|
| 21 |
+
describe('<RadioButtonSelect />', () => {
|
| 22 |
+
it('renders a list of items and matches snapshot', () => {
|
| 23 |
+
const { lastFrame } = renderWithProviders(
|
| 24 |
+
<RadioButtonSelect items={ITEMS} onSelect={() => {}} isFocused={true} />,
|
| 25 |
+
);
|
| 26 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
it('renders with the second item selected and matches snapshot', () => {
|
| 30 |
+
const { lastFrame } = renderWithProviders(
|
| 31 |
+
<RadioButtonSelect items={ITEMS} initialIndex={1} onSelect={() => {}} />,
|
| 32 |
+
);
|
| 33 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
it('renders with numbers hidden and matches snapshot', () => {
|
| 37 |
+
const { lastFrame } = renderWithProviders(
|
| 38 |
+
<RadioButtonSelect
|
| 39 |
+
items={ITEMS}
|
| 40 |
+
onSelect={() => {}}
|
| 41 |
+
showNumbers={false}
|
| 42 |
+
/>,
|
| 43 |
+
);
|
| 44 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
it('renders with scroll arrows and matches snapshot', () => {
|
| 48 |
+
const manyItems = Array.from({ length: 20 }, (_, i) => ({
|
| 49 |
+
label: `Item ${i + 1}`,
|
| 50 |
+
value: `item-${i + 1}`,
|
| 51 |
+
}));
|
| 52 |
+
const { lastFrame } = renderWithProviders(
|
| 53 |
+
<RadioButtonSelect
|
| 54 |
+
items={manyItems}
|
| 55 |
+
onSelect={() => {}}
|
| 56 |
+
showScrollArrows={true}
|
| 57 |
+
maxItemsToShow={5}
|
| 58 |
+
/>,
|
| 59 |
+
);
|
| 60 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
it('renders with special theme display and matches snapshot', () => {
|
| 64 |
+
const themeItems: Array<RadioSelectItem<string>> = [
|
| 65 |
+
{
|
| 66 |
+
label: 'Theme A (Light)',
|
| 67 |
+
value: 'a-light',
|
| 68 |
+
themeNameDisplay: 'Theme A',
|
| 69 |
+
themeTypeDisplay: '(Light)',
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
label: 'Theme B (Dark)',
|
| 73 |
+
value: 'b-dark',
|
| 74 |
+
themeNameDisplay: 'Theme B',
|
| 75 |
+
themeTypeDisplay: '(Dark)',
|
| 76 |
+
},
|
| 77 |
+
];
|
| 78 |
+
const { lastFrame } = renderWithProviders(
|
| 79 |
+
<RadioButtonSelect items={themeItems} onSelect={() => {}} />,
|
| 80 |
+
);
|
| 81 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('renders a list with >10 items and matches snapshot', () => {
|
| 85 |
+
const manyItems = Array.from({ length: 12 }, (_, i) => ({
|
| 86 |
+
label: `Item ${i + 1}`,
|
| 87 |
+
value: `item-${i + 1}`,
|
| 88 |
+
}));
|
| 89 |
+
const { lastFrame } = renderWithProviders(
|
| 90 |
+
<RadioButtonSelect items={manyItems} onSelect={() => {}} />,
|
| 91 |
+
);
|
| 92 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('renders nothing when no items are provided', () => {
|
| 96 |
+
const { lastFrame } = renderWithProviders(
|
| 97 |
+
<RadioButtonSelect items={[]} onSelect={() => {}} isFocused={true} />,
|
| 98 |
+
);
|
| 99 |
+
expect(lastFrame()).toBe('');
|
| 100 |
+
});
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
describe('keyboard navigation', () => {
|
| 104 |
+
it('should call onSelect when "enter" is pressed', () => {
|
| 105 |
+
const onSelect = vi.fn();
|
| 106 |
+
const { stdin } = renderWithProviders(
|
| 107 |
+
<RadioButtonSelect items={ITEMS} onSelect={onSelect} />,
|
| 108 |
+
);
|
| 109 |
+
|
| 110 |
+
stdin.write('\r');
|
| 111 |
+
|
| 112 |
+
expect(onSelect).toHaveBeenCalledWith('one');
|
| 113 |
+
});
|
| 114 |
+
|
| 115 |
+
describe('when isFocused is false', () => {
|
| 116 |
+
it('should not handle any keyboard input', () => {
|
| 117 |
+
const onSelect = vi.fn();
|
| 118 |
+
const { stdin } = renderWithProviders(
|
| 119 |
+
<RadioButtonSelect
|
| 120 |
+
items={ITEMS}
|
| 121 |
+
onSelect={onSelect}
|
| 122 |
+
isFocused={false}
|
| 123 |
+
/>,
|
| 124 |
+
);
|
| 125 |
+
|
| 126 |
+
stdin.write('\u001B[B'); // Down arrow
|
| 127 |
+
stdin.write('\u001B[A'); // Up arrow
|
| 128 |
+
stdin.write('\r'); // Enter
|
| 129 |
+
|
| 130 |
+
expect(onSelect).not.toHaveBeenCalled();
|
| 131 |
+
});
|
| 132 |
+
});
|
| 133 |
+
|
| 134 |
+
describe.each([
|
| 135 |
+
{ description: 'when isFocused is true', isFocused: true },
|
| 136 |
+
{ description: 'when isFocused is omitted', isFocused: undefined },
|
| 137 |
+
])('$description', ({ isFocused }) => {
|
| 138 |
+
it('should navigate down with arrow key and select with enter', async () => {
|
| 139 |
+
const onSelect = vi.fn();
|
| 140 |
+
const { stdin, lastFrame } = renderWithProviders(
|
| 141 |
+
<RadioButtonSelect
|
| 142 |
+
items={ITEMS}
|
| 143 |
+
onSelect={onSelect}
|
| 144 |
+
isFocused={isFocused}
|
| 145 |
+
/>,
|
| 146 |
+
);
|
| 147 |
+
|
| 148 |
+
stdin.write('\u001B[B'); // Down arrow
|
| 149 |
+
|
| 150 |
+
await waitFor(() => {
|
| 151 |
+
expect(lastFrame()).toContain('● 2. Option 2');
|
| 152 |
+
});
|
| 153 |
+
|
| 154 |
+
stdin.write('\r');
|
| 155 |
+
|
| 156 |
+
expect(onSelect).toHaveBeenCalledWith('two');
|
| 157 |
+
});
|
| 158 |
+
|
| 159 |
+
it('should navigate up with arrow key and select with enter', async () => {
|
| 160 |
+
const onSelect = vi.fn();
|
| 161 |
+
const { stdin, lastFrame } = renderWithProviders(
|
| 162 |
+
<RadioButtonSelect
|
| 163 |
+
items={ITEMS}
|
| 164 |
+
onSelect={onSelect}
|
| 165 |
+
initialIndex={1}
|
| 166 |
+
isFocused={isFocused}
|
| 167 |
+
/>,
|
| 168 |
+
);
|
| 169 |
+
|
| 170 |
+
stdin.write('\u001B[A'); // Up arrow
|
| 171 |
+
|
| 172 |
+
await waitFor(() => {
|
| 173 |
+
expect(lastFrame()).toContain('● 1. Option 1');
|
| 174 |
+
});
|
| 175 |
+
|
| 176 |
+
stdin.write('\r');
|
| 177 |
+
|
| 178 |
+
expect(onSelect).toHaveBeenCalledWith('one');
|
| 179 |
+
});
|
| 180 |
+
});
|
| 181 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/RadioButtonSelect.tsx
ADDED
|
@@ -0,0 +1,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, { useEffect, useState, useRef } from 'react';
|
| 8 |
+
import { Text, Box } from 'ink';
|
| 9 |
+
import { Colors } from '../../colors.js';
|
| 10 |
+
import { useKeypress } from '../../hooks/useKeypress.js';
|
| 11 |
+
|
| 12 |
+
/**
|
| 13 |
+
* Represents a single option for the RadioButtonSelect.
|
| 14 |
+
* Requires a label for display and a value to be returned on selection.
|
| 15 |
+
*/
|
| 16 |
+
export interface RadioSelectItem<T> {
|
| 17 |
+
label: string;
|
| 18 |
+
value: T;
|
| 19 |
+
disabled?: boolean;
|
| 20 |
+
themeNameDisplay?: string;
|
| 21 |
+
themeTypeDisplay?: string;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/**
|
| 25 |
+
* Props for the RadioButtonSelect component.
|
| 26 |
+
* @template T The type of the value associated with each radio item.
|
| 27 |
+
*/
|
| 28 |
+
export interface RadioButtonSelectProps<T> {
|
| 29 |
+
/** An array of items to display as radio options. */
|
| 30 |
+
items: Array<RadioSelectItem<T>>;
|
| 31 |
+
/** The initial index selected */
|
| 32 |
+
initialIndex?: number;
|
| 33 |
+
/** Function called when an item is selected. Receives the `value` of the selected item. */
|
| 34 |
+
onSelect: (value: T) => void;
|
| 35 |
+
/** Function called when an item is highlighted. Receives the `value` of the selected item. */
|
| 36 |
+
onHighlight?: (value: T) => void;
|
| 37 |
+
/** Whether this select input is currently focused and should respond to input. */
|
| 38 |
+
isFocused?: boolean;
|
| 39 |
+
/** Whether to show the scroll arrows. */
|
| 40 |
+
showScrollArrows?: boolean;
|
| 41 |
+
/** The maximum number of items to show at once. */
|
| 42 |
+
maxItemsToShow?: number;
|
| 43 |
+
/** Whether to show numbers next to items. */
|
| 44 |
+
showNumbers?: boolean;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/**
|
| 48 |
+
* A custom component that displays a list of items with radio buttons,
|
| 49 |
+
* supporting scrolling and keyboard navigation.
|
| 50 |
+
*
|
| 51 |
+
* @template T The type of the value associated with each radio item.
|
| 52 |
+
*/
|
| 53 |
+
export function RadioButtonSelect<T>({
|
| 54 |
+
items,
|
| 55 |
+
initialIndex = 0,
|
| 56 |
+
onSelect,
|
| 57 |
+
onHighlight,
|
| 58 |
+
isFocused = true,
|
| 59 |
+
showScrollArrows = false,
|
| 60 |
+
maxItemsToShow = 10,
|
| 61 |
+
showNumbers = true,
|
| 62 |
+
}: RadioButtonSelectProps<T>): React.JSX.Element {
|
| 63 |
+
const [activeIndex, setActiveIndex] = useState(initialIndex);
|
| 64 |
+
const [scrollOffset, setScrollOffset] = useState(0);
|
| 65 |
+
const [numberInput, setNumberInput] = useState('');
|
| 66 |
+
const numberInputTimer = useRef<NodeJS.Timeout | null>(null);
|
| 67 |
+
|
| 68 |
+
useEffect(() => {
|
| 69 |
+
const newScrollOffset = Math.max(
|
| 70 |
+
0,
|
| 71 |
+
Math.min(activeIndex - maxItemsToShow + 1, items.length - maxItemsToShow),
|
| 72 |
+
);
|
| 73 |
+
if (activeIndex < scrollOffset) {
|
| 74 |
+
setScrollOffset(activeIndex);
|
| 75 |
+
} else if (activeIndex >= scrollOffset + maxItemsToShow) {
|
| 76 |
+
setScrollOffset(newScrollOffset);
|
| 77 |
+
}
|
| 78 |
+
}, [activeIndex, items.length, scrollOffset, maxItemsToShow]);
|
| 79 |
+
|
| 80 |
+
useEffect(
|
| 81 |
+
() => () => {
|
| 82 |
+
if (numberInputTimer.current) {
|
| 83 |
+
clearTimeout(numberInputTimer.current);
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
[],
|
| 87 |
+
);
|
| 88 |
+
|
| 89 |
+
useKeypress(
|
| 90 |
+
(key) => {
|
| 91 |
+
const { sequence, name } = key;
|
| 92 |
+
const isNumeric = showNumbers && /^[0-9]$/.test(sequence);
|
| 93 |
+
|
| 94 |
+
// Any key press that is not a digit should clear the number input buffer.
|
| 95 |
+
if (!isNumeric && numberInputTimer.current) {
|
| 96 |
+
clearTimeout(numberInputTimer.current);
|
| 97 |
+
setNumberInput('');
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
if (name === 'k' || name === 'up') {
|
| 101 |
+
const newIndex = activeIndex > 0 ? activeIndex - 1 : items.length - 1;
|
| 102 |
+
setActiveIndex(newIndex);
|
| 103 |
+
onHighlight?.(items[newIndex]!.value);
|
| 104 |
+
return;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
if (name === 'j' || name === 'down') {
|
| 108 |
+
const newIndex = activeIndex < items.length - 1 ? activeIndex + 1 : 0;
|
| 109 |
+
setActiveIndex(newIndex);
|
| 110 |
+
onHighlight?.(items[newIndex]!.value);
|
| 111 |
+
return;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
if (name === 'return') {
|
| 115 |
+
onSelect(items[activeIndex]!.value);
|
| 116 |
+
return;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// Handle numeric input for selection.
|
| 120 |
+
if (isNumeric) {
|
| 121 |
+
if (numberInputTimer.current) {
|
| 122 |
+
clearTimeout(numberInputTimer.current);
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
const newNumberInput = numberInput + sequence;
|
| 126 |
+
setNumberInput(newNumberInput);
|
| 127 |
+
|
| 128 |
+
const targetIndex = Number.parseInt(newNumberInput, 10) - 1;
|
| 129 |
+
|
| 130 |
+
// A single '0' is not a valid selection since items are 1-indexed.
|
| 131 |
+
if (newNumberInput === '0') {
|
| 132 |
+
numberInputTimer.current = setTimeout(() => setNumberInput(''), 350);
|
| 133 |
+
return;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
if (targetIndex >= 0 && targetIndex < items.length) {
|
| 137 |
+
const targetItem = items[targetIndex]!;
|
| 138 |
+
setActiveIndex(targetIndex);
|
| 139 |
+
onHighlight?.(targetItem.value);
|
| 140 |
+
|
| 141 |
+
// If the typed number can't be a prefix for another valid number,
|
| 142 |
+
// select it immediately. Otherwise, wait for more input.
|
| 143 |
+
const potentialNextNumber = Number.parseInt(newNumberInput + '0', 10);
|
| 144 |
+
if (potentialNextNumber > items.length) {
|
| 145 |
+
onSelect(targetItem.value);
|
| 146 |
+
setNumberInput('');
|
| 147 |
+
} else {
|
| 148 |
+
numberInputTimer.current = setTimeout(() => {
|
| 149 |
+
onSelect(targetItem.value);
|
| 150 |
+
setNumberInput('');
|
| 151 |
+
}, 350); // Debounce time for multi-digit input.
|
| 152 |
+
}
|
| 153 |
+
} else {
|
| 154 |
+
// The typed number is out of bounds, clear the buffer
|
| 155 |
+
setNumberInput('');
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
},
|
| 159 |
+
{ isActive: !!(isFocused && items.length > 0) },
|
| 160 |
+
);
|
| 161 |
+
|
| 162 |
+
const visibleItems = items.slice(scrollOffset, scrollOffset + maxItemsToShow);
|
| 163 |
+
|
| 164 |
+
return (
|
| 165 |
+
<Box flexDirection="column">
|
| 166 |
+
{showScrollArrows && (
|
| 167 |
+
<Text color={scrollOffset > 0 ? Colors.Foreground : Colors.Gray}>
|
| 168 |
+
▲
|
| 169 |
+
</Text>
|
| 170 |
+
)}
|
| 171 |
+
{visibleItems.map((item, index) => {
|
| 172 |
+
const itemIndex = scrollOffset + index;
|
| 173 |
+
const isSelected = activeIndex === itemIndex;
|
| 174 |
+
|
| 175 |
+
let textColor = Colors.Foreground;
|
| 176 |
+
let numberColor = Colors.Foreground;
|
| 177 |
+
if (isSelected) {
|
| 178 |
+
textColor = Colors.AccentGreen;
|
| 179 |
+
numberColor = Colors.AccentGreen;
|
| 180 |
+
} else if (item.disabled) {
|
| 181 |
+
textColor = Colors.Gray;
|
| 182 |
+
numberColor = Colors.Gray;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
if (!showNumbers) {
|
| 186 |
+
numberColor = Colors.Gray;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
const numberColumnWidth = String(items.length).length;
|
| 190 |
+
const itemNumberText = `${String(itemIndex + 1).padStart(
|
| 191 |
+
numberColumnWidth,
|
| 192 |
+
)}.`;
|
| 193 |
+
|
| 194 |
+
return (
|
| 195 |
+
<Box key={item.label} alignItems="center">
|
| 196 |
+
<Box minWidth={2} flexShrink={0}>
|
| 197 |
+
<Text color={isSelected ? Colors.AccentGreen : Colors.Foreground}>
|
| 198 |
+
{isSelected ? '●' : ' '}
|
| 199 |
+
</Text>
|
| 200 |
+
</Box>
|
| 201 |
+
<Box
|
| 202 |
+
marginRight={1}
|
| 203 |
+
flexShrink={0}
|
| 204 |
+
minWidth={itemNumberText.length}
|
| 205 |
+
>
|
| 206 |
+
<Text color={numberColor}>{itemNumberText}</Text>
|
| 207 |
+
</Box>
|
| 208 |
+
{item.themeNameDisplay && item.themeTypeDisplay ? (
|
| 209 |
+
<Text color={textColor} wrap="truncate">
|
| 210 |
+
{item.themeNameDisplay}{' '}
|
| 211 |
+
<Text color={Colors.Gray}>{item.themeTypeDisplay}</Text>
|
| 212 |
+
</Text>
|
| 213 |
+
) : (
|
| 214 |
+
<Text color={textColor} wrap="truncate">
|
| 215 |
+
{item.label}
|
| 216 |
+
</Text>
|
| 217 |
+
)}
|
| 218 |
+
</Box>
|
| 219 |
+
);
|
| 220 |
+
})}
|
| 221 |
+
{showScrollArrows && (
|
| 222 |
+
<Text
|
| 223 |
+
color={
|
| 224 |
+
scrollOffset + maxItemsToShow < items.length
|
| 225 |
+
? Colors.Foreground
|
| 226 |
+
: Colors.Gray
|
| 227 |
+
}
|
| 228 |
+
>
|
| 229 |
+
▼
|
| 230 |
+
</Text>
|
| 231 |
+
)}
|
| 232 |
+
</Box>
|
| 233 |
+
);
|
| 234 |
+
}
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/__snapshots__/RadioButtonSelect.test.tsx.snap
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
| 2 |
+
|
| 3 |
+
exports[`<RadioButtonSelect /> > renders a list of items and matches snapshot 1`] = `
|
| 4 |
+
"● 1. Option 1
|
| 5 |
+
2. Option 2
|
| 6 |
+
3. Option 3"
|
| 7 |
+
`;
|
| 8 |
+
|
| 9 |
+
exports[`<RadioButtonSelect /> > renders a list with >10 items and matches snapshot 1`] = `
|
| 10 |
+
"● 1. Item 1
|
| 11 |
+
2. Item 2
|
| 12 |
+
3. Item 3
|
| 13 |
+
4. Item 4
|
| 14 |
+
5. Item 5
|
| 15 |
+
6. Item 6
|
| 16 |
+
7. Item 7
|
| 17 |
+
8. Item 8
|
| 18 |
+
9. Item 9
|
| 19 |
+
10. Item 10"
|
| 20 |
+
`;
|
| 21 |
+
|
| 22 |
+
exports[`<RadioButtonSelect /> > renders with numbers hidden and matches snapshot 1`] = `
|
| 23 |
+
"● 1. Option 1
|
| 24 |
+
2. Option 2
|
| 25 |
+
3. Option 3"
|
| 26 |
+
`;
|
| 27 |
+
|
| 28 |
+
exports[`<RadioButtonSelect /> > renders with scroll arrows and matches snapshot 1`] = `
|
| 29 |
+
"▲
|
| 30 |
+
● 1. Item 1
|
| 31 |
+
2. Item 2
|
| 32 |
+
3. Item 3
|
| 33 |
+
4. Item 4
|
| 34 |
+
5. Item 5
|
| 35 |
+
▼"
|
| 36 |
+
`;
|
| 37 |
+
|
| 38 |
+
exports[`<RadioButtonSelect /> > renders with special theme display and matches snapshot 1`] = `
|
| 39 |
+
"● 1. Theme A (Light)
|
| 40 |
+
2. Theme B (Dark)"
|
| 41 |
+
`;
|
| 42 |
+
|
| 43 |
+
exports[`<RadioButtonSelect /> > renders with the second item selected and matches snapshot 1`] = `
|
| 44 |
+
" 1. Option 1
|
| 45 |
+
● 2. Option 2
|
| 46 |
+
3. Option 3"
|
| 47 |
+
`;
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/text-buffer.test.ts
ADDED
|
@@ -0,0 +1,1728 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect, beforeEach } from 'vitest';
|
| 8 |
+
import stripAnsi from 'strip-ansi';
|
| 9 |
+
import { renderHook, act } from '@testing-library/react';
|
| 10 |
+
import {
|
| 11 |
+
useTextBuffer,
|
| 12 |
+
Viewport,
|
| 13 |
+
TextBuffer,
|
| 14 |
+
offsetToLogicalPos,
|
| 15 |
+
logicalPosToOffset,
|
| 16 |
+
textBufferReducer,
|
| 17 |
+
TextBufferState,
|
| 18 |
+
TextBufferAction,
|
| 19 |
+
findWordEndInLine,
|
| 20 |
+
findNextWordStartInLine,
|
| 21 |
+
isWordCharStrict,
|
| 22 |
+
} from './text-buffer.js';
|
| 23 |
+
import { cpLen } from '../../utils/textUtils.js';
|
| 24 |
+
|
| 25 |
+
const initialState: TextBufferState = {
|
| 26 |
+
lines: [''],
|
| 27 |
+
cursorRow: 0,
|
| 28 |
+
cursorCol: 0,
|
| 29 |
+
preferredCol: null,
|
| 30 |
+
undoStack: [],
|
| 31 |
+
redoStack: [],
|
| 32 |
+
clipboard: null,
|
| 33 |
+
selectionAnchor: null,
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
describe('textBufferReducer', () => {
|
| 37 |
+
it('should return the initial state if state is undefined', () => {
|
| 38 |
+
const action = { type: 'unknown_action' } as unknown as TextBufferAction;
|
| 39 |
+
const state = textBufferReducer(initialState, action);
|
| 40 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 41 |
+
expect(state).toEqual(initialState);
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
describe('set_text action', () => {
|
| 45 |
+
it('should set new text and move cursor to the end', () => {
|
| 46 |
+
const action: TextBufferAction = {
|
| 47 |
+
type: 'set_text',
|
| 48 |
+
payload: 'hello\nworld',
|
| 49 |
+
};
|
| 50 |
+
const state = textBufferReducer(initialState, action);
|
| 51 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 52 |
+
expect(state.lines).toEqual(['hello', 'world']);
|
| 53 |
+
expect(state.cursorRow).toBe(1);
|
| 54 |
+
expect(state.cursorCol).toBe(5);
|
| 55 |
+
expect(state.undoStack.length).toBe(1);
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
it('should not create an undo snapshot if pushToUndo is false', () => {
|
| 59 |
+
const action: TextBufferAction = {
|
| 60 |
+
type: 'set_text',
|
| 61 |
+
payload: 'no undo',
|
| 62 |
+
pushToUndo: false,
|
| 63 |
+
};
|
| 64 |
+
const state = textBufferReducer(initialState, action);
|
| 65 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 66 |
+
expect(state.lines).toEqual(['no undo']);
|
| 67 |
+
expect(state.undoStack.length).toBe(0);
|
| 68 |
+
});
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
describe('insert action', () => {
|
| 72 |
+
it('should insert a character', () => {
|
| 73 |
+
const action: TextBufferAction = { type: 'insert', payload: 'a' };
|
| 74 |
+
const state = textBufferReducer(initialState, action);
|
| 75 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 76 |
+
expect(state.lines).toEqual(['a']);
|
| 77 |
+
expect(state.cursorCol).toBe(1);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it('should insert a newline', () => {
|
| 81 |
+
const stateWithText = { ...initialState, lines: ['hello'] };
|
| 82 |
+
const action: TextBufferAction = { type: 'insert', payload: '\n' };
|
| 83 |
+
const state = textBufferReducer(stateWithText, action);
|
| 84 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 85 |
+
expect(state.lines).toEqual(['', 'hello']);
|
| 86 |
+
expect(state.cursorRow).toBe(1);
|
| 87 |
+
expect(state.cursorCol).toBe(0);
|
| 88 |
+
});
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
describe('backspace action', () => {
|
| 92 |
+
it('should remove a character', () => {
|
| 93 |
+
const stateWithText: TextBufferState = {
|
| 94 |
+
...initialState,
|
| 95 |
+
lines: ['a'],
|
| 96 |
+
cursorRow: 0,
|
| 97 |
+
cursorCol: 1,
|
| 98 |
+
};
|
| 99 |
+
const action: TextBufferAction = { type: 'backspace' };
|
| 100 |
+
const state = textBufferReducer(stateWithText, action);
|
| 101 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 102 |
+
expect(state.lines).toEqual(['']);
|
| 103 |
+
expect(state.cursorCol).toBe(0);
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
it('should join lines if at the beginning of a line', () => {
|
| 107 |
+
const stateWithText: TextBufferState = {
|
| 108 |
+
...initialState,
|
| 109 |
+
lines: ['hello', 'world'],
|
| 110 |
+
cursorRow: 1,
|
| 111 |
+
cursorCol: 0,
|
| 112 |
+
};
|
| 113 |
+
const action: TextBufferAction = { type: 'backspace' };
|
| 114 |
+
const state = textBufferReducer(stateWithText, action);
|
| 115 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 116 |
+
expect(state.lines).toEqual(['helloworld']);
|
| 117 |
+
expect(state.cursorRow).toBe(0);
|
| 118 |
+
expect(state.cursorCol).toBe(5);
|
| 119 |
+
});
|
| 120 |
+
});
|
| 121 |
+
|
| 122 |
+
describe('undo/redo actions', () => {
|
| 123 |
+
it('should undo and redo a change', () => {
|
| 124 |
+
// 1. Insert text
|
| 125 |
+
const insertAction: TextBufferAction = {
|
| 126 |
+
type: 'insert',
|
| 127 |
+
payload: 'test',
|
| 128 |
+
};
|
| 129 |
+
const stateAfterInsert = textBufferReducer(initialState, insertAction);
|
| 130 |
+
expect(stateAfterInsert).toHaveOnlyValidCharacters();
|
| 131 |
+
expect(stateAfterInsert.lines).toEqual(['test']);
|
| 132 |
+
expect(stateAfterInsert.undoStack.length).toBe(1);
|
| 133 |
+
|
| 134 |
+
// 2. Undo
|
| 135 |
+
const undoAction: TextBufferAction = { type: 'undo' };
|
| 136 |
+
const stateAfterUndo = textBufferReducer(stateAfterInsert, undoAction);
|
| 137 |
+
expect(stateAfterUndo).toHaveOnlyValidCharacters();
|
| 138 |
+
expect(stateAfterUndo.lines).toEqual(['']);
|
| 139 |
+
expect(stateAfterUndo.undoStack.length).toBe(0);
|
| 140 |
+
expect(stateAfterUndo.redoStack.length).toBe(1);
|
| 141 |
+
|
| 142 |
+
// 3. Redo
|
| 143 |
+
const redoAction: TextBufferAction = { type: 'redo' };
|
| 144 |
+
const stateAfterRedo = textBufferReducer(stateAfterUndo, redoAction);
|
| 145 |
+
expect(stateAfterRedo).toHaveOnlyValidCharacters();
|
| 146 |
+
expect(stateAfterRedo.lines).toEqual(['test']);
|
| 147 |
+
expect(stateAfterRedo.undoStack.length).toBe(1);
|
| 148 |
+
expect(stateAfterRedo.redoStack.length).toBe(0);
|
| 149 |
+
});
|
| 150 |
+
});
|
| 151 |
+
|
| 152 |
+
describe('create_undo_snapshot action', () => {
|
| 153 |
+
it('should create a snapshot without changing state', () => {
|
| 154 |
+
const stateWithText: TextBufferState = {
|
| 155 |
+
...initialState,
|
| 156 |
+
lines: ['hello'],
|
| 157 |
+
cursorRow: 0,
|
| 158 |
+
cursorCol: 5,
|
| 159 |
+
};
|
| 160 |
+
const action: TextBufferAction = { type: 'create_undo_snapshot' };
|
| 161 |
+
const state = textBufferReducer(stateWithText, action);
|
| 162 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 163 |
+
|
| 164 |
+
expect(state.lines).toEqual(['hello']);
|
| 165 |
+
expect(state.cursorRow).toBe(0);
|
| 166 |
+
expect(state.cursorCol).toBe(5);
|
| 167 |
+
expect(state.undoStack.length).toBe(1);
|
| 168 |
+
expect(state.undoStack[0].lines).toEqual(['hello']);
|
| 169 |
+
expect(state.undoStack[0].cursorRow).toBe(0);
|
| 170 |
+
expect(state.undoStack[0].cursorCol).toBe(5);
|
| 171 |
+
});
|
| 172 |
+
});
|
| 173 |
+
});
|
| 174 |
+
|
| 175 |
+
// Helper to get the state from the hook
|
| 176 |
+
const getBufferState = (result: { current: TextBuffer }) => {
|
| 177 |
+
expect(result.current).toHaveOnlyValidCharacters();
|
| 178 |
+
return {
|
| 179 |
+
text: result.current.text,
|
| 180 |
+
lines: [...result.current.lines], // Clone for safety
|
| 181 |
+
cursor: [...result.current.cursor] as [number, number],
|
| 182 |
+
allVisualLines: [...result.current.allVisualLines],
|
| 183 |
+
viewportVisualLines: [...result.current.viewportVisualLines],
|
| 184 |
+
visualCursor: [...result.current.visualCursor] as [number, number],
|
| 185 |
+
visualScrollRow: result.current.visualScrollRow,
|
| 186 |
+
preferredCol: result.current.preferredCol,
|
| 187 |
+
};
|
| 188 |
+
};
|
| 189 |
+
|
| 190 |
+
describe('useTextBuffer', () => {
|
| 191 |
+
let viewport: Viewport;
|
| 192 |
+
|
| 193 |
+
beforeEach(() => {
|
| 194 |
+
viewport = { width: 10, height: 3 }; // Default viewport for tests
|
| 195 |
+
});
|
| 196 |
+
|
| 197 |
+
describe('Initialization', () => {
|
| 198 |
+
it('should initialize with empty text and cursor at (0,0) by default', () => {
|
| 199 |
+
const { result } = renderHook(() =>
|
| 200 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 201 |
+
);
|
| 202 |
+
const state = getBufferState(result);
|
| 203 |
+
expect(state.text).toBe('');
|
| 204 |
+
expect(state.lines).toEqual(['']);
|
| 205 |
+
expect(state.cursor).toEqual([0, 0]);
|
| 206 |
+
expect(state.allVisualLines).toEqual(['']);
|
| 207 |
+
expect(state.viewportVisualLines).toEqual(['']);
|
| 208 |
+
expect(state.visualCursor).toEqual([0, 0]);
|
| 209 |
+
expect(state.visualScrollRow).toBe(0);
|
| 210 |
+
});
|
| 211 |
+
|
| 212 |
+
it('should initialize with provided initialText', () => {
|
| 213 |
+
const { result } = renderHook(() =>
|
| 214 |
+
useTextBuffer({
|
| 215 |
+
initialText: 'hello',
|
| 216 |
+
viewport,
|
| 217 |
+
isValidPath: () => false,
|
| 218 |
+
}),
|
| 219 |
+
);
|
| 220 |
+
const state = getBufferState(result);
|
| 221 |
+
expect(state.text).toBe('hello');
|
| 222 |
+
expect(state.lines).toEqual(['hello']);
|
| 223 |
+
expect(state.cursor).toEqual([0, 0]); // Default cursor if offset not given
|
| 224 |
+
expect(state.allVisualLines).toEqual(['hello']);
|
| 225 |
+
expect(state.viewportVisualLines).toEqual(['hello']);
|
| 226 |
+
expect(state.visualCursor).toEqual([0, 0]);
|
| 227 |
+
});
|
| 228 |
+
|
| 229 |
+
it('should initialize with initialText and initialCursorOffset', () => {
|
| 230 |
+
const { result } = renderHook(() =>
|
| 231 |
+
useTextBuffer({
|
| 232 |
+
initialText: 'hello\nworld',
|
| 233 |
+
initialCursorOffset: 7, // Should be at 'o' in 'world'
|
| 234 |
+
viewport,
|
| 235 |
+
isValidPath: () => false,
|
| 236 |
+
}),
|
| 237 |
+
);
|
| 238 |
+
const state = getBufferState(result);
|
| 239 |
+
expect(state.text).toBe('hello\nworld');
|
| 240 |
+
expect(state.lines).toEqual(['hello', 'world']);
|
| 241 |
+
expect(state.cursor).toEqual([1, 1]); // Logical cursor at 'o' in "world"
|
| 242 |
+
expect(state.allVisualLines).toEqual(['hello', 'world']);
|
| 243 |
+
expect(state.viewportVisualLines).toEqual(['hello', 'world']);
|
| 244 |
+
expect(state.visualCursor[0]).toBe(1); // On the second visual line
|
| 245 |
+
expect(state.visualCursor[1]).toBe(1); // At 'o' in "world"
|
| 246 |
+
});
|
| 247 |
+
|
| 248 |
+
it('should wrap visual lines', () => {
|
| 249 |
+
const { result } = renderHook(() =>
|
| 250 |
+
useTextBuffer({
|
| 251 |
+
initialText: 'The quick brown fox jumps over the lazy dog.',
|
| 252 |
+
initialCursorOffset: 2, // After '好'
|
| 253 |
+
viewport: { width: 15, height: 4 },
|
| 254 |
+
isValidPath: () => false,
|
| 255 |
+
}),
|
| 256 |
+
);
|
| 257 |
+
const state = getBufferState(result);
|
| 258 |
+
expect(state.allVisualLines).toEqual([
|
| 259 |
+
'The quick',
|
| 260 |
+
'brown fox',
|
| 261 |
+
'jumps over the',
|
| 262 |
+
'lazy dog.',
|
| 263 |
+
]);
|
| 264 |
+
});
|
| 265 |
+
|
| 266 |
+
it('should wrap visual lines with multiple spaces', () => {
|
| 267 |
+
const { result } = renderHook(() =>
|
| 268 |
+
useTextBuffer({
|
| 269 |
+
initialText: 'The quick brown fox jumps over the lazy dog.',
|
| 270 |
+
viewport: { width: 15, height: 4 },
|
| 271 |
+
isValidPath: () => false,
|
| 272 |
+
}),
|
| 273 |
+
);
|
| 274 |
+
const state = getBufferState(result);
|
| 275 |
+
// Including multiple spaces at the end of the lines like this is
|
| 276 |
+
// consistent with Google docs behavior and makes it intuitive to edit
|
| 277 |
+
// the spaces as needed.
|
| 278 |
+
expect(state.allVisualLines).toEqual([
|
| 279 |
+
'The quick ',
|
| 280 |
+
'brown fox ',
|
| 281 |
+
'jumps over the',
|
| 282 |
+
'lazy dog.',
|
| 283 |
+
]);
|
| 284 |
+
});
|
| 285 |
+
|
| 286 |
+
it('should wrap visual lines even without spaces', () => {
|
| 287 |
+
const { result } = renderHook(() =>
|
| 288 |
+
useTextBuffer({
|
| 289 |
+
initialText: '123456789012345ABCDEFG', // 4 chars, 12 bytes
|
| 290 |
+
viewport: { width: 15, height: 2 },
|
| 291 |
+
isValidPath: () => false,
|
| 292 |
+
}),
|
| 293 |
+
);
|
| 294 |
+
const state = getBufferState(result);
|
| 295 |
+
// Including multiple spaces at the end of the lines like this is
|
| 296 |
+
// consistent with Google docs behavior and makes it intuitive to edit
|
| 297 |
+
// the spaces as needed.
|
| 298 |
+
expect(state.allVisualLines).toEqual(['123456789012345', 'ABCDEFG']);
|
| 299 |
+
});
|
| 300 |
+
|
| 301 |
+
it('should initialize with multi-byte unicode characters and correct cursor offset', () => {
|
| 302 |
+
const { result } = renderHook(() =>
|
| 303 |
+
useTextBuffer({
|
| 304 |
+
initialText: '你好世界', // 4 chars, 12 bytes
|
| 305 |
+
initialCursorOffset: 2, // After '好'
|
| 306 |
+
viewport: { width: 5, height: 2 },
|
| 307 |
+
isValidPath: () => false,
|
| 308 |
+
}),
|
| 309 |
+
);
|
| 310 |
+
const state = getBufferState(result);
|
| 311 |
+
expect(state.text).toBe('你好世界');
|
| 312 |
+
expect(state.lines).toEqual(['你好世界']);
|
| 313 |
+
expect(state.cursor).toEqual([0, 2]);
|
| 314 |
+
// Visual: "你好" (width 4), "世"界" (width 4) with viewport width 5
|
| 315 |
+
expect(state.allVisualLines).toEqual(['你好', '世界']);
|
| 316 |
+
expect(state.visualCursor).toEqual([1, 0]);
|
| 317 |
+
});
|
| 318 |
+
});
|
| 319 |
+
|
| 320 |
+
describe('Basic Editing', () => {
|
| 321 |
+
it('insert: should insert a character and update cursor', () => {
|
| 322 |
+
const { result } = renderHook(() =>
|
| 323 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 324 |
+
);
|
| 325 |
+
act(() => result.current.insert('a'));
|
| 326 |
+
let state = getBufferState(result);
|
| 327 |
+
expect(state.text).toBe('a');
|
| 328 |
+
expect(state.cursor).toEqual([0, 1]);
|
| 329 |
+
expect(state.visualCursor).toEqual([0, 1]);
|
| 330 |
+
|
| 331 |
+
act(() => result.current.insert('b'));
|
| 332 |
+
state = getBufferState(result);
|
| 333 |
+
expect(state.text).toBe('ab');
|
| 334 |
+
expect(state.cursor).toEqual([0, 2]);
|
| 335 |
+
expect(state.visualCursor).toEqual([0, 2]);
|
| 336 |
+
});
|
| 337 |
+
|
| 338 |
+
it('insert: should insert text in the middle of a line', () => {
|
| 339 |
+
const { result } = renderHook(() =>
|
| 340 |
+
useTextBuffer({
|
| 341 |
+
initialText: 'abc',
|
| 342 |
+
viewport,
|
| 343 |
+
isValidPath: () => false,
|
| 344 |
+
}),
|
| 345 |
+
);
|
| 346 |
+
act(() => result.current.move('right'));
|
| 347 |
+
act(() => result.current.insert('-NEW-'));
|
| 348 |
+
const state = getBufferState(result);
|
| 349 |
+
expect(state.text).toBe('a-NEW-bc');
|
| 350 |
+
expect(state.cursor).toEqual([0, 6]);
|
| 351 |
+
});
|
| 352 |
+
|
| 353 |
+
it('newline: should create a new line and move cursor', () => {
|
| 354 |
+
const { result } = renderHook(() =>
|
| 355 |
+
useTextBuffer({
|
| 356 |
+
initialText: 'ab',
|
| 357 |
+
viewport,
|
| 358 |
+
isValidPath: () => false,
|
| 359 |
+
}),
|
| 360 |
+
);
|
| 361 |
+
act(() => result.current.move('end')); // cursor at [0,2]
|
| 362 |
+
act(() => result.current.newline());
|
| 363 |
+
const state = getBufferState(result);
|
| 364 |
+
expect(state.text).toBe('ab\n');
|
| 365 |
+
expect(state.lines).toEqual(['ab', '']);
|
| 366 |
+
expect(state.cursor).toEqual([1, 0]);
|
| 367 |
+
expect(state.allVisualLines).toEqual(['ab', '']);
|
| 368 |
+
expect(state.viewportVisualLines).toEqual(['ab', '']); // viewport height 3
|
| 369 |
+
expect(state.visualCursor).toEqual([1, 0]); // On the new visual line
|
| 370 |
+
});
|
| 371 |
+
|
| 372 |
+
it('backspace: should delete char to the left or merge lines', () => {
|
| 373 |
+
const { result } = renderHook(() =>
|
| 374 |
+
useTextBuffer({
|
| 375 |
+
initialText: 'a\nb',
|
| 376 |
+
viewport,
|
| 377 |
+
isValidPath: () => false,
|
| 378 |
+
}),
|
| 379 |
+
);
|
| 380 |
+
act(() => {
|
| 381 |
+
result.current.move('down');
|
| 382 |
+
});
|
| 383 |
+
act(() => {
|
| 384 |
+
result.current.move('end'); // cursor to [1,1] (end of 'b')
|
| 385 |
+
});
|
| 386 |
+
act(() => result.current.backspace()); // delete 'b'
|
| 387 |
+
let state = getBufferState(result);
|
| 388 |
+
expect(state.text).toBe('a\n');
|
| 389 |
+
expect(state.cursor).toEqual([1, 0]);
|
| 390 |
+
|
| 391 |
+
act(() => result.current.backspace()); // merge lines
|
| 392 |
+
state = getBufferState(result);
|
| 393 |
+
expect(state.text).toBe('a');
|
| 394 |
+
expect(state.cursor).toEqual([0, 1]); // cursor after 'a'
|
| 395 |
+
expect(state.allVisualLines).toEqual(['a']);
|
| 396 |
+
expect(state.viewportVisualLines).toEqual(['a']);
|
| 397 |
+
expect(state.visualCursor).toEqual([0, 1]);
|
| 398 |
+
});
|
| 399 |
+
|
| 400 |
+
it('del: should delete char to the right or merge lines', () => {
|
| 401 |
+
const { result } = renderHook(() =>
|
| 402 |
+
useTextBuffer({
|
| 403 |
+
initialText: 'a\nb',
|
| 404 |
+
viewport,
|
| 405 |
+
isValidPath: () => false,
|
| 406 |
+
}),
|
| 407 |
+
);
|
| 408 |
+
// cursor at [0,0]
|
| 409 |
+
act(() => result.current.del()); // delete 'a'
|
| 410 |
+
let state = getBufferState(result);
|
| 411 |
+
expect(state.text).toBe('\nb');
|
| 412 |
+
expect(state.cursor).toEqual([0, 0]);
|
| 413 |
+
|
| 414 |
+
act(() => result.current.del()); // merge lines (deletes newline)
|
| 415 |
+
state = getBufferState(result);
|
| 416 |
+
expect(state.text).toBe('b');
|
| 417 |
+
expect(state.cursor).toEqual([0, 0]);
|
| 418 |
+
expect(state.allVisualLines).toEqual(['b']);
|
| 419 |
+
expect(state.viewportVisualLines).toEqual(['b']);
|
| 420 |
+
expect(state.visualCursor).toEqual([0, 0]);
|
| 421 |
+
});
|
| 422 |
+
});
|
| 423 |
+
|
| 424 |
+
describe('Drag and Drop File Paths', () => {
|
| 425 |
+
it('should prepend @ to a valid file path on insert', () => {
|
| 426 |
+
const { result } = renderHook(() =>
|
| 427 |
+
useTextBuffer({ viewport, isValidPath: () => true }),
|
| 428 |
+
);
|
| 429 |
+
const filePath = '/path/to/a/valid/file.txt';
|
| 430 |
+
act(() => result.current.insert(filePath, { paste: true }));
|
| 431 |
+
expect(getBufferState(result).text).toBe(`@${filePath} `);
|
| 432 |
+
});
|
| 433 |
+
|
| 434 |
+
it('should not prepend @ to an invalid file path on insert', () => {
|
| 435 |
+
const { result } = renderHook(() =>
|
| 436 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 437 |
+
);
|
| 438 |
+
const notAPath = 'this is just some long text';
|
| 439 |
+
act(() => result.current.insert(notAPath, { paste: true }));
|
| 440 |
+
expect(getBufferState(result).text).toBe(notAPath);
|
| 441 |
+
});
|
| 442 |
+
|
| 443 |
+
it('should handle quoted paths', () => {
|
| 444 |
+
const { result } = renderHook(() =>
|
| 445 |
+
useTextBuffer({ viewport, isValidPath: () => true }),
|
| 446 |
+
);
|
| 447 |
+
const filePath = "'/path/to/a/valid/file.txt'";
|
| 448 |
+
act(() => result.current.insert(filePath, { paste: true }));
|
| 449 |
+
expect(getBufferState(result).text).toBe(`@/path/to/a/valid/file.txt `);
|
| 450 |
+
});
|
| 451 |
+
|
| 452 |
+
it('should not prepend @ to short text that is not a path', () => {
|
| 453 |
+
const { result } = renderHook(() =>
|
| 454 |
+
useTextBuffer({ viewport, isValidPath: () => true }),
|
| 455 |
+
);
|
| 456 |
+
const shortText = 'ab';
|
| 457 |
+
act(() => result.current.insert(shortText, { paste: true }));
|
| 458 |
+
expect(getBufferState(result).text).toBe(shortText);
|
| 459 |
+
});
|
| 460 |
+
});
|
| 461 |
+
|
| 462 |
+
describe('Shell Mode Behavior', () => {
|
| 463 |
+
it('should not prepend @ to valid file paths when shellModeActive is true', () => {
|
| 464 |
+
const { result } = renderHook(() =>
|
| 465 |
+
useTextBuffer({
|
| 466 |
+
viewport,
|
| 467 |
+
isValidPath: () => true,
|
| 468 |
+
shellModeActive: true,
|
| 469 |
+
}),
|
| 470 |
+
);
|
| 471 |
+
const filePath = '/path/to/a/valid/file.txt';
|
| 472 |
+
act(() => result.current.insert(filePath, { paste: true }));
|
| 473 |
+
expect(getBufferState(result).text).toBe(filePath); // No @ prefix
|
| 474 |
+
});
|
| 475 |
+
|
| 476 |
+
it('should not prepend @ to quoted paths when shellModeActive is true', () => {
|
| 477 |
+
const { result } = renderHook(() =>
|
| 478 |
+
useTextBuffer({
|
| 479 |
+
viewport,
|
| 480 |
+
isValidPath: () => true,
|
| 481 |
+
shellModeActive: true,
|
| 482 |
+
}),
|
| 483 |
+
);
|
| 484 |
+
const quotedFilePath = "'/path/to/a/valid/file.txt'";
|
| 485 |
+
act(() => result.current.insert(quotedFilePath, { paste: true }));
|
| 486 |
+
expect(getBufferState(result).text).toBe(quotedFilePath); // No @ prefix, keeps quotes
|
| 487 |
+
});
|
| 488 |
+
|
| 489 |
+
it('should behave normally with invalid paths when shellModeActive is true', () => {
|
| 490 |
+
const { result } = renderHook(() =>
|
| 491 |
+
useTextBuffer({
|
| 492 |
+
viewport,
|
| 493 |
+
isValidPath: () => false,
|
| 494 |
+
shellModeActive: true,
|
| 495 |
+
}),
|
| 496 |
+
);
|
| 497 |
+
const notAPath = 'this is just some text';
|
| 498 |
+
act(() => result.current.insert(notAPath, { paste: true }));
|
| 499 |
+
expect(getBufferState(result).text).toBe(notAPath);
|
| 500 |
+
});
|
| 501 |
+
|
| 502 |
+
it('should behave normally with short text when shellModeActive is true', () => {
|
| 503 |
+
const { result } = renderHook(() =>
|
| 504 |
+
useTextBuffer({
|
| 505 |
+
viewport,
|
| 506 |
+
isValidPath: () => true,
|
| 507 |
+
shellModeActive: true,
|
| 508 |
+
}),
|
| 509 |
+
);
|
| 510 |
+
const shortText = 'ls';
|
| 511 |
+
act(() => result.current.insert(shortText, { paste: true }));
|
| 512 |
+
expect(getBufferState(result).text).toBe(shortText); // No @ prefix for short text
|
| 513 |
+
});
|
| 514 |
+
});
|
| 515 |
+
|
| 516 |
+
describe('Cursor Movement', () => {
|
| 517 |
+
it('move: left/right should work within and across visual lines (due to wrapping)', () => {
|
| 518 |
+
// Text: "long line1next line2" (20 chars)
|
| 519 |
+
// Viewport width 5. Word wrapping should produce:
|
| 520 |
+
// "long " (5)
|
| 521 |
+
// "line1" (5)
|
| 522 |
+
// "next " (5)
|
| 523 |
+
// "line2" (5)
|
| 524 |
+
const { result } = renderHook(() =>
|
| 525 |
+
useTextBuffer({
|
| 526 |
+
initialText: 'long line1next line2', // Corrected: was 'long line1next line2'
|
| 527 |
+
viewport: { width: 5, height: 4 },
|
| 528 |
+
isValidPath: () => false,
|
| 529 |
+
}),
|
| 530 |
+
);
|
| 531 |
+
// Initial cursor [0,0] logical, visual [0,0] ("l" of "long ")
|
| 532 |
+
|
| 533 |
+
act(() => result.current.move('right')); // visual [0,1] ("o")
|
| 534 |
+
expect(getBufferState(result).visualCursor).toEqual([0, 1]);
|
| 535 |
+
act(() => result.current.move('right')); // visual [0,2] ("n")
|
| 536 |
+
act(() => result.current.move('right')); // visual [0,3] ("g")
|
| 537 |
+
act(() => result.current.move('right')); // visual [0,4] (" ")
|
| 538 |
+
expect(getBufferState(result).visualCursor).toEqual([0, 4]);
|
| 539 |
+
|
| 540 |
+
act(() => result.current.move('right')); // visual [1,0] ("l" of "line1")
|
| 541 |
+
expect(getBufferState(result).visualCursor).toEqual([1, 0]);
|
| 542 |
+
expect(getBufferState(result).cursor).toEqual([0, 5]); // logical cursor
|
| 543 |
+
|
| 544 |
+
act(() => result.current.move('left')); // visual [0,4] (" " of "long ")
|
| 545 |
+
expect(getBufferState(result).visualCursor).toEqual([0, 4]);
|
| 546 |
+
expect(getBufferState(result).cursor).toEqual([0, 4]); // logical cursor
|
| 547 |
+
});
|
| 548 |
+
|
| 549 |
+
it('move: up/down should preserve preferred visual column', () => {
|
| 550 |
+
const text = 'abcde\nxy\n12345';
|
| 551 |
+
const { result } = renderHook(() =>
|
| 552 |
+
useTextBuffer({
|
| 553 |
+
initialText: text,
|
| 554 |
+
viewport,
|
| 555 |
+
isValidPath: () => false,
|
| 556 |
+
}),
|
| 557 |
+
);
|
| 558 |
+
expect(result.current.allVisualLines).toEqual(['abcde', 'xy', '12345']);
|
| 559 |
+
// Place cursor at the end of "abcde" -> logical [0,5]
|
| 560 |
+
act(() => {
|
| 561 |
+
result.current.move('home'); // to [0,0]
|
| 562 |
+
});
|
| 563 |
+
for (let i = 0; i < 5; i++) {
|
| 564 |
+
act(() => {
|
| 565 |
+
result.current.move('right'); // to [0,5]
|
| 566 |
+
});
|
| 567 |
+
}
|
| 568 |
+
expect(getBufferState(result).cursor).toEqual([0, 5]);
|
| 569 |
+
expect(getBufferState(result).visualCursor).toEqual([0, 5]);
|
| 570 |
+
|
| 571 |
+
// Set preferredCol by moving up then down to the same spot, then test.
|
| 572 |
+
act(() => {
|
| 573 |
+
result.current.move('down'); // to xy, logical [1,2], visual [1,2], preferredCol should be 5
|
| 574 |
+
});
|
| 575 |
+
let state = getBufferState(result);
|
| 576 |
+
expect(state.cursor).toEqual([1, 2]); // Logical cursor at end of 'xy'
|
| 577 |
+
expect(state.visualCursor).toEqual([1, 2]); // Visual cursor at end of 'xy'
|
| 578 |
+
expect(state.preferredCol).toBe(5);
|
| 579 |
+
|
| 580 |
+
act(() => result.current.move('down')); // to '12345', preferredCol=5.
|
| 581 |
+
state = getBufferState(result);
|
| 582 |
+
expect(state.cursor).toEqual([2, 5]); // Logical cursor at end of '12345'
|
| 583 |
+
expect(state.visualCursor).toEqual([2, 5]); // Visual cursor at end of '12345'
|
| 584 |
+
expect(state.preferredCol).toBe(5); // Preferred col is maintained
|
| 585 |
+
|
| 586 |
+
act(() => result.current.move('left')); // preferredCol should reset
|
| 587 |
+
state = getBufferState(result);
|
| 588 |
+
expect(state.preferredCol).toBe(null);
|
| 589 |
+
});
|
| 590 |
+
|
| 591 |
+
it('move: home/end should go to visual line start/end', () => {
|
| 592 |
+
const initialText = 'line one\nsecond line';
|
| 593 |
+
const { result } = renderHook(() =>
|
| 594 |
+
useTextBuffer({
|
| 595 |
+
initialText,
|
| 596 |
+
viewport: { width: 5, height: 5 },
|
| 597 |
+
isValidPath: () => false,
|
| 598 |
+
}),
|
| 599 |
+
);
|
| 600 |
+
expect(result.current.allVisualLines).toEqual([
|
| 601 |
+
'line',
|
| 602 |
+
'one',
|
| 603 |
+
'secon',
|
| 604 |
+
'd',
|
| 605 |
+
'line',
|
| 606 |
+
]);
|
| 607 |
+
// Initial cursor [0,0] (start of "line")
|
| 608 |
+
act(() => result.current.move('down')); // visual cursor from [0,0] to [1,0] ("o" of "one")
|
| 609 |
+
act(() => result.current.move('right')); // visual cursor to [1,1] ("n" of "one")
|
| 610 |
+
expect(getBufferState(result).visualCursor).toEqual([1, 1]);
|
| 611 |
+
|
| 612 |
+
act(() => result.current.move('home')); // visual cursor to [1,0] (start of "one")
|
| 613 |
+
expect(getBufferState(result).visualCursor).toEqual([1, 0]);
|
| 614 |
+
|
| 615 |
+
act(() => result.current.move('end')); // visual cursor to [1,3] (end of "one")
|
| 616 |
+
expect(getBufferState(result).visualCursor).toEqual([1, 3]); // "one" is 3 chars
|
| 617 |
+
});
|
| 618 |
+
});
|
| 619 |
+
|
| 620 |
+
describe('Visual Layout & Viewport', () => {
|
| 621 |
+
it('should wrap long lines correctly into visualLines', () => {
|
| 622 |
+
const { result } = renderHook(() =>
|
| 623 |
+
useTextBuffer({
|
| 624 |
+
initialText: 'This is a very long line of text.', // 33 chars
|
| 625 |
+
viewport: { width: 10, height: 5 },
|
| 626 |
+
isValidPath: () => false,
|
| 627 |
+
}),
|
| 628 |
+
);
|
| 629 |
+
const state = getBufferState(result);
|
| 630 |
+
// Expected visual lines with word wrapping (viewport width 10):
|
| 631 |
+
// "This is a"
|
| 632 |
+
// "very long"
|
| 633 |
+
// "line of"
|
| 634 |
+
// "text."
|
| 635 |
+
expect(state.allVisualLines.length).toBe(4);
|
| 636 |
+
expect(state.allVisualLines[0]).toBe('This is a');
|
| 637 |
+
expect(state.allVisualLines[1]).toBe('very long');
|
| 638 |
+
expect(state.allVisualLines[2]).toBe('line of');
|
| 639 |
+
expect(state.allVisualLines[3]).toBe('text.');
|
| 640 |
+
});
|
| 641 |
+
|
| 642 |
+
it('should update visualScrollRow when visualCursor moves out of viewport', () => {
|
| 643 |
+
const { result } = renderHook(() =>
|
| 644 |
+
useTextBuffer({
|
| 645 |
+
initialText: 'l1\nl2\nl3\nl4\nl5',
|
| 646 |
+
viewport: { width: 5, height: 3 }, // Can show 3 visual lines
|
| 647 |
+
isValidPath: () => false,
|
| 648 |
+
}),
|
| 649 |
+
);
|
| 650 |
+
// Initial: l1, l2, l3 visible. visualScrollRow = 0. visualCursor = [0,0]
|
| 651 |
+
expect(getBufferState(result).visualScrollRow).toBe(0);
|
| 652 |
+
expect(getBufferState(result).allVisualLines).toEqual([
|
| 653 |
+
'l1',
|
| 654 |
+
'l2',
|
| 655 |
+
'l3',
|
| 656 |
+
'l4',
|
| 657 |
+
'l5',
|
| 658 |
+
]);
|
| 659 |
+
expect(getBufferState(result).viewportVisualLines).toEqual([
|
| 660 |
+
'l1',
|
| 661 |
+
'l2',
|
| 662 |
+
'l3',
|
| 663 |
+
]);
|
| 664 |
+
|
| 665 |
+
act(() => result.current.move('down')); // vc=[1,0]
|
| 666 |
+
act(() => result.current.move('down')); // vc=[2,0] (l3)
|
| 667 |
+
expect(getBufferState(result).visualScrollRow).toBe(0);
|
| 668 |
+
|
| 669 |
+
act(() => result.current.move('down')); // vc=[3,0] (l4) - scroll should happen
|
| 670 |
+
// Now: l2, l3, l4 visible. visualScrollRow = 1.
|
| 671 |
+
let state = getBufferState(result);
|
| 672 |
+
expect(state.visualScrollRow).toBe(1);
|
| 673 |
+
expect(state.allVisualLines).toEqual(['l1', 'l2', 'l3', 'l4', 'l5']);
|
| 674 |
+
expect(state.viewportVisualLines).toEqual(['l2', 'l3', 'l4']);
|
| 675 |
+
expect(state.visualCursor).toEqual([3, 0]);
|
| 676 |
+
|
| 677 |
+
act(() => result.current.move('up')); // vc=[2,0] (l3)
|
| 678 |
+
act(() => result.current.move('up')); // vc=[1,0] (l2)
|
| 679 |
+
expect(getBufferState(result).visualScrollRow).toBe(1);
|
| 680 |
+
|
| 681 |
+
act(() => result.current.move('up')); // vc=[0,0] (l1) - scroll up
|
| 682 |
+
// Now: l1, l2, l3 visible. visualScrollRow = 0
|
| 683 |
+
state = getBufferState(result); // Assign to the existing `state` variable
|
| 684 |
+
expect(state.visualScrollRow).toBe(0);
|
| 685 |
+
expect(state.allVisualLines).toEqual(['l1', 'l2', 'l3', 'l4', 'l5']);
|
| 686 |
+
expect(state.viewportVisualLines).toEqual(['l1', 'l2', 'l3']);
|
| 687 |
+
expect(state.visualCursor).toEqual([0, 0]);
|
| 688 |
+
});
|
| 689 |
+
});
|
| 690 |
+
|
| 691 |
+
describe('Undo/Redo', () => {
|
| 692 |
+
it('should undo and redo an insert operation', () => {
|
| 693 |
+
const { result } = renderHook(() =>
|
| 694 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 695 |
+
);
|
| 696 |
+
act(() => result.current.insert('a'));
|
| 697 |
+
expect(getBufferState(result).text).toBe('a');
|
| 698 |
+
|
| 699 |
+
act(() => result.current.undo());
|
| 700 |
+
expect(getBufferState(result).text).toBe('');
|
| 701 |
+
expect(getBufferState(result).cursor).toEqual([0, 0]);
|
| 702 |
+
|
| 703 |
+
act(() => result.current.redo());
|
| 704 |
+
expect(getBufferState(result).text).toBe('a');
|
| 705 |
+
expect(getBufferState(result).cursor).toEqual([0, 1]);
|
| 706 |
+
});
|
| 707 |
+
|
| 708 |
+
it('should undo and redo a newline operation', () => {
|
| 709 |
+
const { result } = renderHook(() =>
|
| 710 |
+
useTextBuffer({
|
| 711 |
+
initialText: 'test',
|
| 712 |
+
viewport,
|
| 713 |
+
isValidPath: () => false,
|
| 714 |
+
}),
|
| 715 |
+
);
|
| 716 |
+
act(() => result.current.move('end'));
|
| 717 |
+
act(() => result.current.newline());
|
| 718 |
+
expect(getBufferState(result).text).toBe('test\n');
|
| 719 |
+
|
| 720 |
+
act(() => result.current.undo());
|
| 721 |
+
expect(getBufferState(result).text).toBe('test');
|
| 722 |
+
expect(getBufferState(result).cursor).toEqual([0, 4]);
|
| 723 |
+
|
| 724 |
+
act(() => result.current.redo());
|
| 725 |
+
expect(getBufferState(result).text).toBe('test\n');
|
| 726 |
+
expect(getBufferState(result).cursor).toEqual([1, 0]);
|
| 727 |
+
});
|
| 728 |
+
});
|
| 729 |
+
|
| 730 |
+
describe('Unicode Handling', () => {
|
| 731 |
+
it('insert: should correctly handle multi-byte unicode characters', () => {
|
| 732 |
+
const { result } = renderHook(() =>
|
| 733 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 734 |
+
);
|
| 735 |
+
act(() => result.current.insert('你好'));
|
| 736 |
+
const state = getBufferState(result);
|
| 737 |
+
expect(state.text).toBe('你好');
|
| 738 |
+
expect(state.cursor).toEqual([0, 2]); // Cursor is 2 (char count)
|
| 739 |
+
expect(state.visualCursor).toEqual([0, 2]);
|
| 740 |
+
});
|
| 741 |
+
|
| 742 |
+
it('backspace: should correctly delete multi-byte unicode characters', () => {
|
| 743 |
+
const { result } = renderHook(() =>
|
| 744 |
+
useTextBuffer({
|
| 745 |
+
initialText: '你好',
|
| 746 |
+
viewport,
|
| 747 |
+
isValidPath: () => false,
|
| 748 |
+
}),
|
| 749 |
+
);
|
| 750 |
+
act(() => result.current.move('end')); // cursor at [0,2]
|
| 751 |
+
act(() => result.current.backspace()); // delete '好'
|
| 752 |
+
let state = getBufferState(result);
|
| 753 |
+
expect(state.text).toBe('你');
|
| 754 |
+
expect(state.cursor).toEqual([0, 1]);
|
| 755 |
+
|
| 756 |
+
act(() => result.current.backspace()); // delete '你'
|
| 757 |
+
state = getBufferState(result);
|
| 758 |
+
expect(state.text).toBe('');
|
| 759 |
+
expect(state.cursor).toEqual([0, 0]);
|
| 760 |
+
});
|
| 761 |
+
|
| 762 |
+
it('move: left/right should treat multi-byte chars as single units for visual cursor', () => {
|
| 763 |
+
const { result } = renderHook(() =>
|
| 764 |
+
useTextBuffer({
|
| 765 |
+
initialText: '🐶🐱',
|
| 766 |
+
viewport: { width: 5, height: 1 },
|
| 767 |
+
isValidPath: () => false,
|
| 768 |
+
}),
|
| 769 |
+
);
|
| 770 |
+
// Initial: visualCursor [0,0]
|
| 771 |
+
act(() => result.current.move('right')); // visualCursor [0,1] (after 🐶)
|
| 772 |
+
let state = getBufferState(result);
|
| 773 |
+
expect(state.cursor).toEqual([0, 1]);
|
| 774 |
+
expect(state.visualCursor).toEqual([0, 1]);
|
| 775 |
+
|
| 776 |
+
act(() => result.current.move('right')); // visualCursor [0,2] (after 🐱)
|
| 777 |
+
state = getBufferState(result);
|
| 778 |
+
expect(state.cursor).toEqual([0, 2]);
|
| 779 |
+
expect(state.visualCursor).toEqual([0, 2]);
|
| 780 |
+
|
| 781 |
+
act(() => result.current.move('left')); // visualCursor [0,1] (before 🐱 / after 🐶)
|
| 782 |
+
state = getBufferState(result);
|
| 783 |
+
expect(state.cursor).toEqual([0, 1]);
|
| 784 |
+
expect(state.visualCursor).toEqual([0, 1]);
|
| 785 |
+
});
|
| 786 |
+
});
|
| 787 |
+
|
| 788 |
+
describe('handleInput', () => {
|
| 789 |
+
it('should insert printable characters', () => {
|
| 790 |
+
const { result } = renderHook(() =>
|
| 791 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 792 |
+
);
|
| 793 |
+
act(() =>
|
| 794 |
+
result.current.handleInput({
|
| 795 |
+
name: 'h',
|
| 796 |
+
ctrl: false,
|
| 797 |
+
meta: false,
|
| 798 |
+
shift: false,
|
| 799 |
+
paste: false,
|
| 800 |
+
sequence: 'h',
|
| 801 |
+
}),
|
| 802 |
+
);
|
| 803 |
+
act(() =>
|
| 804 |
+
result.current.handleInput({
|
| 805 |
+
name: 'i',
|
| 806 |
+
ctrl: false,
|
| 807 |
+
meta: false,
|
| 808 |
+
shift: false,
|
| 809 |
+
paste: false,
|
| 810 |
+
sequence: 'i',
|
| 811 |
+
}),
|
| 812 |
+
);
|
| 813 |
+
expect(getBufferState(result).text).toBe('hi');
|
| 814 |
+
});
|
| 815 |
+
|
| 816 |
+
it('should handle "Enter" key as newline', () => {
|
| 817 |
+
const { result } = renderHook(() =>
|
| 818 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 819 |
+
);
|
| 820 |
+
act(() =>
|
| 821 |
+
result.current.handleInput({
|
| 822 |
+
name: 'return',
|
| 823 |
+
ctrl: false,
|
| 824 |
+
meta: false,
|
| 825 |
+
shift: false,
|
| 826 |
+
paste: false,
|
| 827 |
+
sequence: '\r',
|
| 828 |
+
}),
|
| 829 |
+
);
|
| 830 |
+
expect(getBufferState(result).lines).toEqual(['', '']);
|
| 831 |
+
});
|
| 832 |
+
|
| 833 |
+
it('should handle "Backspace" key', () => {
|
| 834 |
+
const { result } = renderHook(() =>
|
| 835 |
+
useTextBuffer({
|
| 836 |
+
initialText: 'a',
|
| 837 |
+
viewport,
|
| 838 |
+
isValidPath: () => false,
|
| 839 |
+
}),
|
| 840 |
+
);
|
| 841 |
+
act(() => result.current.move('end'));
|
| 842 |
+
act(() =>
|
| 843 |
+
result.current.handleInput({
|
| 844 |
+
name: 'backspace',
|
| 845 |
+
ctrl: false,
|
| 846 |
+
meta: false,
|
| 847 |
+
shift: false,
|
| 848 |
+
paste: false,
|
| 849 |
+
sequence: '\x7f',
|
| 850 |
+
}),
|
| 851 |
+
);
|
| 852 |
+
expect(getBufferState(result).text).toBe('');
|
| 853 |
+
});
|
| 854 |
+
|
| 855 |
+
it('should handle multiple delete characters in one input', () => {
|
| 856 |
+
const { result } = renderHook(() =>
|
| 857 |
+
useTextBuffer({
|
| 858 |
+
initialText: 'abcde',
|
| 859 |
+
viewport,
|
| 860 |
+
isValidPath: () => false,
|
| 861 |
+
}),
|
| 862 |
+
);
|
| 863 |
+
act(() => result.current.move('end')); // cursor at the end
|
| 864 |
+
expect(getBufferState(result).cursor).toEqual([0, 5]);
|
| 865 |
+
|
| 866 |
+
act(() => {
|
| 867 |
+
result.current.handleInput({
|
| 868 |
+
name: 'backspace',
|
| 869 |
+
ctrl: false,
|
| 870 |
+
meta: false,
|
| 871 |
+
shift: false,
|
| 872 |
+
paste: false,
|
| 873 |
+
sequence: '\x7f',
|
| 874 |
+
});
|
| 875 |
+
result.current.handleInput({
|
| 876 |
+
name: 'backspace',
|
| 877 |
+
ctrl: false,
|
| 878 |
+
meta: false,
|
| 879 |
+
shift: false,
|
| 880 |
+
paste: false,
|
| 881 |
+
sequence: '\x7f',
|
| 882 |
+
});
|
| 883 |
+
result.current.handleInput({
|
| 884 |
+
name: 'backspace',
|
| 885 |
+
ctrl: false,
|
| 886 |
+
meta: false,
|
| 887 |
+
shift: false,
|
| 888 |
+
paste: false,
|
| 889 |
+
sequence: '\x7f',
|
| 890 |
+
});
|
| 891 |
+
});
|
| 892 |
+
expect(getBufferState(result).text).toBe('ab');
|
| 893 |
+
expect(getBufferState(result).cursor).toEqual([0, 2]);
|
| 894 |
+
});
|
| 895 |
+
|
| 896 |
+
it('should handle inserts that contain delete characters ', () => {
|
| 897 |
+
const { result } = renderHook(() =>
|
| 898 |
+
useTextBuffer({
|
| 899 |
+
initialText: 'abcde',
|
| 900 |
+
viewport,
|
| 901 |
+
isValidPath: () => false,
|
| 902 |
+
}),
|
| 903 |
+
);
|
| 904 |
+
act(() => result.current.move('end')); // cursor at the end
|
| 905 |
+
expect(getBufferState(result).cursor).toEqual([0, 5]);
|
| 906 |
+
|
| 907 |
+
act(() => {
|
| 908 |
+
result.current.insert('\x7f\x7f\x7f');
|
| 909 |
+
});
|
| 910 |
+
expect(getBufferState(result).text).toBe('ab');
|
| 911 |
+
expect(getBufferState(result).cursor).toEqual([0, 2]);
|
| 912 |
+
});
|
| 913 |
+
|
| 914 |
+
it('should handle inserts with a mix of regular and delete characters ', () => {
|
| 915 |
+
const { result } = renderHook(() =>
|
| 916 |
+
useTextBuffer({
|
| 917 |
+
initialText: 'abcde',
|
| 918 |
+
viewport,
|
| 919 |
+
isValidPath: () => false,
|
| 920 |
+
}),
|
| 921 |
+
);
|
| 922 |
+
act(() => result.current.move('end')); // cursor at the end
|
| 923 |
+
expect(getBufferState(result).cursor).toEqual([0, 5]);
|
| 924 |
+
|
| 925 |
+
act(() => {
|
| 926 |
+
result.current.insert('\x7fI\x7f\x7fNEW');
|
| 927 |
+
});
|
| 928 |
+
expect(getBufferState(result).text).toBe('abcNEW');
|
| 929 |
+
expect(getBufferState(result).cursor).toEqual([0, 6]);
|
| 930 |
+
});
|
| 931 |
+
|
| 932 |
+
it('should handle arrow keys for movement', () => {
|
| 933 |
+
const { result } = renderHook(() =>
|
| 934 |
+
useTextBuffer({
|
| 935 |
+
initialText: 'ab',
|
| 936 |
+
viewport,
|
| 937 |
+
isValidPath: () => false,
|
| 938 |
+
}),
|
| 939 |
+
);
|
| 940 |
+
act(() => result.current.move('end')); // cursor [0,2]
|
| 941 |
+
act(() =>
|
| 942 |
+
result.current.handleInput({
|
| 943 |
+
name: 'left',
|
| 944 |
+
ctrl: false,
|
| 945 |
+
meta: false,
|
| 946 |
+
shift: false,
|
| 947 |
+
paste: false,
|
| 948 |
+
sequence: '\x1b[D',
|
| 949 |
+
}),
|
| 950 |
+
); // cursor [0,1]
|
| 951 |
+
expect(getBufferState(result).cursor).toEqual([0, 1]);
|
| 952 |
+
act(() =>
|
| 953 |
+
result.current.handleInput({
|
| 954 |
+
name: 'right',
|
| 955 |
+
ctrl: false,
|
| 956 |
+
meta: false,
|
| 957 |
+
shift: false,
|
| 958 |
+
paste: false,
|
| 959 |
+
sequence: '\x1b[C',
|
| 960 |
+
}),
|
| 961 |
+
); // cursor [0,2]
|
| 962 |
+
expect(getBufferState(result).cursor).toEqual([0, 2]);
|
| 963 |
+
});
|
| 964 |
+
|
| 965 |
+
it('should strip ANSI escape codes when pasting text', () => {
|
| 966 |
+
const { result } = renderHook(() =>
|
| 967 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 968 |
+
);
|
| 969 |
+
const textWithAnsi = '\x1B[31mHello\x1B[0m \x1B[32mWorld\x1B[0m';
|
| 970 |
+
// Simulate pasting by calling handleInput with a string longer than 1 char
|
| 971 |
+
act(() =>
|
| 972 |
+
result.current.handleInput({
|
| 973 |
+
name: '',
|
| 974 |
+
ctrl: false,
|
| 975 |
+
meta: false,
|
| 976 |
+
shift: false,
|
| 977 |
+
paste: false,
|
| 978 |
+
sequence: textWithAnsi,
|
| 979 |
+
}),
|
| 980 |
+
);
|
| 981 |
+
expect(getBufferState(result).text).toBe('Hello World');
|
| 982 |
+
});
|
| 983 |
+
|
| 984 |
+
it('should handle VSCode terminal Shift+Enter as newline', () => {
|
| 985 |
+
const { result } = renderHook(() =>
|
| 986 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 987 |
+
);
|
| 988 |
+
act(() =>
|
| 989 |
+
result.current.handleInput({
|
| 990 |
+
name: 'return',
|
| 991 |
+
ctrl: false,
|
| 992 |
+
meta: false,
|
| 993 |
+
shift: true,
|
| 994 |
+
paste: false,
|
| 995 |
+
sequence: '\r',
|
| 996 |
+
}),
|
| 997 |
+
); // Simulates Shift+Enter in VSCode terminal
|
| 998 |
+
expect(getBufferState(result).lines).toEqual(['', '']);
|
| 999 |
+
});
|
| 1000 |
+
|
| 1001 |
+
it('should correctly handle repeated pasting of long text', () => {
|
| 1002 |
+
const longText = `not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
|
| 1003 |
+
|
| 1004 |
+
Why do we use it?
|
| 1005 |
+
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
|
| 1006 |
+
|
| 1007 |
+
Where does it come from?
|
| 1008 |
+
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lore
|
| 1009 |
+
`;
|
| 1010 |
+
const { result } = renderHook(() =>
|
| 1011 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1012 |
+
);
|
| 1013 |
+
|
| 1014 |
+
// Simulate pasting the long text multiple times
|
| 1015 |
+
act(() => {
|
| 1016 |
+
result.current.insert(longText, { paste: true });
|
| 1017 |
+
result.current.insert(longText, { paste: true });
|
| 1018 |
+
result.current.insert(longText, { paste: true });
|
| 1019 |
+
});
|
| 1020 |
+
|
| 1021 |
+
const state = getBufferState(result);
|
| 1022 |
+
// Check that the text is the result of three concatenations.
|
| 1023 |
+
expect(state.lines).toStrictEqual(
|
| 1024 |
+
(longText + longText + longText).split('\n'),
|
| 1025 |
+
);
|
| 1026 |
+
const expectedCursorPos = offsetToLogicalPos(
|
| 1027 |
+
state.text,
|
| 1028 |
+
state.text.length,
|
| 1029 |
+
);
|
| 1030 |
+
expect(state.cursor).toEqual(expectedCursorPos);
|
| 1031 |
+
});
|
| 1032 |
+
});
|
| 1033 |
+
|
| 1034 |
+
// More tests would be needed for:
|
| 1035 |
+
// - setText, replaceRange
|
| 1036 |
+
// - deleteWordLeft, deleteWordRight
|
| 1037 |
+
// - More complex undo/redo scenarios
|
| 1038 |
+
// - Selection and clipboard (copy/paste) - might need clipboard API mocks or internal state check
|
| 1039 |
+
// - openInExternalEditor (heavy mocking of fs, child_process, os)
|
| 1040 |
+
// - All edge cases for visual scrolling and wrapping with different viewport sizes and text content.
|
| 1041 |
+
|
| 1042 |
+
describe('replaceRange', () => {
|
| 1043 |
+
it('should replace a single-line range with single-line text', () => {
|
| 1044 |
+
const { result } = renderHook(() =>
|
| 1045 |
+
useTextBuffer({
|
| 1046 |
+
initialText: '@pac',
|
| 1047 |
+
viewport,
|
| 1048 |
+
isValidPath: () => false,
|
| 1049 |
+
}),
|
| 1050 |
+
);
|
| 1051 |
+
act(() => result.current.replaceRange(0, 1, 0, 4, 'packages'));
|
| 1052 |
+
const state = getBufferState(result);
|
| 1053 |
+
expect(state.text).toBe('@packages');
|
| 1054 |
+
expect(state.cursor).toEqual([0, 9]); // cursor after 'typescript'
|
| 1055 |
+
});
|
| 1056 |
+
|
| 1057 |
+
it('should replace a multi-line range with single-line text', () => {
|
| 1058 |
+
const { result } = renderHook(() =>
|
| 1059 |
+
useTextBuffer({
|
| 1060 |
+
initialText: 'hello\nworld\nagain',
|
| 1061 |
+
viewport,
|
| 1062 |
+
isValidPath: () => false,
|
| 1063 |
+
}),
|
| 1064 |
+
);
|
| 1065 |
+
act(() => result.current.replaceRange(0, 2, 1, 3, ' new ')); // replace 'llo\nwor' with ' new '
|
| 1066 |
+
const state = getBufferState(result);
|
| 1067 |
+
expect(state.text).toBe('he new ld\nagain');
|
| 1068 |
+
expect(state.cursor).toEqual([0, 7]); // cursor after ' new '
|
| 1069 |
+
});
|
| 1070 |
+
|
| 1071 |
+
it('should delete a range when replacing with an empty string', () => {
|
| 1072 |
+
const { result } = renderHook(() =>
|
| 1073 |
+
useTextBuffer({
|
| 1074 |
+
initialText: 'hello world',
|
| 1075 |
+
viewport,
|
| 1076 |
+
isValidPath: () => false,
|
| 1077 |
+
}),
|
| 1078 |
+
);
|
| 1079 |
+
act(() => result.current.replaceRange(0, 5, 0, 11, '')); // delete ' world'
|
| 1080 |
+
const state = getBufferState(result);
|
| 1081 |
+
expect(state.text).toBe('hello');
|
| 1082 |
+
expect(state.cursor).toEqual([0, 5]);
|
| 1083 |
+
});
|
| 1084 |
+
|
| 1085 |
+
it('should handle replacing at the beginning of the text', () => {
|
| 1086 |
+
const { result } = renderHook(() =>
|
| 1087 |
+
useTextBuffer({
|
| 1088 |
+
initialText: 'world',
|
| 1089 |
+
viewport,
|
| 1090 |
+
isValidPath: () => false,
|
| 1091 |
+
}),
|
| 1092 |
+
);
|
| 1093 |
+
act(() => result.current.replaceRange(0, 0, 0, 0, 'hello '));
|
| 1094 |
+
const state = getBufferState(result);
|
| 1095 |
+
expect(state.text).toBe('hello world');
|
| 1096 |
+
expect(state.cursor).toEqual([0, 6]);
|
| 1097 |
+
});
|
| 1098 |
+
|
| 1099 |
+
it('should handle replacing at the end of the text', () => {
|
| 1100 |
+
const { result } = renderHook(() =>
|
| 1101 |
+
useTextBuffer({
|
| 1102 |
+
initialText: 'hello',
|
| 1103 |
+
viewport,
|
| 1104 |
+
isValidPath: () => false,
|
| 1105 |
+
}),
|
| 1106 |
+
);
|
| 1107 |
+
act(() => result.current.replaceRange(0, 5, 0, 5, ' world'));
|
| 1108 |
+
const state = getBufferState(result);
|
| 1109 |
+
expect(state.text).toBe('hello world');
|
| 1110 |
+
expect(state.cursor).toEqual([0, 11]);
|
| 1111 |
+
});
|
| 1112 |
+
|
| 1113 |
+
it('should handle replacing the entire buffer content', () => {
|
| 1114 |
+
const { result } = renderHook(() =>
|
| 1115 |
+
useTextBuffer({
|
| 1116 |
+
initialText: 'old text',
|
| 1117 |
+
viewport,
|
| 1118 |
+
isValidPath: () => false,
|
| 1119 |
+
}),
|
| 1120 |
+
);
|
| 1121 |
+
act(() => result.current.replaceRange(0, 0, 0, 8, 'new text'));
|
| 1122 |
+
const state = getBufferState(result);
|
| 1123 |
+
expect(state.text).toBe('new text');
|
| 1124 |
+
expect(state.cursor).toEqual([0, 8]);
|
| 1125 |
+
});
|
| 1126 |
+
|
| 1127 |
+
it('should correctly replace with unicode characters', () => {
|
| 1128 |
+
const { result } = renderHook(() =>
|
| 1129 |
+
useTextBuffer({
|
| 1130 |
+
initialText: 'hello *** world',
|
| 1131 |
+
viewport,
|
| 1132 |
+
isValidPath: () => false,
|
| 1133 |
+
}),
|
| 1134 |
+
);
|
| 1135 |
+
act(() => result.current.replaceRange(0, 6, 0, 9, '你好'));
|
| 1136 |
+
const state = getBufferState(result);
|
| 1137 |
+
expect(state.text).toBe('hello 你好 world');
|
| 1138 |
+
expect(state.cursor).toEqual([0, 8]); // after '你好'
|
| 1139 |
+
});
|
| 1140 |
+
|
| 1141 |
+
it('should handle invalid range by returning false and not changing text', () => {
|
| 1142 |
+
const { result } = renderHook(() =>
|
| 1143 |
+
useTextBuffer({
|
| 1144 |
+
initialText: 'test',
|
| 1145 |
+
viewport,
|
| 1146 |
+
isValidPath: () => false,
|
| 1147 |
+
}),
|
| 1148 |
+
);
|
| 1149 |
+
act(() => {
|
| 1150 |
+
result.current.replaceRange(0, 5, 0, 3, 'fail'); // startCol > endCol in same line
|
| 1151 |
+
});
|
| 1152 |
+
|
| 1153 |
+
expect(getBufferState(result).text).toBe('test');
|
| 1154 |
+
|
| 1155 |
+
act(() => {
|
| 1156 |
+
result.current.replaceRange(1, 0, 0, 0, 'fail'); // startRow > endRow
|
| 1157 |
+
});
|
| 1158 |
+
expect(getBufferState(result).text).toBe('test');
|
| 1159 |
+
});
|
| 1160 |
+
|
| 1161 |
+
it('replaceRange: multiple lines with a single character', () => {
|
| 1162 |
+
const { result } = renderHook(() =>
|
| 1163 |
+
useTextBuffer({
|
| 1164 |
+
initialText: 'first\nsecond\nthird',
|
| 1165 |
+
viewport,
|
| 1166 |
+
isValidPath: () => false,
|
| 1167 |
+
}),
|
| 1168 |
+
);
|
| 1169 |
+
act(() => result.current.replaceRange(0, 2, 2, 3, 'X')); // Replace 'rst\nsecond\nthi'
|
| 1170 |
+
const state = getBufferState(result);
|
| 1171 |
+
expect(state.text).toBe('fiXrd');
|
| 1172 |
+
expect(state.cursor).toEqual([0, 3]); // After 'X'
|
| 1173 |
+
});
|
| 1174 |
+
|
| 1175 |
+
it('should replace a single-line range with multi-line text', () => {
|
| 1176 |
+
const { result } = renderHook(() =>
|
| 1177 |
+
useTextBuffer({
|
| 1178 |
+
initialText: 'one two three',
|
| 1179 |
+
viewport,
|
| 1180 |
+
isValidPath: () => false,
|
| 1181 |
+
}),
|
| 1182 |
+
);
|
| 1183 |
+
// Replace "two" with "new\nline"
|
| 1184 |
+
act(() => result.current.replaceRange(0, 4, 0, 7, 'new\nline'));
|
| 1185 |
+
const state = getBufferState(result);
|
| 1186 |
+
expect(state.lines).toEqual(['one new', 'line three']);
|
| 1187 |
+
expect(state.text).toBe('one new\nline three');
|
| 1188 |
+
expect(state.cursor).toEqual([1, 4]); // cursor after 'line'
|
| 1189 |
+
});
|
| 1190 |
+
});
|
| 1191 |
+
|
| 1192 |
+
describe('Input Sanitization', () => {
|
| 1193 |
+
it('should strip ANSI escape codes from input', () => {
|
| 1194 |
+
const { result } = renderHook(() =>
|
| 1195 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1196 |
+
);
|
| 1197 |
+
const textWithAnsi = '\x1B[31mHello\x1B[0m \x1B[32mWorld\x1B[0m';
|
| 1198 |
+
act(() =>
|
| 1199 |
+
result.current.handleInput({
|
| 1200 |
+
name: '',
|
| 1201 |
+
ctrl: false,
|
| 1202 |
+
meta: false,
|
| 1203 |
+
shift: false,
|
| 1204 |
+
paste: false,
|
| 1205 |
+
sequence: textWithAnsi,
|
| 1206 |
+
}),
|
| 1207 |
+
);
|
| 1208 |
+
expect(getBufferState(result).text).toBe('Hello World');
|
| 1209 |
+
});
|
| 1210 |
+
|
| 1211 |
+
it('should strip control characters from input', () => {
|
| 1212 |
+
const { result } = renderHook(() =>
|
| 1213 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1214 |
+
);
|
| 1215 |
+
const textWithControlChars = 'H\x07e\x08l\x0Bl\x0Co'; // BELL, BACKSPACE, VT, FF
|
| 1216 |
+
act(() =>
|
| 1217 |
+
result.current.handleInput({
|
| 1218 |
+
name: '',
|
| 1219 |
+
ctrl: false,
|
| 1220 |
+
meta: false,
|
| 1221 |
+
shift: false,
|
| 1222 |
+
paste: false,
|
| 1223 |
+
sequence: textWithControlChars,
|
| 1224 |
+
}),
|
| 1225 |
+
);
|
| 1226 |
+
expect(getBufferState(result).text).toBe('Hello');
|
| 1227 |
+
});
|
| 1228 |
+
|
| 1229 |
+
it('should strip mixed ANSI and control characters from input', () => {
|
| 1230 |
+
const { result } = renderHook(() =>
|
| 1231 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1232 |
+
);
|
| 1233 |
+
const textWithMixed = '\u001B[4mH\u001B[0mello';
|
| 1234 |
+
act(() =>
|
| 1235 |
+
result.current.handleInput({
|
| 1236 |
+
name: '',
|
| 1237 |
+
ctrl: false,
|
| 1238 |
+
meta: false,
|
| 1239 |
+
shift: false,
|
| 1240 |
+
paste: false,
|
| 1241 |
+
sequence: textWithMixed,
|
| 1242 |
+
}),
|
| 1243 |
+
);
|
| 1244 |
+
expect(getBufferState(result).text).toBe('Hello');
|
| 1245 |
+
});
|
| 1246 |
+
|
| 1247 |
+
it('should not strip standard characters or newlines', () => {
|
| 1248 |
+
const { result } = renderHook(() =>
|
| 1249 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1250 |
+
);
|
| 1251 |
+
const validText = 'Hello World\nThis is a test.';
|
| 1252 |
+
act(() =>
|
| 1253 |
+
result.current.handleInput({
|
| 1254 |
+
name: '',
|
| 1255 |
+
ctrl: false,
|
| 1256 |
+
meta: false,
|
| 1257 |
+
shift: false,
|
| 1258 |
+
paste: false,
|
| 1259 |
+
sequence: validText,
|
| 1260 |
+
}),
|
| 1261 |
+
);
|
| 1262 |
+
expect(getBufferState(result).text).toBe(validText);
|
| 1263 |
+
});
|
| 1264 |
+
|
| 1265 |
+
it('should sanitize pasted text via handleInput', () => {
|
| 1266 |
+
const { result } = renderHook(() =>
|
| 1267 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1268 |
+
);
|
| 1269 |
+
const pastedText = '\u001B[4mPasted\u001B[4m Text';
|
| 1270 |
+
act(() =>
|
| 1271 |
+
result.current.handleInput({
|
| 1272 |
+
name: '',
|
| 1273 |
+
ctrl: false,
|
| 1274 |
+
meta: false,
|
| 1275 |
+
shift: false,
|
| 1276 |
+
paste: false,
|
| 1277 |
+
sequence: pastedText,
|
| 1278 |
+
}),
|
| 1279 |
+
);
|
| 1280 |
+
expect(getBufferState(result).text).toBe('Pasted Text');
|
| 1281 |
+
});
|
| 1282 |
+
|
| 1283 |
+
it('should not strip popular emojis', () => {
|
| 1284 |
+
const { result } = renderHook(() =>
|
| 1285 |
+
useTextBuffer({ viewport, isValidPath: () => false }),
|
| 1286 |
+
);
|
| 1287 |
+
const emojis = '🐍🐳🦀🦄';
|
| 1288 |
+
act(() =>
|
| 1289 |
+
result.current.handleInput({
|
| 1290 |
+
name: '',
|
| 1291 |
+
ctrl: false,
|
| 1292 |
+
meta: false,
|
| 1293 |
+
shift: false,
|
| 1294 |
+
paste: false,
|
| 1295 |
+
sequence: emojis,
|
| 1296 |
+
}),
|
| 1297 |
+
);
|
| 1298 |
+
expect(getBufferState(result).text).toBe(emojis);
|
| 1299 |
+
});
|
| 1300 |
+
});
|
| 1301 |
+
|
| 1302 |
+
describe('stripAnsi', () => {
|
| 1303 |
+
it('should correctly strip ANSI escape codes', () => {
|
| 1304 |
+
const textWithAnsi = '\x1B[31mHello\x1B[0m World';
|
| 1305 |
+
expect(stripAnsi(textWithAnsi)).toBe('Hello World');
|
| 1306 |
+
});
|
| 1307 |
+
|
| 1308 |
+
it('should handle multiple ANSI codes', () => {
|
| 1309 |
+
const textWithMultipleAnsi = '\x1B[1m\x1B[34mBold Blue\x1B[0m Text';
|
| 1310 |
+
expect(stripAnsi(textWithMultipleAnsi)).toBe('Bold Blue Text');
|
| 1311 |
+
});
|
| 1312 |
+
|
| 1313 |
+
it('should not modify text without ANSI codes', () => {
|
| 1314 |
+
const plainText = 'Plain text';
|
| 1315 |
+
expect(stripAnsi(plainText)).toBe('Plain text');
|
| 1316 |
+
});
|
| 1317 |
+
|
| 1318 |
+
it('should handle empty string', () => {
|
| 1319 |
+
expect(stripAnsi('')).toBe('');
|
| 1320 |
+
});
|
| 1321 |
+
});
|
| 1322 |
+
});
|
| 1323 |
+
|
| 1324 |
+
describe('offsetToLogicalPos', () => {
|
| 1325 |
+
it('should return [0,0] for offset 0', () => {
|
| 1326 |
+
expect(offsetToLogicalPos('any text', 0)).toEqual([0, 0]);
|
| 1327 |
+
});
|
| 1328 |
+
|
| 1329 |
+
it('should handle single line text', () => {
|
| 1330 |
+
const text = 'hello';
|
| 1331 |
+
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start
|
| 1332 |
+
expect(offsetToLogicalPos(text, 2)).toEqual([0, 2]); // Middle 'l'
|
| 1333 |
+
expect(offsetToLogicalPos(text, 5)).toEqual([0, 5]); // End
|
| 1334 |
+
expect(offsetToLogicalPos(text, 10)).toEqual([0, 5]); // Beyond end
|
| 1335 |
+
});
|
| 1336 |
+
|
| 1337 |
+
it('should handle multi-line text', () => {
|
| 1338 |
+
const text = 'hello\nworld\n123';
|
| 1339 |
+
// "hello" (5) + \n (1) + "world" (5) + \n (1) + "123" (3)
|
| 1340 |
+
// h e l l o \n w o r l d \n 1 2 3
|
| 1341 |
+
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
|
| 1342 |
+
// Line 0: "hello" (length 5)
|
| 1343 |
+
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start of 'hello'
|
| 1344 |
+
expect(offsetToLogicalPos(text, 3)).toEqual([0, 3]); // 'l' in 'hello'
|
| 1345 |
+
expect(offsetToLogicalPos(text, 5)).toEqual([0, 5]); // End of 'hello' (before \n)
|
| 1346 |
+
|
| 1347 |
+
// Line 1: "world" (length 5)
|
| 1348 |
+
expect(offsetToLogicalPos(text, 6)).toEqual([1, 0]); // Start of 'world' (after \n)
|
| 1349 |
+
expect(offsetToLogicalPos(text, 8)).toEqual([1, 2]); // 'r' in 'world'
|
| 1350 |
+
expect(offsetToLogicalPos(text, 11)).toEqual([1, 5]); // End of 'world' (before \n)
|
| 1351 |
+
|
| 1352 |
+
// Line 2: "123" (length 3)
|
| 1353 |
+
expect(offsetToLogicalPos(text, 12)).toEqual([2, 0]); // Start of '123' (after \n)
|
| 1354 |
+
expect(offsetToLogicalPos(text, 13)).toEqual([2, 1]); // '2' in '123'
|
| 1355 |
+
expect(offsetToLogicalPos(text, 15)).toEqual([2, 3]); // End of '123'
|
| 1356 |
+
expect(offsetToLogicalPos(text, 20)).toEqual([2, 3]); // Beyond end of text
|
| 1357 |
+
});
|
| 1358 |
+
|
| 1359 |
+
it('should handle empty lines', () => {
|
| 1360 |
+
const text = 'a\n\nc'; // "a" (1) + \n (1) + "" (0) + \n (1) + "c" (1)
|
| 1361 |
+
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // 'a'
|
| 1362 |
+
expect(offsetToLogicalPos(text, 1)).toEqual([0, 1]); // End of 'a'
|
| 1363 |
+
expect(offsetToLogicalPos(text, 2)).toEqual([1, 0]); // Start of empty line
|
| 1364 |
+
expect(offsetToLogicalPos(text, 3)).toEqual([2, 0]); // Start of 'c'
|
| 1365 |
+
expect(offsetToLogicalPos(text, 4)).toEqual([2, 1]); // End of 'c'
|
| 1366 |
+
});
|
| 1367 |
+
|
| 1368 |
+
it('should handle text ending with a newline', () => {
|
| 1369 |
+
const text = 'hello\n'; // "hello" (5) + \n (1)
|
| 1370 |
+
expect(offsetToLogicalPos(text, 5)).toEqual([0, 5]); // End of 'hello'
|
| 1371 |
+
expect(offsetToLogicalPos(text, 6)).toEqual([1, 0]); // Position on the new empty line after
|
| 1372 |
+
|
| 1373 |
+
expect(offsetToLogicalPos(text, 7)).toEqual([1, 0]); // Still on the new empty line
|
| 1374 |
+
});
|
| 1375 |
+
|
| 1376 |
+
it('should handle text starting with a newline', () => {
|
| 1377 |
+
const text = '\nhello'; // "" (0) + \n (1) + "hello" (5)
|
| 1378 |
+
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start of first empty line
|
| 1379 |
+
expect(offsetToLogicalPos(text, 1)).toEqual([1, 0]); // Start of 'hello'
|
| 1380 |
+
expect(offsetToLogicalPos(text, 3)).toEqual([1, 2]); // 'l' in 'hello'
|
| 1381 |
+
});
|
| 1382 |
+
|
| 1383 |
+
it('should handle empty string input', () => {
|
| 1384 |
+
expect(offsetToLogicalPos('', 0)).toEqual([0, 0]);
|
| 1385 |
+
expect(offsetToLogicalPos('', 5)).toEqual([0, 0]);
|
| 1386 |
+
});
|
| 1387 |
+
|
| 1388 |
+
it('should handle multi-byte unicode characters correctly', () => {
|
| 1389 |
+
const text = '你好\n世界'; // "你好" (2 chars) + \n (1) + "世界" (2 chars)
|
| 1390 |
+
// Total "code points" for offset calculation: 2 + 1 + 2 = 5
|
| 1391 |
+
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start of '你好'
|
| 1392 |
+
expect(offsetToLogicalPos(text, 1)).toEqual([0, 1]); // After '你', before '好'
|
| 1393 |
+
expect(offsetToLogicalPos(text, 2)).toEqual([0, 2]); // End of '你好'
|
| 1394 |
+
expect(offsetToLogicalPos(text, 3)).toEqual([1, 0]); // Start of '世界'
|
| 1395 |
+
expect(offsetToLogicalPos(text, 4)).toEqual([1, 1]); // After '世', before '界'
|
| 1396 |
+
expect(offsetToLogicalPos(text, 5)).toEqual([1, 2]); // End of '世界'
|
| 1397 |
+
expect(offsetToLogicalPos(text, 6)).toEqual([1, 2]); // Beyond end
|
| 1398 |
+
});
|
| 1399 |
+
|
| 1400 |
+
it('should handle offset exactly at newline character', () => {
|
| 1401 |
+
const text = 'abc\ndef';
|
| 1402 |
+
// a b c \n d e f
|
| 1403 |
+
// 0 1 2 3 4 5 6
|
| 1404 |
+
expect(offsetToLogicalPos(text, 3)).toEqual([0, 3]); // End of 'abc'
|
| 1405 |
+
// The next character is the newline, so an offset of 4 means the start of the next line.
|
| 1406 |
+
expect(offsetToLogicalPos(text, 4)).toEqual([1, 0]); // Start of 'def'
|
| 1407 |
+
});
|
| 1408 |
+
|
| 1409 |
+
it('should handle offset in the middle of a multi-byte character (should place at start of that char)', () => {
|
| 1410 |
+
// This scenario is tricky as "offset" is usually character-based.
|
| 1411 |
+
// Assuming cpLen and related logic handles this by treating multi-byte as one unit.
|
| 1412 |
+
// The current implementation of offsetToLogicalPos uses cpLen, so it should be code-point aware.
|
| 1413 |
+
const text = '🐶🐱'; // 2 code points
|
| 1414 |
+
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]);
|
| 1415 |
+
expect(offsetToLogicalPos(text, 1)).toEqual([0, 1]); // After 🐶
|
| 1416 |
+
expect(offsetToLogicalPos(text, 2)).toEqual([0, 2]); // After 🐱
|
| 1417 |
+
});
|
| 1418 |
+
});
|
| 1419 |
+
|
| 1420 |
+
describe('logicalPosToOffset', () => {
|
| 1421 |
+
it('should convert row/col position to offset correctly', () => {
|
| 1422 |
+
const lines = ['hello', 'world', '123'];
|
| 1423 |
+
|
| 1424 |
+
// Line 0: "hello" (5 chars)
|
| 1425 |
+
expect(logicalPosToOffset(lines, 0, 0)).toBe(0); // Start of 'hello'
|
| 1426 |
+
expect(logicalPosToOffset(lines, 0, 3)).toBe(3); // 'l' in 'hello'
|
| 1427 |
+
expect(logicalPosToOffset(lines, 0, 5)).toBe(5); // End of 'hello'
|
| 1428 |
+
|
| 1429 |
+
// Line 1: "world" (5 chars), offset starts at 6 (5 + 1 for newline)
|
| 1430 |
+
expect(logicalPosToOffset(lines, 1, 0)).toBe(6); // Start of 'world'
|
| 1431 |
+
expect(logicalPosToOffset(lines, 1, 2)).toBe(8); // 'r' in 'world'
|
| 1432 |
+
expect(logicalPosToOffset(lines, 1, 5)).toBe(11); // End of 'world'
|
| 1433 |
+
|
| 1434 |
+
// Line 2: "123" (3 chars), offset starts at 12 (5 + 1 + 5 + 1)
|
| 1435 |
+
expect(logicalPosToOffset(lines, 2, 0)).toBe(12); // Start of '123'
|
| 1436 |
+
expect(logicalPosToOffset(lines, 2, 1)).toBe(13); // '2' in '123'
|
| 1437 |
+
expect(logicalPosToOffset(lines, 2, 3)).toBe(15); // End of '123'
|
| 1438 |
+
});
|
| 1439 |
+
|
| 1440 |
+
it('should handle empty lines', () => {
|
| 1441 |
+
const lines = ['a', '', 'c'];
|
| 1442 |
+
|
| 1443 |
+
expect(logicalPosToOffset(lines, 0, 0)).toBe(0); // 'a'
|
| 1444 |
+
expect(logicalPosToOffset(lines, 0, 1)).toBe(1); // End of 'a'
|
| 1445 |
+
expect(logicalPosToOffset(lines, 1, 0)).toBe(2); // Empty line
|
| 1446 |
+
expect(logicalPosToOffset(lines, 2, 0)).toBe(3); // 'c'
|
| 1447 |
+
expect(logicalPosToOffset(lines, 2, 1)).toBe(4); // End of 'c'
|
| 1448 |
+
});
|
| 1449 |
+
|
| 1450 |
+
it('should handle single empty line', () => {
|
| 1451 |
+
const lines = [''];
|
| 1452 |
+
|
| 1453 |
+
expect(logicalPosToOffset(lines, 0, 0)).toBe(0);
|
| 1454 |
+
});
|
| 1455 |
+
|
| 1456 |
+
it('should be inverse of offsetToLogicalPos', () => {
|
| 1457 |
+
const lines = ['hello', 'world', '123'];
|
| 1458 |
+
const text = lines.join('\n');
|
| 1459 |
+
|
| 1460 |
+
// Test round-trip conversion
|
| 1461 |
+
for (let offset = 0; offset <= text.length; offset++) {
|
| 1462 |
+
const [row, col] = offsetToLogicalPos(text, offset);
|
| 1463 |
+
const convertedOffset = logicalPosToOffset(lines, row, col);
|
| 1464 |
+
expect(convertedOffset).toBe(offset);
|
| 1465 |
+
}
|
| 1466 |
+
});
|
| 1467 |
+
|
| 1468 |
+
it('should handle out-of-bounds positions', () => {
|
| 1469 |
+
const lines = ['hello'];
|
| 1470 |
+
|
| 1471 |
+
// Beyond end of line
|
| 1472 |
+
expect(logicalPosToOffset(lines, 0, 10)).toBe(5); // Clamps to end of line
|
| 1473 |
+
|
| 1474 |
+
// Beyond array bounds - should clamp to the last line
|
| 1475 |
+
expect(logicalPosToOffset(lines, 5, 0)).toBe(0); // Clamps to start of last line (row 0)
|
| 1476 |
+
expect(logicalPosToOffset(lines, 5, 10)).toBe(5); // Clamps to end of last line
|
| 1477 |
+
});
|
| 1478 |
+
});
|
| 1479 |
+
|
| 1480 |
+
describe('textBufferReducer vim operations', () => {
|
| 1481 |
+
describe('vim_delete_line', () => {
|
| 1482 |
+
it('should delete a single line including newline in multi-line text', () => {
|
| 1483 |
+
const initialState: TextBufferState = {
|
| 1484 |
+
lines: ['line1', 'line2', 'line3'],
|
| 1485 |
+
cursorRow: 1,
|
| 1486 |
+
cursorCol: 2,
|
| 1487 |
+
preferredCol: null,
|
| 1488 |
+
visualLines: [['line1'], ['line2'], ['line3']],
|
| 1489 |
+
visualScrollRow: 0,
|
| 1490 |
+
visualCursor: { row: 1, col: 2 },
|
| 1491 |
+
viewport: { width: 10, height: 5 },
|
| 1492 |
+
undoStack: [],
|
| 1493 |
+
redoStack: [],
|
| 1494 |
+
};
|
| 1495 |
+
|
| 1496 |
+
const action: TextBufferAction = {
|
| 1497 |
+
type: 'vim_delete_line',
|
| 1498 |
+
payload: { count: 1 },
|
| 1499 |
+
};
|
| 1500 |
+
|
| 1501 |
+
const result = textBufferReducer(initialState, action);
|
| 1502 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 1503 |
+
|
| 1504 |
+
// After deleting line2, we should have line1 and line3, with cursor on line3 (now at index 1)
|
| 1505 |
+
expect(result.lines).toEqual(['line1', 'line3']);
|
| 1506 |
+
expect(result.cursorRow).toBe(1);
|
| 1507 |
+
expect(result.cursorCol).toBe(0);
|
| 1508 |
+
});
|
| 1509 |
+
|
| 1510 |
+
it('should delete multiple lines when count > 1', () => {
|
| 1511 |
+
const initialState: TextBufferState = {
|
| 1512 |
+
lines: ['line1', 'line2', 'line3', 'line4'],
|
| 1513 |
+
cursorRow: 1,
|
| 1514 |
+
cursorCol: 0,
|
| 1515 |
+
preferredCol: null,
|
| 1516 |
+
visualLines: [['line1'], ['line2'], ['line3'], ['line4']],
|
| 1517 |
+
visualScrollRow: 0,
|
| 1518 |
+
visualCursor: { row: 1, col: 0 },
|
| 1519 |
+
viewport: { width: 10, height: 5 },
|
| 1520 |
+
undoStack: [],
|
| 1521 |
+
redoStack: [],
|
| 1522 |
+
};
|
| 1523 |
+
|
| 1524 |
+
const action: TextBufferAction = {
|
| 1525 |
+
type: 'vim_delete_line',
|
| 1526 |
+
payload: { count: 2 },
|
| 1527 |
+
};
|
| 1528 |
+
|
| 1529 |
+
const result = textBufferReducer(initialState, action);
|
| 1530 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 1531 |
+
|
| 1532 |
+
// Should delete line2 and line3, leaving line1 and line4
|
| 1533 |
+
expect(result.lines).toEqual(['line1', 'line4']);
|
| 1534 |
+
expect(result.cursorRow).toBe(1);
|
| 1535 |
+
expect(result.cursorCol).toBe(0);
|
| 1536 |
+
});
|
| 1537 |
+
|
| 1538 |
+
it('should clear single line content when only one line exists', () => {
|
| 1539 |
+
const initialState: TextBufferState = {
|
| 1540 |
+
lines: ['only line'],
|
| 1541 |
+
cursorRow: 0,
|
| 1542 |
+
cursorCol: 5,
|
| 1543 |
+
preferredCol: null,
|
| 1544 |
+
visualLines: [['only line']],
|
| 1545 |
+
visualScrollRow: 0,
|
| 1546 |
+
visualCursor: { row: 0, col: 5 },
|
| 1547 |
+
viewport: { width: 10, height: 5 },
|
| 1548 |
+
undoStack: [],
|
| 1549 |
+
redoStack: [],
|
| 1550 |
+
};
|
| 1551 |
+
|
| 1552 |
+
const action: TextBufferAction = {
|
| 1553 |
+
type: 'vim_delete_line',
|
| 1554 |
+
payload: { count: 1 },
|
| 1555 |
+
};
|
| 1556 |
+
|
| 1557 |
+
const result = textBufferReducer(initialState, action);
|
| 1558 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 1559 |
+
|
| 1560 |
+
// Should clear the line content but keep the line
|
| 1561 |
+
expect(result.lines).toEqual(['']);
|
| 1562 |
+
expect(result.cursorRow).toBe(0);
|
| 1563 |
+
expect(result.cursorCol).toBe(0);
|
| 1564 |
+
});
|
| 1565 |
+
|
| 1566 |
+
it('should handle deleting the last line properly', () => {
|
| 1567 |
+
const initialState: TextBufferState = {
|
| 1568 |
+
lines: ['line1', 'line2'],
|
| 1569 |
+
cursorRow: 1,
|
| 1570 |
+
cursorCol: 0,
|
| 1571 |
+
preferredCol: null,
|
| 1572 |
+
visualLines: [['line1'], ['line2']],
|
| 1573 |
+
visualScrollRow: 0,
|
| 1574 |
+
visualCursor: { row: 1, col: 0 },
|
| 1575 |
+
viewport: { width: 10, height: 5 },
|
| 1576 |
+
undoStack: [],
|
| 1577 |
+
redoStack: [],
|
| 1578 |
+
};
|
| 1579 |
+
|
| 1580 |
+
const action: TextBufferAction = {
|
| 1581 |
+
type: 'vim_delete_line',
|
| 1582 |
+
payload: { count: 1 },
|
| 1583 |
+
};
|
| 1584 |
+
|
| 1585 |
+
const result = textBufferReducer(initialState, action);
|
| 1586 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 1587 |
+
|
| 1588 |
+
// Should delete the last line completely, not leave empty line
|
| 1589 |
+
expect(result.lines).toEqual(['line1']);
|
| 1590 |
+
expect(result.cursorRow).toBe(0);
|
| 1591 |
+
expect(result.cursorCol).toBe(0);
|
| 1592 |
+
});
|
| 1593 |
+
|
| 1594 |
+
it('should handle deleting all lines and maintain valid state for subsequent paste', () => {
|
| 1595 |
+
const initialState: TextBufferState = {
|
| 1596 |
+
lines: ['line1', 'line2', 'line3', 'line4'],
|
| 1597 |
+
cursorRow: 0,
|
| 1598 |
+
cursorCol: 0,
|
| 1599 |
+
preferredCol: null,
|
| 1600 |
+
visualLines: [['line1'], ['line2'], ['line3'], ['line4']],
|
| 1601 |
+
visualScrollRow: 0,
|
| 1602 |
+
visualCursor: { row: 0, col: 0 },
|
| 1603 |
+
viewport: { width: 10, height: 5 },
|
| 1604 |
+
undoStack: [],
|
| 1605 |
+
redoStack: [],
|
| 1606 |
+
};
|
| 1607 |
+
|
| 1608 |
+
// Delete all 4 lines with 4dd
|
| 1609 |
+
const deleteAction: TextBufferAction = {
|
| 1610 |
+
type: 'vim_delete_line',
|
| 1611 |
+
payload: { count: 4 },
|
| 1612 |
+
};
|
| 1613 |
+
|
| 1614 |
+
const afterDelete = textBufferReducer(initialState, deleteAction);
|
| 1615 |
+
expect(afterDelete).toHaveOnlyValidCharacters();
|
| 1616 |
+
|
| 1617 |
+
// After deleting all lines, should have one empty line
|
| 1618 |
+
expect(afterDelete.lines).toEqual(['']);
|
| 1619 |
+
expect(afterDelete.cursorRow).toBe(0);
|
| 1620 |
+
expect(afterDelete.cursorCol).toBe(0);
|
| 1621 |
+
|
| 1622 |
+
// Now paste multiline content - this should work correctly
|
| 1623 |
+
const pasteAction: TextBufferAction = {
|
| 1624 |
+
type: 'insert',
|
| 1625 |
+
payload: 'new1\nnew2\nnew3\nnew4',
|
| 1626 |
+
};
|
| 1627 |
+
|
| 1628 |
+
const afterPaste = textBufferReducer(afterDelete, pasteAction);
|
| 1629 |
+
expect(afterPaste).toHaveOnlyValidCharacters();
|
| 1630 |
+
|
| 1631 |
+
// All lines including the first one should be present
|
| 1632 |
+
expect(afterPaste.lines).toEqual(['new1', 'new2', 'new3', 'new4']);
|
| 1633 |
+
expect(afterPaste.cursorRow).toBe(3);
|
| 1634 |
+
expect(afterPaste.cursorCol).toBe(4);
|
| 1635 |
+
});
|
| 1636 |
+
});
|
| 1637 |
+
});
|
| 1638 |
+
|
| 1639 |
+
describe('Unicode helper functions', () => {
|
| 1640 |
+
describe('findWordEndInLine with Unicode', () => {
|
| 1641 |
+
it('should handle combining characters', () => {
|
| 1642 |
+
// café with combining accent
|
| 1643 |
+
const cafeWithCombining = 'cafe\u0301';
|
| 1644 |
+
const result = findWordEndInLine(cafeWithCombining + ' test', 0);
|
| 1645 |
+
expect(result).toBe(3); // End of 'café' at base character 'e', not combining accent
|
| 1646 |
+
});
|
| 1647 |
+
|
| 1648 |
+
it('should handle precomposed characters with diacritics', () => {
|
| 1649 |
+
// café with precomposed é (U+00E9)
|
| 1650 |
+
const cafePrecomposed = 'café';
|
| 1651 |
+
const result = findWordEndInLine(cafePrecomposed + ' test', 0);
|
| 1652 |
+
expect(result).toBe(3); // End of 'café' at precomposed character 'é'
|
| 1653 |
+
});
|
| 1654 |
+
|
| 1655 |
+
it('should return null when no word end found', () => {
|
| 1656 |
+
const result = findWordEndInLine(' ', 0);
|
| 1657 |
+
expect(result).toBeNull(); // No word end found in whitespace-only string string
|
| 1658 |
+
});
|
| 1659 |
+
});
|
| 1660 |
+
|
| 1661 |
+
describe('findNextWordStartInLine with Unicode', () => {
|
| 1662 |
+
it('should handle right-to-left text', () => {
|
| 1663 |
+
const result = findNextWordStartInLine('hello مرحبا world', 0);
|
| 1664 |
+
expect(result).toBe(6); // Start of Arabic word
|
| 1665 |
+
});
|
| 1666 |
+
|
| 1667 |
+
it('should handle Chinese characters', () => {
|
| 1668 |
+
const result = findNextWordStartInLine('hello 你好 world', 0);
|
| 1669 |
+
expect(result).toBe(6); // Start of Chinese word
|
| 1670 |
+
});
|
| 1671 |
+
|
| 1672 |
+
it('should return null at end of line', () => {
|
| 1673 |
+
const result = findNextWordStartInLine('hello', 10);
|
| 1674 |
+
expect(result).toBeNull();
|
| 1675 |
+
});
|
| 1676 |
+
|
| 1677 |
+
it('should handle combining characters', () => {
|
| 1678 |
+
// café with combining accent + next word
|
| 1679 |
+
const textWithCombining = 'cafe\u0301 test';
|
| 1680 |
+
const result = findNextWordStartInLine(textWithCombining, 0);
|
| 1681 |
+
expect(result).toBe(6); // Start of 'test' after 'café ' (combining char makes string longer)
|
| 1682 |
+
});
|
| 1683 |
+
|
| 1684 |
+
it('should handle precomposed characters with diacritics', () => {
|
| 1685 |
+
// café with precomposed é + next word
|
| 1686 |
+
const textPrecomposed = 'café test';
|
| 1687 |
+
const result = findNextWordStartInLine(textPrecomposed, 0);
|
| 1688 |
+
expect(result).toBe(5); // Start of 'test' after 'café '
|
| 1689 |
+
});
|
| 1690 |
+
});
|
| 1691 |
+
|
| 1692 |
+
describe('isWordCharStrict with Unicode', () => {
|
| 1693 |
+
it('should return true for ASCII word characters', () => {
|
| 1694 |
+
expect(isWordCharStrict('a')).toBe(true);
|
| 1695 |
+
expect(isWordCharStrict('Z')).toBe(true);
|
| 1696 |
+
expect(isWordCharStrict('0')).toBe(true);
|
| 1697 |
+
expect(isWordCharStrict('_')).toBe(true);
|
| 1698 |
+
});
|
| 1699 |
+
|
| 1700 |
+
it('should return false for punctuation', () => {
|
| 1701 |
+
expect(isWordCharStrict('.')).toBe(false);
|
| 1702 |
+
expect(isWordCharStrict(',')).toBe(false);
|
| 1703 |
+
expect(isWordCharStrict('!')).toBe(false);
|
| 1704 |
+
});
|
| 1705 |
+
|
| 1706 |
+
it('should return true for non-Latin scripts', () => {
|
| 1707 |
+
expect(isWordCharStrict('你')).toBe(true); // Chinese character
|
| 1708 |
+
expect(isWordCharStrict('م')).toBe(true); // Arabic character
|
| 1709 |
+
});
|
| 1710 |
+
|
| 1711 |
+
it('should return false for whitespace', () => {
|
| 1712 |
+
expect(isWordCharStrict(' ')).toBe(false);
|
| 1713 |
+
expect(isWordCharStrict('\t')).toBe(false);
|
| 1714 |
+
});
|
| 1715 |
+
});
|
| 1716 |
+
|
| 1717 |
+
describe('cpLen with Unicode', () => {
|
| 1718 |
+
it('should handle combining characters', () => {
|
| 1719 |
+
expect(cpLen('é')).toBe(1); // Precomposed
|
| 1720 |
+
expect(cpLen('e\u0301')).toBe(2); // e + combining acute
|
| 1721 |
+
});
|
| 1722 |
+
|
| 1723 |
+
it('should handle Chinese and Arabic text', () => {
|
| 1724 |
+
expect(cpLen('hello 你好 world')).toBe(14); // 5 + 1 + 2 + 1 + 5 = 14
|
| 1725 |
+
expect(cpLen('hello مرحبا world')).toBe(17);
|
| 1726 |
+
});
|
| 1727 |
+
});
|
| 1728 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/text-buffer.ts
ADDED
|
@@ -0,0 +1,2227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import stripAnsi from 'strip-ansi';
|
| 8 |
+
import { stripVTControlCharacters } from 'util';
|
| 9 |
+
import { spawnSync } from 'child_process';
|
| 10 |
+
import fs from 'fs';
|
| 11 |
+
import os from 'os';
|
| 12 |
+
import pathMod from 'path';
|
| 13 |
+
import { useState, useCallback, useEffect, useMemo, useReducer } from 'react';
|
| 14 |
+
import stringWidth from 'string-width';
|
| 15 |
+
import { unescapePath } from '@qwen-code/qwen-code-core';
|
| 16 |
+
import { toCodePoints, cpLen, cpSlice } from '../../utils/textUtils.js';
|
| 17 |
+
import { handleVimAction, VimAction } from './vim-buffer-actions.js';
|
| 18 |
+
|
| 19 |
+
export type Direction =
|
| 20 |
+
| 'left'
|
| 21 |
+
| 'right'
|
| 22 |
+
| 'up'
|
| 23 |
+
| 'down'
|
| 24 |
+
| 'wordLeft'
|
| 25 |
+
| 'wordRight'
|
| 26 |
+
| 'home'
|
| 27 |
+
| 'end';
|
| 28 |
+
|
| 29 |
+
// Simple helper for word‑wise ops.
|
| 30 |
+
function isWordChar(ch: string | undefined): boolean {
|
| 31 |
+
if (ch === undefined) {
|
| 32 |
+
return false;
|
| 33 |
+
}
|
| 34 |
+
return !/[\s,.;!?]/.test(ch);
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Helper functions for line-based word navigation
|
| 38 |
+
export const isWordCharStrict = (char: string): boolean =>
|
| 39 |
+
/[\w\p{L}\p{N}]/u.test(char); // Matches a single character that is any Unicode letter, any Unicode number, or an underscore
|
| 40 |
+
|
| 41 |
+
export const isWhitespace = (char: string): boolean => /\s/.test(char);
|
| 42 |
+
|
| 43 |
+
// Check if a character is a combining mark (only diacritics for now)
|
| 44 |
+
export const isCombiningMark = (char: string): boolean => /\p{M}/u.test(char);
|
| 45 |
+
|
| 46 |
+
// Check if a character should be considered part of a word (including combining marks)
|
| 47 |
+
export const isWordCharWithCombining = (char: string): boolean =>
|
| 48 |
+
isWordCharStrict(char) || isCombiningMark(char);
|
| 49 |
+
|
| 50 |
+
// Get the script of a character (simplified for common scripts)
|
| 51 |
+
export const getCharScript = (char: string): string => {
|
| 52 |
+
if (/[\p{Script=Latin}]/u.test(char)) return 'latin'; // All Latin script chars including diacritics
|
| 53 |
+
if (/[\p{Script=Han}]/u.test(char)) return 'han'; // Chinese
|
| 54 |
+
if (/[\p{Script=Arabic}]/u.test(char)) return 'arabic';
|
| 55 |
+
if (/[\p{Script=Hiragana}]/u.test(char)) return 'hiragana';
|
| 56 |
+
if (/[\p{Script=Katakana}]/u.test(char)) return 'katakana';
|
| 57 |
+
if (/[\p{Script=Cyrillic}]/u.test(char)) return 'cyrillic';
|
| 58 |
+
return 'other';
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
// Check if two characters are from different scripts (indicating word boundary)
|
| 62 |
+
export const isDifferentScript = (char1: string, char2: string): boolean => {
|
| 63 |
+
if (!isWordCharStrict(char1) || !isWordCharStrict(char2)) return false;
|
| 64 |
+
return getCharScript(char1) !== getCharScript(char2);
|
| 65 |
+
};
|
| 66 |
+
|
| 67 |
+
// Find next word start within a line, starting from col
|
| 68 |
+
export const findNextWordStartInLine = (
|
| 69 |
+
line: string,
|
| 70 |
+
col: number,
|
| 71 |
+
): number | null => {
|
| 72 |
+
const chars = toCodePoints(line);
|
| 73 |
+
let i = col;
|
| 74 |
+
|
| 75 |
+
if (i >= chars.length) return null;
|
| 76 |
+
|
| 77 |
+
const currentChar = chars[i];
|
| 78 |
+
|
| 79 |
+
// Skip current word/sequence based on character type
|
| 80 |
+
if (isWordCharStrict(currentChar)) {
|
| 81 |
+
while (i < chars.length && isWordCharWithCombining(chars[i])) {
|
| 82 |
+
// Check for script boundary - if next character is from different script, stop here
|
| 83 |
+
if (
|
| 84 |
+
i + 1 < chars.length &&
|
| 85 |
+
isWordCharStrict(chars[i + 1]) &&
|
| 86 |
+
isDifferentScript(chars[i], chars[i + 1])
|
| 87 |
+
) {
|
| 88 |
+
i++; // Include current character
|
| 89 |
+
break; // Stop at script boundary
|
| 90 |
+
}
|
| 91 |
+
i++;
|
| 92 |
+
}
|
| 93 |
+
} else if (!isWhitespace(currentChar)) {
|
| 94 |
+
while (
|
| 95 |
+
i < chars.length &&
|
| 96 |
+
!isWordCharStrict(chars[i]) &&
|
| 97 |
+
!isWhitespace(chars[i])
|
| 98 |
+
) {
|
| 99 |
+
i++;
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
// Skip whitespace
|
| 104 |
+
while (i < chars.length && isWhitespace(chars[i])) {
|
| 105 |
+
i++;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
return i < chars.length ? i : null;
|
| 109 |
+
};
|
| 110 |
+
|
| 111 |
+
// Find previous word start within a line
|
| 112 |
+
export const findPrevWordStartInLine = (
|
| 113 |
+
line: string,
|
| 114 |
+
col: number,
|
| 115 |
+
): number | null => {
|
| 116 |
+
const chars = toCodePoints(line);
|
| 117 |
+
let i = col;
|
| 118 |
+
|
| 119 |
+
if (i <= 0) return null;
|
| 120 |
+
|
| 121 |
+
i--;
|
| 122 |
+
|
| 123 |
+
// Skip whitespace moving backwards
|
| 124 |
+
while (i >= 0 && isWhitespace(chars[i])) {
|
| 125 |
+
i--;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
if (i < 0) return null;
|
| 129 |
+
|
| 130 |
+
if (isWordCharStrict(chars[i])) {
|
| 131 |
+
// We're in a word, move to its beginning
|
| 132 |
+
while (i >= 0 && isWordCharStrict(chars[i])) {
|
| 133 |
+
// Check for script boundary - if previous character is from different script, stop here
|
| 134 |
+
if (
|
| 135 |
+
i - 1 >= 0 &&
|
| 136 |
+
isWordCharStrict(chars[i - 1]) &&
|
| 137 |
+
isDifferentScript(chars[i], chars[i - 1])
|
| 138 |
+
) {
|
| 139 |
+
return i; // Return current position at script boundary
|
| 140 |
+
}
|
| 141 |
+
i--;
|
| 142 |
+
}
|
| 143 |
+
return i + 1;
|
| 144 |
+
} else {
|
| 145 |
+
// We're in punctuation, move to its beginning
|
| 146 |
+
while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
|
| 147 |
+
i--;
|
| 148 |
+
}
|
| 149 |
+
return i + 1;
|
| 150 |
+
}
|
| 151 |
+
};
|
| 152 |
+
|
| 153 |
+
// Find word end within a line
|
| 154 |
+
export const findWordEndInLine = (line: string, col: number): number | null => {
|
| 155 |
+
const chars = toCodePoints(line);
|
| 156 |
+
let i = col;
|
| 157 |
+
|
| 158 |
+
// If we're already at the end of a word (including punctuation sequences), advance to next word
|
| 159 |
+
// This includes both regular word endings and script boundaries
|
| 160 |
+
const atEndOfWordChar =
|
| 161 |
+
i < chars.length &&
|
| 162 |
+
isWordCharWithCombining(chars[i]) &&
|
| 163 |
+
(i + 1 >= chars.length ||
|
| 164 |
+
!isWordCharWithCombining(chars[i + 1]) ||
|
| 165 |
+
(isWordCharStrict(chars[i]) &&
|
| 166 |
+
i + 1 < chars.length &&
|
| 167 |
+
isWordCharStrict(chars[i + 1]) &&
|
| 168 |
+
isDifferentScript(chars[i], chars[i + 1])));
|
| 169 |
+
|
| 170 |
+
const atEndOfPunctuation =
|
| 171 |
+
i < chars.length &&
|
| 172 |
+
!isWordCharWithCombining(chars[i]) &&
|
| 173 |
+
!isWhitespace(chars[i]) &&
|
| 174 |
+
(i + 1 >= chars.length ||
|
| 175 |
+
isWhitespace(chars[i + 1]) ||
|
| 176 |
+
isWordCharWithCombining(chars[i + 1]));
|
| 177 |
+
|
| 178 |
+
if (atEndOfWordChar || atEndOfPunctuation) {
|
| 179 |
+
// We're at the end of a word or punctuation sequence, move forward to find next word
|
| 180 |
+
i++;
|
| 181 |
+
// Skip whitespace to find next word or punctuation
|
| 182 |
+
while (i < chars.length && isWhitespace(chars[i])) {
|
| 183 |
+
i++;
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
// If we're not on a word character, find the next word or punctuation sequence
|
| 188 |
+
if (i < chars.length && !isWordCharWithCombining(chars[i])) {
|
| 189 |
+
// Skip whitespace to find next word or punctuation
|
| 190 |
+
while (i < chars.length && isWhitespace(chars[i])) {
|
| 191 |
+
i++;
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// Move to end of current word (including combining marks, but stop at script boundaries)
|
| 196 |
+
let foundWord = false;
|
| 197 |
+
let lastBaseCharPos = -1;
|
| 198 |
+
|
| 199 |
+
if (i < chars.length && isWordCharWithCombining(chars[i])) {
|
| 200 |
+
// Handle word characters
|
| 201 |
+
while (i < chars.length && isWordCharWithCombining(chars[i])) {
|
| 202 |
+
foundWord = true;
|
| 203 |
+
|
| 204 |
+
// Track the position of the last base character (not combining mark)
|
| 205 |
+
if (isWordCharStrict(chars[i])) {
|
| 206 |
+
lastBaseCharPos = i;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// Check if next character is from a different script (word boundary)
|
| 210 |
+
if (
|
| 211 |
+
i + 1 < chars.length &&
|
| 212 |
+
isWordCharStrict(chars[i + 1]) &&
|
| 213 |
+
isDifferentScript(chars[i], chars[i + 1])
|
| 214 |
+
) {
|
| 215 |
+
i++; // Include current character
|
| 216 |
+
if (isWordCharStrict(chars[i - 1])) {
|
| 217 |
+
lastBaseCharPos = i - 1;
|
| 218 |
+
}
|
| 219 |
+
break; // Stop at script boundary
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
i++;
|
| 223 |
+
}
|
| 224 |
+
} else if (i < chars.length && !isWhitespace(chars[i])) {
|
| 225 |
+
// Handle punctuation sequences (like ████)
|
| 226 |
+
while (
|
| 227 |
+
i < chars.length &&
|
| 228 |
+
!isWordCharStrict(chars[i]) &&
|
| 229 |
+
!isWhitespace(chars[i])
|
| 230 |
+
) {
|
| 231 |
+
foundWord = true;
|
| 232 |
+
lastBaseCharPos = i;
|
| 233 |
+
i++;
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
// Only return a position if we actually found a word
|
| 238 |
+
// Return the position of the last base character, not combining marks
|
| 239 |
+
if (foundWord && lastBaseCharPos >= col) {
|
| 240 |
+
return lastBaseCharPos;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
return null;
|
| 244 |
+
};
|
| 245 |
+
|
| 246 |
+
// Find next word across lines
|
| 247 |
+
export const findNextWordAcrossLines = (
|
| 248 |
+
lines: string[],
|
| 249 |
+
cursorRow: number,
|
| 250 |
+
cursorCol: number,
|
| 251 |
+
searchForWordStart: boolean,
|
| 252 |
+
): { row: number; col: number } | null => {
|
| 253 |
+
// First try current line
|
| 254 |
+
const currentLine = lines[cursorRow] || '';
|
| 255 |
+
const colInCurrentLine = searchForWordStart
|
| 256 |
+
? findNextWordStartInLine(currentLine, cursorCol)
|
| 257 |
+
: findWordEndInLine(currentLine, cursorCol);
|
| 258 |
+
|
| 259 |
+
if (colInCurrentLine !== null) {
|
| 260 |
+
return { row: cursorRow, col: colInCurrentLine };
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
// Search subsequent lines
|
| 264 |
+
for (let row = cursorRow + 1; row < lines.length; row++) {
|
| 265 |
+
const line = lines[row] || '';
|
| 266 |
+
const chars = toCodePoints(line);
|
| 267 |
+
|
| 268 |
+
// For empty lines, if we haven't found any words yet, return the empty line
|
| 269 |
+
if (chars.length === 0) {
|
| 270 |
+
// Check if there are any words in remaining lines
|
| 271 |
+
let hasWordsInLaterLines = false;
|
| 272 |
+
for (let laterRow = row + 1; laterRow < lines.length; laterRow++) {
|
| 273 |
+
const laterLine = lines[laterRow] || '';
|
| 274 |
+
const laterChars = toCodePoints(laterLine);
|
| 275 |
+
let firstNonWhitespace = 0;
|
| 276 |
+
while (
|
| 277 |
+
firstNonWhitespace < laterChars.length &&
|
| 278 |
+
isWhitespace(laterChars[firstNonWhitespace])
|
| 279 |
+
) {
|
| 280 |
+
firstNonWhitespace++;
|
| 281 |
+
}
|
| 282 |
+
if (firstNonWhitespace < laterChars.length) {
|
| 283 |
+
hasWordsInLaterLines = true;
|
| 284 |
+
break;
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
// If no words in later lines, return the empty line
|
| 289 |
+
if (!hasWordsInLaterLines) {
|
| 290 |
+
return { row, col: 0 };
|
| 291 |
+
}
|
| 292 |
+
continue;
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
// Find first non-whitespace
|
| 296 |
+
let firstNonWhitespace = 0;
|
| 297 |
+
while (
|
| 298 |
+
firstNonWhitespace < chars.length &&
|
| 299 |
+
isWhitespace(chars[firstNonWhitespace])
|
| 300 |
+
) {
|
| 301 |
+
firstNonWhitespace++;
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
if (firstNonWhitespace < chars.length) {
|
| 305 |
+
if (searchForWordStart) {
|
| 306 |
+
return { row, col: firstNonWhitespace };
|
| 307 |
+
} else {
|
| 308 |
+
// For word end, find the end of the first word
|
| 309 |
+
const endCol = findWordEndInLine(line, firstNonWhitespace);
|
| 310 |
+
if (endCol !== null) {
|
| 311 |
+
return { row, col: endCol };
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
return null;
|
| 318 |
+
};
|
| 319 |
+
|
| 320 |
+
// Find previous word across lines
|
| 321 |
+
export const findPrevWordAcrossLines = (
|
| 322 |
+
lines: string[],
|
| 323 |
+
cursorRow: number,
|
| 324 |
+
cursorCol: number,
|
| 325 |
+
): { row: number; col: number } | null => {
|
| 326 |
+
// First try current line
|
| 327 |
+
const currentLine = lines[cursorRow] || '';
|
| 328 |
+
const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);
|
| 329 |
+
|
| 330 |
+
if (colInCurrentLine !== null) {
|
| 331 |
+
return { row: cursorRow, col: colInCurrentLine };
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
// Search previous lines
|
| 335 |
+
for (let row = cursorRow - 1; row >= 0; row--) {
|
| 336 |
+
const line = lines[row] || '';
|
| 337 |
+
const chars = toCodePoints(line);
|
| 338 |
+
|
| 339 |
+
if (chars.length === 0) continue;
|
| 340 |
+
|
| 341 |
+
// Find last word start
|
| 342 |
+
let lastWordStart = chars.length;
|
| 343 |
+
while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
|
| 344 |
+
lastWordStart--;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
if (lastWordStart > 0) {
|
| 348 |
+
// Find start of this word
|
| 349 |
+
const wordStart = findPrevWordStartInLine(line, lastWordStart);
|
| 350 |
+
if (wordStart !== null) {
|
| 351 |
+
return { row, col: wordStart };
|
| 352 |
+
}
|
| 353 |
+
}
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
return null;
|
| 357 |
+
};
|
| 358 |
+
|
| 359 |
+
// Helper functions for vim line operations
|
| 360 |
+
export const getPositionFromOffsets = (
|
| 361 |
+
startOffset: number,
|
| 362 |
+
endOffset: number,
|
| 363 |
+
lines: string[],
|
| 364 |
+
) => {
|
| 365 |
+
let offset = 0;
|
| 366 |
+
let startRow = 0;
|
| 367 |
+
let startCol = 0;
|
| 368 |
+
let endRow = 0;
|
| 369 |
+
let endCol = 0;
|
| 370 |
+
|
| 371 |
+
// Find start position
|
| 372 |
+
for (let i = 0; i < lines.length; i++) {
|
| 373 |
+
const lineLength = lines[i].length + 1; // +1 for newline
|
| 374 |
+
if (offset + lineLength > startOffset) {
|
| 375 |
+
startRow = i;
|
| 376 |
+
startCol = startOffset - offset;
|
| 377 |
+
break;
|
| 378 |
+
}
|
| 379 |
+
offset += lineLength;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
// Find end position
|
| 383 |
+
offset = 0;
|
| 384 |
+
for (let i = 0; i < lines.length; i++) {
|
| 385 |
+
const lineLength = lines[i].length + (i < lines.length - 1 ? 1 : 0); // +1 for newline except last line
|
| 386 |
+
if (offset + lineLength >= endOffset) {
|
| 387 |
+
endRow = i;
|
| 388 |
+
endCol = endOffset - offset;
|
| 389 |
+
break;
|
| 390 |
+
}
|
| 391 |
+
offset += lineLength;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
return { startRow, startCol, endRow, endCol };
|
| 395 |
+
};
|
| 396 |
+
|
| 397 |
+
export const getLineRangeOffsets = (
|
| 398 |
+
startRow: number,
|
| 399 |
+
lineCount: number,
|
| 400 |
+
lines: string[],
|
| 401 |
+
) => {
|
| 402 |
+
let startOffset = 0;
|
| 403 |
+
|
| 404 |
+
// Calculate start offset
|
| 405 |
+
for (let i = 0; i < startRow; i++) {
|
| 406 |
+
startOffset += lines[i].length + 1; // +1 for newline
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
// Calculate end offset
|
| 410 |
+
let endOffset = startOffset;
|
| 411 |
+
for (let i = 0; i < lineCount; i++) {
|
| 412 |
+
const lineIndex = startRow + i;
|
| 413 |
+
if (lineIndex < lines.length) {
|
| 414 |
+
endOffset += lines[lineIndex].length;
|
| 415 |
+
if (lineIndex < lines.length - 1) {
|
| 416 |
+
endOffset += 1; // +1 for newline
|
| 417 |
+
}
|
| 418 |
+
}
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
return { startOffset, endOffset };
|
| 422 |
+
};
|
| 423 |
+
|
| 424 |
+
export const replaceRangeInternal = (
|
| 425 |
+
state: TextBufferState,
|
| 426 |
+
startRow: number,
|
| 427 |
+
startCol: number,
|
| 428 |
+
endRow: number,
|
| 429 |
+
endCol: number,
|
| 430 |
+
text: string,
|
| 431 |
+
): TextBufferState => {
|
| 432 |
+
const currentLine = (row: number) => state.lines[row] || '';
|
| 433 |
+
const currentLineLen = (row: number) => cpLen(currentLine(row));
|
| 434 |
+
const clamp = (value: number, min: number, max: number) =>
|
| 435 |
+
Math.min(Math.max(value, min), max);
|
| 436 |
+
|
| 437 |
+
if (
|
| 438 |
+
startRow > endRow ||
|
| 439 |
+
(startRow === endRow && startCol > endCol) ||
|
| 440 |
+
startRow < 0 ||
|
| 441 |
+
startCol < 0 ||
|
| 442 |
+
endRow >= state.lines.length ||
|
| 443 |
+
(endRow < state.lines.length && endCol > currentLineLen(endRow))
|
| 444 |
+
) {
|
| 445 |
+
return state; // Invalid range
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
const newLines = [...state.lines];
|
| 449 |
+
|
| 450 |
+
const sCol = clamp(startCol, 0, currentLineLen(startRow));
|
| 451 |
+
const eCol = clamp(endCol, 0, currentLineLen(endRow));
|
| 452 |
+
|
| 453 |
+
const prefix = cpSlice(currentLine(startRow), 0, sCol);
|
| 454 |
+
const suffix = cpSlice(currentLine(endRow), eCol);
|
| 455 |
+
|
| 456 |
+
const normalisedReplacement = text
|
| 457 |
+
.replace(/\r\n/g, '\n')
|
| 458 |
+
.replace(/\r/g, '\n');
|
| 459 |
+
const replacementParts = normalisedReplacement.split('\n');
|
| 460 |
+
|
| 461 |
+
// The combined first line of the new text
|
| 462 |
+
const firstLine = prefix + replacementParts[0];
|
| 463 |
+
|
| 464 |
+
if (replacementParts.length === 1) {
|
| 465 |
+
// No newlines in replacement: combine prefix, replacement, and suffix on one line.
|
| 466 |
+
newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
|
| 467 |
+
} else {
|
| 468 |
+
// Newlines in replacement: create new lines.
|
| 469 |
+
const lastLine = replacementParts[replacementParts.length - 1] + suffix;
|
| 470 |
+
const middleLines = replacementParts.slice(1, -1);
|
| 471 |
+
newLines.splice(
|
| 472 |
+
startRow,
|
| 473 |
+
endRow - startRow + 1,
|
| 474 |
+
firstLine,
|
| 475 |
+
...middleLines,
|
| 476 |
+
lastLine,
|
| 477 |
+
);
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
const finalCursorRow = startRow + replacementParts.length - 1;
|
| 481 |
+
const finalCursorCol =
|
| 482 |
+
(replacementParts.length > 1 ? 0 : sCol) +
|
| 483 |
+
cpLen(replacementParts[replacementParts.length - 1]);
|
| 484 |
+
|
| 485 |
+
return {
|
| 486 |
+
...state,
|
| 487 |
+
lines: newLines,
|
| 488 |
+
cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
|
| 489 |
+
cursorCol: Math.max(
|
| 490 |
+
0,
|
| 491 |
+
Math.min(finalCursorCol, cpLen(newLines[finalCursorRow] || '')),
|
| 492 |
+
),
|
| 493 |
+
preferredCol: null,
|
| 494 |
+
};
|
| 495 |
+
};
|
| 496 |
+
|
| 497 |
+
/**
|
| 498 |
+
* Strip characters that can break terminal rendering.
|
| 499 |
+
*
|
| 500 |
+
* Uses Node.js built-in stripVTControlCharacters to handle VT sequences,
|
| 501 |
+
* then filters remaining control characters that can disrupt display.
|
| 502 |
+
*
|
| 503 |
+
* Characters stripped:
|
| 504 |
+
* - ANSI escape sequences (via strip-ansi)
|
| 505 |
+
* - VT control sequences (via Node.js util.stripVTControlCharacters)
|
| 506 |
+
* - C0 control chars (0x00-0x1F) except CR/LF which are handled elsewhere
|
| 507 |
+
* - C1 control chars (0x80-0x9F) that can cause display issues
|
| 508 |
+
*
|
| 509 |
+
* Characters preserved:
|
| 510 |
+
* - All printable Unicode including emojis
|
| 511 |
+
* - DEL (0x7F) - handled functionally by applyOperations, not a display issue
|
| 512 |
+
* - CR/LF (0x0D/0x0A) - needed for line breaks
|
| 513 |
+
*/
|
| 514 |
+
function stripUnsafeCharacters(str: string): string {
|
| 515 |
+
const strippedAnsi = stripAnsi(str);
|
| 516 |
+
const strippedVT = stripVTControlCharacters(strippedAnsi);
|
| 517 |
+
|
| 518 |
+
return toCodePoints(strippedVT)
|
| 519 |
+
.filter((char) => {
|
| 520 |
+
const code = char.codePointAt(0);
|
| 521 |
+
if (code === undefined) return false;
|
| 522 |
+
|
| 523 |
+
// Preserve CR/LF for line handling
|
| 524 |
+
if (code === 0x0a || code === 0x0d) return true;
|
| 525 |
+
|
| 526 |
+
// Remove C0 control chars (except CR/LF) that can break display
|
| 527 |
+
// Examples: BELL(0x07) makes noise, BS(0x08) moves cursor, VT(0x0B), FF(0x0C)
|
| 528 |
+
if (code >= 0x00 && code <= 0x1f) return false;
|
| 529 |
+
|
| 530 |
+
// Remove C1 control chars (0x80-0x9F) - legacy 8-bit control codes
|
| 531 |
+
if (code >= 0x80 && code <= 0x9f) return false;
|
| 532 |
+
|
| 533 |
+
// Preserve DEL (0x7F) - it's handled functionally by applyOperations as backspace
|
| 534 |
+
// and doesn't cause rendering issues when displayed
|
| 535 |
+
|
| 536 |
+
// Preserve all other characters including Unicode/emojis
|
| 537 |
+
return true;
|
| 538 |
+
})
|
| 539 |
+
.join('');
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
export interface Viewport {
|
| 543 |
+
height: number;
|
| 544 |
+
width: number;
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
function clamp(v: number, min: number, max: number): number {
|
| 548 |
+
return v < min ? min : v > max ? max : v;
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
/* ────────────────────────────────────────────────────────────────────────── */
|
| 552 |
+
|
| 553 |
+
interface UseTextBufferProps {
|
| 554 |
+
initialText?: string;
|
| 555 |
+
initialCursorOffset?: number;
|
| 556 |
+
viewport: Viewport; // Viewport dimensions needed for scrolling
|
| 557 |
+
stdin?: NodeJS.ReadStream | null; // For external editor
|
| 558 |
+
setRawMode?: (mode: boolean) => void; // For external editor
|
| 559 |
+
onChange?: (text: string) => void; // Callback for when text changes
|
| 560 |
+
isValidPath: (path: string) => boolean;
|
| 561 |
+
shellModeActive?: boolean; // Whether the text buffer is in shell mode
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
interface UndoHistoryEntry {
|
| 565 |
+
lines: string[];
|
| 566 |
+
cursorRow: number;
|
| 567 |
+
cursorCol: number;
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
function calculateInitialCursorPosition(
|
| 571 |
+
initialLines: string[],
|
| 572 |
+
offset: number,
|
| 573 |
+
): [number, number] {
|
| 574 |
+
let remainingChars = offset;
|
| 575 |
+
let row = 0;
|
| 576 |
+
while (row < initialLines.length) {
|
| 577 |
+
const lineLength = cpLen(initialLines[row]);
|
| 578 |
+
// Add 1 for the newline character (except for the last line)
|
| 579 |
+
const totalCharsInLineAndNewline =
|
| 580 |
+
lineLength + (row < initialLines.length - 1 ? 1 : 0);
|
| 581 |
+
|
| 582 |
+
if (remainingChars <= lineLength) {
|
| 583 |
+
// Cursor is on this line
|
| 584 |
+
return [row, remainingChars];
|
| 585 |
+
}
|
| 586 |
+
remainingChars -= totalCharsInLineAndNewline;
|
| 587 |
+
row++;
|
| 588 |
+
}
|
| 589 |
+
// Offset is beyond the text, place cursor at the end of the last line
|
| 590 |
+
if (initialLines.length > 0) {
|
| 591 |
+
const lastRow = initialLines.length - 1;
|
| 592 |
+
return [lastRow, cpLen(initialLines[lastRow])];
|
| 593 |
+
}
|
| 594 |
+
return [0, 0]; // Default for empty text
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
export function offsetToLogicalPos(
|
| 598 |
+
text: string,
|
| 599 |
+
offset: number,
|
| 600 |
+
): [number, number] {
|
| 601 |
+
let row = 0;
|
| 602 |
+
let col = 0;
|
| 603 |
+
let currentOffset = 0;
|
| 604 |
+
|
| 605 |
+
if (offset === 0) return [0, 0];
|
| 606 |
+
|
| 607 |
+
const lines = text.split('\n');
|
| 608 |
+
for (let i = 0; i < lines.length; i++) {
|
| 609 |
+
const line = lines[i];
|
| 610 |
+
const lineLength = cpLen(line);
|
| 611 |
+
const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
|
| 612 |
+
|
| 613 |
+
if (offset <= currentOffset + lineLength) {
|
| 614 |
+
// Check against lineLength first
|
| 615 |
+
row = i;
|
| 616 |
+
col = offset - currentOffset;
|
| 617 |
+
return [row, col];
|
| 618 |
+
} else if (offset <= currentOffset + lineLengthWithNewline) {
|
| 619 |
+
// Check if offset is the newline itself
|
| 620 |
+
row = i;
|
| 621 |
+
col = lineLength; // Position cursor at the end of the current line content
|
| 622 |
+
// If the offset IS the newline, and it's not the last line, advance to next line, col 0
|
| 623 |
+
if (
|
| 624 |
+
offset === currentOffset + lineLengthWithNewline &&
|
| 625 |
+
i < lines.length - 1
|
| 626 |
+
) {
|
| 627 |
+
return [i + 1, 0];
|
| 628 |
+
}
|
| 629 |
+
return [row, col]; // Otherwise, it's at the end of the current line content
|
| 630 |
+
}
|
| 631 |
+
currentOffset += lineLengthWithNewline;
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
// If offset is beyond the text length, place cursor at the end of the last line
|
| 635 |
+
// or [0,0] if text is empty
|
| 636 |
+
if (lines.length > 0) {
|
| 637 |
+
row = lines.length - 1;
|
| 638 |
+
col = cpLen(lines[row]);
|
| 639 |
+
} else {
|
| 640 |
+
row = 0;
|
| 641 |
+
col = 0;
|
| 642 |
+
}
|
| 643 |
+
return [row, col];
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
/**
|
| 647 |
+
* Converts logical row/col position to absolute text offset
|
| 648 |
+
* Inverse operation of offsetToLogicalPos
|
| 649 |
+
*/
|
| 650 |
+
export function logicalPosToOffset(
|
| 651 |
+
lines: string[],
|
| 652 |
+
row: number,
|
| 653 |
+
col: number,
|
| 654 |
+
): number {
|
| 655 |
+
let offset = 0;
|
| 656 |
+
|
| 657 |
+
// Clamp row to valid range
|
| 658 |
+
const actualRow = Math.min(row, lines.length - 1);
|
| 659 |
+
|
| 660 |
+
// Add lengths of all lines before the target row
|
| 661 |
+
for (let i = 0; i < actualRow; i++) {
|
| 662 |
+
offset += cpLen(lines[i]) + 1; // +1 for newline
|
| 663 |
+
}
|
| 664 |
+
|
| 665 |
+
// Add column offset within the target row
|
| 666 |
+
if (actualRow >= 0 && actualRow < lines.length) {
|
| 667 |
+
offset += Math.min(col, cpLen(lines[actualRow]));
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
return offset;
|
| 671 |
+
}
|
| 672 |
+
|
| 673 |
+
// Helper to calculate visual lines and map cursor positions
|
| 674 |
+
function calculateVisualLayout(
|
| 675 |
+
logicalLines: string[],
|
| 676 |
+
logicalCursor: [number, number],
|
| 677 |
+
viewportWidth: number,
|
| 678 |
+
): {
|
| 679 |
+
visualLines: string[];
|
| 680 |
+
visualCursor: [number, number];
|
| 681 |
+
logicalToVisualMap: Array<Array<[number, number]>>; // For each logical line, an array of [visualLineIndex, startColInLogical]
|
| 682 |
+
visualToLogicalMap: Array<[number, number]>; // For each visual line, its [logicalLineIndex, startColInLogical]
|
| 683 |
+
} {
|
| 684 |
+
const visualLines: string[] = [];
|
| 685 |
+
const logicalToVisualMap: Array<Array<[number, number]>> = [];
|
| 686 |
+
const visualToLogicalMap: Array<[number, number]> = [];
|
| 687 |
+
let currentVisualCursor: [number, number] = [0, 0];
|
| 688 |
+
|
| 689 |
+
logicalLines.forEach((logLine, logIndex) => {
|
| 690 |
+
logicalToVisualMap[logIndex] = [];
|
| 691 |
+
if (logLine.length === 0) {
|
| 692 |
+
// Handle empty logical line
|
| 693 |
+
logicalToVisualMap[logIndex].push([visualLines.length, 0]);
|
| 694 |
+
visualToLogicalMap.push([logIndex, 0]);
|
| 695 |
+
visualLines.push('');
|
| 696 |
+
if (logIndex === logicalCursor[0] && logicalCursor[1] === 0) {
|
| 697 |
+
currentVisualCursor = [visualLines.length - 1, 0];
|
| 698 |
+
}
|
| 699 |
+
} else {
|
| 700 |
+
// Non-empty logical line
|
| 701 |
+
let currentPosInLogLine = 0; // Tracks position within the current logical line (code point index)
|
| 702 |
+
const codePointsInLogLine = toCodePoints(logLine);
|
| 703 |
+
|
| 704 |
+
while (currentPosInLogLine < codePointsInLogLine.length) {
|
| 705 |
+
let currentChunk = '';
|
| 706 |
+
let currentChunkVisualWidth = 0;
|
| 707 |
+
let numCodePointsInChunk = 0;
|
| 708 |
+
let lastWordBreakPoint = -1; // Index in codePointsInLogLine for word break
|
| 709 |
+
let numCodePointsAtLastWordBreak = 0;
|
| 710 |
+
|
| 711 |
+
// Iterate through code points to build the current visual line (chunk)
|
| 712 |
+
for (let i = currentPosInLogLine; i < codePointsInLogLine.length; i++) {
|
| 713 |
+
const char = codePointsInLogLine[i];
|
| 714 |
+
const charVisualWidth = stringWidth(char);
|
| 715 |
+
|
| 716 |
+
if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
|
| 717 |
+
// Character would exceed viewport width
|
| 718 |
+
if (
|
| 719 |
+
lastWordBreakPoint !== -1 &&
|
| 720 |
+
numCodePointsAtLastWordBreak > 0 &&
|
| 721 |
+
currentPosInLogLine + numCodePointsAtLastWordBreak < i
|
| 722 |
+
) {
|
| 723 |
+
// We have a valid word break point to use, and it's not the start of the current segment
|
| 724 |
+
currentChunk = codePointsInLogLine
|
| 725 |
+
.slice(
|
| 726 |
+
currentPosInLogLine,
|
| 727 |
+
currentPosInLogLine + numCodePointsAtLastWordBreak,
|
| 728 |
+
)
|
| 729 |
+
.join('');
|
| 730 |
+
numCodePointsInChunk = numCodePointsAtLastWordBreak;
|
| 731 |
+
} else {
|
| 732 |
+
// No word break, or word break is at the start of this potential chunk, or word break leads to empty chunk.
|
| 733 |
+
// Hard break: take characters up to viewportWidth, or just the current char if it alone is too wide.
|
| 734 |
+
if (
|
| 735 |
+
numCodePointsInChunk === 0 &&
|
| 736 |
+
charVisualWidth > viewportWidth
|
| 737 |
+
) {
|
| 738 |
+
// Single character is wider than viewport, take it anyway
|
| 739 |
+
currentChunk = char;
|
| 740 |
+
numCodePointsInChunk = 1;
|
| 741 |
+
} else if (
|
| 742 |
+
numCodePointsInChunk === 0 &&
|
| 743 |
+
charVisualWidth <= viewportWidth
|
| 744 |
+
) {
|
| 745 |
+
// This case should ideally be caught by the next iteration if the char fits.
|
| 746 |
+
// If it doesn't fit (because currentChunkVisualWidth was already > 0 from a previous char that filled the line),
|
| 747 |
+
// then numCodePointsInChunk would not be 0.
|
| 748 |
+
// This branch means the current char *itself* doesn't fit an empty line, which is handled by the above.
|
| 749 |
+
// If we are here, it means the loop should break and the current chunk (which is empty) is finalized.
|
| 750 |
+
}
|
| 751 |
+
}
|
| 752 |
+
break; // Break from inner loop to finalize this chunk
|
| 753 |
+
}
|
| 754 |
+
|
| 755 |
+
currentChunk += char;
|
| 756 |
+
currentChunkVisualWidth += charVisualWidth;
|
| 757 |
+
numCodePointsInChunk++;
|
| 758 |
+
|
| 759 |
+
// Check for word break opportunity (space)
|
| 760 |
+
if (char === ' ') {
|
| 761 |
+
lastWordBreakPoint = i; // Store code point index of the space
|
| 762 |
+
// Store the state *before* adding the space, if we decide to break here.
|
| 763 |
+
numCodePointsAtLastWordBreak = numCodePointsInChunk - 1; // Chars *before* the space
|
| 764 |
+
}
|
| 765 |
+
}
|
| 766 |
+
|
| 767 |
+
// If the inner loop completed without breaking (i.e., remaining text fits)
|
| 768 |
+
// or if the loop broke but numCodePointsInChunk is still 0 (e.g. first char too wide for empty line)
|
| 769 |
+
if (
|
| 770 |
+
numCodePointsInChunk === 0 &&
|
| 771 |
+
currentPosInLogLine < codePointsInLogLine.length
|
| 772 |
+
) {
|
| 773 |
+
// This can happen if the very first character considered for a new visual line is wider than the viewport.
|
| 774 |
+
// In this case, we take that single character.
|
| 775 |
+
const firstChar = codePointsInLogLine[currentPosInLogLine];
|
| 776 |
+
currentChunk = firstChar;
|
| 777 |
+
numCodePointsInChunk = 1; // Ensure we advance
|
| 778 |
+
}
|
| 779 |
+
|
| 780 |
+
// If after everything, numCodePointsInChunk is still 0 but we haven't processed the whole logical line,
|
| 781 |
+
// it implies an issue, like viewportWidth being 0 or less. Avoid infinite loop.
|
| 782 |
+
if (
|
| 783 |
+
numCodePointsInChunk === 0 &&
|
| 784 |
+
currentPosInLogLine < codePointsInLogLine.length
|
| 785 |
+
) {
|
| 786 |
+
// Force advance by one character to prevent infinite loop if something went wrong
|
| 787 |
+
currentChunk = codePointsInLogLine[currentPosInLogLine];
|
| 788 |
+
numCodePointsInChunk = 1;
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
logicalToVisualMap[logIndex].push([
|
| 792 |
+
visualLines.length,
|
| 793 |
+
currentPosInLogLine,
|
| 794 |
+
]);
|
| 795 |
+
visualToLogicalMap.push([logIndex, currentPosInLogLine]);
|
| 796 |
+
visualLines.push(currentChunk);
|
| 797 |
+
|
| 798 |
+
// Cursor mapping logic
|
| 799 |
+
// Note: currentPosInLogLine here is the start of the currentChunk within the logical line.
|
| 800 |
+
if (logIndex === logicalCursor[0]) {
|
| 801 |
+
const cursorLogCol = logicalCursor[1]; // This is a code point index
|
| 802 |
+
if (
|
| 803 |
+
cursorLogCol >= currentPosInLogLine &&
|
| 804 |
+
cursorLogCol < currentPosInLogLine + numCodePointsInChunk // Cursor is within this chunk
|
| 805 |
+
) {
|
| 806 |
+
currentVisualCursor = [
|
| 807 |
+
visualLines.length - 1,
|
| 808 |
+
cursorLogCol - currentPosInLogLine, // Visual col is also code point index within visual line
|
| 809 |
+
];
|
| 810 |
+
} else if (
|
| 811 |
+
cursorLogCol === currentPosInLogLine + numCodePointsInChunk &&
|
| 812 |
+
numCodePointsInChunk > 0
|
| 813 |
+
) {
|
| 814 |
+
// Cursor is exactly at the end of this non-empty chunk
|
| 815 |
+
currentVisualCursor = [
|
| 816 |
+
visualLines.length - 1,
|
| 817 |
+
numCodePointsInChunk,
|
| 818 |
+
];
|
| 819 |
+
}
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
const logicalStartOfThisChunk = currentPosInLogLine;
|
| 823 |
+
currentPosInLogLine += numCodePointsInChunk;
|
| 824 |
+
|
| 825 |
+
// If the chunk processed did not consume the entire logical line,
|
| 826 |
+
// and the character immediately following the chunk is a space,
|
| 827 |
+
// advance past this space as it acted as a delimiter for word wrapping.
|
| 828 |
+
if (
|
| 829 |
+
logicalStartOfThisChunk + numCodePointsInChunk <
|
| 830 |
+
codePointsInLogLine.length &&
|
| 831 |
+
currentPosInLogLine < codePointsInLogLine.length && // Redundant if previous is true, but safe
|
| 832 |
+
codePointsInLogLine[currentPosInLogLine] === ' '
|
| 833 |
+
) {
|
| 834 |
+
currentPosInLogLine++;
|
| 835 |
+
}
|
| 836 |
+
}
|
| 837 |
+
// After all chunks of a non-empty logical line are processed,
|
| 838 |
+
// if the cursor is at the very end of this logical line, update visual cursor.
|
| 839 |
+
if (
|
| 840 |
+
logIndex === logicalCursor[0] &&
|
| 841 |
+
logicalCursor[1] === codePointsInLogLine.length // Cursor at end of logical line
|
| 842 |
+
) {
|
| 843 |
+
const lastVisualLineIdx = visualLines.length - 1;
|
| 844 |
+
if (
|
| 845 |
+
lastVisualLineIdx >= 0 &&
|
| 846 |
+
visualLines[lastVisualLineIdx] !== undefined
|
| 847 |
+
) {
|
| 848 |
+
currentVisualCursor = [
|
| 849 |
+
lastVisualLineIdx,
|
| 850 |
+
cpLen(visualLines[lastVisualLineIdx]), // Cursor at end of last visual line for this logical line
|
| 851 |
+
];
|
| 852 |
+
}
|
| 853 |
+
}
|
| 854 |
+
}
|
| 855 |
+
});
|
| 856 |
+
|
| 857 |
+
// If the entire logical text was empty, ensure there's one empty visual line.
|
| 858 |
+
if (
|
| 859 |
+
logicalLines.length === 0 ||
|
| 860 |
+
(logicalLines.length === 1 && logicalLines[0] === '')
|
| 861 |
+
) {
|
| 862 |
+
if (visualLines.length === 0) {
|
| 863 |
+
visualLines.push('');
|
| 864 |
+
if (!logicalToVisualMap[0]) logicalToVisualMap[0] = [];
|
| 865 |
+
logicalToVisualMap[0].push([0, 0]);
|
| 866 |
+
visualToLogicalMap.push([0, 0]);
|
| 867 |
+
}
|
| 868 |
+
currentVisualCursor = [0, 0];
|
| 869 |
+
}
|
| 870 |
+
// Handle cursor at the very end of the text (after all processing)
|
| 871 |
+
// This case might be covered by the loop end condition now, but kept for safety.
|
| 872 |
+
else if (
|
| 873 |
+
logicalCursor[0] === logicalLines.length - 1 &&
|
| 874 |
+
logicalCursor[1] === cpLen(logicalLines[logicalLines.length - 1]) &&
|
| 875 |
+
visualLines.length > 0
|
| 876 |
+
) {
|
| 877 |
+
const lastVisLineIdx = visualLines.length - 1;
|
| 878 |
+
currentVisualCursor = [lastVisLineIdx, cpLen(visualLines[lastVisLineIdx])];
|
| 879 |
+
}
|
| 880 |
+
|
| 881 |
+
return {
|
| 882 |
+
visualLines,
|
| 883 |
+
visualCursor: currentVisualCursor,
|
| 884 |
+
logicalToVisualMap,
|
| 885 |
+
visualToLogicalMap,
|
| 886 |
+
};
|
| 887 |
+
}
|
| 888 |
+
|
| 889 |
+
// --- Start of reducer logic ---
|
| 890 |
+
|
| 891 |
+
export interface TextBufferState {
|
| 892 |
+
lines: string[];
|
| 893 |
+
cursorRow: number;
|
| 894 |
+
cursorCol: number;
|
| 895 |
+
preferredCol: number | null; // This is visual preferred col
|
| 896 |
+
undoStack: UndoHistoryEntry[];
|
| 897 |
+
redoStack: UndoHistoryEntry[];
|
| 898 |
+
clipboard: string | null;
|
| 899 |
+
selectionAnchor: [number, number] | null;
|
| 900 |
+
viewportWidth: number;
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
const historyLimit = 100;
|
| 904 |
+
|
| 905 |
+
export const pushUndo = (currentState: TextBufferState): TextBufferState => {
|
| 906 |
+
const snapshot = {
|
| 907 |
+
lines: [...currentState.lines],
|
| 908 |
+
cursorRow: currentState.cursorRow,
|
| 909 |
+
cursorCol: currentState.cursorCol,
|
| 910 |
+
};
|
| 911 |
+
const newStack = [...currentState.undoStack, snapshot];
|
| 912 |
+
if (newStack.length > historyLimit) {
|
| 913 |
+
newStack.shift();
|
| 914 |
+
}
|
| 915 |
+
return { ...currentState, undoStack: newStack, redoStack: [] };
|
| 916 |
+
};
|
| 917 |
+
|
| 918 |
+
export type TextBufferAction =
|
| 919 |
+
| { type: 'set_text'; payload: string; pushToUndo?: boolean }
|
| 920 |
+
| { type: 'insert'; payload: string }
|
| 921 |
+
| { type: 'backspace' }
|
| 922 |
+
| {
|
| 923 |
+
type: 'move';
|
| 924 |
+
payload: {
|
| 925 |
+
dir: Direction;
|
| 926 |
+
};
|
| 927 |
+
}
|
| 928 |
+
| { type: 'delete' }
|
| 929 |
+
| { type: 'delete_word_left' }
|
| 930 |
+
| { type: 'delete_word_right' }
|
| 931 |
+
| { type: 'kill_line_right' }
|
| 932 |
+
| { type: 'kill_line_left' }
|
| 933 |
+
| { type: 'undo' }
|
| 934 |
+
| { type: 'redo' }
|
| 935 |
+
| {
|
| 936 |
+
type: 'replace_range';
|
| 937 |
+
payload: {
|
| 938 |
+
startRow: number;
|
| 939 |
+
startCol: number;
|
| 940 |
+
endRow: number;
|
| 941 |
+
endCol: number;
|
| 942 |
+
text: string;
|
| 943 |
+
};
|
| 944 |
+
}
|
| 945 |
+
| { type: 'move_to_offset'; payload: { offset: number } }
|
| 946 |
+
| { type: 'create_undo_snapshot' }
|
| 947 |
+
| { type: 'set_viewport_width'; payload: number }
|
| 948 |
+
| { type: 'vim_delete_word_forward'; payload: { count: number } }
|
| 949 |
+
| { type: 'vim_delete_word_backward'; payload: { count: number } }
|
| 950 |
+
| { type: 'vim_delete_word_end'; payload: { count: number } }
|
| 951 |
+
| { type: 'vim_change_word_forward'; payload: { count: number } }
|
| 952 |
+
| { type: 'vim_change_word_backward'; payload: { count: number } }
|
| 953 |
+
| { type: 'vim_change_word_end'; payload: { count: number } }
|
| 954 |
+
| { type: 'vim_delete_line'; payload: { count: number } }
|
| 955 |
+
| { type: 'vim_change_line'; payload: { count: number } }
|
| 956 |
+
| { type: 'vim_delete_to_end_of_line' }
|
| 957 |
+
| { type: 'vim_change_to_end_of_line' }
|
| 958 |
+
| {
|
| 959 |
+
type: 'vim_change_movement';
|
| 960 |
+
payload: { movement: 'h' | 'j' | 'k' | 'l'; count: number };
|
| 961 |
+
}
|
| 962 |
+
// New vim actions for stateless command handling
|
| 963 |
+
| { type: 'vim_move_left'; payload: { count: number } }
|
| 964 |
+
| { type: 'vim_move_right'; payload: { count: number } }
|
| 965 |
+
| { type: 'vim_move_up'; payload: { count: number } }
|
| 966 |
+
| { type: 'vim_move_down'; payload: { count: number } }
|
| 967 |
+
| { type: 'vim_move_word_forward'; payload: { count: number } }
|
| 968 |
+
| { type: 'vim_move_word_backward'; payload: { count: number } }
|
| 969 |
+
| { type: 'vim_move_word_end'; payload: { count: number } }
|
| 970 |
+
| { type: 'vim_delete_char'; payload: { count: number } }
|
| 971 |
+
| { type: 'vim_insert_at_cursor' }
|
| 972 |
+
| { type: 'vim_append_at_cursor' }
|
| 973 |
+
| { type: 'vim_open_line_below' }
|
| 974 |
+
| { type: 'vim_open_line_above' }
|
| 975 |
+
| { type: 'vim_append_at_line_end' }
|
| 976 |
+
| { type: 'vim_insert_at_line_start' }
|
| 977 |
+
| { type: 'vim_move_to_line_start' }
|
| 978 |
+
| { type: 'vim_move_to_line_end' }
|
| 979 |
+
| { type: 'vim_move_to_first_nonwhitespace' }
|
| 980 |
+
| { type: 'vim_move_to_first_line' }
|
| 981 |
+
| { type: 'vim_move_to_last_line' }
|
| 982 |
+
| { type: 'vim_move_to_line'; payload: { lineNumber: number } }
|
| 983 |
+
| { type: 'vim_escape_insert_mode' };
|
| 984 |
+
|
| 985 |
+
export function textBufferReducer(
|
| 986 |
+
state: TextBufferState,
|
| 987 |
+
action: TextBufferAction,
|
| 988 |
+
): TextBufferState {
|
| 989 |
+
const pushUndoLocal = pushUndo;
|
| 990 |
+
|
| 991 |
+
const currentLine = (r: number): string => state.lines[r] ?? '';
|
| 992 |
+
const currentLineLen = (r: number): number => cpLen(currentLine(r));
|
| 993 |
+
|
| 994 |
+
switch (action.type) {
|
| 995 |
+
case 'set_text': {
|
| 996 |
+
let nextState = state;
|
| 997 |
+
if (action.pushToUndo !== false) {
|
| 998 |
+
nextState = pushUndoLocal(state);
|
| 999 |
+
}
|
| 1000 |
+
const newContentLines = action.payload
|
| 1001 |
+
.replace(/\r\n?/g, '\n')
|
| 1002 |
+
.split('\n');
|
| 1003 |
+
const lines = newContentLines.length === 0 ? [''] : newContentLines;
|
| 1004 |
+
const lastNewLineIndex = lines.length - 1;
|
| 1005 |
+
return {
|
| 1006 |
+
...nextState,
|
| 1007 |
+
lines,
|
| 1008 |
+
cursorRow: lastNewLineIndex,
|
| 1009 |
+
cursorCol: cpLen(lines[lastNewLineIndex] ?? ''),
|
| 1010 |
+
preferredCol: null,
|
| 1011 |
+
};
|
| 1012 |
+
}
|
| 1013 |
+
|
| 1014 |
+
case 'insert': {
|
| 1015 |
+
const nextState = pushUndoLocal(state);
|
| 1016 |
+
const newLines = [...nextState.lines];
|
| 1017 |
+
let newCursorRow = nextState.cursorRow;
|
| 1018 |
+
let newCursorCol = nextState.cursorCol;
|
| 1019 |
+
|
| 1020 |
+
const currentLine = (r: number) => newLines[r] ?? '';
|
| 1021 |
+
|
| 1022 |
+
const str = stripUnsafeCharacters(
|
| 1023 |
+
action.payload.replace(/\r\n/g, '\n').replace(/\r/g, '\n'),
|
| 1024 |
+
);
|
| 1025 |
+
const parts = str.split('\n');
|
| 1026 |
+
const lineContent = currentLine(newCursorRow);
|
| 1027 |
+
const before = cpSlice(lineContent, 0, newCursorCol);
|
| 1028 |
+
const after = cpSlice(lineContent, newCursorCol);
|
| 1029 |
+
|
| 1030 |
+
if (parts.length > 1) {
|
| 1031 |
+
newLines[newCursorRow] = before + parts[0];
|
| 1032 |
+
const remainingParts = parts.slice(1);
|
| 1033 |
+
const lastPartOriginal = remainingParts.pop() ?? '';
|
| 1034 |
+
newLines.splice(newCursorRow + 1, 0, ...remainingParts);
|
| 1035 |
+
newLines.splice(
|
| 1036 |
+
newCursorRow + parts.length - 1,
|
| 1037 |
+
0,
|
| 1038 |
+
lastPartOriginal + after,
|
| 1039 |
+
);
|
| 1040 |
+
newCursorRow = newCursorRow + parts.length - 1;
|
| 1041 |
+
newCursorCol = cpLen(lastPartOriginal);
|
| 1042 |
+
} else {
|
| 1043 |
+
newLines[newCursorRow] = before + parts[0] + after;
|
| 1044 |
+
newCursorCol = cpLen(before) + cpLen(parts[0]);
|
| 1045 |
+
}
|
| 1046 |
+
|
| 1047 |
+
return {
|
| 1048 |
+
...nextState,
|
| 1049 |
+
lines: newLines,
|
| 1050 |
+
cursorRow: newCursorRow,
|
| 1051 |
+
cursorCol: newCursorCol,
|
| 1052 |
+
preferredCol: null,
|
| 1053 |
+
};
|
| 1054 |
+
}
|
| 1055 |
+
|
| 1056 |
+
case 'backspace': {
|
| 1057 |
+
const nextState = pushUndoLocal(state);
|
| 1058 |
+
const newLines = [...nextState.lines];
|
| 1059 |
+
let newCursorRow = nextState.cursorRow;
|
| 1060 |
+
let newCursorCol = nextState.cursorCol;
|
| 1061 |
+
|
| 1062 |
+
const currentLine = (r: number) => newLines[r] ?? '';
|
| 1063 |
+
|
| 1064 |
+
if (newCursorCol === 0 && newCursorRow === 0) return state;
|
| 1065 |
+
|
| 1066 |
+
if (newCursorCol > 0) {
|
| 1067 |
+
const lineContent = currentLine(newCursorRow);
|
| 1068 |
+
newLines[newCursorRow] =
|
| 1069 |
+
cpSlice(lineContent, 0, newCursorCol - 1) +
|
| 1070 |
+
cpSlice(lineContent, newCursorCol);
|
| 1071 |
+
newCursorCol--;
|
| 1072 |
+
} else if (newCursorRow > 0) {
|
| 1073 |
+
const prevLineContent = currentLine(newCursorRow - 1);
|
| 1074 |
+
const currentLineContentVal = currentLine(newCursorRow);
|
| 1075 |
+
const newCol = cpLen(prevLineContent);
|
| 1076 |
+
newLines[newCursorRow - 1] = prevLineContent + currentLineContentVal;
|
| 1077 |
+
newLines.splice(newCursorRow, 1);
|
| 1078 |
+
newCursorRow--;
|
| 1079 |
+
newCursorCol = newCol;
|
| 1080 |
+
}
|
| 1081 |
+
|
| 1082 |
+
return {
|
| 1083 |
+
...nextState,
|
| 1084 |
+
lines: newLines,
|
| 1085 |
+
cursorRow: newCursorRow,
|
| 1086 |
+
cursorCol: newCursorCol,
|
| 1087 |
+
preferredCol: null,
|
| 1088 |
+
};
|
| 1089 |
+
}
|
| 1090 |
+
|
| 1091 |
+
case 'set_viewport_width': {
|
| 1092 |
+
if (action.payload === state.viewportWidth) {
|
| 1093 |
+
return state;
|
| 1094 |
+
}
|
| 1095 |
+
return { ...state, viewportWidth: action.payload };
|
| 1096 |
+
}
|
| 1097 |
+
|
| 1098 |
+
case 'move': {
|
| 1099 |
+
const { dir } = action.payload;
|
| 1100 |
+
const { lines, cursorRow, cursorCol, viewportWidth } = state;
|
| 1101 |
+
const visualLayout = calculateVisualLayout(
|
| 1102 |
+
lines,
|
| 1103 |
+
[cursorRow, cursorCol],
|
| 1104 |
+
viewportWidth,
|
| 1105 |
+
);
|
| 1106 |
+
const { visualLines, visualCursor, visualToLogicalMap } = visualLayout;
|
| 1107 |
+
|
| 1108 |
+
let newVisualRow = visualCursor[0];
|
| 1109 |
+
let newVisualCol = visualCursor[1];
|
| 1110 |
+
let newPreferredCol = state.preferredCol;
|
| 1111 |
+
|
| 1112 |
+
const currentVisLineLen = cpLen(visualLines[newVisualRow] ?? '');
|
| 1113 |
+
|
| 1114 |
+
switch (dir) {
|
| 1115 |
+
case 'left':
|
| 1116 |
+
newPreferredCol = null;
|
| 1117 |
+
if (newVisualCol > 0) {
|
| 1118 |
+
newVisualCol--;
|
| 1119 |
+
} else if (newVisualRow > 0) {
|
| 1120 |
+
newVisualRow--;
|
| 1121 |
+
newVisualCol = cpLen(visualLines[newVisualRow] ?? '');
|
| 1122 |
+
}
|
| 1123 |
+
break;
|
| 1124 |
+
case 'right':
|
| 1125 |
+
newPreferredCol = null;
|
| 1126 |
+
if (newVisualCol < currentVisLineLen) {
|
| 1127 |
+
newVisualCol++;
|
| 1128 |
+
} else if (newVisualRow < visualLines.length - 1) {
|
| 1129 |
+
newVisualRow++;
|
| 1130 |
+
newVisualCol = 0;
|
| 1131 |
+
}
|
| 1132 |
+
break;
|
| 1133 |
+
case 'up':
|
| 1134 |
+
if (newVisualRow > 0) {
|
| 1135 |
+
if (newPreferredCol === null) newPreferredCol = newVisualCol;
|
| 1136 |
+
newVisualRow--;
|
| 1137 |
+
newVisualCol = clamp(
|
| 1138 |
+
newPreferredCol,
|
| 1139 |
+
0,
|
| 1140 |
+
cpLen(visualLines[newVisualRow] ?? ''),
|
| 1141 |
+
);
|
| 1142 |
+
}
|
| 1143 |
+
break;
|
| 1144 |
+
case 'down':
|
| 1145 |
+
if (newVisualRow < visualLines.length - 1) {
|
| 1146 |
+
if (newPreferredCol === null) newPreferredCol = newVisualCol;
|
| 1147 |
+
newVisualRow++;
|
| 1148 |
+
newVisualCol = clamp(
|
| 1149 |
+
newPreferredCol,
|
| 1150 |
+
0,
|
| 1151 |
+
cpLen(visualLines[newVisualRow] ?? ''),
|
| 1152 |
+
);
|
| 1153 |
+
}
|
| 1154 |
+
break;
|
| 1155 |
+
case 'home':
|
| 1156 |
+
newPreferredCol = null;
|
| 1157 |
+
newVisualCol = 0;
|
| 1158 |
+
break;
|
| 1159 |
+
case 'end':
|
| 1160 |
+
newPreferredCol = null;
|
| 1161 |
+
newVisualCol = currentVisLineLen;
|
| 1162 |
+
break;
|
| 1163 |
+
case 'wordLeft': {
|
| 1164 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 1165 |
+
if (cursorCol === 0 && cursorRow === 0) return state;
|
| 1166 |
+
|
| 1167 |
+
let newCursorRow = cursorRow;
|
| 1168 |
+
let newCursorCol = cursorCol;
|
| 1169 |
+
|
| 1170 |
+
if (cursorCol === 0) {
|
| 1171 |
+
newCursorRow--;
|
| 1172 |
+
newCursorCol = cpLen(lines[newCursorRow] ?? '');
|
| 1173 |
+
} else {
|
| 1174 |
+
const lineContent = lines[cursorRow];
|
| 1175 |
+
const arr = toCodePoints(lineContent);
|
| 1176 |
+
let start = cursorCol;
|
| 1177 |
+
let onlySpaces = true;
|
| 1178 |
+
for (let i = 0; i < start; i++) {
|
| 1179 |
+
if (isWordChar(arr[i])) {
|
| 1180 |
+
onlySpaces = false;
|
| 1181 |
+
break;
|
| 1182 |
+
}
|
| 1183 |
+
}
|
| 1184 |
+
if (onlySpaces && start > 0) {
|
| 1185 |
+
start--;
|
| 1186 |
+
} else {
|
| 1187 |
+
while (start > 0 && !isWordChar(arr[start - 1])) start--;
|
| 1188 |
+
while (start > 0 && isWordChar(arr[start - 1])) start--;
|
| 1189 |
+
}
|
| 1190 |
+
newCursorCol = start;
|
| 1191 |
+
}
|
| 1192 |
+
return {
|
| 1193 |
+
...state,
|
| 1194 |
+
cursorRow: newCursorRow,
|
| 1195 |
+
cursorCol: newCursorCol,
|
| 1196 |
+
preferredCol: null,
|
| 1197 |
+
};
|
| 1198 |
+
}
|
| 1199 |
+
case 'wordRight': {
|
| 1200 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 1201 |
+
if (
|
| 1202 |
+
cursorRow === lines.length - 1 &&
|
| 1203 |
+
cursorCol === cpLen(lines[cursorRow] ?? '')
|
| 1204 |
+
) {
|
| 1205 |
+
return state;
|
| 1206 |
+
}
|
| 1207 |
+
|
| 1208 |
+
let newCursorRow = cursorRow;
|
| 1209 |
+
let newCursorCol = cursorCol;
|
| 1210 |
+
const lineContent = lines[cursorRow] ?? '';
|
| 1211 |
+
const arr = toCodePoints(lineContent);
|
| 1212 |
+
|
| 1213 |
+
if (cursorCol >= arr.length) {
|
| 1214 |
+
newCursorRow++;
|
| 1215 |
+
newCursorCol = 0;
|
| 1216 |
+
} else {
|
| 1217 |
+
let end = cursorCol;
|
| 1218 |
+
while (end < arr.length && !isWordChar(arr[end])) end++;
|
| 1219 |
+
while (end < arr.length && isWordChar(arr[end])) end++;
|
| 1220 |
+
newCursorCol = end;
|
| 1221 |
+
}
|
| 1222 |
+
return {
|
| 1223 |
+
...state,
|
| 1224 |
+
cursorRow: newCursorRow,
|
| 1225 |
+
cursorCol: newCursorCol,
|
| 1226 |
+
preferredCol: null,
|
| 1227 |
+
};
|
| 1228 |
+
}
|
| 1229 |
+
default:
|
| 1230 |
+
break;
|
| 1231 |
+
}
|
| 1232 |
+
|
| 1233 |
+
if (visualToLogicalMap[newVisualRow]) {
|
| 1234 |
+
const [logRow, logStartCol] = visualToLogicalMap[newVisualRow];
|
| 1235 |
+
return {
|
| 1236 |
+
...state,
|
| 1237 |
+
cursorRow: logRow,
|
| 1238 |
+
cursorCol: clamp(
|
| 1239 |
+
logStartCol + newVisualCol,
|
| 1240 |
+
0,
|
| 1241 |
+
cpLen(state.lines[logRow] ?? ''),
|
| 1242 |
+
),
|
| 1243 |
+
preferredCol: newPreferredCol,
|
| 1244 |
+
};
|
| 1245 |
+
}
|
| 1246 |
+
return state;
|
| 1247 |
+
}
|
| 1248 |
+
|
| 1249 |
+
case 'delete': {
|
| 1250 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 1251 |
+
const lineContent = currentLine(cursorRow);
|
| 1252 |
+
if (cursorCol < currentLineLen(cursorRow)) {
|
| 1253 |
+
const nextState = pushUndoLocal(state);
|
| 1254 |
+
const newLines = [...nextState.lines];
|
| 1255 |
+
newLines[cursorRow] =
|
| 1256 |
+
cpSlice(lineContent, 0, cursorCol) +
|
| 1257 |
+
cpSlice(lineContent, cursorCol + 1);
|
| 1258 |
+
return { ...nextState, lines: newLines, preferredCol: null };
|
| 1259 |
+
} else if (cursorRow < lines.length - 1) {
|
| 1260 |
+
const nextState = pushUndoLocal(state);
|
| 1261 |
+
const nextLineContent = currentLine(cursorRow + 1);
|
| 1262 |
+
const newLines = [...nextState.lines];
|
| 1263 |
+
newLines[cursorRow] = lineContent + nextLineContent;
|
| 1264 |
+
newLines.splice(cursorRow + 1, 1);
|
| 1265 |
+
return { ...nextState, lines: newLines, preferredCol: null };
|
| 1266 |
+
}
|
| 1267 |
+
return state;
|
| 1268 |
+
}
|
| 1269 |
+
|
| 1270 |
+
case 'delete_word_left': {
|
| 1271 |
+
const { cursorRow, cursorCol } = state;
|
| 1272 |
+
if (cursorCol === 0 && cursorRow === 0) return state;
|
| 1273 |
+
if (cursorCol === 0) {
|
| 1274 |
+
// Act as a backspace
|
| 1275 |
+
const nextState = pushUndoLocal(state);
|
| 1276 |
+
const prevLineContent = currentLine(cursorRow - 1);
|
| 1277 |
+
const currentLineContentVal = currentLine(cursorRow);
|
| 1278 |
+
const newCol = cpLen(prevLineContent);
|
| 1279 |
+
const newLines = [...nextState.lines];
|
| 1280 |
+
newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
|
| 1281 |
+
newLines.splice(cursorRow, 1);
|
| 1282 |
+
return {
|
| 1283 |
+
...nextState,
|
| 1284 |
+
lines: newLines,
|
| 1285 |
+
cursorRow: cursorRow - 1,
|
| 1286 |
+
cursorCol: newCol,
|
| 1287 |
+
preferredCol: null,
|
| 1288 |
+
};
|
| 1289 |
+
}
|
| 1290 |
+
const nextState = pushUndoLocal(state);
|
| 1291 |
+
const lineContent = currentLine(cursorRow);
|
| 1292 |
+
const arr = toCodePoints(lineContent);
|
| 1293 |
+
let start = cursorCol;
|
| 1294 |
+
let onlySpaces = true;
|
| 1295 |
+
for (let i = 0; i < start; i++) {
|
| 1296 |
+
if (isWordChar(arr[i])) {
|
| 1297 |
+
onlySpaces = false;
|
| 1298 |
+
break;
|
| 1299 |
+
}
|
| 1300 |
+
}
|
| 1301 |
+
if (onlySpaces && start > 0) {
|
| 1302 |
+
start--;
|
| 1303 |
+
} else {
|
| 1304 |
+
while (start > 0 && !isWordChar(arr[start - 1])) start--;
|
| 1305 |
+
while (start > 0 && isWordChar(arr[start - 1])) start--;
|
| 1306 |
+
}
|
| 1307 |
+
const newLines = [...nextState.lines];
|
| 1308 |
+
newLines[cursorRow] =
|
| 1309 |
+
cpSlice(lineContent, 0, start) + cpSlice(lineContent, cursorCol);
|
| 1310 |
+
return {
|
| 1311 |
+
...nextState,
|
| 1312 |
+
lines: newLines,
|
| 1313 |
+
cursorCol: start,
|
| 1314 |
+
preferredCol: null,
|
| 1315 |
+
};
|
| 1316 |
+
}
|
| 1317 |
+
|
| 1318 |
+
case 'delete_word_right': {
|
| 1319 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 1320 |
+
const lineContent = currentLine(cursorRow);
|
| 1321 |
+
const arr = toCodePoints(lineContent);
|
| 1322 |
+
if (cursorCol >= arr.length && cursorRow === lines.length - 1)
|
| 1323 |
+
return state;
|
| 1324 |
+
if (cursorCol >= arr.length) {
|
| 1325 |
+
// Act as a delete
|
| 1326 |
+
const nextState = pushUndoLocal(state);
|
| 1327 |
+
const nextLineContent = currentLine(cursorRow + 1);
|
| 1328 |
+
const newLines = [...nextState.lines];
|
| 1329 |
+
newLines[cursorRow] = lineContent + nextLineContent;
|
| 1330 |
+
newLines.splice(cursorRow + 1, 1);
|
| 1331 |
+
return { ...nextState, lines: newLines, preferredCol: null };
|
| 1332 |
+
}
|
| 1333 |
+
const nextState = pushUndoLocal(state);
|
| 1334 |
+
let end = cursorCol;
|
| 1335 |
+
while (end < arr.length && !isWordChar(arr[end])) end++;
|
| 1336 |
+
while (end < arr.length && isWordChar(arr[end])) end++;
|
| 1337 |
+
const newLines = [...nextState.lines];
|
| 1338 |
+
newLines[cursorRow] =
|
| 1339 |
+
cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, end);
|
| 1340 |
+
return { ...nextState, lines: newLines, preferredCol: null };
|
| 1341 |
+
}
|
| 1342 |
+
|
| 1343 |
+
case 'kill_line_right': {
|
| 1344 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 1345 |
+
const lineContent = currentLine(cursorRow);
|
| 1346 |
+
if (cursorCol < currentLineLen(cursorRow)) {
|
| 1347 |
+
const nextState = pushUndoLocal(state);
|
| 1348 |
+
const newLines = [...nextState.lines];
|
| 1349 |
+
newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol);
|
| 1350 |
+
return { ...nextState, lines: newLines };
|
| 1351 |
+
} else if (cursorRow < lines.length - 1) {
|
| 1352 |
+
// Act as a delete
|
| 1353 |
+
const nextState = pushUndoLocal(state);
|
| 1354 |
+
const nextLineContent = currentLine(cursorRow + 1);
|
| 1355 |
+
const newLines = [...nextState.lines];
|
| 1356 |
+
newLines[cursorRow] = lineContent + nextLineContent;
|
| 1357 |
+
newLines.splice(cursorRow + 1, 1);
|
| 1358 |
+
return { ...nextState, lines: newLines, preferredCol: null };
|
| 1359 |
+
}
|
| 1360 |
+
return state;
|
| 1361 |
+
}
|
| 1362 |
+
|
| 1363 |
+
case 'kill_line_left': {
|
| 1364 |
+
const { cursorRow, cursorCol } = state;
|
| 1365 |
+
if (cursorCol > 0) {
|
| 1366 |
+
const nextState = pushUndoLocal(state);
|
| 1367 |
+
const lineContent = currentLine(cursorRow);
|
| 1368 |
+
const newLines = [...nextState.lines];
|
| 1369 |
+
newLines[cursorRow] = cpSlice(lineContent, cursorCol);
|
| 1370 |
+
return {
|
| 1371 |
+
...nextState,
|
| 1372 |
+
lines: newLines,
|
| 1373 |
+
cursorCol: 0,
|
| 1374 |
+
preferredCol: null,
|
| 1375 |
+
};
|
| 1376 |
+
}
|
| 1377 |
+
return state;
|
| 1378 |
+
}
|
| 1379 |
+
|
| 1380 |
+
case 'undo': {
|
| 1381 |
+
const stateToRestore = state.undoStack[state.undoStack.length - 1];
|
| 1382 |
+
if (!stateToRestore) return state;
|
| 1383 |
+
|
| 1384 |
+
const currentSnapshot = {
|
| 1385 |
+
lines: [...state.lines],
|
| 1386 |
+
cursorRow: state.cursorRow,
|
| 1387 |
+
cursorCol: state.cursorCol,
|
| 1388 |
+
};
|
| 1389 |
+
return {
|
| 1390 |
+
...state,
|
| 1391 |
+
...stateToRestore,
|
| 1392 |
+
undoStack: state.undoStack.slice(0, -1),
|
| 1393 |
+
redoStack: [...state.redoStack, currentSnapshot],
|
| 1394 |
+
};
|
| 1395 |
+
}
|
| 1396 |
+
|
| 1397 |
+
case 'redo': {
|
| 1398 |
+
const stateToRestore = state.redoStack[state.redoStack.length - 1];
|
| 1399 |
+
if (!stateToRestore) return state;
|
| 1400 |
+
|
| 1401 |
+
const currentSnapshot = {
|
| 1402 |
+
lines: [...state.lines],
|
| 1403 |
+
cursorRow: state.cursorRow,
|
| 1404 |
+
cursorCol: state.cursorCol,
|
| 1405 |
+
};
|
| 1406 |
+
return {
|
| 1407 |
+
...state,
|
| 1408 |
+
...stateToRestore,
|
| 1409 |
+
redoStack: state.redoStack.slice(0, -1),
|
| 1410 |
+
undoStack: [...state.undoStack, currentSnapshot],
|
| 1411 |
+
};
|
| 1412 |
+
}
|
| 1413 |
+
|
| 1414 |
+
case 'replace_range': {
|
| 1415 |
+
const { startRow, startCol, endRow, endCol, text } = action.payload;
|
| 1416 |
+
const nextState = pushUndoLocal(state);
|
| 1417 |
+
return replaceRangeInternal(
|
| 1418 |
+
nextState,
|
| 1419 |
+
startRow,
|
| 1420 |
+
startCol,
|
| 1421 |
+
endRow,
|
| 1422 |
+
endCol,
|
| 1423 |
+
text,
|
| 1424 |
+
);
|
| 1425 |
+
}
|
| 1426 |
+
|
| 1427 |
+
case 'move_to_offset': {
|
| 1428 |
+
const { offset } = action.payload;
|
| 1429 |
+
const [newRow, newCol] = offsetToLogicalPos(
|
| 1430 |
+
state.lines.join('\n'),
|
| 1431 |
+
offset,
|
| 1432 |
+
);
|
| 1433 |
+
return {
|
| 1434 |
+
...state,
|
| 1435 |
+
cursorRow: newRow,
|
| 1436 |
+
cursorCol: newCol,
|
| 1437 |
+
preferredCol: null,
|
| 1438 |
+
};
|
| 1439 |
+
}
|
| 1440 |
+
|
| 1441 |
+
case 'create_undo_snapshot': {
|
| 1442 |
+
return pushUndoLocal(state);
|
| 1443 |
+
}
|
| 1444 |
+
|
| 1445 |
+
// Vim-specific operations
|
| 1446 |
+
case 'vim_delete_word_forward':
|
| 1447 |
+
case 'vim_delete_word_backward':
|
| 1448 |
+
case 'vim_delete_word_end':
|
| 1449 |
+
case 'vim_change_word_forward':
|
| 1450 |
+
case 'vim_change_word_backward':
|
| 1451 |
+
case 'vim_change_word_end':
|
| 1452 |
+
case 'vim_delete_line':
|
| 1453 |
+
case 'vim_change_line':
|
| 1454 |
+
case 'vim_delete_to_end_of_line':
|
| 1455 |
+
case 'vim_change_to_end_of_line':
|
| 1456 |
+
case 'vim_change_movement':
|
| 1457 |
+
case 'vim_move_left':
|
| 1458 |
+
case 'vim_move_right':
|
| 1459 |
+
case 'vim_move_up':
|
| 1460 |
+
case 'vim_move_down':
|
| 1461 |
+
case 'vim_move_word_forward':
|
| 1462 |
+
case 'vim_move_word_backward':
|
| 1463 |
+
case 'vim_move_word_end':
|
| 1464 |
+
case 'vim_delete_char':
|
| 1465 |
+
case 'vim_insert_at_cursor':
|
| 1466 |
+
case 'vim_append_at_cursor':
|
| 1467 |
+
case 'vim_open_line_below':
|
| 1468 |
+
case 'vim_open_line_above':
|
| 1469 |
+
case 'vim_append_at_line_end':
|
| 1470 |
+
case 'vim_insert_at_line_start':
|
| 1471 |
+
case 'vim_move_to_line_start':
|
| 1472 |
+
case 'vim_move_to_line_end':
|
| 1473 |
+
case 'vim_move_to_first_nonwhitespace':
|
| 1474 |
+
case 'vim_move_to_first_line':
|
| 1475 |
+
case 'vim_move_to_last_line':
|
| 1476 |
+
case 'vim_move_to_line':
|
| 1477 |
+
case 'vim_escape_insert_mode':
|
| 1478 |
+
return handleVimAction(state, action as VimAction);
|
| 1479 |
+
|
| 1480 |
+
default: {
|
| 1481 |
+
const exhaustiveCheck: never = action;
|
| 1482 |
+
console.error(`Unknown action encountered: ${exhaustiveCheck}`);
|
| 1483 |
+
return state;
|
| 1484 |
+
}
|
| 1485 |
+
}
|
| 1486 |
+
}
|
| 1487 |
+
|
| 1488 |
+
// --- End of reducer logic ---
|
| 1489 |
+
|
| 1490 |
+
export function useTextBuffer({
|
| 1491 |
+
initialText = '',
|
| 1492 |
+
initialCursorOffset = 0,
|
| 1493 |
+
viewport,
|
| 1494 |
+
stdin,
|
| 1495 |
+
setRawMode,
|
| 1496 |
+
onChange,
|
| 1497 |
+
isValidPath,
|
| 1498 |
+
shellModeActive = false,
|
| 1499 |
+
}: UseTextBufferProps): TextBuffer {
|
| 1500 |
+
const initialState = useMemo((): TextBufferState => {
|
| 1501 |
+
const lines = initialText.split('\n');
|
| 1502 |
+
const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition(
|
| 1503 |
+
lines.length === 0 ? [''] : lines,
|
| 1504 |
+
initialCursorOffset,
|
| 1505 |
+
);
|
| 1506 |
+
return {
|
| 1507 |
+
lines: lines.length === 0 ? [''] : lines,
|
| 1508 |
+
cursorRow: initialCursorRow,
|
| 1509 |
+
cursorCol: initialCursorCol,
|
| 1510 |
+
preferredCol: null,
|
| 1511 |
+
undoStack: [],
|
| 1512 |
+
redoStack: [],
|
| 1513 |
+
clipboard: null,
|
| 1514 |
+
selectionAnchor: null,
|
| 1515 |
+
viewportWidth: viewport.width,
|
| 1516 |
+
};
|
| 1517 |
+
}, [initialText, initialCursorOffset, viewport.width]);
|
| 1518 |
+
|
| 1519 |
+
const [state, dispatch] = useReducer(textBufferReducer, initialState);
|
| 1520 |
+
const { lines, cursorRow, cursorCol, preferredCol, selectionAnchor } = state;
|
| 1521 |
+
|
| 1522 |
+
const text = useMemo(() => lines.join('\n'), [lines]);
|
| 1523 |
+
|
| 1524 |
+
const visualLayout = useMemo(
|
| 1525 |
+
() =>
|
| 1526 |
+
calculateVisualLayout(lines, [cursorRow, cursorCol], state.viewportWidth),
|
| 1527 |
+
[lines, cursorRow, cursorCol, state.viewportWidth],
|
| 1528 |
+
);
|
| 1529 |
+
|
| 1530 |
+
const { visualLines, visualCursor } = visualLayout;
|
| 1531 |
+
|
| 1532 |
+
const [visualScrollRow, setVisualScrollRow] = useState<number>(0);
|
| 1533 |
+
|
| 1534 |
+
useEffect(() => {
|
| 1535 |
+
if (onChange) {
|
| 1536 |
+
onChange(text);
|
| 1537 |
+
}
|
| 1538 |
+
}, [text, onChange]);
|
| 1539 |
+
|
| 1540 |
+
useEffect(() => {
|
| 1541 |
+
dispatch({ type: 'set_viewport_width', payload: viewport.width });
|
| 1542 |
+
}, [viewport.width]);
|
| 1543 |
+
|
| 1544 |
+
// Update visual scroll (vertical)
|
| 1545 |
+
useEffect(() => {
|
| 1546 |
+
const { height } = viewport;
|
| 1547 |
+
let newVisualScrollRow = visualScrollRow;
|
| 1548 |
+
|
| 1549 |
+
if (visualCursor[0] < visualScrollRow) {
|
| 1550 |
+
newVisualScrollRow = visualCursor[0];
|
| 1551 |
+
} else if (visualCursor[0] >= visualScrollRow + height) {
|
| 1552 |
+
newVisualScrollRow = visualCursor[0] - height + 1;
|
| 1553 |
+
}
|
| 1554 |
+
if (newVisualScrollRow !== visualScrollRow) {
|
| 1555 |
+
setVisualScrollRow(newVisualScrollRow);
|
| 1556 |
+
}
|
| 1557 |
+
}, [visualCursor, visualScrollRow, viewport]);
|
| 1558 |
+
|
| 1559 |
+
const insert = useCallback(
|
| 1560 |
+
(ch: string, { paste = false }: { paste?: boolean } = {}): void => {
|
| 1561 |
+
if (/[\n\r]/.test(ch)) {
|
| 1562 |
+
dispatch({ type: 'insert', payload: ch });
|
| 1563 |
+
return;
|
| 1564 |
+
}
|
| 1565 |
+
|
| 1566 |
+
const minLengthToInferAsDragDrop = 3;
|
| 1567 |
+
if (
|
| 1568 |
+
ch.length >= minLengthToInferAsDragDrop &&
|
| 1569 |
+
!shellModeActive &&
|
| 1570 |
+
paste
|
| 1571 |
+
) {
|
| 1572 |
+
let potentialPath = ch.trim();
|
| 1573 |
+
const quoteMatch = potentialPath.match(/^'(.*)'$/);
|
| 1574 |
+
if (quoteMatch) {
|
| 1575 |
+
potentialPath = quoteMatch[1];
|
| 1576 |
+
}
|
| 1577 |
+
|
| 1578 |
+
potentialPath = potentialPath.trim();
|
| 1579 |
+
if (isValidPath(unescapePath(potentialPath))) {
|
| 1580 |
+
ch = `@${potentialPath} `;
|
| 1581 |
+
}
|
| 1582 |
+
}
|
| 1583 |
+
|
| 1584 |
+
let currentText = '';
|
| 1585 |
+
for (const char of toCodePoints(ch)) {
|
| 1586 |
+
if (char.codePointAt(0) === 127) {
|
| 1587 |
+
if (currentText.length > 0) {
|
| 1588 |
+
dispatch({ type: 'insert', payload: currentText });
|
| 1589 |
+
currentText = '';
|
| 1590 |
+
}
|
| 1591 |
+
dispatch({ type: 'backspace' });
|
| 1592 |
+
} else {
|
| 1593 |
+
currentText += char;
|
| 1594 |
+
}
|
| 1595 |
+
}
|
| 1596 |
+
if (currentText.length > 0) {
|
| 1597 |
+
dispatch({ type: 'insert', payload: currentText });
|
| 1598 |
+
}
|
| 1599 |
+
},
|
| 1600 |
+
[isValidPath, shellModeActive],
|
| 1601 |
+
);
|
| 1602 |
+
|
| 1603 |
+
const newline = useCallback((): void => {
|
| 1604 |
+
dispatch({ type: 'insert', payload: '\n' });
|
| 1605 |
+
}, []);
|
| 1606 |
+
|
| 1607 |
+
const backspace = useCallback((): void => {
|
| 1608 |
+
dispatch({ type: 'backspace' });
|
| 1609 |
+
}, []);
|
| 1610 |
+
|
| 1611 |
+
const del = useCallback((): void => {
|
| 1612 |
+
dispatch({ type: 'delete' });
|
| 1613 |
+
}, []);
|
| 1614 |
+
|
| 1615 |
+
const move = useCallback((dir: Direction): void => {
|
| 1616 |
+
dispatch({ type: 'move', payload: { dir } });
|
| 1617 |
+
}, []);
|
| 1618 |
+
|
| 1619 |
+
const undo = useCallback((): void => {
|
| 1620 |
+
dispatch({ type: 'undo' });
|
| 1621 |
+
}, []);
|
| 1622 |
+
|
| 1623 |
+
const redo = useCallback((): void => {
|
| 1624 |
+
dispatch({ type: 'redo' });
|
| 1625 |
+
}, []);
|
| 1626 |
+
|
| 1627 |
+
const setText = useCallback((newText: string): void => {
|
| 1628 |
+
dispatch({ type: 'set_text', payload: newText });
|
| 1629 |
+
}, []);
|
| 1630 |
+
|
| 1631 |
+
const deleteWordLeft = useCallback((): void => {
|
| 1632 |
+
dispatch({ type: 'delete_word_left' });
|
| 1633 |
+
}, []);
|
| 1634 |
+
|
| 1635 |
+
const deleteWordRight = useCallback((): void => {
|
| 1636 |
+
dispatch({ type: 'delete_word_right' });
|
| 1637 |
+
}, []);
|
| 1638 |
+
|
| 1639 |
+
const killLineRight = useCallback((): void => {
|
| 1640 |
+
dispatch({ type: 'kill_line_right' });
|
| 1641 |
+
}, []);
|
| 1642 |
+
|
| 1643 |
+
const killLineLeft = useCallback((): void => {
|
| 1644 |
+
dispatch({ type: 'kill_line_left' });
|
| 1645 |
+
}, []);
|
| 1646 |
+
|
| 1647 |
+
// Vim-specific operations
|
| 1648 |
+
const vimDeleteWordForward = useCallback((count: number): void => {
|
| 1649 |
+
dispatch({ type: 'vim_delete_word_forward', payload: { count } });
|
| 1650 |
+
}, []);
|
| 1651 |
+
|
| 1652 |
+
const vimDeleteWordBackward = useCallback((count: number): void => {
|
| 1653 |
+
dispatch({ type: 'vim_delete_word_backward', payload: { count } });
|
| 1654 |
+
}, []);
|
| 1655 |
+
|
| 1656 |
+
const vimDeleteWordEnd = useCallback((count: number): void => {
|
| 1657 |
+
dispatch({ type: 'vim_delete_word_end', payload: { count } });
|
| 1658 |
+
}, []);
|
| 1659 |
+
|
| 1660 |
+
const vimChangeWordForward = useCallback((count: number): void => {
|
| 1661 |
+
dispatch({ type: 'vim_change_word_forward', payload: { count } });
|
| 1662 |
+
}, []);
|
| 1663 |
+
|
| 1664 |
+
const vimChangeWordBackward = useCallback((count: number): void => {
|
| 1665 |
+
dispatch({ type: 'vim_change_word_backward', payload: { count } });
|
| 1666 |
+
}, []);
|
| 1667 |
+
|
| 1668 |
+
const vimChangeWordEnd = useCallback((count: number): void => {
|
| 1669 |
+
dispatch({ type: 'vim_change_word_end', payload: { count } });
|
| 1670 |
+
}, []);
|
| 1671 |
+
|
| 1672 |
+
const vimDeleteLine = useCallback((count: number): void => {
|
| 1673 |
+
dispatch({ type: 'vim_delete_line', payload: { count } });
|
| 1674 |
+
}, []);
|
| 1675 |
+
|
| 1676 |
+
const vimChangeLine = useCallback((count: number): void => {
|
| 1677 |
+
dispatch({ type: 'vim_change_line', payload: { count } });
|
| 1678 |
+
}, []);
|
| 1679 |
+
|
| 1680 |
+
const vimDeleteToEndOfLine = useCallback((): void => {
|
| 1681 |
+
dispatch({ type: 'vim_delete_to_end_of_line' });
|
| 1682 |
+
}, []);
|
| 1683 |
+
|
| 1684 |
+
const vimChangeToEndOfLine = useCallback((): void => {
|
| 1685 |
+
dispatch({ type: 'vim_change_to_end_of_line' });
|
| 1686 |
+
}, []);
|
| 1687 |
+
|
| 1688 |
+
const vimChangeMovement = useCallback(
|
| 1689 |
+
(movement: 'h' | 'j' | 'k' | 'l', count: number): void => {
|
| 1690 |
+
dispatch({ type: 'vim_change_movement', payload: { movement, count } });
|
| 1691 |
+
},
|
| 1692 |
+
[],
|
| 1693 |
+
);
|
| 1694 |
+
|
| 1695 |
+
// New vim navigation and operation methods
|
| 1696 |
+
const vimMoveLeft = useCallback((count: number): void => {
|
| 1697 |
+
dispatch({ type: 'vim_move_left', payload: { count } });
|
| 1698 |
+
}, []);
|
| 1699 |
+
|
| 1700 |
+
const vimMoveRight = useCallback((count: number): void => {
|
| 1701 |
+
dispatch({ type: 'vim_move_right', payload: { count } });
|
| 1702 |
+
}, []);
|
| 1703 |
+
|
| 1704 |
+
const vimMoveUp = useCallback((count: number): void => {
|
| 1705 |
+
dispatch({ type: 'vim_move_up', payload: { count } });
|
| 1706 |
+
}, []);
|
| 1707 |
+
|
| 1708 |
+
const vimMoveDown = useCallback((count: number): void => {
|
| 1709 |
+
dispatch({ type: 'vim_move_down', payload: { count } });
|
| 1710 |
+
}, []);
|
| 1711 |
+
|
| 1712 |
+
const vimMoveWordForward = useCallback((count: number): void => {
|
| 1713 |
+
dispatch({ type: 'vim_move_word_forward', payload: { count } });
|
| 1714 |
+
}, []);
|
| 1715 |
+
|
| 1716 |
+
const vimMoveWordBackward = useCallback((count: number): void => {
|
| 1717 |
+
dispatch({ type: 'vim_move_word_backward', payload: { count } });
|
| 1718 |
+
}, []);
|
| 1719 |
+
|
| 1720 |
+
const vimMoveWordEnd = useCallback((count: number): void => {
|
| 1721 |
+
dispatch({ type: 'vim_move_word_end', payload: { count } });
|
| 1722 |
+
}, []);
|
| 1723 |
+
|
| 1724 |
+
const vimDeleteChar = useCallback((count: number): void => {
|
| 1725 |
+
dispatch({ type: 'vim_delete_char', payload: { count } });
|
| 1726 |
+
}, []);
|
| 1727 |
+
|
| 1728 |
+
const vimInsertAtCursor = useCallback((): void => {
|
| 1729 |
+
dispatch({ type: 'vim_insert_at_cursor' });
|
| 1730 |
+
}, []);
|
| 1731 |
+
|
| 1732 |
+
const vimAppendAtCursor = useCallback((): void => {
|
| 1733 |
+
dispatch({ type: 'vim_append_at_cursor' });
|
| 1734 |
+
}, []);
|
| 1735 |
+
|
| 1736 |
+
const vimOpenLineBelow = useCallback((): void => {
|
| 1737 |
+
dispatch({ type: 'vim_open_line_below' });
|
| 1738 |
+
}, []);
|
| 1739 |
+
|
| 1740 |
+
const vimOpenLineAbove = useCallback((): void => {
|
| 1741 |
+
dispatch({ type: 'vim_open_line_above' });
|
| 1742 |
+
}, []);
|
| 1743 |
+
|
| 1744 |
+
const vimAppendAtLineEnd = useCallback((): void => {
|
| 1745 |
+
dispatch({ type: 'vim_append_at_line_end' });
|
| 1746 |
+
}, []);
|
| 1747 |
+
|
| 1748 |
+
const vimInsertAtLineStart = useCallback((): void => {
|
| 1749 |
+
dispatch({ type: 'vim_insert_at_line_start' });
|
| 1750 |
+
}, []);
|
| 1751 |
+
|
| 1752 |
+
const vimMoveToLineStart = useCallback((): void => {
|
| 1753 |
+
dispatch({ type: 'vim_move_to_line_start' });
|
| 1754 |
+
}, []);
|
| 1755 |
+
|
| 1756 |
+
const vimMoveToLineEnd = useCallback((): void => {
|
| 1757 |
+
dispatch({ type: 'vim_move_to_line_end' });
|
| 1758 |
+
}, []);
|
| 1759 |
+
|
| 1760 |
+
const vimMoveToFirstNonWhitespace = useCallback((): void => {
|
| 1761 |
+
dispatch({ type: 'vim_move_to_first_nonwhitespace' });
|
| 1762 |
+
}, []);
|
| 1763 |
+
|
| 1764 |
+
const vimMoveToFirstLine = useCallback((): void => {
|
| 1765 |
+
dispatch({ type: 'vim_move_to_first_line' });
|
| 1766 |
+
}, []);
|
| 1767 |
+
|
| 1768 |
+
const vimMoveToLastLine = useCallback((): void => {
|
| 1769 |
+
dispatch({ type: 'vim_move_to_last_line' });
|
| 1770 |
+
}, []);
|
| 1771 |
+
|
| 1772 |
+
const vimMoveToLine = useCallback((lineNumber: number): void => {
|
| 1773 |
+
dispatch({ type: 'vim_move_to_line', payload: { lineNumber } });
|
| 1774 |
+
}, []);
|
| 1775 |
+
|
| 1776 |
+
const vimEscapeInsertMode = useCallback((): void => {
|
| 1777 |
+
dispatch({ type: 'vim_escape_insert_mode' });
|
| 1778 |
+
}, []);
|
| 1779 |
+
|
| 1780 |
+
const openInExternalEditor = useCallback(
|
| 1781 |
+
async (opts: { editor?: string } = {}): Promise<void> => {
|
| 1782 |
+
const editor =
|
| 1783 |
+
opts.editor ??
|
| 1784 |
+
process.env['VISUAL'] ??
|
| 1785 |
+
process.env['EDITOR'] ??
|
| 1786 |
+
(process.platform === 'win32' ? 'notepad' : 'vi');
|
| 1787 |
+
const tmpDir = fs.mkdtempSync(pathMod.join(os.tmpdir(), 'gemini-edit-'));
|
| 1788 |
+
const filePath = pathMod.join(tmpDir, 'buffer.txt');
|
| 1789 |
+
fs.writeFileSync(filePath, text, 'utf8');
|
| 1790 |
+
|
| 1791 |
+
dispatch({ type: 'create_undo_snapshot' });
|
| 1792 |
+
|
| 1793 |
+
const wasRaw = stdin?.isRaw ?? false;
|
| 1794 |
+
try {
|
| 1795 |
+
setRawMode?.(false);
|
| 1796 |
+
const { status, error } = spawnSync(editor, [filePath], {
|
| 1797 |
+
stdio: 'inherit',
|
| 1798 |
+
});
|
| 1799 |
+
if (error) throw error;
|
| 1800 |
+
if (typeof status === 'number' && status !== 0)
|
| 1801 |
+
throw new Error(`External editor exited with status ${status}`);
|
| 1802 |
+
|
| 1803 |
+
let newText = fs.readFileSync(filePath, 'utf8');
|
| 1804 |
+
newText = newText.replace(/\r\n?/g, '\n');
|
| 1805 |
+
dispatch({ type: 'set_text', payload: newText, pushToUndo: false });
|
| 1806 |
+
} catch (err) {
|
| 1807 |
+
console.error('[useTextBuffer] external editor error', err);
|
| 1808 |
+
} finally {
|
| 1809 |
+
if (wasRaw) setRawMode?.(true);
|
| 1810 |
+
try {
|
| 1811 |
+
fs.unlinkSync(filePath);
|
| 1812 |
+
} catch {
|
| 1813 |
+
/* ignore */
|
| 1814 |
+
}
|
| 1815 |
+
try {
|
| 1816 |
+
fs.rmdirSync(tmpDir);
|
| 1817 |
+
} catch {
|
| 1818 |
+
/* ignore */
|
| 1819 |
+
}
|
| 1820 |
+
}
|
| 1821 |
+
},
|
| 1822 |
+
[text, stdin, setRawMode],
|
| 1823 |
+
);
|
| 1824 |
+
|
| 1825 |
+
const handleInput = useCallback(
|
| 1826 |
+
(key: {
|
| 1827 |
+
name: string;
|
| 1828 |
+
ctrl: boolean;
|
| 1829 |
+
meta: boolean;
|
| 1830 |
+
shift: boolean;
|
| 1831 |
+
paste: boolean;
|
| 1832 |
+
sequence: string;
|
| 1833 |
+
}): void => {
|
| 1834 |
+
const { sequence: input } = key;
|
| 1835 |
+
|
| 1836 |
+
if (key.paste) {
|
| 1837 |
+
// Do not do any other processing on pastes so ensure we handle them
|
| 1838 |
+
// before all other cases.
|
| 1839 |
+
insert(input, { paste: key.paste });
|
| 1840 |
+
return;
|
| 1841 |
+
}
|
| 1842 |
+
|
| 1843 |
+
if (
|
| 1844 |
+
key.name === 'return' ||
|
| 1845 |
+
input === '\r' ||
|
| 1846 |
+
input === '\n' ||
|
| 1847 |
+
input === '\\\r' // VSCode terminal represents shift + enter this way
|
| 1848 |
+
)
|
| 1849 |
+
newline();
|
| 1850 |
+
else if (key.name === 'left' && !key.meta && !key.ctrl) move('left');
|
| 1851 |
+
else if (key.ctrl && key.name === 'b') move('left');
|
| 1852 |
+
else if (key.name === 'right' && !key.meta && !key.ctrl) move('right');
|
| 1853 |
+
else if (key.ctrl && key.name === 'f') move('right');
|
| 1854 |
+
else if (key.name === 'up') move('up');
|
| 1855 |
+
else if (key.name === 'down') move('down');
|
| 1856 |
+
else if ((key.ctrl || key.meta) && key.name === 'left') move('wordLeft');
|
| 1857 |
+
else if (key.meta && key.name === 'b') move('wordLeft');
|
| 1858 |
+
else if ((key.ctrl || key.meta) && key.name === 'right')
|
| 1859 |
+
move('wordRight');
|
| 1860 |
+
else if (key.meta && key.name === 'f') move('wordRight');
|
| 1861 |
+
else if (key.name === 'home') move('home');
|
| 1862 |
+
else if (key.ctrl && key.name === 'a') move('home');
|
| 1863 |
+
else if (key.name === 'end') move('end');
|
| 1864 |
+
else if (key.ctrl && key.name === 'e') move('end');
|
| 1865 |
+
else if (key.ctrl && key.name === 'w') deleteWordLeft();
|
| 1866 |
+
else if (
|
| 1867 |
+
(key.meta || key.ctrl) &&
|
| 1868 |
+
(key.name === 'backspace' || input === '\x7f')
|
| 1869 |
+
)
|
| 1870 |
+
deleteWordLeft();
|
| 1871 |
+
else if ((key.meta || key.ctrl) && key.name === 'delete')
|
| 1872 |
+
deleteWordRight();
|
| 1873 |
+
else if (
|
| 1874 |
+
key.name === 'backspace' ||
|
| 1875 |
+
input === '\x7f' ||
|
| 1876 |
+
(key.ctrl && key.name === 'h')
|
| 1877 |
+
)
|
| 1878 |
+
backspace();
|
| 1879 |
+
else if (key.name === 'delete' || (key.ctrl && key.name === 'd')) del();
|
| 1880 |
+
else if (input && !key.ctrl && !key.meta) {
|
| 1881 |
+
insert(input, { paste: key.paste });
|
| 1882 |
+
}
|
| 1883 |
+
},
|
| 1884 |
+
[newline, move, deleteWordLeft, deleteWordRight, backspace, del, insert],
|
| 1885 |
+
);
|
| 1886 |
+
|
| 1887 |
+
const renderedVisualLines = useMemo(
|
| 1888 |
+
() => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height),
|
| 1889 |
+
[visualLines, visualScrollRow, viewport.height],
|
| 1890 |
+
);
|
| 1891 |
+
|
| 1892 |
+
const replaceRange = useCallback(
|
| 1893 |
+
(
|
| 1894 |
+
startRow: number,
|
| 1895 |
+
startCol: number,
|
| 1896 |
+
endRow: number,
|
| 1897 |
+
endCol: number,
|
| 1898 |
+
text: string,
|
| 1899 |
+
): void => {
|
| 1900 |
+
dispatch({
|
| 1901 |
+
type: 'replace_range',
|
| 1902 |
+
payload: { startRow, startCol, endRow, endCol, text },
|
| 1903 |
+
});
|
| 1904 |
+
},
|
| 1905 |
+
[],
|
| 1906 |
+
);
|
| 1907 |
+
|
| 1908 |
+
const replaceRangeByOffset = useCallback(
|
| 1909 |
+
(startOffset: number, endOffset: number, replacementText: string): void => {
|
| 1910 |
+
const [startRow, startCol] = offsetToLogicalPos(text, startOffset);
|
| 1911 |
+
const [endRow, endCol] = offsetToLogicalPos(text, endOffset);
|
| 1912 |
+
replaceRange(startRow, startCol, endRow, endCol, replacementText);
|
| 1913 |
+
},
|
| 1914 |
+
[text, replaceRange],
|
| 1915 |
+
);
|
| 1916 |
+
|
| 1917 |
+
const moveToOffset = useCallback((offset: number): void => {
|
| 1918 |
+
dispatch({ type: 'move_to_offset', payload: { offset } });
|
| 1919 |
+
}, []);
|
| 1920 |
+
|
| 1921 |
+
const returnValue: TextBuffer = {
|
| 1922 |
+
lines,
|
| 1923 |
+
text,
|
| 1924 |
+
cursor: [cursorRow, cursorCol],
|
| 1925 |
+
preferredCol,
|
| 1926 |
+
selectionAnchor,
|
| 1927 |
+
|
| 1928 |
+
allVisualLines: visualLines,
|
| 1929 |
+
viewportVisualLines: renderedVisualLines,
|
| 1930 |
+
visualCursor,
|
| 1931 |
+
visualScrollRow,
|
| 1932 |
+
|
| 1933 |
+
setText,
|
| 1934 |
+
insert,
|
| 1935 |
+
newline,
|
| 1936 |
+
backspace,
|
| 1937 |
+
del,
|
| 1938 |
+
move,
|
| 1939 |
+
undo,
|
| 1940 |
+
redo,
|
| 1941 |
+
replaceRange,
|
| 1942 |
+
replaceRangeByOffset,
|
| 1943 |
+
moveToOffset,
|
| 1944 |
+
deleteWordLeft,
|
| 1945 |
+
deleteWordRight,
|
| 1946 |
+
killLineRight,
|
| 1947 |
+
killLineLeft,
|
| 1948 |
+
handleInput,
|
| 1949 |
+
openInExternalEditor,
|
| 1950 |
+
// Vim-specific operations
|
| 1951 |
+
vimDeleteWordForward,
|
| 1952 |
+
vimDeleteWordBackward,
|
| 1953 |
+
vimDeleteWordEnd,
|
| 1954 |
+
vimChangeWordForward,
|
| 1955 |
+
vimChangeWordBackward,
|
| 1956 |
+
vimChangeWordEnd,
|
| 1957 |
+
vimDeleteLine,
|
| 1958 |
+
vimChangeLine,
|
| 1959 |
+
vimDeleteToEndOfLine,
|
| 1960 |
+
vimChangeToEndOfLine,
|
| 1961 |
+
vimChangeMovement,
|
| 1962 |
+
vimMoveLeft,
|
| 1963 |
+
vimMoveRight,
|
| 1964 |
+
vimMoveUp,
|
| 1965 |
+
vimMoveDown,
|
| 1966 |
+
vimMoveWordForward,
|
| 1967 |
+
vimMoveWordBackward,
|
| 1968 |
+
vimMoveWordEnd,
|
| 1969 |
+
vimDeleteChar,
|
| 1970 |
+
vimInsertAtCursor,
|
| 1971 |
+
vimAppendAtCursor,
|
| 1972 |
+
vimOpenLineBelow,
|
| 1973 |
+
vimOpenLineAbove,
|
| 1974 |
+
vimAppendAtLineEnd,
|
| 1975 |
+
vimInsertAtLineStart,
|
| 1976 |
+
vimMoveToLineStart,
|
| 1977 |
+
vimMoveToLineEnd,
|
| 1978 |
+
vimMoveToFirstNonWhitespace,
|
| 1979 |
+
vimMoveToFirstLine,
|
| 1980 |
+
vimMoveToLastLine,
|
| 1981 |
+
vimMoveToLine,
|
| 1982 |
+
vimEscapeInsertMode,
|
| 1983 |
+
};
|
| 1984 |
+
return returnValue;
|
| 1985 |
+
}
|
| 1986 |
+
|
| 1987 |
+
export interface TextBuffer {
|
| 1988 |
+
// State
|
| 1989 |
+
lines: string[]; // Logical lines
|
| 1990 |
+
text: string;
|
| 1991 |
+
cursor: [number, number]; // Logical cursor [row, col]
|
| 1992 |
+
/**
|
| 1993 |
+
* When the user moves the caret vertically we try to keep their original
|
| 1994 |
+
* horizontal column even when passing through shorter lines. We remember
|
| 1995 |
+
* that *preferred* column in this field while the user is still travelling
|
| 1996 |
+
* vertically. Any explicit horizontal movement resets the preference.
|
| 1997 |
+
*/
|
| 1998 |
+
preferredCol: number | null; // Preferred visual column
|
| 1999 |
+
selectionAnchor: [number, number] | null; // Logical selection anchor
|
| 2000 |
+
|
| 2001 |
+
// Visual state (handles wrapping)
|
| 2002 |
+
allVisualLines: string[]; // All visual lines for the current text and viewport width.
|
| 2003 |
+
viewportVisualLines: string[]; // The subset of visual lines to be rendered based on visualScrollRow and viewport.height
|
| 2004 |
+
visualCursor: [number, number]; // Visual cursor [row, col] relative to the start of all visualLines
|
| 2005 |
+
visualScrollRow: number; // Scroll position for visual lines (index of the first visible visual line)
|
| 2006 |
+
|
| 2007 |
+
// Actions
|
| 2008 |
+
|
| 2009 |
+
/**
|
| 2010 |
+
* Replaces the entire buffer content with the provided text.
|
| 2011 |
+
* The operation is undoable.
|
| 2012 |
+
*/
|
| 2013 |
+
setText: (text: string) => void;
|
| 2014 |
+
/**
|
| 2015 |
+
* Insert a single character or string without newlines.
|
| 2016 |
+
*/
|
| 2017 |
+
insert: (ch: string, opts?: { paste?: boolean }) => void;
|
| 2018 |
+
newline: () => void;
|
| 2019 |
+
backspace: () => void;
|
| 2020 |
+
del: () => void;
|
| 2021 |
+
move: (dir: Direction) => void;
|
| 2022 |
+
undo: () => void;
|
| 2023 |
+
redo: () => void;
|
| 2024 |
+
/**
|
| 2025 |
+
* Replaces the text within the specified range with new text.
|
| 2026 |
+
* Handles both single-line and multi-line ranges.
|
| 2027 |
+
*
|
| 2028 |
+
* @param startRow The starting row index (inclusive).
|
| 2029 |
+
* @param startCol The starting column index (inclusive, code-point based).
|
| 2030 |
+
* @param endRow The ending row index (inclusive).
|
| 2031 |
+
* @param endCol The ending column index (exclusive, code-point based).
|
| 2032 |
+
* @param text The new text to insert.
|
| 2033 |
+
* @returns True if the buffer was modified, false otherwise.
|
| 2034 |
+
*/
|
| 2035 |
+
replaceRange: (
|
| 2036 |
+
startRow: number,
|
| 2037 |
+
startCol: number,
|
| 2038 |
+
endRow: number,
|
| 2039 |
+
endCol: number,
|
| 2040 |
+
text: string,
|
| 2041 |
+
) => void;
|
| 2042 |
+
/**
|
| 2043 |
+
* Delete the word to the *left* of the caret, mirroring common
|
| 2044 |
+
* Ctrl/Alt+Backspace behaviour in editors & terminals. Both the adjacent
|
| 2045 |
+
* whitespace *and* the word characters immediately preceding the caret are
|
| 2046 |
+
* removed. If the caret is already at column‑0 this becomes a no-op.
|
| 2047 |
+
*/
|
| 2048 |
+
deleteWordLeft: () => void;
|
| 2049 |
+
/**
|
| 2050 |
+
* Delete the word to the *right* of the caret, akin to many editors'
|
| 2051 |
+
* Ctrl/Alt+Delete shortcut. Removes any whitespace/punctuation that
|
| 2052 |
+
* follows the caret and the next contiguous run of word characters.
|
| 2053 |
+
*/
|
| 2054 |
+
deleteWordRight: () => void;
|
| 2055 |
+
/**
|
| 2056 |
+
* Deletes text from the cursor to the end of the current line.
|
| 2057 |
+
*/
|
| 2058 |
+
killLineRight: () => void;
|
| 2059 |
+
/**
|
| 2060 |
+
* Deletes text from the start of the current line to the cursor.
|
| 2061 |
+
*/
|
| 2062 |
+
killLineLeft: () => void;
|
| 2063 |
+
/**
|
| 2064 |
+
* High level "handleInput" – receives what Ink gives us.
|
| 2065 |
+
*/
|
| 2066 |
+
handleInput: (key: {
|
| 2067 |
+
name: string;
|
| 2068 |
+
ctrl: boolean;
|
| 2069 |
+
meta: boolean;
|
| 2070 |
+
shift: boolean;
|
| 2071 |
+
paste: boolean;
|
| 2072 |
+
sequence: string;
|
| 2073 |
+
}) => void;
|
| 2074 |
+
/**
|
| 2075 |
+
* Opens the current buffer contents in the user's preferred terminal text
|
| 2076 |
+
* editor ($VISUAL or $EDITOR, falling back to "vi"). The method blocks
|
| 2077 |
+
* until the editor exits, then reloads the file and replaces the in‑memory
|
| 2078 |
+
* buffer with whatever the user saved.
|
| 2079 |
+
*
|
| 2080 |
+
* The operation is treated as a single undoable edit – we snapshot the
|
| 2081 |
+
* previous state *once* before launching the editor so one `undo()` will
|
| 2082 |
+
* revert the entire change set.
|
| 2083 |
+
*
|
| 2084 |
+
* Note: We purposefully rely on the *synchronous* spawn API so that the
|
| 2085 |
+
* calling process genuinely waits for the editor to close before
|
| 2086 |
+
* continuing. This mirrors Git's behaviour and simplifies downstream
|
| 2087 |
+
* control‑flow (callers can simply `await` the Promise).
|
| 2088 |
+
*/
|
| 2089 |
+
openInExternalEditor: (opts?: { editor?: string }) => Promise<void>;
|
| 2090 |
+
|
| 2091 |
+
replaceRangeByOffset: (
|
| 2092 |
+
startOffset: number,
|
| 2093 |
+
endOffset: number,
|
| 2094 |
+
replacementText: string,
|
| 2095 |
+
) => void;
|
| 2096 |
+
moveToOffset(offset: number): void;
|
| 2097 |
+
|
| 2098 |
+
// Vim-specific operations
|
| 2099 |
+
/**
|
| 2100 |
+
* Delete N words forward from cursor position (vim 'dw' command)
|
| 2101 |
+
*/
|
| 2102 |
+
vimDeleteWordForward: (count: number) => void;
|
| 2103 |
+
/**
|
| 2104 |
+
* Delete N words backward from cursor position (vim 'db' command)
|
| 2105 |
+
*/
|
| 2106 |
+
vimDeleteWordBackward: (count: number) => void;
|
| 2107 |
+
/**
|
| 2108 |
+
* Delete to end of N words from cursor position (vim 'de' command)
|
| 2109 |
+
*/
|
| 2110 |
+
vimDeleteWordEnd: (count: number) => void;
|
| 2111 |
+
/**
|
| 2112 |
+
* Change N words forward from cursor position (vim 'cw' command)
|
| 2113 |
+
*/
|
| 2114 |
+
vimChangeWordForward: (count: number) => void;
|
| 2115 |
+
/**
|
| 2116 |
+
* Change N words backward from cursor position (vim 'cb' command)
|
| 2117 |
+
*/
|
| 2118 |
+
vimChangeWordBackward: (count: number) => void;
|
| 2119 |
+
/**
|
| 2120 |
+
* Change to end of N words from cursor position (vim 'ce' command)
|
| 2121 |
+
*/
|
| 2122 |
+
vimChangeWordEnd: (count: number) => void;
|
| 2123 |
+
/**
|
| 2124 |
+
* Delete N lines from cursor position (vim 'dd' command)
|
| 2125 |
+
*/
|
| 2126 |
+
vimDeleteLine: (count: number) => void;
|
| 2127 |
+
/**
|
| 2128 |
+
* Change N lines from cursor position (vim 'cc' command)
|
| 2129 |
+
*/
|
| 2130 |
+
vimChangeLine: (count: number) => void;
|
| 2131 |
+
/**
|
| 2132 |
+
* Delete from cursor to end of line (vim 'D' command)
|
| 2133 |
+
*/
|
| 2134 |
+
vimDeleteToEndOfLine: () => void;
|
| 2135 |
+
/**
|
| 2136 |
+
* Change from cursor to end of line (vim 'C' command)
|
| 2137 |
+
*/
|
| 2138 |
+
vimChangeToEndOfLine: () => void;
|
| 2139 |
+
/**
|
| 2140 |
+
* Change movement operations (vim 'ch', 'cj', 'ck', 'cl' commands)
|
| 2141 |
+
*/
|
| 2142 |
+
vimChangeMovement: (movement: 'h' | 'j' | 'k' | 'l', count: number) => void;
|
| 2143 |
+
/**
|
| 2144 |
+
* Move cursor left N times (vim 'h' command)
|
| 2145 |
+
*/
|
| 2146 |
+
vimMoveLeft: (count: number) => void;
|
| 2147 |
+
/**
|
| 2148 |
+
* Move cursor right N times (vim 'l' command)
|
| 2149 |
+
*/
|
| 2150 |
+
vimMoveRight: (count: number) => void;
|
| 2151 |
+
/**
|
| 2152 |
+
* Move cursor up N times (vim 'k' command)
|
| 2153 |
+
*/
|
| 2154 |
+
vimMoveUp: (count: number) => void;
|
| 2155 |
+
/**
|
| 2156 |
+
* Move cursor down N times (vim 'j' command)
|
| 2157 |
+
*/
|
| 2158 |
+
vimMoveDown: (count: number) => void;
|
| 2159 |
+
/**
|
| 2160 |
+
* Move cursor forward N words (vim 'w' command)
|
| 2161 |
+
*/
|
| 2162 |
+
vimMoveWordForward: (count: number) => void;
|
| 2163 |
+
/**
|
| 2164 |
+
* Move cursor backward N words (vim 'b' command)
|
| 2165 |
+
*/
|
| 2166 |
+
vimMoveWordBackward: (count: number) => void;
|
| 2167 |
+
/**
|
| 2168 |
+
* Move cursor to end of Nth word (vim 'e' command)
|
| 2169 |
+
*/
|
| 2170 |
+
vimMoveWordEnd: (count: number) => void;
|
| 2171 |
+
/**
|
| 2172 |
+
* Delete N characters at cursor (vim 'x' command)
|
| 2173 |
+
*/
|
| 2174 |
+
vimDeleteChar: (count: number) => void;
|
| 2175 |
+
/**
|
| 2176 |
+
* Enter insert mode at cursor (vim 'i' command)
|
| 2177 |
+
*/
|
| 2178 |
+
vimInsertAtCursor: () => void;
|
| 2179 |
+
/**
|
| 2180 |
+
* Enter insert mode after cursor (vim 'a' command)
|
| 2181 |
+
*/
|
| 2182 |
+
vimAppendAtCursor: () => void;
|
| 2183 |
+
/**
|
| 2184 |
+
* Open new line below and enter insert mode (vim 'o' command)
|
| 2185 |
+
*/
|
| 2186 |
+
vimOpenLineBelow: () => void;
|
| 2187 |
+
/**
|
| 2188 |
+
* Open new line above and enter insert mode (vim 'O' command)
|
| 2189 |
+
*/
|
| 2190 |
+
vimOpenLineAbove: () => void;
|
| 2191 |
+
/**
|
| 2192 |
+
* Move to end of line and enter insert mode (vim 'A' command)
|
| 2193 |
+
*/
|
| 2194 |
+
vimAppendAtLineEnd: () => void;
|
| 2195 |
+
/**
|
| 2196 |
+
* Move to first non-whitespace and enter insert mode (vim 'I' command)
|
| 2197 |
+
*/
|
| 2198 |
+
vimInsertAtLineStart: () => void;
|
| 2199 |
+
/**
|
| 2200 |
+
* Move cursor to beginning of line (vim '0' command)
|
| 2201 |
+
*/
|
| 2202 |
+
vimMoveToLineStart: () => void;
|
| 2203 |
+
/**
|
| 2204 |
+
* Move cursor to end of line (vim '$' command)
|
| 2205 |
+
*/
|
| 2206 |
+
vimMoveToLineEnd: () => void;
|
| 2207 |
+
/**
|
| 2208 |
+
* Move cursor to first non-whitespace character (vim '^' command)
|
| 2209 |
+
*/
|
| 2210 |
+
vimMoveToFirstNonWhitespace: () => void;
|
| 2211 |
+
/**
|
| 2212 |
+
* Move cursor to first line (vim 'gg' command)
|
| 2213 |
+
*/
|
| 2214 |
+
vimMoveToFirstLine: () => void;
|
| 2215 |
+
/**
|
| 2216 |
+
* Move cursor to last line (vim 'G' command)
|
| 2217 |
+
*/
|
| 2218 |
+
vimMoveToLastLine: () => void;
|
| 2219 |
+
/**
|
| 2220 |
+
* Move cursor to specific line number (vim '[N]G' command)
|
| 2221 |
+
*/
|
| 2222 |
+
vimMoveToLine: (lineNumber: number) => void;
|
| 2223 |
+
/**
|
| 2224 |
+
* Handle escape from insert mode (moves cursor left if not at line start)
|
| 2225 |
+
*/
|
| 2226 |
+
vimEscapeInsertMode: () => void;
|
| 2227 |
+
}
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/vim-buffer-actions.test.ts
ADDED
|
@@ -0,0 +1,1119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect } from 'vitest';
|
| 8 |
+
import { handleVimAction } from './vim-buffer-actions.js';
|
| 9 |
+
import type { TextBufferState } from './text-buffer.js';
|
| 10 |
+
|
| 11 |
+
// Helper to create test state
|
| 12 |
+
const createTestState = (
|
| 13 |
+
lines: string[] = ['hello world'],
|
| 14 |
+
cursorRow = 0,
|
| 15 |
+
cursorCol = 0,
|
| 16 |
+
): TextBufferState => ({
|
| 17 |
+
lines,
|
| 18 |
+
cursorRow,
|
| 19 |
+
cursorCol,
|
| 20 |
+
preferredCol: null,
|
| 21 |
+
undoStack: [],
|
| 22 |
+
redoStack: [],
|
| 23 |
+
clipboard: null,
|
| 24 |
+
selectionAnchor: null,
|
| 25 |
+
viewportWidth: 80,
|
| 26 |
+
});
|
| 27 |
+
|
| 28 |
+
describe('vim-buffer-actions', () => {
|
| 29 |
+
describe('Movement commands', () => {
|
| 30 |
+
describe('vim_move_left', () => {
|
| 31 |
+
it('should move cursor left by count', () => {
|
| 32 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 33 |
+
const action = {
|
| 34 |
+
type: 'vim_move_left' as const,
|
| 35 |
+
payload: { count: 3 },
|
| 36 |
+
};
|
| 37 |
+
|
| 38 |
+
const result = handleVimAction(state, action);
|
| 39 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 40 |
+
expect(result.cursorCol).toBe(2);
|
| 41 |
+
expect(result.preferredCol).toBeNull();
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
it('should not move past beginning of line', () => {
|
| 45 |
+
const state = createTestState(['hello'], 0, 2);
|
| 46 |
+
const action = {
|
| 47 |
+
type: 'vim_move_left' as const,
|
| 48 |
+
payload: { count: 5 },
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
const result = handleVimAction(state, action);
|
| 52 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 53 |
+
expect(result.cursorCol).toBe(0);
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
it('should wrap to previous line when at beginning', () => {
|
| 57 |
+
const state = createTestState(['line1', 'line2'], 1, 0);
|
| 58 |
+
const action = {
|
| 59 |
+
type: 'vim_move_left' as const,
|
| 60 |
+
payload: { count: 1 },
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
const result = handleVimAction(state, action);
|
| 64 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 65 |
+
expect(result.cursorRow).toBe(0);
|
| 66 |
+
expect(result.cursorCol).toBe(4); // On last character '1' of 'line1'
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
it('should handle multiple line wrapping', () => {
|
| 70 |
+
const state = createTestState(['abc', 'def', 'ghi'], 2, 0);
|
| 71 |
+
const action = {
|
| 72 |
+
type: 'vim_move_left' as const,
|
| 73 |
+
payload: { count: 5 },
|
| 74 |
+
};
|
| 75 |
+
|
| 76 |
+
const result = handleVimAction(state, action);
|
| 77 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 78 |
+
expect(result.cursorRow).toBe(0);
|
| 79 |
+
expect(result.cursorCol).toBe(1); // On 'b' after 5 left movements
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it('should correctly handle h/l movement between lines', () => {
|
| 83 |
+
// Start at end of first line at 'd' (position 10)
|
| 84 |
+
let state = createTestState(['hello world', 'foo bar'], 0, 10);
|
| 85 |
+
|
| 86 |
+
// Move right - should go to beginning of next line
|
| 87 |
+
state = handleVimAction(state, {
|
| 88 |
+
type: 'vim_move_right' as const,
|
| 89 |
+
payload: { count: 1 },
|
| 90 |
+
});
|
| 91 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 92 |
+
expect(state.cursorRow).toBe(1);
|
| 93 |
+
expect(state.cursorCol).toBe(0); // Should be on 'f'
|
| 94 |
+
|
| 95 |
+
// Move left - should go back to end of previous line on 'd'
|
| 96 |
+
state = handleVimAction(state, {
|
| 97 |
+
type: 'vim_move_left' as const,
|
| 98 |
+
payload: { count: 1 },
|
| 99 |
+
});
|
| 100 |
+
expect(state).toHaveOnlyValidCharacters();
|
| 101 |
+
expect(state.cursorRow).toBe(0);
|
| 102 |
+
expect(state.cursorCol).toBe(10); // Should be on 'd', not past it
|
| 103 |
+
});
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
describe('vim_move_right', () => {
|
| 107 |
+
it('should move cursor right by count', () => {
|
| 108 |
+
const state = createTestState(['hello world'], 0, 2);
|
| 109 |
+
const action = {
|
| 110 |
+
type: 'vim_move_right' as const,
|
| 111 |
+
payload: { count: 3 },
|
| 112 |
+
};
|
| 113 |
+
|
| 114 |
+
const result = handleVimAction(state, action);
|
| 115 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 116 |
+
expect(result.cursorCol).toBe(5);
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it('should not move past last character of line', () => {
|
| 120 |
+
const state = createTestState(['hello'], 0, 3);
|
| 121 |
+
const action = {
|
| 122 |
+
type: 'vim_move_right' as const,
|
| 123 |
+
payload: { count: 5 },
|
| 124 |
+
};
|
| 125 |
+
|
| 126 |
+
const result = handleVimAction(state, action);
|
| 127 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 128 |
+
expect(result.cursorCol).toBe(4); // Last character of 'hello'
|
| 129 |
+
});
|
| 130 |
+
|
| 131 |
+
it('should wrap to next line when at end', () => {
|
| 132 |
+
const state = createTestState(['line1', 'line2'], 0, 4); // At end of 'line1'
|
| 133 |
+
const action = {
|
| 134 |
+
type: 'vim_move_right' as const,
|
| 135 |
+
payload: { count: 1 },
|
| 136 |
+
};
|
| 137 |
+
|
| 138 |
+
const result = handleVimAction(state, action);
|
| 139 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 140 |
+
expect(result.cursorRow).toBe(1);
|
| 141 |
+
expect(result.cursorCol).toBe(0);
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
it('should skip over combining marks to avoid cursor disappearing', () => {
|
| 145 |
+
// Test case for combining character cursor disappearing bug
|
| 146 |
+
// "café test" where é is represented as e + combining acute accent
|
| 147 |
+
const state = createTestState(['cafe\u0301 test'], 0, 2); // Start at 'f'
|
| 148 |
+
const action = {
|
| 149 |
+
type: 'vim_move_right' as const,
|
| 150 |
+
payload: { count: 1 },
|
| 151 |
+
};
|
| 152 |
+
|
| 153 |
+
const result = handleVimAction(state, action);
|
| 154 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 155 |
+
expect(result.cursorCol).toBe(3); // Should be on 'e' of 'café'
|
| 156 |
+
|
| 157 |
+
// Move right again - should skip combining mark and land on space
|
| 158 |
+
const result2 = handleVimAction(result, action);
|
| 159 |
+
expect(result2).toHaveOnlyValidCharacters();
|
| 160 |
+
expect(result2.cursorCol).toBe(5); // Should be on space after 'café'
|
| 161 |
+
});
|
| 162 |
+
});
|
| 163 |
+
|
| 164 |
+
describe('vim_move_up', () => {
|
| 165 |
+
it('should move cursor up by count', () => {
|
| 166 |
+
const state = createTestState(['line1', 'line2', 'line3'], 2, 3);
|
| 167 |
+
const action = { type: 'vim_move_up' as const, payload: { count: 2 } };
|
| 168 |
+
|
| 169 |
+
const result = handleVimAction(state, action);
|
| 170 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 171 |
+
expect(result.cursorRow).toBe(0);
|
| 172 |
+
expect(result.cursorCol).toBe(3);
|
| 173 |
+
});
|
| 174 |
+
|
| 175 |
+
it('should not move past first line', () => {
|
| 176 |
+
const state = createTestState(['line1', 'line2'], 1, 3);
|
| 177 |
+
const action = { type: 'vim_move_up' as const, payload: { count: 5 } };
|
| 178 |
+
|
| 179 |
+
const result = handleVimAction(state, action);
|
| 180 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 181 |
+
expect(result.cursorRow).toBe(0);
|
| 182 |
+
});
|
| 183 |
+
|
| 184 |
+
it('should adjust column for shorter lines', () => {
|
| 185 |
+
const state = createTestState(['short', 'very long line'], 1, 10);
|
| 186 |
+
const action = { type: 'vim_move_up' as const, payload: { count: 1 } };
|
| 187 |
+
|
| 188 |
+
const result = handleVimAction(state, action);
|
| 189 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 190 |
+
expect(result.cursorRow).toBe(0);
|
| 191 |
+
expect(result.cursorCol).toBe(4); // Last character 't' of 'short', not past it
|
| 192 |
+
});
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
describe('vim_move_down', () => {
|
| 196 |
+
it('should move cursor down by count', () => {
|
| 197 |
+
const state = createTestState(['line1', 'line2', 'line3'], 0, 2);
|
| 198 |
+
const action = {
|
| 199 |
+
type: 'vim_move_down' as const,
|
| 200 |
+
payload: { count: 2 },
|
| 201 |
+
};
|
| 202 |
+
|
| 203 |
+
const result = handleVimAction(state, action);
|
| 204 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 205 |
+
expect(result.cursorRow).toBe(2);
|
| 206 |
+
expect(result.cursorCol).toBe(2);
|
| 207 |
+
});
|
| 208 |
+
|
| 209 |
+
it('should not move past last line', () => {
|
| 210 |
+
const state = createTestState(['line1', 'line2'], 0, 2);
|
| 211 |
+
const action = {
|
| 212 |
+
type: 'vim_move_down' as const,
|
| 213 |
+
payload: { count: 5 },
|
| 214 |
+
};
|
| 215 |
+
|
| 216 |
+
const result = handleVimAction(state, action);
|
| 217 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 218 |
+
expect(result.cursorRow).toBe(1);
|
| 219 |
+
});
|
| 220 |
+
});
|
| 221 |
+
|
| 222 |
+
describe('vim_move_word_forward', () => {
|
| 223 |
+
it('should move to start of next word', () => {
|
| 224 |
+
const state = createTestState(['hello world test'], 0, 0);
|
| 225 |
+
const action = {
|
| 226 |
+
type: 'vim_move_word_forward' as const,
|
| 227 |
+
payload: { count: 1 },
|
| 228 |
+
};
|
| 229 |
+
|
| 230 |
+
const result = handleVimAction(state, action);
|
| 231 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 232 |
+
expect(result.cursorCol).toBe(6); // Start of 'world'
|
| 233 |
+
});
|
| 234 |
+
|
| 235 |
+
it('should handle multiple words', () => {
|
| 236 |
+
const state = createTestState(['hello world test'], 0, 0);
|
| 237 |
+
const action = {
|
| 238 |
+
type: 'vim_move_word_forward' as const,
|
| 239 |
+
payload: { count: 2 },
|
| 240 |
+
};
|
| 241 |
+
|
| 242 |
+
const result = handleVimAction(state, action);
|
| 243 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 244 |
+
expect(result.cursorCol).toBe(12); // Start of 'test'
|
| 245 |
+
});
|
| 246 |
+
|
| 247 |
+
it('should handle punctuation correctly', () => {
|
| 248 |
+
const state = createTestState(['hello, world!'], 0, 0);
|
| 249 |
+
const action = {
|
| 250 |
+
type: 'vim_move_word_forward' as const,
|
| 251 |
+
payload: { count: 1 },
|
| 252 |
+
};
|
| 253 |
+
|
| 254 |
+
const result = handleVimAction(state, action);
|
| 255 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 256 |
+
expect(result.cursorCol).toBe(5); // Start of ','
|
| 257 |
+
});
|
| 258 |
+
|
| 259 |
+
it('should move across empty lines when starting from within a word', () => {
|
| 260 |
+
// Testing the exact scenario: cursor on 'w' of 'hello world', w should move to next line
|
| 261 |
+
const state = createTestState(['hello world', ''], 0, 6); // At 'w' of 'world'
|
| 262 |
+
const action = {
|
| 263 |
+
type: 'vim_move_word_forward' as const,
|
| 264 |
+
payload: { count: 1 },
|
| 265 |
+
};
|
| 266 |
+
|
| 267 |
+
const result = handleVimAction(state, action);
|
| 268 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 269 |
+
expect(result.cursorRow).toBe(1); // Should move to empty line
|
| 270 |
+
expect(result.cursorCol).toBe(0); // Beginning of empty line
|
| 271 |
+
});
|
| 272 |
+
});
|
| 273 |
+
|
| 274 |
+
describe('vim_move_word_backward', () => {
|
| 275 |
+
it('should move to start of previous word', () => {
|
| 276 |
+
const state = createTestState(['hello world test'], 0, 12);
|
| 277 |
+
const action = {
|
| 278 |
+
type: 'vim_move_word_backward' as const,
|
| 279 |
+
payload: { count: 1 },
|
| 280 |
+
};
|
| 281 |
+
|
| 282 |
+
const result = handleVimAction(state, action);
|
| 283 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 284 |
+
expect(result.cursorCol).toBe(6); // Start of 'world'
|
| 285 |
+
});
|
| 286 |
+
|
| 287 |
+
it('should handle multiple words', () => {
|
| 288 |
+
const state = createTestState(['hello world test'], 0, 12);
|
| 289 |
+
const action = {
|
| 290 |
+
type: 'vim_move_word_backward' as const,
|
| 291 |
+
payload: { count: 2 },
|
| 292 |
+
};
|
| 293 |
+
|
| 294 |
+
const result = handleVimAction(state, action);
|
| 295 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 296 |
+
expect(result.cursorCol).toBe(0); // Start of 'hello'
|
| 297 |
+
});
|
| 298 |
+
});
|
| 299 |
+
|
| 300 |
+
describe('vim_move_word_end', () => {
|
| 301 |
+
it('should move to end of current word', () => {
|
| 302 |
+
const state = createTestState(['hello world'], 0, 0);
|
| 303 |
+
const action = {
|
| 304 |
+
type: 'vim_move_word_end' as const,
|
| 305 |
+
payload: { count: 1 },
|
| 306 |
+
};
|
| 307 |
+
|
| 308 |
+
const result = handleVimAction(state, action);
|
| 309 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 310 |
+
expect(result.cursorCol).toBe(4); // End of 'hello'
|
| 311 |
+
});
|
| 312 |
+
|
| 313 |
+
it('should move to end of next word if already at word end', () => {
|
| 314 |
+
const state = createTestState(['hello world'], 0, 4);
|
| 315 |
+
const action = {
|
| 316 |
+
type: 'vim_move_word_end' as const,
|
| 317 |
+
payload: { count: 1 },
|
| 318 |
+
};
|
| 319 |
+
|
| 320 |
+
const result = handleVimAction(state, action);
|
| 321 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 322 |
+
expect(result.cursorCol).toBe(10); // End of 'world'
|
| 323 |
+
});
|
| 324 |
+
|
| 325 |
+
it('should move across empty lines when at word end', () => {
|
| 326 |
+
const state = createTestState(['hello world', '', 'test'], 0, 10); // At 'd' of 'world'
|
| 327 |
+
const action = {
|
| 328 |
+
type: 'vim_move_word_end' as const,
|
| 329 |
+
payload: { count: 1 },
|
| 330 |
+
};
|
| 331 |
+
|
| 332 |
+
const result = handleVimAction(state, action);
|
| 333 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 334 |
+
expect(result.cursorRow).toBe(2); // Should move to line with 'test'
|
| 335 |
+
expect(result.cursorCol).toBe(3); // Should be at 't' (end of 'test')
|
| 336 |
+
});
|
| 337 |
+
|
| 338 |
+
it('should handle consecutive word-end movements across empty lines', () => {
|
| 339 |
+
// Testing the exact scenario: cursor on 'w' of world, press 'e' twice
|
| 340 |
+
const state = createTestState(['hello world', ''], 0, 6); // At 'w' of 'world'
|
| 341 |
+
|
| 342 |
+
// First 'e' should move to 'd' of 'world'
|
| 343 |
+
let result = handleVimAction(state, {
|
| 344 |
+
type: 'vim_move_word_end' as const,
|
| 345 |
+
payload: { count: 1 },
|
| 346 |
+
});
|
| 347 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 348 |
+
expect(result.cursorRow).toBe(0);
|
| 349 |
+
expect(result.cursorCol).toBe(10); // At 'd' of 'world'
|
| 350 |
+
|
| 351 |
+
// Second 'e' should move to the empty line (end of file in this case)
|
| 352 |
+
result = handleVimAction(result, {
|
| 353 |
+
type: 'vim_move_word_end' as const,
|
| 354 |
+
payload: { count: 1 },
|
| 355 |
+
});
|
| 356 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 357 |
+
expect(result.cursorRow).toBe(1); // Should move to empty line
|
| 358 |
+
expect(result.cursorCol).toBe(0); // Empty line has col 0
|
| 359 |
+
});
|
| 360 |
+
|
| 361 |
+
it('should handle combining characters - advance from end of base character', () => {
|
| 362 |
+
// Test case for combining character word end bug
|
| 363 |
+
// "café test" where é is represented as e + combining acute accent
|
| 364 |
+
const state = createTestState(['cafe\u0301 test'], 0, 0); // Start at 'c'
|
| 365 |
+
|
| 366 |
+
// First 'e' command should move to the 'e' (position 3)
|
| 367 |
+
let result = handleVimAction(state, {
|
| 368 |
+
type: 'vim_move_word_end' as const,
|
| 369 |
+
payload: { count: 1 },
|
| 370 |
+
});
|
| 371 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 372 |
+
expect(result.cursorCol).toBe(3); // At 'e' of café
|
| 373 |
+
|
| 374 |
+
// Second 'e' command should advance to end of "test" (position 9), not stay stuck
|
| 375 |
+
result = handleVimAction(result, {
|
| 376 |
+
type: 'vim_move_word_end' as const,
|
| 377 |
+
payload: { count: 1 },
|
| 378 |
+
});
|
| 379 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 380 |
+
expect(result.cursorCol).toBe(9); // At 't' of "test"
|
| 381 |
+
});
|
| 382 |
+
|
| 383 |
+
it('should handle precomposed characters with diacritics', () => {
|
| 384 |
+
// Test case with precomposed é for comparison
|
| 385 |
+
const state = createTestState(['café test'], 0, 0); // Start at 'c'
|
| 386 |
+
|
| 387 |
+
// First 'e' command should move to the 'é' (position 3)
|
| 388 |
+
let result = handleVimAction(state, {
|
| 389 |
+
type: 'vim_move_word_end' as const,
|
| 390 |
+
payload: { count: 1 },
|
| 391 |
+
});
|
| 392 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 393 |
+
expect(result.cursorCol).toBe(3); // At 'é' of café
|
| 394 |
+
|
| 395 |
+
// Second 'e' command should advance to end of "test" (position 8)
|
| 396 |
+
result = handleVimAction(result, {
|
| 397 |
+
type: 'vim_move_word_end' as const,
|
| 398 |
+
payload: { count: 1 },
|
| 399 |
+
});
|
| 400 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 401 |
+
expect(result.cursorCol).toBe(8); // At 't' of "test"
|
| 402 |
+
});
|
| 403 |
+
});
|
| 404 |
+
|
| 405 |
+
describe('Position commands', () => {
|
| 406 |
+
it('vim_move_to_line_start should move to column 0', () => {
|
| 407 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 408 |
+
const action = { type: 'vim_move_to_line_start' as const };
|
| 409 |
+
|
| 410 |
+
const result = handleVimAction(state, action);
|
| 411 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 412 |
+
expect(result.cursorCol).toBe(0);
|
| 413 |
+
});
|
| 414 |
+
|
| 415 |
+
it('vim_move_to_line_end should move to last character', () => {
|
| 416 |
+
const state = createTestState(['hello world'], 0, 0);
|
| 417 |
+
const action = { type: 'vim_move_to_line_end' as const };
|
| 418 |
+
|
| 419 |
+
const result = handleVimAction(state, action);
|
| 420 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 421 |
+
expect(result.cursorCol).toBe(10); // Last character of 'hello world'
|
| 422 |
+
});
|
| 423 |
+
|
| 424 |
+
it('vim_move_to_first_nonwhitespace should skip leading whitespace', () => {
|
| 425 |
+
const state = createTestState([' hello world'], 0, 0);
|
| 426 |
+
const action = { type: 'vim_move_to_first_nonwhitespace' as const };
|
| 427 |
+
|
| 428 |
+
const result = handleVimAction(state, action);
|
| 429 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 430 |
+
expect(result.cursorCol).toBe(3); // Position of 'h'
|
| 431 |
+
});
|
| 432 |
+
|
| 433 |
+
it('vim_move_to_first_line should move to row 0', () => {
|
| 434 |
+
const state = createTestState(['line1', 'line2', 'line3'], 2, 5);
|
| 435 |
+
const action = { type: 'vim_move_to_first_line' as const };
|
| 436 |
+
|
| 437 |
+
const result = handleVimAction(state, action);
|
| 438 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 439 |
+
expect(result.cursorRow).toBe(0);
|
| 440 |
+
expect(result.cursorCol).toBe(0);
|
| 441 |
+
});
|
| 442 |
+
|
| 443 |
+
it('vim_move_to_last_line should move to last row', () => {
|
| 444 |
+
const state = createTestState(['line1', 'line2', 'line3'], 0, 5);
|
| 445 |
+
const action = { type: 'vim_move_to_last_line' as const };
|
| 446 |
+
|
| 447 |
+
const result = handleVimAction(state, action);
|
| 448 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 449 |
+
expect(result.cursorRow).toBe(2);
|
| 450 |
+
expect(result.cursorCol).toBe(0);
|
| 451 |
+
});
|
| 452 |
+
|
| 453 |
+
it('vim_move_to_line should move to specific line', () => {
|
| 454 |
+
const state = createTestState(['line1', 'line2', 'line3'], 0, 5);
|
| 455 |
+
const action = {
|
| 456 |
+
type: 'vim_move_to_line' as const,
|
| 457 |
+
payload: { lineNumber: 2 },
|
| 458 |
+
};
|
| 459 |
+
|
| 460 |
+
const result = handleVimAction(state, action);
|
| 461 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 462 |
+
expect(result.cursorRow).toBe(1); // 0-indexed
|
| 463 |
+
expect(result.cursorCol).toBe(0);
|
| 464 |
+
});
|
| 465 |
+
|
| 466 |
+
it('vim_move_to_line should clamp to valid range', () => {
|
| 467 |
+
const state = createTestState(['line1', 'line2'], 0, 0);
|
| 468 |
+
const action = {
|
| 469 |
+
type: 'vim_move_to_line' as const,
|
| 470 |
+
payload: { lineNumber: 10 },
|
| 471 |
+
};
|
| 472 |
+
|
| 473 |
+
const result = handleVimAction(state, action);
|
| 474 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 475 |
+
expect(result.cursorRow).toBe(1); // Last line
|
| 476 |
+
});
|
| 477 |
+
});
|
| 478 |
+
});
|
| 479 |
+
|
| 480 |
+
describe('Edit commands', () => {
|
| 481 |
+
describe('vim_delete_char', () => {
|
| 482 |
+
it('should delete single character', () => {
|
| 483 |
+
const state = createTestState(['hello'], 0, 1);
|
| 484 |
+
const action = {
|
| 485 |
+
type: 'vim_delete_char' as const,
|
| 486 |
+
payload: { count: 1 },
|
| 487 |
+
};
|
| 488 |
+
|
| 489 |
+
const result = handleVimAction(state, action);
|
| 490 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 491 |
+
expect(result.lines[0]).toBe('hllo');
|
| 492 |
+
expect(result.cursorCol).toBe(1);
|
| 493 |
+
});
|
| 494 |
+
|
| 495 |
+
it('should delete multiple characters', () => {
|
| 496 |
+
const state = createTestState(['hello'], 0, 1);
|
| 497 |
+
const action = {
|
| 498 |
+
type: 'vim_delete_char' as const,
|
| 499 |
+
payload: { count: 3 },
|
| 500 |
+
};
|
| 501 |
+
|
| 502 |
+
const result = handleVimAction(state, action);
|
| 503 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 504 |
+
expect(result.lines[0]).toBe('ho');
|
| 505 |
+
expect(result.cursorCol).toBe(1);
|
| 506 |
+
});
|
| 507 |
+
|
| 508 |
+
it('should not delete past end of line', () => {
|
| 509 |
+
const state = createTestState(['hello'], 0, 3);
|
| 510 |
+
const action = {
|
| 511 |
+
type: 'vim_delete_char' as const,
|
| 512 |
+
payload: { count: 5 },
|
| 513 |
+
};
|
| 514 |
+
|
| 515 |
+
const result = handleVimAction(state, action);
|
| 516 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 517 |
+
expect(result.lines[0]).toBe('hel');
|
| 518 |
+
expect(result.cursorCol).toBe(3);
|
| 519 |
+
});
|
| 520 |
+
|
| 521 |
+
it('should do nothing at end of line', () => {
|
| 522 |
+
const state = createTestState(['hello'], 0, 5);
|
| 523 |
+
const action = {
|
| 524 |
+
type: 'vim_delete_char' as const,
|
| 525 |
+
payload: { count: 1 },
|
| 526 |
+
};
|
| 527 |
+
|
| 528 |
+
const result = handleVimAction(state, action);
|
| 529 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 530 |
+
expect(result.lines[0]).toBe('hello');
|
| 531 |
+
expect(result.cursorCol).toBe(5);
|
| 532 |
+
});
|
| 533 |
+
});
|
| 534 |
+
|
| 535 |
+
describe('vim_delete_word_forward', () => {
|
| 536 |
+
it('should delete from cursor to next word start', () => {
|
| 537 |
+
const state = createTestState(['hello world test'], 0, 0);
|
| 538 |
+
const action = {
|
| 539 |
+
type: 'vim_delete_word_forward' as const,
|
| 540 |
+
payload: { count: 1 },
|
| 541 |
+
};
|
| 542 |
+
|
| 543 |
+
const result = handleVimAction(state, action);
|
| 544 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 545 |
+
expect(result.lines[0]).toBe('world test');
|
| 546 |
+
expect(result.cursorCol).toBe(0);
|
| 547 |
+
});
|
| 548 |
+
|
| 549 |
+
it('should delete multiple words', () => {
|
| 550 |
+
const state = createTestState(['hello world test'], 0, 0);
|
| 551 |
+
const action = {
|
| 552 |
+
type: 'vim_delete_word_forward' as const,
|
| 553 |
+
payload: { count: 2 },
|
| 554 |
+
};
|
| 555 |
+
|
| 556 |
+
const result = handleVimAction(state, action);
|
| 557 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 558 |
+
expect(result.lines[0]).toBe('test');
|
| 559 |
+
expect(result.cursorCol).toBe(0);
|
| 560 |
+
});
|
| 561 |
+
|
| 562 |
+
it('should delete to end if no more words', () => {
|
| 563 |
+
const state = createTestState(['hello world'], 0, 6);
|
| 564 |
+
const action = {
|
| 565 |
+
type: 'vim_delete_word_forward' as const,
|
| 566 |
+
payload: { count: 2 },
|
| 567 |
+
};
|
| 568 |
+
|
| 569 |
+
const result = handleVimAction(state, action);
|
| 570 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 571 |
+
expect(result.lines[0]).toBe('hello ');
|
| 572 |
+
expect(result.cursorCol).toBe(6);
|
| 573 |
+
});
|
| 574 |
+
});
|
| 575 |
+
|
| 576 |
+
describe('vim_delete_word_backward', () => {
|
| 577 |
+
it('should delete from cursor to previous word start', () => {
|
| 578 |
+
const state = createTestState(['hello world test'], 0, 12);
|
| 579 |
+
const action = {
|
| 580 |
+
type: 'vim_delete_word_backward' as const,
|
| 581 |
+
payload: { count: 1 },
|
| 582 |
+
};
|
| 583 |
+
|
| 584 |
+
const result = handleVimAction(state, action);
|
| 585 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 586 |
+
expect(result.lines[0]).toBe('hello test');
|
| 587 |
+
expect(result.cursorCol).toBe(6);
|
| 588 |
+
});
|
| 589 |
+
|
| 590 |
+
it('should delete multiple words backward', () => {
|
| 591 |
+
const state = createTestState(['hello world test'], 0, 12);
|
| 592 |
+
const action = {
|
| 593 |
+
type: 'vim_delete_word_backward' as const,
|
| 594 |
+
payload: { count: 2 },
|
| 595 |
+
};
|
| 596 |
+
|
| 597 |
+
const result = handleVimAction(state, action);
|
| 598 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 599 |
+
expect(result.lines[0]).toBe('test');
|
| 600 |
+
expect(result.cursorCol).toBe(0);
|
| 601 |
+
});
|
| 602 |
+
});
|
| 603 |
+
|
| 604 |
+
describe('vim_delete_line', () => {
|
| 605 |
+
it('should delete current line', () => {
|
| 606 |
+
const state = createTestState(['line1', 'line2', 'line3'], 1, 2);
|
| 607 |
+
const action = {
|
| 608 |
+
type: 'vim_delete_line' as const,
|
| 609 |
+
payload: { count: 1 },
|
| 610 |
+
};
|
| 611 |
+
|
| 612 |
+
const result = handleVimAction(state, action);
|
| 613 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 614 |
+
expect(result.lines).toEqual(['line1', 'line3']);
|
| 615 |
+
expect(result.cursorRow).toBe(1);
|
| 616 |
+
expect(result.cursorCol).toBe(0);
|
| 617 |
+
});
|
| 618 |
+
|
| 619 |
+
it('should delete multiple lines', () => {
|
| 620 |
+
const state = createTestState(['line1', 'line2', 'line3'], 0, 2);
|
| 621 |
+
const action = {
|
| 622 |
+
type: 'vim_delete_line' as const,
|
| 623 |
+
payload: { count: 2 },
|
| 624 |
+
};
|
| 625 |
+
|
| 626 |
+
const result = handleVimAction(state, action);
|
| 627 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 628 |
+
expect(result.lines).toEqual(['line3']);
|
| 629 |
+
expect(result.cursorRow).toBe(0);
|
| 630 |
+
expect(result.cursorCol).toBe(0);
|
| 631 |
+
});
|
| 632 |
+
|
| 633 |
+
it('should leave empty line when deleting all lines', () => {
|
| 634 |
+
const state = createTestState(['only line'], 0, 0);
|
| 635 |
+
const action = {
|
| 636 |
+
type: 'vim_delete_line' as const,
|
| 637 |
+
payload: { count: 1 },
|
| 638 |
+
};
|
| 639 |
+
|
| 640 |
+
const result = handleVimAction(state, action);
|
| 641 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 642 |
+
expect(result.lines).toEqual(['']);
|
| 643 |
+
expect(result.cursorRow).toBe(0);
|
| 644 |
+
expect(result.cursorCol).toBe(0);
|
| 645 |
+
});
|
| 646 |
+
});
|
| 647 |
+
|
| 648 |
+
describe('vim_delete_to_end_of_line', () => {
|
| 649 |
+
it('should delete from cursor to end of line', () => {
|
| 650 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 651 |
+
const action = { type: 'vim_delete_to_end_of_line' as const };
|
| 652 |
+
|
| 653 |
+
const result = handleVimAction(state, action);
|
| 654 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 655 |
+
expect(result.lines[0]).toBe('hello');
|
| 656 |
+
expect(result.cursorCol).toBe(5);
|
| 657 |
+
});
|
| 658 |
+
|
| 659 |
+
it('should do nothing at end of line', () => {
|
| 660 |
+
const state = createTestState(['hello'], 0, 5);
|
| 661 |
+
const action = { type: 'vim_delete_to_end_of_line' as const };
|
| 662 |
+
|
| 663 |
+
const result = handleVimAction(state, action);
|
| 664 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 665 |
+
expect(result.lines[0]).toBe('hello');
|
| 666 |
+
});
|
| 667 |
+
});
|
| 668 |
+
});
|
| 669 |
+
|
| 670 |
+
describe('Insert mode commands', () => {
|
| 671 |
+
describe('vim_insert_at_cursor', () => {
|
| 672 |
+
it('should not change cursor position', () => {
|
| 673 |
+
const state = createTestState(['hello'], 0, 2);
|
| 674 |
+
const action = { type: 'vim_insert_at_cursor' as const };
|
| 675 |
+
|
| 676 |
+
const result = handleVimAction(state, action);
|
| 677 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 678 |
+
expect(result.cursorRow).toBe(0);
|
| 679 |
+
expect(result.cursorCol).toBe(2);
|
| 680 |
+
});
|
| 681 |
+
});
|
| 682 |
+
|
| 683 |
+
describe('vim_append_at_cursor', () => {
|
| 684 |
+
it('should move cursor right by one', () => {
|
| 685 |
+
const state = createTestState(['hello'], 0, 2);
|
| 686 |
+
const action = { type: 'vim_append_at_cursor' as const };
|
| 687 |
+
|
| 688 |
+
const result = handleVimAction(state, action);
|
| 689 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 690 |
+
expect(result.cursorCol).toBe(3);
|
| 691 |
+
});
|
| 692 |
+
|
| 693 |
+
it('should not move past end of line', () => {
|
| 694 |
+
const state = createTestState(['hello'], 0, 5);
|
| 695 |
+
const action = { type: 'vim_append_at_cursor' as const };
|
| 696 |
+
|
| 697 |
+
const result = handleVimAction(state, action);
|
| 698 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 699 |
+
expect(result.cursorCol).toBe(5);
|
| 700 |
+
});
|
| 701 |
+
});
|
| 702 |
+
|
| 703 |
+
describe('vim_append_at_line_end', () => {
|
| 704 |
+
it('should move cursor to end of line', () => {
|
| 705 |
+
const state = createTestState(['hello world'], 0, 3);
|
| 706 |
+
const action = { type: 'vim_append_at_line_end' as const };
|
| 707 |
+
|
| 708 |
+
const result = handleVimAction(state, action);
|
| 709 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 710 |
+
expect(result.cursorCol).toBe(11);
|
| 711 |
+
});
|
| 712 |
+
});
|
| 713 |
+
|
| 714 |
+
describe('vim_insert_at_line_start', () => {
|
| 715 |
+
it('should move to first non-whitespace character', () => {
|
| 716 |
+
const state = createTestState([' hello world'], 0, 5);
|
| 717 |
+
const action = { type: 'vim_insert_at_line_start' as const };
|
| 718 |
+
|
| 719 |
+
const result = handleVimAction(state, action);
|
| 720 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 721 |
+
expect(result.cursorCol).toBe(2);
|
| 722 |
+
});
|
| 723 |
+
|
| 724 |
+
it('should move to column 0 for line with only whitespace', () => {
|
| 725 |
+
const state = createTestState([' '], 0, 1);
|
| 726 |
+
const action = { type: 'vim_insert_at_line_start' as const };
|
| 727 |
+
|
| 728 |
+
const result = handleVimAction(state, action);
|
| 729 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 730 |
+
expect(result.cursorCol).toBe(3);
|
| 731 |
+
});
|
| 732 |
+
});
|
| 733 |
+
|
| 734 |
+
describe('vim_open_line_below', () => {
|
| 735 |
+
it('should insert a new line below the current one', () => {
|
| 736 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 737 |
+
const action = { type: 'vim_open_line_below' as const };
|
| 738 |
+
|
| 739 |
+
const result = handleVimAction(state, action);
|
| 740 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 741 |
+
expect(result.lines).toEqual(['hello world', '']);
|
| 742 |
+
expect(result.cursorRow).toBe(1);
|
| 743 |
+
expect(result.cursorCol).toBe(0);
|
| 744 |
+
});
|
| 745 |
+
});
|
| 746 |
+
|
| 747 |
+
describe('vim_open_line_above', () => {
|
| 748 |
+
it('should insert a new line above the current one', () => {
|
| 749 |
+
const state = createTestState(['hello', 'world'], 1, 2);
|
| 750 |
+
const action = { type: 'vim_open_line_above' as const };
|
| 751 |
+
|
| 752 |
+
const result = handleVimAction(state, action);
|
| 753 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 754 |
+
expect(result.lines).toEqual(['hello', '', 'world']);
|
| 755 |
+
expect(result.cursorRow).toBe(1);
|
| 756 |
+
expect(result.cursorCol).toBe(0);
|
| 757 |
+
});
|
| 758 |
+
});
|
| 759 |
+
|
| 760 |
+
describe('vim_escape_insert_mode', () => {
|
| 761 |
+
it('should move cursor left', () => {
|
| 762 |
+
const state = createTestState(['hello'], 0, 3);
|
| 763 |
+
const action = { type: 'vim_escape_insert_mode' as const };
|
| 764 |
+
|
| 765 |
+
const result = handleVimAction(state, action);
|
| 766 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 767 |
+
expect(result.cursorCol).toBe(2);
|
| 768 |
+
});
|
| 769 |
+
|
| 770 |
+
it('should not move past beginning of line', () => {
|
| 771 |
+
const state = createTestState(['hello'], 0, 0);
|
| 772 |
+
const action = { type: 'vim_escape_insert_mode' as const };
|
| 773 |
+
|
| 774 |
+
const result = handleVimAction(state, action);
|
| 775 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 776 |
+
expect(result.cursorCol).toBe(0);
|
| 777 |
+
});
|
| 778 |
+
});
|
| 779 |
+
});
|
| 780 |
+
|
| 781 |
+
describe('Change commands', () => {
|
| 782 |
+
describe('vim_change_word_forward', () => {
|
| 783 |
+
it('should delete from cursor to next word start', () => {
|
| 784 |
+
const state = createTestState(['hello world test'], 0, 0);
|
| 785 |
+
const action = {
|
| 786 |
+
type: 'vim_change_word_forward' as const,
|
| 787 |
+
payload: { count: 1 },
|
| 788 |
+
};
|
| 789 |
+
|
| 790 |
+
const result = handleVimAction(state, action);
|
| 791 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 792 |
+
expect(result.lines[0]).toBe('world test');
|
| 793 |
+
expect(result.cursorCol).toBe(0);
|
| 794 |
+
});
|
| 795 |
+
});
|
| 796 |
+
|
| 797 |
+
describe('vim_change_line', () => {
|
| 798 |
+
it('should delete entire line content', () => {
|
| 799 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 800 |
+
const action = {
|
| 801 |
+
type: 'vim_change_line' as const,
|
| 802 |
+
payload: { count: 1 },
|
| 803 |
+
};
|
| 804 |
+
|
| 805 |
+
const result = handleVimAction(state, action);
|
| 806 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 807 |
+
expect(result.lines[0]).toBe('');
|
| 808 |
+
expect(result.cursorCol).toBe(0);
|
| 809 |
+
});
|
| 810 |
+
});
|
| 811 |
+
|
| 812 |
+
describe('vim_change_movement', () => {
|
| 813 |
+
it('should change characters to the left', () => {
|
| 814 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 815 |
+
const action = {
|
| 816 |
+
type: 'vim_change_movement' as const,
|
| 817 |
+
payload: { movement: 'h', count: 2 },
|
| 818 |
+
};
|
| 819 |
+
|
| 820 |
+
const result = handleVimAction(state, action);
|
| 821 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 822 |
+
expect(result.lines[0]).toBe('hel world');
|
| 823 |
+
expect(result.cursorCol).toBe(3);
|
| 824 |
+
});
|
| 825 |
+
|
| 826 |
+
it('should change characters to the right', () => {
|
| 827 |
+
const state = createTestState(['hello world'], 0, 5);
|
| 828 |
+
const action = {
|
| 829 |
+
type: 'vim_change_movement' as const,
|
| 830 |
+
payload: { movement: 'l', count: 3 },
|
| 831 |
+
};
|
| 832 |
+
|
| 833 |
+
const result = handleVimAction(state, action);
|
| 834 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 835 |
+
expect(result.lines[0]).toBe('hellorld'); // Deletes ' wo' (3 chars to the right)
|
| 836 |
+
expect(result.cursorCol).toBe(5);
|
| 837 |
+
});
|
| 838 |
+
|
| 839 |
+
it('should change multiple lines down', () => {
|
| 840 |
+
const state = createTestState(['line1', 'line2', 'line3'], 0, 2);
|
| 841 |
+
const action = {
|
| 842 |
+
type: 'vim_change_movement' as const,
|
| 843 |
+
payload: { movement: 'j', count: 2 },
|
| 844 |
+
};
|
| 845 |
+
|
| 846 |
+
const result = handleVimAction(state, action);
|
| 847 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 848 |
+
// The movement 'j' with count 2 changes 2 lines starting from cursor row
|
| 849 |
+
// Since we're at cursor position 2, it changes lines starting from current row
|
| 850 |
+
expect(result.lines).toEqual(['line1', 'line2', 'line3']); // No change because count > available lines
|
| 851 |
+
expect(result.cursorRow).toBe(0);
|
| 852 |
+
expect(result.cursorCol).toBe(2);
|
| 853 |
+
});
|
| 854 |
+
});
|
| 855 |
+
});
|
| 856 |
+
|
| 857 |
+
describe('Edge cases', () => {
|
| 858 |
+
it('should handle empty text', () => {
|
| 859 |
+
const state = createTestState([''], 0, 0);
|
| 860 |
+
const action = {
|
| 861 |
+
type: 'vim_move_word_forward' as const,
|
| 862 |
+
payload: { count: 1 },
|
| 863 |
+
};
|
| 864 |
+
|
| 865 |
+
const result = handleVimAction(state, action);
|
| 866 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 867 |
+
expect(result.cursorRow).toBe(0);
|
| 868 |
+
expect(result.cursorCol).toBe(0);
|
| 869 |
+
});
|
| 870 |
+
|
| 871 |
+
it('should handle single character line', () => {
|
| 872 |
+
const state = createTestState(['a'], 0, 0);
|
| 873 |
+
const action = { type: 'vim_move_to_line_end' as const };
|
| 874 |
+
|
| 875 |
+
const result = handleVimAction(state, action);
|
| 876 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 877 |
+
expect(result.cursorCol).toBe(0); // Should be last character position
|
| 878 |
+
});
|
| 879 |
+
|
| 880 |
+
it('should handle empty lines in multi-line text', () => {
|
| 881 |
+
const state = createTestState(['line1', '', 'line3'], 1, 0);
|
| 882 |
+
const action = {
|
| 883 |
+
type: 'vim_move_word_forward' as const,
|
| 884 |
+
payload: { count: 1 },
|
| 885 |
+
};
|
| 886 |
+
|
| 887 |
+
const result = handleVimAction(state, action);
|
| 888 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 889 |
+
// Should move to next line with content
|
| 890 |
+
expect(result.cursorRow).toBe(2);
|
| 891 |
+
expect(result.cursorCol).toBe(0);
|
| 892 |
+
});
|
| 893 |
+
|
| 894 |
+
it('should preserve undo stack in operations', () => {
|
| 895 |
+
const state = createTestState(['hello'], 0, 0);
|
| 896 |
+
state.undoStack = [{ lines: ['previous'], cursorRow: 0, cursorCol: 0 }];
|
| 897 |
+
|
| 898 |
+
const action = {
|
| 899 |
+
type: 'vim_delete_char' as const,
|
| 900 |
+
payload: { count: 1 },
|
| 901 |
+
};
|
| 902 |
+
|
| 903 |
+
const result = handleVimAction(state, action);
|
| 904 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 905 |
+
expect(result.undoStack).toHaveLength(2); // Original plus new snapshot
|
| 906 |
+
});
|
| 907 |
+
});
|
| 908 |
+
|
| 909 |
+
describe('UTF-32 character handling in word/line operations', () => {
|
| 910 |
+
describe('Right-to-left text handling', () => {
|
| 911 |
+
it('should handle Arabic text in word movements', () => {
|
| 912 |
+
const state = createTestState(['hello مرحبا world'], 0, 0);
|
| 913 |
+
|
| 914 |
+
// Move to end of 'hello'
|
| 915 |
+
let result = handleVimAction(state, {
|
| 916 |
+
type: 'vim_move_word_end' as const,
|
| 917 |
+
payload: { count: 1 },
|
| 918 |
+
});
|
| 919 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 920 |
+
expect(result.cursorCol).toBe(4); // End of 'hello'
|
| 921 |
+
|
| 922 |
+
// Move to end of Arabic word
|
| 923 |
+
result = handleVimAction(result, {
|
| 924 |
+
type: 'vim_move_word_end' as const,
|
| 925 |
+
payload: { count: 1 },
|
| 926 |
+
});
|
| 927 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 928 |
+
expect(result.cursorCol).toBe(10); // End of Arabic word 'مرحبا'
|
| 929 |
+
});
|
| 930 |
+
});
|
| 931 |
+
|
| 932 |
+
describe('Chinese character handling', () => {
|
| 933 |
+
it('should handle Chinese characters in word movements', () => {
|
| 934 |
+
const state = createTestState(['hello 你好 world'], 0, 0);
|
| 935 |
+
|
| 936 |
+
// Move to end of 'hello'
|
| 937 |
+
let result = handleVimAction(state, {
|
| 938 |
+
type: 'vim_move_word_end' as const,
|
| 939 |
+
payload: { count: 1 },
|
| 940 |
+
});
|
| 941 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 942 |
+
expect(result.cursorCol).toBe(4); // End of 'hello'
|
| 943 |
+
|
| 944 |
+
// Move forward to start of 'world'
|
| 945 |
+
result = handleVimAction(result, {
|
| 946 |
+
type: 'vim_move_word_forward' as const,
|
| 947 |
+
payload: { count: 1 },
|
| 948 |
+
});
|
| 949 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 950 |
+
expect(result.cursorCol).toBe(6); // Start of '你好'
|
| 951 |
+
});
|
| 952 |
+
});
|
| 953 |
+
|
| 954 |
+
describe('Mixed script handling', () => {
|
| 955 |
+
it('should handle mixed Latin and non-Latin scripts with word end commands', () => {
|
| 956 |
+
const state = createTestState(['test中文test'], 0, 0);
|
| 957 |
+
|
| 958 |
+
let result = handleVimAction(state, {
|
| 959 |
+
type: 'vim_move_word_end' as const,
|
| 960 |
+
payload: { count: 1 },
|
| 961 |
+
});
|
| 962 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 963 |
+
expect(result.cursorCol).toBe(3); // End of 'test'
|
| 964 |
+
|
| 965 |
+
// Second word end command should move to end of '中文'
|
| 966 |
+
result = handleVimAction(result, {
|
| 967 |
+
type: 'vim_move_word_end' as const,
|
| 968 |
+
payload: { count: 1 },
|
| 969 |
+
});
|
| 970 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 971 |
+
expect(result.cursorCol).toBe(5); // End of '中文'
|
| 972 |
+
});
|
| 973 |
+
|
| 974 |
+
it('should handle mixed Latin and non-Latin scripts with word forward commands', () => {
|
| 975 |
+
const state = createTestState(['test中文test'], 0, 0);
|
| 976 |
+
|
| 977 |
+
let result = handleVimAction(state, {
|
| 978 |
+
type: 'vim_move_word_forward' as const,
|
| 979 |
+
payload: { count: 1 },
|
| 980 |
+
});
|
| 981 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 982 |
+
expect(result.cursorCol).toBe(4); // Start of '中'
|
| 983 |
+
|
| 984 |
+
// Second word forward command should move to start of final 'test'
|
| 985 |
+
result = handleVimAction(result, {
|
| 986 |
+
type: 'vim_move_word_forward' as const,
|
| 987 |
+
payload: { count: 1 },
|
| 988 |
+
});
|
| 989 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 990 |
+
expect(result.cursorCol).toBe(6); // Start of final 'test'
|
| 991 |
+
});
|
| 992 |
+
|
| 993 |
+
it('should handle mixed Latin and non-Latin scripts with word backward commands', () => {
|
| 994 |
+
const state = createTestState(['test中文test'], 0, 9); // Start at end of final 'test'
|
| 995 |
+
|
| 996 |
+
let result = handleVimAction(state, {
|
| 997 |
+
type: 'vim_move_word_backward' as const,
|
| 998 |
+
payload: { count: 1 },
|
| 999 |
+
});
|
| 1000 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 1001 |
+
expect(result.cursorCol).toBe(6); // Start of final 'test'
|
| 1002 |
+
|
| 1003 |
+
// Second word backward command should move to start of '中文'
|
| 1004 |
+
result = handleVimAction(result, {
|
| 1005 |
+
type: 'vim_move_word_backward' as const,
|
| 1006 |
+
payload: { count: 1 },
|
| 1007 |
+
});
|
| 1008 |
+
expect(result).toHaveOnlyValidCharacters();
|
| 1009 |
+
expect(result.cursorCol).toBe(4); // Start of '中'
|
| 1010 |
+
});
|
| 1011 |
+
|
| 1012 |
+
it('should handle Unicode block characters consistently with w and e commands', () => {
|
| 1013 |
+
const state = createTestState(['██ █████ ██'], 0, 0);
|
| 1014 |
+
|
| 1015 |
+
// Test w command progression
|
| 1016 |
+
let wResult = handleVimAction(state, {
|
| 1017 |
+
type: 'vim_move_word_forward' as const,
|
| 1018 |
+
payload: { count: 1 },
|
| 1019 |
+
});
|
| 1020 |
+
expect(wResult).toHaveOnlyValidCharacters();
|
| 1021 |
+
expect(wResult.cursorCol).toBe(3); // Start of second block sequence
|
| 1022 |
+
|
| 1023 |
+
wResult = handleVimAction(wResult, {
|
| 1024 |
+
type: 'vim_move_word_forward' as const,
|
| 1025 |
+
payload: { count: 1 },
|
| 1026 |
+
});
|
| 1027 |
+
expect(wResult).toHaveOnlyValidCharacters();
|
| 1028 |
+
expect(wResult.cursorCol).toBe(9); // Start of third block sequence
|
| 1029 |
+
|
| 1030 |
+
// Test e command progression from beginning
|
| 1031 |
+
let eResult = handleVimAction(state, {
|
| 1032 |
+
type: 'vim_move_word_end' as const,
|
| 1033 |
+
payload: { count: 1 },
|
| 1034 |
+
});
|
| 1035 |
+
expect(eResult).toHaveOnlyValidCharacters();
|
| 1036 |
+
expect(eResult.cursorCol).toBe(1); // End of first block sequence
|
| 1037 |
+
|
| 1038 |
+
eResult = handleVimAction(eResult, {
|
| 1039 |
+
type: 'vim_move_word_end' as const,
|
| 1040 |
+
payload: { count: 1 },
|
| 1041 |
+
});
|
| 1042 |
+
expect(eResult).toHaveOnlyValidCharacters();
|
| 1043 |
+
expect(eResult.cursorCol).toBe(7); // End of second block sequence
|
| 1044 |
+
|
| 1045 |
+
eResult = handleVimAction(eResult, {
|
| 1046 |
+
type: 'vim_move_word_end' as const,
|
| 1047 |
+
payload: { count: 1 },
|
| 1048 |
+
});
|
| 1049 |
+
expect(eResult).toHaveOnlyValidCharacters();
|
| 1050 |
+
expect(eResult.cursorCol).toBe(10); // End of third block sequence
|
| 1051 |
+
});
|
| 1052 |
+
|
| 1053 |
+
it('should handle strings starting with Chinese characters', () => {
|
| 1054 |
+
const state = createTestState(['中文test英文word'], 0, 0);
|
| 1055 |
+
|
| 1056 |
+
// Test 'w' command - when at start of non-Latin word, w moves to next word
|
| 1057 |
+
let wResult = handleVimAction(state, {
|
| 1058 |
+
type: 'vim_move_word_forward' as const,
|
| 1059 |
+
payload: { count: 1 },
|
| 1060 |
+
});
|
| 1061 |
+
expect(wResult).toHaveOnlyValidCharacters();
|
| 1062 |
+
expect(wResult.cursorCol).toBe(2); // Start of 'test'
|
| 1063 |
+
|
| 1064 |
+
wResult = handleVimAction(wResult, {
|
| 1065 |
+
type: 'vim_move_word_forward' as const,
|
| 1066 |
+
payload: { count: 1 },
|
| 1067 |
+
});
|
| 1068 |
+
expect(wResult.cursorCol).toBe(6); // Start of '英文'
|
| 1069 |
+
|
| 1070 |
+
// Test 'e' command
|
| 1071 |
+
let eResult = handleVimAction(state, {
|
| 1072 |
+
type: 'vim_move_word_end' as const,
|
| 1073 |
+
payload: { count: 1 },
|
| 1074 |
+
});
|
| 1075 |
+
expect(eResult).toHaveOnlyValidCharacters();
|
| 1076 |
+
expect(eResult.cursorCol).toBe(1); // End of 中文
|
| 1077 |
+
|
| 1078 |
+
eResult = handleVimAction(eResult, {
|
| 1079 |
+
type: 'vim_move_word_end' as const,
|
| 1080 |
+
payload: { count: 1 },
|
| 1081 |
+
});
|
| 1082 |
+
expect(eResult.cursorCol).toBe(5); // End of test
|
| 1083 |
+
});
|
| 1084 |
+
|
| 1085 |
+
it('should handle strings starting with Arabic characters', () => {
|
| 1086 |
+
const state = createTestState(['مرحباhelloسلام'], 0, 0);
|
| 1087 |
+
|
| 1088 |
+
// Test 'w' command - when at start of non-Latin word, w moves to next word
|
| 1089 |
+
let wResult = handleVimAction(state, {
|
| 1090 |
+
type: 'vim_move_word_forward' as const,
|
| 1091 |
+
payload: { count: 1 },
|
| 1092 |
+
});
|
| 1093 |
+
expect(wResult).toHaveOnlyValidCharacters();
|
| 1094 |
+
expect(wResult.cursorCol).toBe(5); // Start of 'hello'
|
| 1095 |
+
|
| 1096 |
+
wResult = handleVimAction(wResult, {
|
| 1097 |
+
type: 'vim_move_word_forward' as const,
|
| 1098 |
+
payload: { count: 1 },
|
| 1099 |
+
});
|
| 1100 |
+
expect(wResult.cursorCol).toBe(10); // Start of 'سلام'
|
| 1101 |
+
|
| 1102 |
+
// Test 'b' command from end
|
| 1103 |
+
const bState = createTestState(['مرحباhelloسلام'], 0, 13);
|
| 1104 |
+
let bResult = handleVimAction(bState, {
|
| 1105 |
+
type: 'vim_move_word_backward' as const,
|
| 1106 |
+
payload: { count: 1 },
|
| 1107 |
+
});
|
| 1108 |
+
expect(bResult).toHaveOnlyValidCharacters();
|
| 1109 |
+
expect(bResult.cursorCol).toBe(10); // Start of سلام
|
| 1110 |
+
|
| 1111 |
+
bResult = handleVimAction(bResult, {
|
| 1112 |
+
type: 'vim_move_word_backward' as const,
|
| 1113 |
+
payload: { count: 1 },
|
| 1114 |
+
});
|
| 1115 |
+
expect(bResult.cursorCol).toBe(5); // Start of hello
|
| 1116 |
+
});
|
| 1117 |
+
});
|
| 1118 |
+
});
|
| 1119 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/shared/vim-buffer-actions.ts
ADDED
|
@@ -0,0 +1,814 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
TextBufferState,
|
| 9 |
+
TextBufferAction,
|
| 10 |
+
getLineRangeOffsets,
|
| 11 |
+
getPositionFromOffsets,
|
| 12 |
+
replaceRangeInternal,
|
| 13 |
+
pushUndo,
|
| 14 |
+
isWordCharStrict,
|
| 15 |
+
isWordCharWithCombining,
|
| 16 |
+
isCombiningMark,
|
| 17 |
+
findNextWordAcrossLines,
|
| 18 |
+
findPrevWordAcrossLines,
|
| 19 |
+
findWordEndInLine,
|
| 20 |
+
} from './text-buffer.js';
|
| 21 |
+
import { cpLen, toCodePoints } from '../../utils/textUtils.js';
|
| 22 |
+
import { assumeExhaustive } from '../../../utils/checks.js';
|
| 23 |
+
|
| 24 |
+
// Check if we're at the end of a base word (on the last base character)
|
| 25 |
+
// Returns true if current position has a base character followed only by combining marks until non-word
|
| 26 |
+
function isAtEndOfBaseWord(lineCodePoints: string[], col: number): boolean {
|
| 27 |
+
if (!isWordCharStrict(lineCodePoints[col])) return false;
|
| 28 |
+
|
| 29 |
+
// Look ahead to see if we have only combining marks followed by non-word
|
| 30 |
+
let i = col + 1;
|
| 31 |
+
|
| 32 |
+
// Skip any combining marks
|
| 33 |
+
while (i < lineCodePoints.length && isCombiningMark(lineCodePoints[i])) {
|
| 34 |
+
i++;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// If we hit end of line or non-word character, we were at end of base word
|
| 38 |
+
return i >= lineCodePoints.length || !isWordCharStrict(lineCodePoints[i]);
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
export type VimAction = Extract<
|
| 42 |
+
TextBufferAction,
|
| 43 |
+
| { type: 'vim_delete_word_forward' }
|
| 44 |
+
| { type: 'vim_delete_word_backward' }
|
| 45 |
+
| { type: 'vim_delete_word_end' }
|
| 46 |
+
| { type: 'vim_change_word_forward' }
|
| 47 |
+
| { type: 'vim_change_word_backward' }
|
| 48 |
+
| { type: 'vim_change_word_end' }
|
| 49 |
+
| { type: 'vim_delete_line' }
|
| 50 |
+
| { type: 'vim_change_line' }
|
| 51 |
+
| { type: 'vim_delete_to_end_of_line' }
|
| 52 |
+
| { type: 'vim_change_to_end_of_line' }
|
| 53 |
+
| { type: 'vim_change_movement' }
|
| 54 |
+
| { type: 'vim_move_left' }
|
| 55 |
+
| { type: 'vim_move_right' }
|
| 56 |
+
| { type: 'vim_move_up' }
|
| 57 |
+
| { type: 'vim_move_down' }
|
| 58 |
+
| { type: 'vim_move_word_forward' }
|
| 59 |
+
| { type: 'vim_move_word_backward' }
|
| 60 |
+
| { type: 'vim_move_word_end' }
|
| 61 |
+
| { type: 'vim_delete_char' }
|
| 62 |
+
| { type: 'vim_insert_at_cursor' }
|
| 63 |
+
| { type: 'vim_append_at_cursor' }
|
| 64 |
+
| { type: 'vim_open_line_below' }
|
| 65 |
+
| { type: 'vim_open_line_above' }
|
| 66 |
+
| { type: 'vim_append_at_line_end' }
|
| 67 |
+
| { type: 'vim_insert_at_line_start' }
|
| 68 |
+
| { type: 'vim_move_to_line_start' }
|
| 69 |
+
| { type: 'vim_move_to_line_end' }
|
| 70 |
+
| { type: 'vim_move_to_first_nonwhitespace' }
|
| 71 |
+
| { type: 'vim_move_to_first_line' }
|
| 72 |
+
| { type: 'vim_move_to_last_line' }
|
| 73 |
+
| { type: 'vim_move_to_line' }
|
| 74 |
+
| { type: 'vim_escape_insert_mode' }
|
| 75 |
+
>;
|
| 76 |
+
|
| 77 |
+
export function handleVimAction(
|
| 78 |
+
state: TextBufferState,
|
| 79 |
+
action: VimAction,
|
| 80 |
+
): TextBufferState {
|
| 81 |
+
const { lines, cursorRow, cursorCol } = state;
|
| 82 |
+
|
| 83 |
+
switch (action.type) {
|
| 84 |
+
case 'vim_delete_word_forward':
|
| 85 |
+
case 'vim_change_word_forward': {
|
| 86 |
+
const { count } = action.payload;
|
| 87 |
+
let endRow = cursorRow;
|
| 88 |
+
let endCol = cursorCol;
|
| 89 |
+
|
| 90 |
+
for (let i = 0; i < count; i++) {
|
| 91 |
+
const nextWord = findNextWordAcrossLines(lines, endRow, endCol, true);
|
| 92 |
+
if (nextWord) {
|
| 93 |
+
endRow = nextWord.row;
|
| 94 |
+
endCol = nextWord.col;
|
| 95 |
+
} else {
|
| 96 |
+
// No more words, delete/change to end of current word or line
|
| 97 |
+
const currentLine = lines[endRow] || '';
|
| 98 |
+
const wordEnd = findWordEndInLine(currentLine, endCol);
|
| 99 |
+
if (wordEnd !== null) {
|
| 100 |
+
endCol = wordEnd + 1; // Include the character at word end
|
| 101 |
+
} else {
|
| 102 |
+
endCol = cpLen(currentLine);
|
| 103 |
+
}
|
| 104 |
+
break;
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
if (endRow !== cursorRow || endCol !== cursorCol) {
|
| 109 |
+
const nextState = pushUndo(state);
|
| 110 |
+
return replaceRangeInternal(
|
| 111 |
+
nextState,
|
| 112 |
+
cursorRow,
|
| 113 |
+
cursorCol,
|
| 114 |
+
endRow,
|
| 115 |
+
endCol,
|
| 116 |
+
'',
|
| 117 |
+
);
|
| 118 |
+
}
|
| 119 |
+
return state;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
case 'vim_delete_word_backward':
|
| 123 |
+
case 'vim_change_word_backward': {
|
| 124 |
+
const { count } = action.payload;
|
| 125 |
+
let startRow = cursorRow;
|
| 126 |
+
let startCol = cursorCol;
|
| 127 |
+
|
| 128 |
+
for (let i = 0; i < count; i++) {
|
| 129 |
+
const prevWord = findPrevWordAcrossLines(lines, startRow, startCol);
|
| 130 |
+
if (prevWord) {
|
| 131 |
+
startRow = prevWord.row;
|
| 132 |
+
startCol = prevWord.col;
|
| 133 |
+
} else {
|
| 134 |
+
break;
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
if (startRow !== cursorRow || startCol !== cursorCol) {
|
| 139 |
+
const nextState = pushUndo(state);
|
| 140 |
+
return replaceRangeInternal(
|
| 141 |
+
nextState,
|
| 142 |
+
startRow,
|
| 143 |
+
startCol,
|
| 144 |
+
cursorRow,
|
| 145 |
+
cursorCol,
|
| 146 |
+
'',
|
| 147 |
+
);
|
| 148 |
+
}
|
| 149 |
+
return state;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
case 'vim_delete_word_end':
|
| 153 |
+
case 'vim_change_word_end': {
|
| 154 |
+
const { count } = action.payload;
|
| 155 |
+
let row = cursorRow;
|
| 156 |
+
let col = cursorCol;
|
| 157 |
+
let endRow = cursorRow;
|
| 158 |
+
let endCol = cursorCol;
|
| 159 |
+
|
| 160 |
+
for (let i = 0; i < count; i++) {
|
| 161 |
+
const wordEnd = findNextWordAcrossLines(lines, row, col, false);
|
| 162 |
+
if (wordEnd) {
|
| 163 |
+
endRow = wordEnd.row;
|
| 164 |
+
endCol = wordEnd.col + 1; // Include the character at word end
|
| 165 |
+
// For next iteration, move to start of next word
|
| 166 |
+
if (i < count - 1) {
|
| 167 |
+
const nextWord = findNextWordAcrossLines(
|
| 168 |
+
lines,
|
| 169 |
+
wordEnd.row,
|
| 170 |
+
wordEnd.col + 1,
|
| 171 |
+
true,
|
| 172 |
+
);
|
| 173 |
+
if (nextWord) {
|
| 174 |
+
row = nextWord.row;
|
| 175 |
+
col = nextWord.col;
|
| 176 |
+
} else {
|
| 177 |
+
break; // No more words
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
} else {
|
| 181 |
+
break;
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
// Ensure we don't go past the end of the last line
|
| 186 |
+
if (endRow < lines.length) {
|
| 187 |
+
const lineLen = cpLen(lines[endRow] || '');
|
| 188 |
+
endCol = Math.min(endCol, lineLen);
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
if (endRow !== cursorRow || endCol !== cursorCol) {
|
| 192 |
+
const nextState = pushUndo(state);
|
| 193 |
+
return replaceRangeInternal(
|
| 194 |
+
nextState,
|
| 195 |
+
cursorRow,
|
| 196 |
+
cursorCol,
|
| 197 |
+
endRow,
|
| 198 |
+
endCol,
|
| 199 |
+
'',
|
| 200 |
+
);
|
| 201 |
+
}
|
| 202 |
+
return state;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
case 'vim_delete_line': {
|
| 206 |
+
const { count } = action.payload;
|
| 207 |
+
if (lines.length === 0) return state;
|
| 208 |
+
|
| 209 |
+
const linesToDelete = Math.min(count, lines.length - cursorRow);
|
| 210 |
+
const totalLines = lines.length;
|
| 211 |
+
|
| 212 |
+
if (totalLines === 1 || linesToDelete >= totalLines) {
|
| 213 |
+
// If there's only one line, or we're deleting all remaining lines,
|
| 214 |
+
// clear the content but keep one empty line (text editors should never be completely empty)
|
| 215 |
+
const nextState = pushUndo(state);
|
| 216 |
+
return {
|
| 217 |
+
...nextState,
|
| 218 |
+
lines: [''],
|
| 219 |
+
cursorRow: 0,
|
| 220 |
+
cursorCol: 0,
|
| 221 |
+
preferredCol: null,
|
| 222 |
+
};
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
const nextState = pushUndo(state);
|
| 226 |
+
const newLines = [...nextState.lines];
|
| 227 |
+
newLines.splice(cursorRow, linesToDelete);
|
| 228 |
+
|
| 229 |
+
// Adjust cursor position
|
| 230 |
+
const newCursorRow = Math.min(cursorRow, newLines.length - 1);
|
| 231 |
+
const newCursorCol = 0; // Vim places cursor at beginning of line after dd
|
| 232 |
+
|
| 233 |
+
return {
|
| 234 |
+
...nextState,
|
| 235 |
+
lines: newLines,
|
| 236 |
+
cursorRow: newCursorRow,
|
| 237 |
+
cursorCol: newCursorCol,
|
| 238 |
+
preferredCol: null,
|
| 239 |
+
};
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
case 'vim_change_line': {
|
| 243 |
+
const { count } = action.payload;
|
| 244 |
+
if (lines.length === 0) return state;
|
| 245 |
+
|
| 246 |
+
const linesToChange = Math.min(count, lines.length - cursorRow);
|
| 247 |
+
const nextState = pushUndo(state);
|
| 248 |
+
|
| 249 |
+
const { startOffset, endOffset } = getLineRangeOffsets(
|
| 250 |
+
cursorRow,
|
| 251 |
+
linesToChange,
|
| 252 |
+
nextState.lines,
|
| 253 |
+
);
|
| 254 |
+
const { startRow, startCol, endRow, endCol } = getPositionFromOffsets(
|
| 255 |
+
startOffset,
|
| 256 |
+
endOffset,
|
| 257 |
+
nextState.lines,
|
| 258 |
+
);
|
| 259 |
+
return replaceRangeInternal(
|
| 260 |
+
nextState,
|
| 261 |
+
startRow,
|
| 262 |
+
startCol,
|
| 263 |
+
endRow,
|
| 264 |
+
endCol,
|
| 265 |
+
'',
|
| 266 |
+
);
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
case 'vim_delete_to_end_of_line':
|
| 270 |
+
case 'vim_change_to_end_of_line': {
|
| 271 |
+
const currentLine = lines[cursorRow] || '';
|
| 272 |
+
if (cursorCol < cpLen(currentLine)) {
|
| 273 |
+
const nextState = pushUndo(state);
|
| 274 |
+
return replaceRangeInternal(
|
| 275 |
+
nextState,
|
| 276 |
+
cursorRow,
|
| 277 |
+
cursorCol,
|
| 278 |
+
cursorRow,
|
| 279 |
+
cpLen(currentLine),
|
| 280 |
+
'',
|
| 281 |
+
);
|
| 282 |
+
}
|
| 283 |
+
return state;
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
case 'vim_change_movement': {
|
| 287 |
+
const { movement, count } = action.payload;
|
| 288 |
+
const totalLines = lines.length;
|
| 289 |
+
|
| 290 |
+
switch (movement) {
|
| 291 |
+
case 'h': {
|
| 292 |
+
// Left
|
| 293 |
+
// Change N characters to the left
|
| 294 |
+
const startCol = Math.max(0, cursorCol - count);
|
| 295 |
+
return replaceRangeInternal(
|
| 296 |
+
pushUndo(state),
|
| 297 |
+
cursorRow,
|
| 298 |
+
startCol,
|
| 299 |
+
cursorRow,
|
| 300 |
+
cursorCol,
|
| 301 |
+
'',
|
| 302 |
+
);
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
case 'j': {
|
| 306 |
+
// Down
|
| 307 |
+
const linesToChange = Math.min(count, totalLines - cursorRow);
|
| 308 |
+
if (linesToChange > 0) {
|
| 309 |
+
if (totalLines === 1) {
|
| 310 |
+
const currentLine = state.lines[0] || '';
|
| 311 |
+
return replaceRangeInternal(
|
| 312 |
+
pushUndo(state),
|
| 313 |
+
0,
|
| 314 |
+
0,
|
| 315 |
+
0,
|
| 316 |
+
cpLen(currentLine),
|
| 317 |
+
'',
|
| 318 |
+
);
|
| 319 |
+
} else {
|
| 320 |
+
const nextState = pushUndo(state);
|
| 321 |
+
const { startOffset, endOffset } = getLineRangeOffsets(
|
| 322 |
+
cursorRow,
|
| 323 |
+
linesToChange,
|
| 324 |
+
nextState.lines,
|
| 325 |
+
);
|
| 326 |
+
const { startRow, startCol, endRow, endCol } =
|
| 327 |
+
getPositionFromOffsets(startOffset, endOffset, nextState.lines);
|
| 328 |
+
return replaceRangeInternal(
|
| 329 |
+
nextState,
|
| 330 |
+
startRow,
|
| 331 |
+
startCol,
|
| 332 |
+
endRow,
|
| 333 |
+
endCol,
|
| 334 |
+
'',
|
| 335 |
+
);
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
return state;
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
case 'k': {
|
| 342 |
+
// Up
|
| 343 |
+
const upLines = Math.min(count, cursorRow + 1);
|
| 344 |
+
if (upLines > 0) {
|
| 345 |
+
if (state.lines.length === 1) {
|
| 346 |
+
const currentLine = state.lines[0] || '';
|
| 347 |
+
return replaceRangeInternal(
|
| 348 |
+
pushUndo(state),
|
| 349 |
+
0,
|
| 350 |
+
0,
|
| 351 |
+
0,
|
| 352 |
+
cpLen(currentLine),
|
| 353 |
+
'',
|
| 354 |
+
);
|
| 355 |
+
} else {
|
| 356 |
+
const startRow = Math.max(0, cursorRow - count + 1);
|
| 357 |
+
const linesToChange = cursorRow - startRow + 1;
|
| 358 |
+
const nextState = pushUndo(state);
|
| 359 |
+
const { startOffset, endOffset } = getLineRangeOffsets(
|
| 360 |
+
startRow,
|
| 361 |
+
linesToChange,
|
| 362 |
+
nextState.lines,
|
| 363 |
+
);
|
| 364 |
+
const {
|
| 365 |
+
startRow: newStartRow,
|
| 366 |
+
startCol,
|
| 367 |
+
endRow,
|
| 368 |
+
endCol,
|
| 369 |
+
} = getPositionFromOffsets(
|
| 370 |
+
startOffset,
|
| 371 |
+
endOffset,
|
| 372 |
+
nextState.lines,
|
| 373 |
+
);
|
| 374 |
+
const resultState = replaceRangeInternal(
|
| 375 |
+
nextState,
|
| 376 |
+
newStartRow,
|
| 377 |
+
startCol,
|
| 378 |
+
endRow,
|
| 379 |
+
endCol,
|
| 380 |
+
'',
|
| 381 |
+
);
|
| 382 |
+
return {
|
| 383 |
+
...resultState,
|
| 384 |
+
cursorRow: startRow,
|
| 385 |
+
cursorCol: 0,
|
| 386 |
+
};
|
| 387 |
+
}
|
| 388 |
+
}
|
| 389 |
+
return state;
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
case 'l': {
|
| 393 |
+
// Right
|
| 394 |
+
// Change N characters to the right
|
| 395 |
+
return replaceRangeInternal(
|
| 396 |
+
pushUndo(state),
|
| 397 |
+
cursorRow,
|
| 398 |
+
cursorCol,
|
| 399 |
+
cursorRow,
|
| 400 |
+
Math.min(cpLen(lines[cursorRow] || ''), cursorCol + count),
|
| 401 |
+
'',
|
| 402 |
+
);
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
default:
|
| 406 |
+
return state;
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
case 'vim_move_left': {
|
| 411 |
+
const { count } = action.payload;
|
| 412 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 413 |
+
let newRow = cursorRow;
|
| 414 |
+
let newCol = cursorCol;
|
| 415 |
+
|
| 416 |
+
for (let i = 0; i < count; i++) {
|
| 417 |
+
if (newCol > 0) {
|
| 418 |
+
newCol--;
|
| 419 |
+
} else if (newRow > 0) {
|
| 420 |
+
// Move to end of previous line
|
| 421 |
+
newRow--;
|
| 422 |
+
const prevLine = lines[newRow] || '';
|
| 423 |
+
const prevLineLength = cpLen(prevLine);
|
| 424 |
+
// Position on last character, or column 0 for empty lines
|
| 425 |
+
newCol = prevLineLength === 0 ? 0 : prevLineLength - 1;
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
return {
|
| 430 |
+
...state,
|
| 431 |
+
cursorRow: newRow,
|
| 432 |
+
cursorCol: newCol,
|
| 433 |
+
preferredCol: null,
|
| 434 |
+
};
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
case 'vim_move_right': {
|
| 438 |
+
const { count } = action.payload;
|
| 439 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 440 |
+
let newRow = cursorRow;
|
| 441 |
+
let newCol = cursorCol;
|
| 442 |
+
|
| 443 |
+
for (let i = 0; i < count; i++) {
|
| 444 |
+
const currentLine = lines[newRow] || '';
|
| 445 |
+
const lineLength = cpLen(currentLine);
|
| 446 |
+
// Don't move past the last character of the line
|
| 447 |
+
// For empty lines, stay at column 0; for non-empty lines, don't go past last character
|
| 448 |
+
if (lineLength === 0) {
|
| 449 |
+
// Empty line - try to move to next line
|
| 450 |
+
if (newRow < lines.length - 1) {
|
| 451 |
+
newRow++;
|
| 452 |
+
newCol = 0;
|
| 453 |
+
}
|
| 454 |
+
} else if (newCol < lineLength - 1) {
|
| 455 |
+
newCol++;
|
| 456 |
+
|
| 457 |
+
// Skip over combining marks - don't let cursor land on them
|
| 458 |
+
const currentLinePoints = toCodePoints(currentLine);
|
| 459 |
+
while (
|
| 460 |
+
newCol < currentLinePoints.length &&
|
| 461 |
+
isCombiningMark(currentLinePoints[newCol]) &&
|
| 462 |
+
newCol < lineLength - 1
|
| 463 |
+
) {
|
| 464 |
+
newCol++;
|
| 465 |
+
}
|
| 466 |
+
} else if (newRow < lines.length - 1) {
|
| 467 |
+
// At end of line - move to beginning of next line
|
| 468 |
+
newRow++;
|
| 469 |
+
newCol = 0;
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
return {
|
| 474 |
+
...state,
|
| 475 |
+
cursorRow: newRow,
|
| 476 |
+
cursorCol: newCol,
|
| 477 |
+
preferredCol: null,
|
| 478 |
+
};
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
case 'vim_move_up': {
|
| 482 |
+
const { count } = action.payload;
|
| 483 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 484 |
+
const newRow = Math.max(0, cursorRow - count);
|
| 485 |
+
const targetLine = lines[newRow] || '';
|
| 486 |
+
const targetLineLength = cpLen(targetLine);
|
| 487 |
+
const newCol = Math.min(
|
| 488 |
+
cursorCol,
|
| 489 |
+
targetLineLength > 0 ? targetLineLength - 1 : 0,
|
| 490 |
+
);
|
| 491 |
+
|
| 492 |
+
return {
|
| 493 |
+
...state,
|
| 494 |
+
cursorRow: newRow,
|
| 495 |
+
cursorCol: newCol,
|
| 496 |
+
preferredCol: null,
|
| 497 |
+
};
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
case 'vim_move_down': {
|
| 501 |
+
const { count } = action.payload;
|
| 502 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 503 |
+
const newRow = Math.min(lines.length - 1, cursorRow + count);
|
| 504 |
+
const targetLine = lines[newRow] || '';
|
| 505 |
+
const targetLineLength = cpLen(targetLine);
|
| 506 |
+
const newCol = Math.min(
|
| 507 |
+
cursorCol,
|
| 508 |
+
targetLineLength > 0 ? targetLineLength - 1 : 0,
|
| 509 |
+
);
|
| 510 |
+
|
| 511 |
+
return {
|
| 512 |
+
...state,
|
| 513 |
+
cursorRow: newRow,
|
| 514 |
+
cursorCol: newCol,
|
| 515 |
+
preferredCol: null,
|
| 516 |
+
};
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
case 'vim_move_word_forward': {
|
| 520 |
+
const { count } = action.payload;
|
| 521 |
+
let row = cursorRow;
|
| 522 |
+
let col = cursorCol;
|
| 523 |
+
|
| 524 |
+
for (let i = 0; i < count; i++) {
|
| 525 |
+
const nextWord = findNextWordAcrossLines(lines, row, col, true);
|
| 526 |
+
if (nextWord) {
|
| 527 |
+
row = nextWord.row;
|
| 528 |
+
col = nextWord.col;
|
| 529 |
+
} else {
|
| 530 |
+
// No more words to move to
|
| 531 |
+
break;
|
| 532 |
+
}
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
return {
|
| 536 |
+
...state,
|
| 537 |
+
cursorRow: row,
|
| 538 |
+
cursorCol: col,
|
| 539 |
+
preferredCol: null,
|
| 540 |
+
};
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
case 'vim_move_word_backward': {
|
| 544 |
+
const { count } = action.payload;
|
| 545 |
+
let row = cursorRow;
|
| 546 |
+
let col = cursorCol;
|
| 547 |
+
|
| 548 |
+
for (let i = 0; i < count; i++) {
|
| 549 |
+
const prevWord = findPrevWordAcrossLines(lines, row, col);
|
| 550 |
+
if (prevWord) {
|
| 551 |
+
row = prevWord.row;
|
| 552 |
+
col = prevWord.col;
|
| 553 |
+
} else {
|
| 554 |
+
break;
|
| 555 |
+
}
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
return {
|
| 559 |
+
...state,
|
| 560 |
+
cursorRow: row,
|
| 561 |
+
cursorCol: col,
|
| 562 |
+
preferredCol: null,
|
| 563 |
+
};
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
case 'vim_move_word_end': {
|
| 567 |
+
const { count } = action.payload;
|
| 568 |
+
let row = cursorRow;
|
| 569 |
+
let col = cursorCol;
|
| 570 |
+
|
| 571 |
+
for (let i = 0; i < count; i++) {
|
| 572 |
+
// Special handling for the first iteration when we're at end of word
|
| 573 |
+
if (i === 0) {
|
| 574 |
+
const currentLine = lines[row] || '';
|
| 575 |
+
const lineCodePoints = toCodePoints(currentLine);
|
| 576 |
+
|
| 577 |
+
// Check if we're at the end of a word (on the last base character)
|
| 578 |
+
const atEndOfWord =
|
| 579 |
+
col < lineCodePoints.length &&
|
| 580 |
+
isWordCharStrict(lineCodePoints[col]) &&
|
| 581 |
+
(col + 1 >= lineCodePoints.length ||
|
| 582 |
+
!isWordCharWithCombining(lineCodePoints[col + 1]) ||
|
| 583 |
+
// Or if we're on a base char followed only by combining marks until non-word
|
| 584 |
+
(isWordCharStrict(lineCodePoints[col]) &&
|
| 585 |
+
isAtEndOfBaseWord(lineCodePoints, col)));
|
| 586 |
+
|
| 587 |
+
if (atEndOfWord) {
|
| 588 |
+
// We're already at end of word, find next word end
|
| 589 |
+
const nextWord = findNextWordAcrossLines(
|
| 590 |
+
lines,
|
| 591 |
+
row,
|
| 592 |
+
col + 1,
|
| 593 |
+
false,
|
| 594 |
+
);
|
| 595 |
+
if (nextWord) {
|
| 596 |
+
row = nextWord.row;
|
| 597 |
+
col = nextWord.col;
|
| 598 |
+
continue;
|
| 599 |
+
}
|
| 600 |
+
}
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
const wordEnd = findNextWordAcrossLines(lines, row, col, false);
|
| 604 |
+
if (wordEnd) {
|
| 605 |
+
row = wordEnd.row;
|
| 606 |
+
col = wordEnd.col;
|
| 607 |
+
} else {
|
| 608 |
+
break;
|
| 609 |
+
}
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
return {
|
| 613 |
+
...state,
|
| 614 |
+
cursorRow: row,
|
| 615 |
+
cursorCol: col,
|
| 616 |
+
preferredCol: null,
|
| 617 |
+
};
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
case 'vim_delete_char': {
|
| 621 |
+
const { count } = action.payload;
|
| 622 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 623 |
+
const currentLine = lines[cursorRow] || '';
|
| 624 |
+
const lineLength = cpLen(currentLine);
|
| 625 |
+
|
| 626 |
+
if (cursorCol < lineLength) {
|
| 627 |
+
const deleteCount = Math.min(count, lineLength - cursorCol);
|
| 628 |
+
const nextState = pushUndo(state);
|
| 629 |
+
return replaceRangeInternal(
|
| 630 |
+
nextState,
|
| 631 |
+
cursorRow,
|
| 632 |
+
cursorCol,
|
| 633 |
+
cursorRow,
|
| 634 |
+
cursorCol + deleteCount,
|
| 635 |
+
'',
|
| 636 |
+
);
|
| 637 |
+
}
|
| 638 |
+
return state;
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
case 'vim_insert_at_cursor': {
|
| 642 |
+
// Just return state - mode change is handled elsewhere
|
| 643 |
+
return state;
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
case 'vim_append_at_cursor': {
|
| 647 |
+
const { cursorRow, cursorCol, lines } = state;
|
| 648 |
+
const currentLine = lines[cursorRow] || '';
|
| 649 |
+
const newCol = cursorCol < cpLen(currentLine) ? cursorCol + 1 : cursorCol;
|
| 650 |
+
|
| 651 |
+
return {
|
| 652 |
+
...state,
|
| 653 |
+
cursorCol: newCol,
|
| 654 |
+
preferredCol: null,
|
| 655 |
+
};
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
case 'vim_open_line_below': {
|
| 659 |
+
const { cursorRow, lines } = state;
|
| 660 |
+
const nextState = pushUndo(state);
|
| 661 |
+
|
| 662 |
+
// Insert newline at end of current line
|
| 663 |
+
const endOfLine = cpLen(lines[cursorRow] || '');
|
| 664 |
+
return replaceRangeInternal(
|
| 665 |
+
nextState,
|
| 666 |
+
cursorRow,
|
| 667 |
+
endOfLine,
|
| 668 |
+
cursorRow,
|
| 669 |
+
endOfLine,
|
| 670 |
+
'\n',
|
| 671 |
+
);
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
case 'vim_open_line_above': {
|
| 675 |
+
const { cursorRow } = state;
|
| 676 |
+
const nextState = pushUndo(state);
|
| 677 |
+
|
| 678 |
+
// Insert newline at beginning of current line
|
| 679 |
+
const resultState = replaceRangeInternal(
|
| 680 |
+
nextState,
|
| 681 |
+
cursorRow,
|
| 682 |
+
0,
|
| 683 |
+
cursorRow,
|
| 684 |
+
0,
|
| 685 |
+
'\n',
|
| 686 |
+
);
|
| 687 |
+
|
| 688 |
+
// Move cursor to the new line above
|
| 689 |
+
return {
|
| 690 |
+
...resultState,
|
| 691 |
+
cursorRow,
|
| 692 |
+
cursorCol: 0,
|
| 693 |
+
};
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
case 'vim_append_at_line_end': {
|
| 697 |
+
const { cursorRow, lines } = state;
|
| 698 |
+
const lineLength = cpLen(lines[cursorRow] || '');
|
| 699 |
+
|
| 700 |
+
return {
|
| 701 |
+
...state,
|
| 702 |
+
cursorCol: lineLength,
|
| 703 |
+
preferredCol: null,
|
| 704 |
+
};
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
case 'vim_insert_at_line_start': {
|
| 708 |
+
const { cursorRow, lines } = state;
|
| 709 |
+
const currentLine = lines[cursorRow] || '';
|
| 710 |
+
let col = 0;
|
| 711 |
+
|
| 712 |
+
// Find first non-whitespace character using proper Unicode handling
|
| 713 |
+
const lineCodePoints = toCodePoints(currentLine);
|
| 714 |
+
while (col < lineCodePoints.length && /\s/.test(lineCodePoints[col])) {
|
| 715 |
+
col++;
|
| 716 |
+
}
|
| 717 |
+
|
| 718 |
+
return {
|
| 719 |
+
...state,
|
| 720 |
+
cursorCol: col,
|
| 721 |
+
preferredCol: null,
|
| 722 |
+
};
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
case 'vim_move_to_line_start': {
|
| 726 |
+
return {
|
| 727 |
+
...state,
|
| 728 |
+
cursorCol: 0,
|
| 729 |
+
preferredCol: null,
|
| 730 |
+
};
|
| 731 |
+
}
|
| 732 |
+
|
| 733 |
+
case 'vim_move_to_line_end': {
|
| 734 |
+
const { cursorRow, lines } = state;
|
| 735 |
+
const lineLength = cpLen(lines[cursorRow] || '');
|
| 736 |
+
|
| 737 |
+
return {
|
| 738 |
+
...state,
|
| 739 |
+
cursorCol: lineLength > 0 ? lineLength - 1 : 0,
|
| 740 |
+
preferredCol: null,
|
| 741 |
+
};
|
| 742 |
+
}
|
| 743 |
+
|
| 744 |
+
case 'vim_move_to_first_nonwhitespace': {
|
| 745 |
+
const { cursorRow, lines } = state;
|
| 746 |
+
const currentLine = lines[cursorRow] || '';
|
| 747 |
+
let col = 0;
|
| 748 |
+
|
| 749 |
+
// Find first non-whitespace character using proper Unicode handling
|
| 750 |
+
const lineCodePoints = toCodePoints(currentLine);
|
| 751 |
+
while (col < lineCodePoints.length && /\s/.test(lineCodePoints[col])) {
|
| 752 |
+
col++;
|
| 753 |
+
}
|
| 754 |
+
|
| 755 |
+
return {
|
| 756 |
+
...state,
|
| 757 |
+
cursorCol: col,
|
| 758 |
+
preferredCol: null,
|
| 759 |
+
};
|
| 760 |
+
}
|
| 761 |
+
|
| 762 |
+
case 'vim_move_to_first_line': {
|
| 763 |
+
return {
|
| 764 |
+
...state,
|
| 765 |
+
cursorRow: 0,
|
| 766 |
+
cursorCol: 0,
|
| 767 |
+
preferredCol: null,
|
| 768 |
+
};
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
case 'vim_move_to_last_line': {
|
| 772 |
+
const { lines } = state;
|
| 773 |
+
const lastRow = lines.length - 1;
|
| 774 |
+
|
| 775 |
+
return {
|
| 776 |
+
...state,
|
| 777 |
+
cursorRow: lastRow,
|
| 778 |
+
cursorCol: 0,
|
| 779 |
+
preferredCol: null,
|
| 780 |
+
};
|
| 781 |
+
}
|
| 782 |
+
|
| 783 |
+
case 'vim_move_to_line': {
|
| 784 |
+
const { lineNumber } = action.payload;
|
| 785 |
+
const { lines } = state;
|
| 786 |
+
const targetRow = Math.min(Math.max(0, lineNumber - 1), lines.length - 1);
|
| 787 |
+
|
| 788 |
+
return {
|
| 789 |
+
...state,
|
| 790 |
+
cursorRow: targetRow,
|
| 791 |
+
cursorCol: 0,
|
| 792 |
+
preferredCol: null,
|
| 793 |
+
};
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
case 'vim_escape_insert_mode': {
|
| 797 |
+
// Move cursor left if not at beginning of line (vim behavior when exiting insert mode)
|
| 798 |
+
const { cursorCol } = state;
|
| 799 |
+
const newCol = cursorCol > 0 ? cursorCol - 1 : 0;
|
| 800 |
+
|
| 801 |
+
return {
|
| 802 |
+
...state,
|
| 803 |
+
cursorCol: newCol,
|
| 804 |
+
preferredCol: null,
|
| 805 |
+
};
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
default: {
|
| 809 |
+
// This should never happen if TypeScript is working correctly
|
| 810 |
+
assumeExhaustive(action);
|
| 811 |
+
return state;
|
| 812 |
+
}
|
| 813 |
+
}
|
| 814 |
+
}
|
projects/ui/qwen-code/packages/cli/src/ui/utils/__snapshots__/MarkdownDisplay.test.tsx.snap
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
| 2 |
+
|
| 3 |
+
exports[`<MarkdownDisplay /> > correctly parses a mix of markdown elements 1`] = `
|
| 4 |
+
"Main Title
|
| 5 |
+
|
| 6 |
+
Here is a paragraph.
|
| 7 |
+
|
| 8 |
+
- List item 1
|
| 9 |
+
- List item 2
|
| 10 |
+
|
| 11 |
+
1 some code
|
| 12 |
+
|
| 13 |
+
Another paragraph.
|
| 14 |
+
"
|
| 15 |
+
`;
|
| 16 |
+
|
| 17 |
+
exports[`<MarkdownDisplay /> > handles a table at the end of the input 1`] = `
|
| 18 |
+
"Some text before.
|
| 19 |
+
| A | B |
|
| 20 |
+
|---|
|
| 21 |
+
| 1 | 2 |"
|
| 22 |
+
`;
|
| 23 |
+
|
| 24 |
+
exports[`<MarkdownDisplay /> > handles unclosed (pending) code blocks 1`] = `" 1 let y = 2;"`;
|
| 25 |
+
|
| 26 |
+
exports[`<MarkdownDisplay /> > hides line numbers in code blocks when showLineNumbers is false 1`] = `" const x = 1;"`;
|
| 27 |
+
|
| 28 |
+
exports[`<MarkdownDisplay /> > inserts a single space between paragraphs 1`] = `
|
| 29 |
+
"Paragraph 1.
|
| 30 |
+
|
| 31 |
+
Paragraph 2."
|
| 32 |
+
`;
|
| 33 |
+
|
| 34 |
+
exports[`<MarkdownDisplay /> > renders a fenced code block with a language 1`] = `
|
| 35 |
+
" 1 const x = 1;
|
| 36 |
+
2 console.log(x);"
|
| 37 |
+
`;
|
| 38 |
+
|
| 39 |
+
exports[`<MarkdownDisplay /> > renders a fenced code block without a language 1`] = `" 1 plain text"`;
|
| 40 |
+
|
| 41 |
+
exports[`<MarkdownDisplay /> > renders a simple paragraph 1`] = `"Hello, world."`;
|
| 42 |
+
|
| 43 |
+
exports[`<MarkdownDisplay /> > renders headers with correct levels 1`] = `
|
| 44 |
+
"Header 1
|
| 45 |
+
Header 2
|
| 46 |
+
Header 3
|
| 47 |
+
Header 4
|
| 48 |
+
"
|
| 49 |
+
`;
|
| 50 |
+
|
| 51 |
+
exports[`<MarkdownDisplay /> > renders horizontal rules 1`] = `
|
| 52 |
+
"Hello
|
| 53 |
+
---
|
| 54 |
+
World
|
| 55 |
+
---
|
| 56 |
+
Test
|
| 57 |
+
"
|
| 58 |
+
`;
|
| 59 |
+
|
| 60 |
+
exports[`<MarkdownDisplay /> > renders nested unordered lists 1`] = `
|
| 61 |
+
" * Level 1
|
| 62 |
+
* Level 2
|
| 63 |
+
* Level 3
|
| 64 |
+
"
|
| 65 |
+
`;
|
| 66 |
+
|
| 67 |
+
exports[`<MarkdownDisplay /> > renders nothing for empty text 1`] = `""`;
|
| 68 |
+
|
| 69 |
+
exports[`<MarkdownDisplay /> > renders ordered lists 1`] = `
|
| 70 |
+
" 1. First item
|
| 71 |
+
2. Second item
|
| 72 |
+
"
|
| 73 |
+
`;
|
| 74 |
+
|
| 75 |
+
exports[`<MarkdownDisplay /> > renders tables correctly 1`] = `
|
| 76 |
+
"
|
| 77 |
+
┌──────────┬──────────┐
|
| 78 |
+
│ Header 1 │ Header 2 │
|
| 79 |
+
├──────────┼──────────┤
|
| 80 |
+
│ Cell 1 │ Cell 2 │
|
| 81 |
+
│ Cell 3 │ Cell 4 │
|
| 82 |
+
└──────────┴──────────┘
|
| 83 |
+
"
|
| 84 |
+
`;
|
| 85 |
+
|
| 86 |
+
exports[`<MarkdownDisplay /> > renders unordered lists with different markers 1`] = `
|
| 87 |
+
" - item A
|
| 88 |
+
* item B
|
| 89 |
+
+ item C
|
| 90 |
+
"
|
| 91 |
+
`;
|
| 92 |
+
|
| 93 |
+
exports[`<MarkdownDisplay /> > shows line numbers in code blocks by default 1`] = `" 1 const x = 1;"`;
|
projects/ui/qwen-code/packages/core/src/code_assist/codeAssist.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { AuthType, ContentGenerator } from '../core/contentGenerator.js';
|
| 8 |
+
import { getOauthClient } from './oauth2.js';
|
| 9 |
+
import { setupUser } from './setup.js';
|
| 10 |
+
import { CodeAssistServer, HttpOptions } from './server.js';
|
| 11 |
+
import { Config } from '../config/config.js';
|
| 12 |
+
|
| 13 |
+
export async function createCodeAssistContentGenerator(
|
| 14 |
+
httpOptions: HttpOptions,
|
| 15 |
+
authType: AuthType,
|
| 16 |
+
config: Config,
|
| 17 |
+
sessionId?: string,
|
| 18 |
+
): Promise<ContentGenerator> {
|
| 19 |
+
if (
|
| 20 |
+
authType === AuthType.LOGIN_WITH_GOOGLE ||
|
| 21 |
+
authType === AuthType.CLOUD_SHELL
|
| 22 |
+
) {
|
| 23 |
+
const authClient = await getOauthClient(authType, config);
|
| 24 |
+
const userData = await setupUser(authClient);
|
| 25 |
+
return new CodeAssistServer(
|
| 26 |
+
authClient,
|
| 27 |
+
userData.projectId,
|
| 28 |
+
httpOptions,
|
| 29 |
+
sessionId,
|
| 30 |
+
userData.userTier,
|
| 31 |
+
);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
throw new Error(`Unsupported authType: ${authType}`);
|
| 35 |
+
}
|
projects/ui/qwen-code/packages/core/src/index.test.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect } from 'vitest';
|
| 8 |
+
|
| 9 |
+
describe('placeholder tests', () => {
|
| 10 |
+
it('should pass', () => {
|
| 11 |
+
expect(true).toBe(true);
|
| 12 |
+
});
|
| 13 |
+
});
|
projects/ui/qwen-code/packages/core/src/index.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
// Export config
|
| 8 |
+
export * from './config/config.js';
|
| 9 |
+
|
| 10 |
+
// Export Core Logic
|
| 11 |
+
export * from './core/client.js';
|
| 12 |
+
export * from './core/contentGenerator.js';
|
| 13 |
+
export * from './core/loggingContentGenerator.js';
|
| 14 |
+
export * from './core/geminiChat.js';
|
| 15 |
+
export * from './core/logger.js';
|
| 16 |
+
export * from './core/prompts.js';
|
| 17 |
+
export * from './core/tokenLimits.js';
|
| 18 |
+
export * from './core/turn.js';
|
| 19 |
+
export * from './core/geminiRequest.js';
|
| 20 |
+
export * from './core/coreToolScheduler.js';
|
| 21 |
+
export * from './core/nonInteractiveToolExecutor.js';
|
| 22 |
+
|
| 23 |
+
export * from './code_assist/codeAssist.js';
|
| 24 |
+
export * from './code_assist/oauth2.js';
|
| 25 |
+
export * from './qwen/qwenOAuth2.js';
|
| 26 |
+
export * from './code_assist/server.js';
|
| 27 |
+
export * from './code_assist/types.js';
|
| 28 |
+
|
| 29 |
+
// Export utilities
|
| 30 |
+
export * from './utils/paths.js';
|
| 31 |
+
export * from './utils/schemaValidator.js';
|
| 32 |
+
export * from './utils/errors.js';
|
| 33 |
+
export * from './utils/getFolderStructure.js';
|
| 34 |
+
export * from './utils/memoryDiscovery.js';
|
| 35 |
+
export * from './utils/gitIgnoreParser.js';
|
| 36 |
+
export * from './utils/gitUtils.js';
|
| 37 |
+
export * from './utils/editor.js';
|
| 38 |
+
export * from './utils/quotaErrorDetection.js';
|
| 39 |
+
export * from './utils/fileUtils.js';
|
| 40 |
+
export * from './utils/retry.js';
|
| 41 |
+
export * from './utils/shell-utils.js';
|
| 42 |
+
export * from './utils/systemEncoding.js';
|
| 43 |
+
export * from './utils/textUtils.js';
|
| 44 |
+
export * from './utils/formatters.js';
|
| 45 |
+
export * from './utils/filesearch/fileSearch.js';
|
| 46 |
+
export * from './utils/errorParsing.js';
|
| 47 |
+
|
| 48 |
+
// Export services
|
| 49 |
+
export * from './services/fileDiscoveryService.js';
|
| 50 |
+
export * from './services/gitService.js';
|
| 51 |
+
export * from './services/chatRecordingService.js';
|
| 52 |
+
export * from './services/fileSystemService.js';
|
| 53 |
+
|
| 54 |
+
// Export IDE specific logic
|
| 55 |
+
export * from './ide/ide-client.js';
|
| 56 |
+
export * from './ide/ideContext.js';
|
| 57 |
+
export * from './ide/ide-installer.js';
|
| 58 |
+
export * from './ide/constants.js';
|
| 59 |
+
export { getIdeInfo, DetectedIde, IdeInfo } from './ide/detect-ide.js';
|
| 60 |
+
export * from './ide/constants.js';
|
| 61 |
+
|
| 62 |
+
// Export Shell Execution Service
|
| 63 |
+
export * from './services/shellExecutionService.js';
|
| 64 |
+
|
| 65 |
+
// Export base tool definitions
|
| 66 |
+
export * from './tools/tools.js';
|
| 67 |
+
export * from './tools/tool-error.js';
|
| 68 |
+
export * from './tools/tool-registry.js';
|
| 69 |
+
|
| 70 |
+
// Export prompt logic
|
| 71 |
+
export * from './prompts/mcp-prompts.js';
|
| 72 |
+
|
| 73 |
+
// Export specific tool logic
|
| 74 |
+
export * from './tools/read-file.js';
|
| 75 |
+
export * from './tools/ls.js';
|
| 76 |
+
export * from './tools/grep.js';
|
| 77 |
+
export * from './tools/glob.js';
|
| 78 |
+
export * from './tools/edit.js';
|
| 79 |
+
export * from './tools/write-file.js';
|
| 80 |
+
export * from './tools/web-fetch.js';
|
| 81 |
+
export * from './tools/memoryTool.js';
|
| 82 |
+
export * from './tools/shell.js';
|
| 83 |
+
export * from './tools/web-search.js';
|
| 84 |
+
export * from './tools/read-many-files.js';
|
| 85 |
+
export * from './tools/mcp-client.js';
|
| 86 |
+
export * from './tools/mcp-tool.js';
|
| 87 |
+
|
| 88 |
+
// MCP OAuth
|
| 89 |
+
export { MCPOAuthProvider } from './mcp/oauth-provider.js';
|
| 90 |
+
export {
|
| 91 |
+
MCPOAuthToken,
|
| 92 |
+
MCPOAuthCredentials,
|
| 93 |
+
MCPOAuthTokenStorage,
|
| 94 |
+
} from './mcp/oauth-token-storage.js';
|
| 95 |
+
export type { MCPOAuthConfig } from './mcp/oauth-provider.js';
|
| 96 |
+
export type {
|
| 97 |
+
OAuthAuthorizationServerMetadata,
|
| 98 |
+
OAuthProtectedResourceMetadata,
|
| 99 |
+
} from './mcp/oauth-utils.js';
|
| 100 |
+
export { OAuthUtils } from './mcp/oauth-utils.js';
|
| 101 |
+
|
| 102 |
+
// Export telemetry functions
|
| 103 |
+
export * from './telemetry/index.js';
|
| 104 |
+
export { sessionId } from './utils/session.js';
|
| 105 |
+
export * from './utils/browser.js';
|
| 106 |
+
// OpenAI Logging Utilities
|
| 107 |
+
export { OpenAILogger, openaiLogger } from './utils/openaiLogger.js';
|