| 1 | import { Position } from "../.."; |
| 2 | import { |
| 3 | INSTINCT_EDITABLE_REGION_END_TOKEN, |
| 4 | INSTINCT_EDITABLE_REGION_START_TOKEN, |
| 5 | NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 6 | NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 7 | } from "../constants"; |
| 8 | |
| 9 | export function insertCursorToken( |
| 10 | lines: string[], |
| 11 | cursorPos: Position, |
| 12 | cursorToken: string, |
| 13 | ) { |
| 14 | if (cursorPos.line < 0 || cursorPos.line >= lines.length) { |
| 15 | return lines; |
| 16 | } |
| 17 | |
| 18 | // Ensure character position is within bounds or at the end of the line. |
| 19 | const lineLength = lines[cursorPos.line].length; |
| 20 | const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); |
| 21 | |
| 22 | lines[cursorPos.line] = |
| 23 | lines[cursorPos.line].slice(0, charPos) + |
| 24 | cursorToken + |
| 25 | lines[cursorPos.line].slice(charPos); |
| 26 | |
| 27 | return lines; |
| 28 | } |
| 29 | |
| 30 | export function insertEditableRegionTokensWithStaticRange( |
| 31 | lines: string[], |
| 32 | cursorPos: Position, |
| 33 | editableRegionStart?: number, |
| 34 | editableRegionEnd?: number, |
| 35 | ) { |
| 36 | if (cursorPos.line < 0 || cursorPos.line >= lines.length) { |
| 37 | return lines; |
| 38 | } |
| 39 | |
| 40 | // Ensure editable regions are within bounds. |
| 41 | if (editableRegionStart === undefined) { |
| 42 | editableRegionStart = Math.max( |
| 43 | cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 44 | 0, |
| 45 | ); |
| 46 | } |
| 47 | if (editableRegionEnd === undefined) { |
| 48 | editableRegionEnd = Math.min( |
| 49 | cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 50 | lines.length - 1, // Line numbers should be zero-indexed. |
| 51 | ); |
| 52 | } |
| 53 | |
| 54 | const instrumentedLines = [ |
| 55 | ...lines.slice(0, editableRegionStart), |
| 56 | INSTINCT_EDITABLE_REGION_START_TOKEN, |
| 57 | ...lines.slice(editableRegionStart, editableRegionEnd + 1), |
| 58 | INSTINCT_EDITABLE_REGION_END_TOKEN, |
| 59 | ...lines.slice(editableRegionEnd + 1), |
| 60 | ]; |
| 61 | |
| 62 | return instrumentedLines; |
| 63 | } |