|
| 1 | +import {Position} from 'codemirror' |
| 2 | + |
| 3 | +const rejoinScript = (scriptLines: string[]): string => { |
| 4 | + return scriptLines.join('\n') |
| 5 | +} |
| 6 | + |
| 7 | +const getCursorPosition = ( |
| 8 | + currentLineNumber: number, |
| 9 | + currentCharacterNumber: number, |
| 10 | + variableName: string |
| 11 | +) => { |
| 12 | + return { |
| 13 | + line: currentLineNumber, |
| 14 | + ch: currentCharacterNumber + formatVariable(variableName).length, |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +const insertAtCharacter = ( |
| 19 | + lineNumber: number, |
| 20 | + characterNumber: number, |
| 21 | + scriptLines: string[], |
| 22 | + variableName: string |
| 23 | +): string => { |
| 24 | + const lineToEdit = scriptLines[lineNumber] |
| 25 | + const front = lineToEdit.slice(0, characterNumber) |
| 26 | + const back = lineToEdit.slice(characterNumber, lineToEdit.length) |
| 27 | + |
| 28 | + const updatedLine = `${front}${formatVariable(variableName)}${back}` |
| 29 | + scriptLines[lineNumber] = updatedLine |
| 30 | + |
| 31 | + return rejoinScript(scriptLines) |
| 32 | +} |
| 33 | + |
| 34 | +const formatVariable = (variableName: string): string => { |
| 35 | + return `v.${variableName}` |
| 36 | +} |
| 37 | + |
| 38 | +export const insertVariable = ( |
| 39 | + currentLineNumber: number, |
| 40 | + currentCharacterNumber: number, |
| 41 | + currentScript: string, |
| 42 | + variableName: string |
| 43 | +): {updatedScript: string; cursorPosition: Position} => { |
| 44 | + const scriptLines = currentScript.split('\n') |
| 45 | + |
| 46 | + const updatedScript = insertAtCharacter( |
| 47 | + currentLineNumber, |
| 48 | + currentCharacterNumber, |
| 49 | + scriptLines, |
| 50 | + variableName |
| 51 | + ) |
| 52 | + |
| 53 | + const updatedCursorPosition = getCursorPosition( |
| 54 | + currentLineNumber, |
| 55 | + currentCharacterNumber, |
| 56 | + variableName |
| 57 | + ) |
| 58 | + |
| 59 | + return {updatedScript, cursorPosition: updatedCursorPosition} |
| 60 | +} |
0 commit comments