From eba911ddc148c14455eac91f11d75a8d1500e116 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:51:12 -0700 Subject: [PATCH] refactor: move util functions --- core/nextEdit/templating/utils.ts | 85 +++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 core/nextEdit/templating/utils.ts diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts new file mode 100644 index 000000000..9eca26866 --- /dev/null +++ b/core/nextEdit/templating/utils.ts @@ -0,0 +1,85 @@ +import { Position } from "../.."; +import { + EDITABLE_REGION_END_TOKEN, + EDITABLE_REGION_START_TOKEN, + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + USER_CURSOR_IS_HERE_TOKEN, +} from "../constants"; + +export function insertCursorToken( + lines: string[], + cursorPos: Position, + cursorToken: string, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure character position is within bounds or at the end of the line. + const lineLength = lines[cursorPos.line].length; + const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); + + lines[cursorPos.line] = + lines[cursorPos.line].slice(0, charPos) + + cursorToken + + lines[cursorPos.line].slice(charPos); + + return lines; +} + +export function insertEditableRegionTokensWithStaticRange( + lines: string[], + cursorPos: Position, + editableRegionStart?: number, + editableRegionEnd?: number, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure editable regions are within bounds. + if (editableRegionStart === undefined) { + editableRegionStart = Math.max( + cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + } + if (editableRegionEnd === undefined) { + editableRegionEnd = Math.min( + cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + lines.length - 1, // Line numbers should be zero-indexed. + ); + } + + // console.log("editableRegionStart:", editableRegionStart); + + const instrumentedLines = [ + ...lines.slice(0, editableRegionStart), + EDITABLE_REGION_START_TOKEN, + ...lines.slice(editableRegionStart, editableRegionEnd + 1), + EDITABLE_REGION_END_TOKEN, + ...lines.slice(editableRegionEnd + 1), + ]; + + return instrumentedLines; +} + +export function insertEditableRegionTokensWithAst( + lines: string[], + cursorPos: Position, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure character position is within bounds or at the end of the line. + const lineLength = lines[cursorPos.line].length; + const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); + + (lines[cursorPos.line] = + lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN), + lines[cursorPos.line].slice(charPos); + + return lines; +}