| 1 |
/** |
| 2 |
* All changes to a CodeMirror editor happen as transactions that can be dispatched on the editor. |
| 3 |
*/ |
| 4 |
|
| 5 |
import type { Diagnostic } from "@codemirror/lint"; |
| 6 |
import { setDiagnostics } from "@codemirror/lint"; |
| 7 |
import type { EditorState, TransactionSpec } from "@codemirror/state"; |
| 8 |
|
| 9 |
import type { BeancountError } from "../api/validators"; |
| 10 |
|
| 11 |
/** |
| 12 |
* Returns a transaction to completely replace the contents of the editor with the given value. |
| 13 |
*/ |
| 14 |
export function replaceContents( |
| 15 |
state: EditorState, |
| 16 |
value: string, |
| 17 |
): TransactionSpec { |
| 18 |
return { |
| 19 |
changes: { from: 0, to: state.doc.length, insert: value }, |
| 20 |
}; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Returns a transaction to select the line with the given number and scroll it into view. |
| 25 |
*/ |
| 26 |
export function scrollToLine( |
| 27 |
state: EditorState, |
| 28 |
line: number, |
| 29 |
): TransactionSpec { |
| 30 |
if (line < 1 || line > state.doc.lines) { |
| 31 |
return {}; |
| 32 |
} |
| 33 |
const linePos = state.doc.line(line); |
| 34 |
return { |
| 35 |
selection: { anchor: linePos.from }, |
| 36 |
scrollIntoView: true, |
| 37 |
}; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Returns a transaction that set diagnostics for Beancount errors for in the editor, highlighting them. |
| 42 |
*/ |
| 43 |
export function setErrors( |
| 44 |
state: EditorState, |
| 45 |
errors: BeancountError[], |
| 46 |
): TransactionSpec { |
| 47 |
const { doc } = state; |
| 48 |
const diagnostics = errors.map(({ source, message }): Diagnostic => { |
| 49 |
// Show errors without a line number on first line and ensure it is within the document. |
| 50 |
const lineno = Math.min(Math.max(source?.lineno ?? 1, 1), doc.lines); |
| 51 |
const line = doc.line(lineno); |
| 52 |
return { |
| 53 |
from: line.from, |
| 54 |
to: line.to, |
| 55 |
severity: "error", |
| 56 |
message, |
| 57 |
}; |
| 58 |
}); |
| 59 |
return setDiagnostics(state, diagnostics); |
| 60 |
} |