@stacksjs/components 0.2.853 → 0.2.855
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CodeEditor-jg4w7e15.stx +497 -0
- package/dist/code-editor/editor.js +2166 -0
- package/dist/components/CodeBlock.d.ts +12 -5
- package/dist/index.d.ts +2 -0
- package/dist/index.js +29 -12
- package/dist/ui/code-editor/CodeEditor.d.ts +46 -0
- package/dist/ui/code-editor/controller.d.ts +103 -0
- package/dist/ui/code-editor/core/commands.d.ts +55 -0
- package/dist/ui/code-editor/core/completion.d.ts +40 -0
- package/dist/ui/code-editor/core/editor.d.ts +69 -0
- package/dist/ui/code-editor/core/highlight.d.ts +61 -0
- package/dist/ui/code-editor/core/history.d.ts +27 -0
- package/dist/ui/code-editor/core/index.d.ts +13 -0
- package/dist/ui/code-editor/core/keymap.d.ts +38 -0
- package/dist/ui/code-editor/core/selection.d.ts +30 -0
- package/dist/ui/code-editor/core/text.d.ts +64 -0
- package/dist/ui/code-editor/editor.d.ts +15 -0
- package/dist/ui/code-editor/index.d.ts +29 -0
- package/dist/ui/code-editor/tokenizer.d.ts +18 -0
- package/dist/ui/code-editor/view.d.ts +59 -0
- package/dist/utils/highlighter.d.ts +19 -1
- package/dist/utils/highlighter.js +24 -7
- package/dist/utils/syntax-theme.d.ts +44 -0
- package/package.json +9 -4
- package/src/components/CodeBlock.stx +195 -17
- package/src/index.ts +2 -0
- package/src/ui/code-editor/CodeEditor.stx +497 -0
- package/src/ui/code-editor/README.md +134 -0
- package/src/ui/code-editor/controller.ts +517 -0
- package/src/ui/code-editor/core/commands.ts +381 -0
- package/src/ui/code-editor/core/completion.ts +212 -0
- package/src/ui/code-editor/core/editor.ts +319 -0
- package/src/ui/code-editor/core/highlight.ts +203 -0
- package/src/ui/code-editor/core/history.ts +190 -0
- package/src/ui/code-editor/core/index.ts +14 -0
- package/src/ui/code-editor/core/keymap.ts +125 -0
- package/src/ui/code-editor/core/selection.ts +104 -0
- package/src/ui/code-editor/core/text.ts +252 -0
- package/src/ui/code-editor/editor.ts +16 -0
- package/src/ui/code-editor/index.ts +46 -0
- package/src/ui/code-editor/tokenizer.ts +74 -0
- package/src/ui/code-editor/view.ts +1066 -0
- package/src/utils/highlighter.ts +121 -218
- package/src/utils/syntax-theme.ts +144 -0
|
@@ -0,0 +1,1066 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The editor's view: a text field laid over a painted copy of itself.
|
|
3
|
+
*
|
|
4
|
+
* The field is a real `<textarea>` holding the whole document, with its text
|
|
5
|
+
* made transparent. Underneath it, the same text is drawn again in colour. The
|
|
6
|
+
* reader sees the coloured copy and types into the field, and because it is a
|
|
7
|
+
* real field the browser supplies everything that is hard to build: the caret,
|
|
8
|
+
* the selection, input methods, dictation, spellcheck replacements, drag and
|
|
9
|
+
* drop, the clipboard, and a control a screen reader already understands.
|
|
10
|
+
*
|
|
11
|
+
* What this file adds is everything a field does not do. It keeps the two
|
|
12
|
+
* layers on the same pixels, draws only the lines on screen, repaints only the
|
|
13
|
+
* lines whose tokens changed, and positions what hangs off a line: a number in
|
|
14
|
+
* the gutter, a squiggle under a range, a result after the end, ghost text at
|
|
15
|
+
* the caret.
|
|
16
|
+
*
|
|
17
|
+
* Both layers scroll inside one scroller, as ordinary content. The field is as
|
|
18
|
+
* tall and as wide as the document, so it never scrolls on its own, and there
|
|
19
|
+
* is no scroll position to copy from one layer to the other - which is where
|
|
20
|
+
* the two layers of an overlay editor usually come apart for a frame.
|
|
21
|
+
*
|
|
22
|
+
* This is the one file in the editor that owns DOM. The stx template declares
|
|
23
|
+
* the elements; this fills and positions them. The model, in `./core`, knows
|
|
24
|
+
* nothing about any of it.
|
|
25
|
+
*/
|
|
26
|
+
import type { EditorCore, HighlightedLine, LineTokenizer, Position, ResolvedKeymap, Transaction } from './core'
|
|
27
|
+
import { handleTextInput, LineHighlighter, mapOffset, rangeEmpty, rangeFrom, rangeTo } from './core'
|
|
28
|
+
|
|
29
|
+
/** Something shown beside or after a line: a result, a note, an error. */
|
|
30
|
+
export interface EditorWidget {
|
|
31
|
+
/** Zero-based line. */
|
|
32
|
+
line: number
|
|
33
|
+
/** A column to sit at, or `'end'` (the default) to follow the line's text. */
|
|
34
|
+
column?: number | 'end'
|
|
35
|
+
text: string
|
|
36
|
+
/** Free-form: `result`, `error`, `info`. Becomes `data-kind` for styling. */
|
|
37
|
+
kind?: string
|
|
38
|
+
className?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type DiagnosticSeverity = 'error' | 'warning' | 'info' | 'hint'
|
|
42
|
+
|
|
43
|
+
/** A range with something to say about it, drawn as a squiggle. */
|
|
44
|
+
export interface EditorDiagnostic {
|
|
45
|
+
from: Position
|
|
46
|
+
to: Position
|
|
47
|
+
message: string
|
|
48
|
+
severity?: DiagnosticSeverity
|
|
49
|
+
source?: string
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Where the caret is, for anything that has to be placed beside it. */
|
|
53
|
+
export interface CaretAnchor {
|
|
54
|
+
/** Relative to the text area, which is what a popup is positioned in. */
|
|
55
|
+
left: number
|
|
56
|
+
top: number
|
|
57
|
+
bottom: number
|
|
58
|
+
/** Room between the caret line and each edge of what is visible. */
|
|
59
|
+
spaceAbove: number
|
|
60
|
+
spaceBelow: number
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface EditorViewOptions {
|
|
64
|
+
core: EditorCore
|
|
65
|
+
keymap: ResolvedKeymap
|
|
66
|
+
/** Told about every transaction, after the view has caught up with it. */
|
|
67
|
+
onTransaction?: (transaction: Transaction) => void
|
|
68
|
+
/** A command the core does not own: `run`, `runSelection`, `triggerCompletion`. */
|
|
69
|
+
onCommand?: (name: string) => boolean
|
|
70
|
+
/** First refusal on a key, before any binding. True means it was handled. */
|
|
71
|
+
onKeydown?: (event: KeyboardEvent) => boolean
|
|
72
|
+
onFocus?: () => void
|
|
73
|
+
onBlur?: () => void
|
|
74
|
+
/** Ghost text was taken or let go. */
|
|
75
|
+
onGhost?: (outcome: 'accept' | 'dismiss', text: string) => void
|
|
76
|
+
/** Show each diagnostic's message after its line. Default true. */
|
|
77
|
+
inlineDiagnostics?: boolean
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface StoredDiagnostic {
|
|
81
|
+
from: number
|
|
82
|
+
to: number
|
|
83
|
+
message: string
|
|
84
|
+
severity: DiagnosticSeverity
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface StoredWidget {
|
|
88
|
+
offset: number
|
|
89
|
+
atEnd: boolean
|
|
90
|
+
text: string
|
|
91
|
+
kind: string
|
|
92
|
+
className: string
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
interface Metrics {
|
|
96
|
+
lineHeight: number
|
|
97
|
+
charWidth: number
|
|
98
|
+
padTop: number
|
|
99
|
+
padBottom: number
|
|
100
|
+
padLeft: number
|
|
101
|
+
padRight: number
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Lines drawn above and below what is visible, so a scroll has something to show. */
|
|
105
|
+
const OVERSCAN = 12
|
|
106
|
+
/** Lines tokenized past the screen in the pass that follows a change. */
|
|
107
|
+
const SYNC_BUDGET = 200
|
|
108
|
+
/** Lines tokenized per idle pass while a long cascade or a first load finishes. */
|
|
109
|
+
const IDLE_BUDGET = 600
|
|
110
|
+
const SEVERITY_RANK: Record<DiagnosticSeverity, number> = { error: 3, warning: 2, info: 1, hint: 0 }
|
|
111
|
+
const PRINTABLE_ASCII = /^[\x20-\x7E]*$/
|
|
112
|
+
|
|
113
|
+
function escapeHtml(text: string): string {
|
|
114
|
+
// Tested before replacing: most lines of most files have nothing to escape.
|
|
115
|
+
if (!/[&<>]/.test(text))
|
|
116
|
+
return text
|
|
117
|
+
|
|
118
|
+
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** One line as HTML: a span per coloured run, plain text left unwrapped. */
|
|
122
|
+
export function renderLineHtml(line: HighlightedLine | null, text: string): string {
|
|
123
|
+
if (!line || line.text !== text)
|
|
124
|
+
return escapeHtml(text)
|
|
125
|
+
|
|
126
|
+
let html = ''
|
|
127
|
+
for (const token of line.tokens)
|
|
128
|
+
html += token.type === '' ? escapeHtml(token.content) : `<span class="tok-${token.type}">${escapeHtml(token.content)}</span>`
|
|
129
|
+
|
|
130
|
+
return html
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function part(root: HTMLElement, name: string): HTMLElement {
|
|
134
|
+
const element = root.querySelector<HTMLElement>(`[data-ce="${name}"]`)
|
|
135
|
+
if (!element)
|
|
136
|
+
throw new Error(`CodeEditor: the template has no [data-ce="${name}"] element`)
|
|
137
|
+
|
|
138
|
+
return element
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export class EditorView {
|
|
142
|
+
readonly core: EditorCore
|
|
143
|
+
private readonly options: EditorViewOptions
|
|
144
|
+
private readonly root: HTMLElement
|
|
145
|
+
private readonly scroller: HTMLElement
|
|
146
|
+
private readonly content: HTMLElement
|
|
147
|
+
private readonly gutter: HTMLElement
|
|
148
|
+
private readonly gutterRows: HTMLElement
|
|
149
|
+
private readonly region: HTMLElement
|
|
150
|
+
private readonly rows: HTMLElement
|
|
151
|
+
private readonly textarea: HTMLTextAreaElement
|
|
152
|
+
private readonly activeLine: HTMLElement
|
|
153
|
+
private readonly decorations: HTMLElement
|
|
154
|
+
private readonly widgetLayer: HTMLElement
|
|
155
|
+
private readonly measure: HTMLElement
|
|
156
|
+
private readonly status: HTMLElement | null
|
|
157
|
+
|
|
158
|
+
private keymap: ResolvedKeymap
|
|
159
|
+
private highlighter: LineHighlighter | null = null
|
|
160
|
+
private metrics: Metrics = { lineHeight: 20, charWidth: 8, padTop: 0, padBottom: 0, padLeft: 0, padRight: 0 }
|
|
161
|
+
private widthCache: Map<string, number> = new Map()
|
|
162
|
+
|
|
163
|
+
/** What each drawn row currently shows, so an unchanged row is left alone. */
|
|
164
|
+
private rendered: Array<HighlightedLine | string | null> = []
|
|
165
|
+
private renderedNumbers: number[] = []
|
|
166
|
+
private firstRow = 0
|
|
167
|
+
private gutterWidth = 0
|
|
168
|
+
private showLineNumbers = true
|
|
169
|
+
private contentWidth = -1
|
|
170
|
+
private contentHeight = -1
|
|
171
|
+
private activeRow = -1
|
|
172
|
+
|
|
173
|
+
private widgets: StoredWidget[] = []
|
|
174
|
+
private diagnostics: StoredDiagnostic[] = []
|
|
175
|
+
private ghost: { offset: number, text: string } | null = null
|
|
176
|
+
private announced = ''
|
|
177
|
+
|
|
178
|
+
private composing = false
|
|
179
|
+
private focused = false
|
|
180
|
+
private tabLeavesNext = false
|
|
181
|
+
private frame = 0
|
|
182
|
+
private idle: ReturnType<typeof setTimeout> | undefined
|
|
183
|
+
private resizeObserver: ResizeObserver | undefined
|
|
184
|
+
private readonly disposers: Array<() => void> = []
|
|
185
|
+
private destroyed = false
|
|
186
|
+
|
|
187
|
+
constructor(root: HTMLElement, options: EditorViewOptions) {
|
|
188
|
+
this.root = root
|
|
189
|
+
this.options = options
|
|
190
|
+
this.core = options.core
|
|
191
|
+
this.keymap = options.keymap
|
|
192
|
+
this.scroller = part(root, 'scroller')
|
|
193
|
+
this.content = part(root, 'content')
|
|
194
|
+
this.gutter = part(root, 'gutter')
|
|
195
|
+
this.gutterRows = part(root, 'gutter-rows')
|
|
196
|
+
this.region = part(root, 'region')
|
|
197
|
+
this.rows = part(root, 'rows')
|
|
198
|
+
this.textarea = part(root, 'input') as HTMLTextAreaElement
|
|
199
|
+
this.activeLine = part(root, 'active-line')
|
|
200
|
+
this.decorations = part(root, 'decorations')
|
|
201
|
+
this.widgetLayer = part(root, 'widgets')
|
|
202
|
+
this.measure = part(root, 'measure')
|
|
203
|
+
this.status = root.querySelector<HTMLElement>('[data-ce="status"]')
|
|
204
|
+
|
|
205
|
+
// The field may already hold text the server rendered into it. The model is
|
|
206
|
+
// the authority from here on, so whichever differs is brought into line.
|
|
207
|
+
if (this.textarea.value !== this.core.value)
|
|
208
|
+
this.textarea.value = this.core.value
|
|
209
|
+
|
|
210
|
+
this.listen(this.textarea, 'beforeinput', event => this.onBeforeInput(event as InputEvent))
|
|
211
|
+
this.listen(this.textarea, 'input', () => this.onInput())
|
|
212
|
+
this.listen(this.textarea, 'keydown', event => this.onKeydown(event as KeyboardEvent))
|
|
213
|
+
this.listen(this.textarea, 'compositionstart', () => {
|
|
214
|
+
this.composing = true
|
|
215
|
+
})
|
|
216
|
+
this.listen(this.textarea, 'compositionend', () => {
|
|
217
|
+
this.composing = false
|
|
218
|
+
this.onInput()
|
|
219
|
+
})
|
|
220
|
+
this.listen(this.textarea, 'focus', () => {
|
|
221
|
+
this.focused = true
|
|
222
|
+
this.root.setAttribute('data-focused', '')
|
|
223
|
+
this.syncSelection()
|
|
224
|
+
this.render()
|
|
225
|
+
this.options.onFocus?.()
|
|
226
|
+
})
|
|
227
|
+
this.listen(this.textarea, 'blur', () => {
|
|
228
|
+
this.focused = false
|
|
229
|
+
this.tabLeavesNext = false
|
|
230
|
+
this.root.removeAttribute('data-focused')
|
|
231
|
+
this.render()
|
|
232
|
+
this.options.onBlur?.()
|
|
233
|
+
})
|
|
234
|
+
// The field is as large as its text and should never scroll by itself. A
|
|
235
|
+
// browser that nudges it anyway would slide the caret off the painted copy.
|
|
236
|
+
this.listen(this.textarea, 'scroll', () => {
|
|
237
|
+
if (this.textarea.scrollTop !== 0)
|
|
238
|
+
this.textarea.scrollTop = 0
|
|
239
|
+
if (this.textarea.scrollLeft !== 0)
|
|
240
|
+
this.textarea.scrollLeft = 0
|
|
241
|
+
})
|
|
242
|
+
this.listen(this.textarea, 'select', () => this.syncSelection())
|
|
243
|
+
this.listen(this.textarea, 'mouseup', () => this.syncSelection())
|
|
244
|
+
this.listen(this.textarea, 'keyup', () => this.syncSelection())
|
|
245
|
+
// Where a selection change is announced: on the document, for the field
|
|
246
|
+
// that has focus. Not every engine sends it to the field itself.
|
|
247
|
+
this.listen(root.ownerDocument, 'selectionchange', () => {
|
|
248
|
+
if (root.ownerDocument.activeElement === this.textarea)
|
|
249
|
+
this.syncSelection()
|
|
250
|
+
})
|
|
251
|
+
this.listen(this.scroller, 'scroll', () => this.scheduleRender(), { passive: true })
|
|
252
|
+
this.listen(this.gutter, 'mousedown', event => this.onGutterMouseDown(event as MouseEvent))
|
|
253
|
+
|
|
254
|
+
if (typeof ResizeObserver !== 'undefined') {
|
|
255
|
+
this.resizeObserver = new ResizeObserver(() => this.layout())
|
|
256
|
+
this.resizeObserver.observe(this.scroller)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// A web font that arrives late changes every character's width.
|
|
260
|
+
const fonts = root.ownerDocument.fonts
|
|
261
|
+
if (fonts?.ready)
|
|
262
|
+
void fonts.ready.then(() => !this.destroyed && this.layout())
|
|
263
|
+
|
|
264
|
+
this.disposers.push(this.core.subscribe(transaction => this.onTransaction(transaction)))
|
|
265
|
+
|
|
266
|
+
this.root.setAttribute('data-ce-ready', '')
|
|
267
|
+
this.layout()
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private listen(target: EventTarget, type: string, handler: (event: Event) => void, options?: AddEventListenerOptions): void {
|
|
271
|
+
target.addEventListener(type, handler, options)
|
|
272
|
+
this.disposers.push(() => target.removeEventListener(type, handler, options))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ---------------------------------------------------------------- settings
|
|
276
|
+
|
|
277
|
+
setKeymap(keymap: ResolvedKeymap): void {
|
|
278
|
+
this.keymap = keymap
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
setLineNumbers(show: boolean): void {
|
|
282
|
+
this.showLineNumbers = show
|
|
283
|
+
this.layout()
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
setReadOnly(readOnly: boolean): void {
|
|
287
|
+
this.core.readOnly = readOnly
|
|
288
|
+
this.textarea.readOnly = readOnly
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Give the editor a tokenizer, or take it away. Everything is recoloured. */
|
|
292
|
+
setTokenizer<State>(tokenizer: LineTokenizer<State> | null): void {
|
|
293
|
+
// The view never looks inside a tokenizer's state, only hands it back.
|
|
294
|
+
this.highlighter = tokenizer ? new LineHighlighter(tokenizer, this.core.doc) as unknown as LineHighlighter : null
|
|
295
|
+
this.rendered = []
|
|
296
|
+
this.render()
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ----------------------------------------------------------------- metrics
|
|
300
|
+
|
|
301
|
+
/** Re-read the font and the padding, then draw. For a resize or a font change. */
|
|
302
|
+
layout(): void {
|
|
303
|
+
if (this.destroyed)
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
const view = this.root.ownerDocument.defaultView
|
|
307
|
+
const style = view ? view.getComputedStyle(this.textarea) : null
|
|
308
|
+
const number = (value: string | undefined, fallback: number): number => {
|
|
309
|
+
const parsed = Number.parseFloat(value ?? '')
|
|
310
|
+
return Number.isFinite(parsed) ? parsed : fallback
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
this.measure.textContent = 'x'.repeat(64)
|
|
314
|
+
const sample = this.measure.getBoundingClientRect().width / 64
|
|
315
|
+
const fontSize = number(style?.fontSize, 13)
|
|
316
|
+
|
|
317
|
+
this.metrics = {
|
|
318
|
+
lineHeight: number(style?.lineHeight, Math.round(fontSize * 1.5)) || Math.round(fontSize * 1.5),
|
|
319
|
+
charWidth: sample > 0 ? sample : fontSize * 0.6,
|
|
320
|
+
padTop: number(style?.paddingTop, 0),
|
|
321
|
+
padBottom: number(style?.paddingBottom, 0),
|
|
322
|
+
padLeft: number(style?.paddingLeft, 0),
|
|
323
|
+
padRight: number(style?.paddingRight, 0),
|
|
324
|
+
}
|
|
325
|
+
this.widthCache.clear()
|
|
326
|
+
this.activeRow = -1
|
|
327
|
+
this.contentWidth = -1
|
|
328
|
+
this.contentHeight = -1
|
|
329
|
+
this.render()
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Width in pixels of the first `column` characters of a line. */
|
|
333
|
+
private widthOf(text: string, column: number): number {
|
|
334
|
+
if (column <= 0)
|
|
335
|
+
return 0
|
|
336
|
+
|
|
337
|
+
const slice = column >= text.length ? text : text.slice(0, column)
|
|
338
|
+
// A monospaced font makes this a multiplication for nearly every line.
|
|
339
|
+
// Anything else - a tab, an accent, a wide character - is measured.
|
|
340
|
+
if (PRINTABLE_ASCII.test(slice))
|
|
341
|
+
return slice.length * this.metrics.charWidth
|
|
342
|
+
|
|
343
|
+
const cached = this.widthCache.get(slice)
|
|
344
|
+
if (cached !== undefined)
|
|
345
|
+
return cached
|
|
346
|
+
|
|
347
|
+
this.measure.textContent = slice
|
|
348
|
+
const width = this.measure.getBoundingClientRect().width
|
|
349
|
+
if (this.widthCache.size > 500)
|
|
350
|
+
this.widthCache.clear()
|
|
351
|
+
this.widthCache.set(slice, width)
|
|
352
|
+
|
|
353
|
+
return width
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ------------------------------------------------------------------- input
|
|
357
|
+
|
|
358
|
+
private syncSelection(): void {
|
|
359
|
+
if (this.destroyed)
|
|
360
|
+
return
|
|
361
|
+
|
|
362
|
+
const start = this.textarea.selectionStart ?? 0
|
|
363
|
+
const end = this.textarea.selectionEnd ?? start
|
|
364
|
+
const backward = this.textarea.selectionDirection === 'backward'
|
|
365
|
+
const anchor = backward ? end : start
|
|
366
|
+
const head = backward ? start : end
|
|
367
|
+
const main = this.core.main
|
|
368
|
+
|
|
369
|
+
if (main.anchor === anchor && main.head === head)
|
|
370
|
+
return
|
|
371
|
+
// Nothing selected has no direction, so do not report one changing.
|
|
372
|
+
if (start === end && main.anchor === main.head && main.head === start)
|
|
373
|
+
return
|
|
374
|
+
|
|
375
|
+
this.core.dispatch({ selection: { anchor, head }, origin: 'input', kind: 'select' })
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private onBeforeInput(event: InputEvent): void {
|
|
379
|
+
if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {
|
|
380
|
+
// The menu's Undo, or a shake. The field's own history does not know
|
|
381
|
+
// about anything the editor wrote into it, so the editor's is the one.
|
|
382
|
+
event.preventDefault()
|
|
383
|
+
this.core.exec(event.inputType === 'historyUndo' ? 'undo' : 'redo')
|
|
384
|
+
return
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (this.composing || event.isComposing)
|
|
388
|
+
return
|
|
389
|
+
|
|
390
|
+
// A line break or a backspace does not always come with a key. An
|
|
391
|
+
// on-screen keyboard, dictation and some input methods send only the
|
|
392
|
+
// input event, and those deserve the same indentation as a key press.
|
|
393
|
+
// (A real key was already handled, and cancelled, in keydown.)
|
|
394
|
+
if (event.inputType === 'insertLineBreak' || event.inputType === 'insertParagraph') {
|
|
395
|
+
this.syncSelection()
|
|
396
|
+
if (this.core.exec('insertNewlineAndIndent'))
|
|
397
|
+
event.preventDefault()
|
|
398
|
+
return
|
|
399
|
+
}
|
|
400
|
+
if (event.inputType === 'deleteContentBackward') {
|
|
401
|
+
this.syncSelection()
|
|
402
|
+
if (this.core.exec('deleteBackward'))
|
|
403
|
+
event.preventDefault()
|
|
404
|
+
return
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (event.inputType !== 'insertText' || !event.data)
|
|
408
|
+
return
|
|
409
|
+
|
|
410
|
+
this.syncSelection()
|
|
411
|
+
if (handleTextInput(this.core, event.data))
|
|
412
|
+
event.preventDefault()
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private onInput(): void {
|
|
416
|
+
if (this.destroyed)
|
|
417
|
+
return
|
|
418
|
+
|
|
419
|
+
const field = this.textarea
|
|
420
|
+
this.core.syncInput(
|
|
421
|
+
field.value,
|
|
422
|
+
field.selectionStart ?? 0,
|
|
423
|
+
field.selectionEnd ?? 0,
|
|
424
|
+
field.selectionDirection === 'backward',
|
|
425
|
+
)
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
private onKeydown(event: KeyboardEvent): void {
|
|
429
|
+
// A key pressed inside a composition belongs to the input method.
|
|
430
|
+
if (event.isComposing || event.keyCode === 229)
|
|
431
|
+
return
|
|
432
|
+
|
|
433
|
+
if (this.options.onKeydown?.(event)) {
|
|
434
|
+
event.preventDefault()
|
|
435
|
+
return
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const plain = !event.ctrlKey && !event.metaKey && !event.altKey
|
|
439
|
+
|
|
440
|
+
if (this.ghost && plain && !event.shiftKey) {
|
|
441
|
+
if (event.key === 'Tab') {
|
|
442
|
+
event.preventDefault()
|
|
443
|
+
this.acceptGhost()
|
|
444
|
+
return
|
|
445
|
+
}
|
|
446
|
+
if (event.key === 'Escape') {
|
|
447
|
+
event.preventDefault()
|
|
448
|
+
event.stopPropagation()
|
|
449
|
+
this.setGhostText(null, 'dismiss')
|
|
450
|
+
return
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Tab indents, which would trap anyone moving through the page by
|
|
455
|
+
// keyboard. Escape lets the next Tab through.
|
|
456
|
+
if (event.key === 'Escape' && plain) {
|
|
457
|
+
this.tabLeavesNext = true
|
|
458
|
+
this.announce('Tab now moves focus out of the editor.')
|
|
459
|
+
return
|
|
460
|
+
}
|
|
461
|
+
if (event.key === 'Tab' && this.tabLeavesNext) {
|
|
462
|
+
this.tabLeavesNext = false
|
|
463
|
+
return
|
|
464
|
+
}
|
|
465
|
+
if (event.key !== 'Shift')
|
|
466
|
+
this.tabLeavesNext = false
|
|
467
|
+
|
|
468
|
+
const name = this.keymap.lookup(event)
|
|
469
|
+
if (!name)
|
|
470
|
+
return
|
|
471
|
+
|
|
472
|
+
this.syncSelection()
|
|
473
|
+
const handled = this.core.commands.has(name) ? this.core.exec(name) : this.options.onCommand?.(name) === true
|
|
474
|
+
// Undo with nothing to undo still must not reach the field's own history.
|
|
475
|
+
if (handled || name === 'undo' || name === 'redo')
|
|
476
|
+
event.preventDefault()
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
private onGutterMouseDown(event: MouseEvent): void {
|
|
480
|
+
event.preventDefault()
|
|
481
|
+
const bounds = this.rows.getBoundingClientRect()
|
|
482
|
+
const row = Math.floor((event.clientY - bounds.top) / this.metrics.lineHeight)
|
|
483
|
+
const line = Math.max(0, Math.min(this.core.doc.lineCount - 1, this.firstRow + row))
|
|
484
|
+
const info = this.core.doc.lineInfo(line)
|
|
485
|
+
const end = line + 1 < this.core.doc.lineCount ? info.to + 1 : info.to
|
|
486
|
+
|
|
487
|
+
this.textarea.focus()
|
|
488
|
+
this.core.setSelection(info.from, end)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// ------------------------------------------------------------ transactions
|
|
492
|
+
|
|
493
|
+
private onTransaction(transaction: Transaction): void {
|
|
494
|
+
const { changes } = transaction
|
|
495
|
+
|
|
496
|
+
if (transaction.docChanged) {
|
|
497
|
+
// Last first: that is the order they were applied in, so each one's line
|
|
498
|
+
// numbers are true when it is read.
|
|
499
|
+
for (let index = changes.length - 1; index >= 0; index--)
|
|
500
|
+
this.highlighter?.applyChange(changes[index]!)
|
|
501
|
+
|
|
502
|
+
for (const diagnostic of this.diagnostics) {
|
|
503
|
+
diagnostic.from = mapOffset(diagnostic.from, changes, 1)
|
|
504
|
+
diagnostic.to = Math.max(diagnostic.from, mapOffset(diagnostic.to, changes, -1))
|
|
505
|
+
}
|
|
506
|
+
for (const widget of this.widgets)
|
|
507
|
+
widget.offset = mapOffset(widget.offset, changes, widget.atEnd ? 1 : -1)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
if (transaction.origin !== 'input') {
|
|
511
|
+
// The field did not make this change, so it has to be told.
|
|
512
|
+
if (transaction.docChanged) {
|
|
513
|
+
if (transaction.kind === 'set' || changes.length > 64) {
|
|
514
|
+
this.textarea.value = this.core.value
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
for (let index = changes.length - 1; index >= 0; index--) {
|
|
518
|
+
const change = changes[index]!
|
|
519
|
+
this.textarea.setRangeText(change.insert, change.from, change.to, 'preserve')
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const main = this.core.main
|
|
525
|
+
const backward = main.head < main.anchor
|
|
526
|
+
this.textarea.setSelectionRange(rangeFrom(main), rangeTo(main), backward ? 'backward' : 'forward')
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
this.updateGhost(transaction)
|
|
530
|
+
this.render()
|
|
531
|
+
|
|
532
|
+
if (transaction.scrollIntoView && (this.focused || transaction.origin !== 'api'))
|
|
533
|
+
this.revealCaret()
|
|
534
|
+
|
|
535
|
+
this.announceDiagnostic()
|
|
536
|
+
this.options.onTransaction?.(transaction)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// --------------------------------------------------------------- rendering
|
|
540
|
+
|
|
541
|
+
private scheduleRender(): void {
|
|
542
|
+
if (this.frame !== 0 || this.destroyed)
|
|
543
|
+
return
|
|
544
|
+
|
|
545
|
+
const view = this.root.ownerDocument.defaultView
|
|
546
|
+
if (!view?.requestAnimationFrame) {
|
|
547
|
+
this.render()
|
|
548
|
+
return
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
this.frame = view.requestAnimationFrame(() => {
|
|
552
|
+
this.frame = 0
|
|
553
|
+
this.render()
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private visibleRange(): { first: number, last: number } {
|
|
558
|
+
const { lineHeight, padTop } = this.metrics
|
|
559
|
+
const count = this.core.doc.lineCount
|
|
560
|
+
const top = this.scroller.scrollTop - padTop
|
|
561
|
+
// A scroller that has not been laid out reports no height. Draw a screenful
|
|
562
|
+
// anyway, so the first frame is not an empty editor.
|
|
563
|
+
const height = this.scroller.clientHeight || 600
|
|
564
|
+
const first = Math.max(0, Math.floor(top / lineHeight) - OVERSCAN)
|
|
565
|
+
const last = Math.min(count, Math.ceil((top + height) / lineHeight) + OVERSCAN)
|
|
566
|
+
|
|
567
|
+
return { first: Math.min(first, Math.max(0, count - 1)), last: Math.max(last, Math.min(count, first + 1)) }
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Draw what is on screen. Safe to call at any time, and cheap when little changed. */
|
|
571
|
+
render(): void {
|
|
572
|
+
if (this.destroyed)
|
|
573
|
+
return
|
|
574
|
+
|
|
575
|
+
const doc = this.core.doc
|
|
576
|
+
const { lineHeight, padTop, padBottom, padLeft, padRight, charWidth } = this.metrics
|
|
577
|
+
const count = doc.lineCount
|
|
578
|
+
|
|
579
|
+
// The gutter is as wide as the largest line number, and no narrower than
|
|
580
|
+
// three digits so it does not twitch as a file passes ten or a hundred lines.
|
|
581
|
+
const digits = Math.max(3, String(count).length)
|
|
582
|
+
const gutterWidth = this.showLineNumbers ? Math.ceil(digits * charWidth + 2 * charWidth) : 0
|
|
583
|
+
if (gutterWidth !== this.gutterWidth) {
|
|
584
|
+
this.gutterWidth = gutterWidth
|
|
585
|
+
this.gutter.style.width = `${gutterWidth}px`
|
|
586
|
+
this.gutter.style.display = gutterWidth === 0 ? 'none' : ''
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// The document's size, which is the field's size, so the scroller scrolls
|
|
590
|
+
// and the field never has to.
|
|
591
|
+
let longest = ''
|
|
592
|
+
for (let index = 0; index < count; index++) {
|
|
593
|
+
const text = doc.line(index)
|
|
594
|
+
if (text.length > longest.length)
|
|
595
|
+
longest = text
|
|
596
|
+
}
|
|
597
|
+
const width = Math.ceil(padLeft + this.widthOf(longest, longest.length) + padRight + 2 * charWidth)
|
|
598
|
+
const height = Math.ceil(padTop + count * lineHeight + padBottom)
|
|
599
|
+
if (width !== this.contentWidth) {
|
|
600
|
+
this.contentWidth = width
|
|
601
|
+
this.region.style.minWidth = `${width}px`
|
|
602
|
+
}
|
|
603
|
+
if (height !== this.contentHeight) {
|
|
604
|
+
this.contentHeight = height
|
|
605
|
+
this.content.style.height = `${height}px`
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const { first, last } = this.visibleRange()
|
|
609
|
+
|
|
610
|
+
if (this.highlighter?.pending) {
|
|
611
|
+
this.highlighter.update({ through: last - 1, maxLines: SYNC_BUDGET })
|
|
612
|
+
if (this.highlighter.pending)
|
|
613
|
+
this.scheduleIdle()
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
this.renderRows(first, last)
|
|
617
|
+
this.renderGutter(first, last)
|
|
618
|
+
this.renderActiveLine()
|
|
619
|
+
this.renderDecorations(first, last)
|
|
620
|
+
this.renderWidgets(first, last)
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
private renderRows(first: number, last: number): void {
|
|
624
|
+
const doc = this.core.doc
|
|
625
|
+
const wanted = last - first
|
|
626
|
+
|
|
627
|
+
while (this.rows.childElementCount < wanted) {
|
|
628
|
+
const row = this.root.ownerDocument.createElement('div')
|
|
629
|
+
row.className = 'stx-ce-line'
|
|
630
|
+
this.rows.appendChild(row)
|
|
631
|
+
}
|
|
632
|
+
while (this.rows.childElementCount > wanted)
|
|
633
|
+
this.rows.lastElementChild!.remove()
|
|
634
|
+
|
|
635
|
+
if (first !== this.firstRow) {
|
|
636
|
+
// The same elements now stand for different lines.
|
|
637
|
+
this.rendered = []
|
|
638
|
+
this.firstRow = first
|
|
639
|
+
}
|
|
640
|
+
this.rows.style.transform = `translateY(${first * this.metrics.lineHeight}px)`
|
|
641
|
+
this.rendered.length = wanted
|
|
642
|
+
|
|
643
|
+
const children = this.rows.children
|
|
644
|
+
for (let index = 0; index < wanted; index++) {
|
|
645
|
+
const text = doc.line(first + index)
|
|
646
|
+
const line = this.highlighter?.get(first + index) ?? null
|
|
647
|
+
// A line whose tokens are for older text is drawn plain until its turn.
|
|
648
|
+
const source = line && line.text === text ? line : text
|
|
649
|
+
|
|
650
|
+
if (this.rendered[index] === source)
|
|
651
|
+
continue
|
|
652
|
+
|
|
653
|
+
this.rendered[index] = source
|
|
654
|
+
children[index]!.innerHTML = typeof source === 'string' ? escapeHtml(source) : renderLineHtml(source, text)
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
private renderGutter(first: number, last: number): void {
|
|
659
|
+
if (this.gutterWidth === 0)
|
|
660
|
+
return
|
|
661
|
+
|
|
662
|
+
const wanted = last - first
|
|
663
|
+
while (this.gutterRows.childElementCount < wanted) {
|
|
664
|
+
const row = this.root.ownerDocument.createElement('div')
|
|
665
|
+
row.className = 'stx-ce-number'
|
|
666
|
+
this.gutterRows.appendChild(row)
|
|
667
|
+
}
|
|
668
|
+
while (this.gutterRows.childElementCount > wanted)
|
|
669
|
+
this.gutterRows.lastElementChild!.remove()
|
|
670
|
+
|
|
671
|
+
this.gutterRows.style.transform = `translateY(${first * this.metrics.lineHeight}px)`
|
|
672
|
+
this.renderedNumbers.length = wanted
|
|
673
|
+
|
|
674
|
+
const active = this.focused && rangeEmpty(this.core.main) ? this.core.cursor.line : -1
|
|
675
|
+
const marked = this.markedLines()
|
|
676
|
+
const children = this.gutterRows.children
|
|
677
|
+
|
|
678
|
+
for (let index = 0; index < wanted; index++) {
|
|
679
|
+
const line = first + index
|
|
680
|
+
const row = children[index] as HTMLElement
|
|
681
|
+
if (this.renderedNumbers[index] !== line) {
|
|
682
|
+
this.renderedNumbers[index] = line
|
|
683
|
+
row.textContent = String(line + 1)
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const severity = marked.get(line) ?? ''
|
|
687
|
+
if ((row.dataset.severity ?? '') !== severity) {
|
|
688
|
+
if (severity)
|
|
689
|
+
row.dataset.severity = severity
|
|
690
|
+
else
|
|
691
|
+
delete row.dataset.severity
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const isActive = line === active
|
|
695
|
+
if (row.hasAttribute('data-active') !== isActive)
|
|
696
|
+
row.toggleAttribute('data-active', isActive)
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
private renderActiveLine(): void {
|
|
701
|
+
const show = this.focused && rangeEmpty(this.core.main)
|
|
702
|
+
const line = show ? this.core.cursor.line : -1
|
|
703
|
+
if (line === this.activeRow)
|
|
704
|
+
return
|
|
705
|
+
|
|
706
|
+
this.activeRow = line
|
|
707
|
+
if (line < 0) {
|
|
708
|
+
this.activeLine.style.display = 'none'
|
|
709
|
+
return
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
this.activeLine.style.display = ''
|
|
713
|
+
this.activeLine.style.transform = `translateY(${this.metrics.padTop + line * this.metrics.lineHeight}px)`
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** The worst severity on each line that has a diagnostic. */
|
|
717
|
+
private markedLines(): Map<number, DiagnosticSeverity> {
|
|
718
|
+
const marked = new Map<number, DiagnosticSeverity>()
|
|
719
|
+
for (const diagnostic of this.diagnostics) {
|
|
720
|
+
const line = this.core.doc.lineIndexAt(diagnostic.from)
|
|
721
|
+
const existing = marked.get(line)
|
|
722
|
+
if (!existing || SEVERITY_RANK[diagnostic.severity] > SEVERITY_RANK[existing])
|
|
723
|
+
marked.set(line, diagnostic.severity)
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
return marked
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
private renderDecorations(first: number, last: number): void {
|
|
730
|
+
if (this.diagnostics.length === 0) {
|
|
731
|
+
if (this.decorations.childElementCount > 0)
|
|
732
|
+
this.decorations.replaceChildren()
|
|
733
|
+
return
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const doc = this.core.doc
|
|
737
|
+
const { lineHeight, padTop, padLeft } = this.metrics
|
|
738
|
+
const fragment = this.root.ownerDocument.createDocumentFragment()
|
|
739
|
+
|
|
740
|
+
for (const diagnostic of this.diagnostics) {
|
|
741
|
+
const start = doc.positionAt(diagnostic.from)
|
|
742
|
+
const end = doc.positionAt(diagnostic.to)
|
|
743
|
+
|
|
744
|
+
for (let line = Math.max(first, start.line); line <= Math.min(last - 1, end.line); line++) {
|
|
745
|
+
const text = doc.line(line)
|
|
746
|
+
const fromColumn = line === start.line ? start.column : 0
|
|
747
|
+
let toColumn = line === end.line ? end.column : text.length
|
|
748
|
+
// A range with nothing in it still has to be visible somewhere.
|
|
749
|
+
if (toColumn <= fromColumn)
|
|
750
|
+
toColumn = Math.min(text.length, fromColumn + 1)
|
|
751
|
+
|
|
752
|
+
const mark = this.root.ownerDocument.createElement('div')
|
|
753
|
+
mark.className = 'stx-ce-squiggle'
|
|
754
|
+
mark.dataset.severity = diagnostic.severity
|
|
755
|
+
// The same characters, invisible, so the underline is exactly as wide
|
|
756
|
+
// as the text it sits under whatever the characters are.
|
|
757
|
+
mark.textContent = text.slice(fromColumn, toColumn) || ' '
|
|
758
|
+
mark.style.transform = `translate(${padLeft + this.widthOf(text, fromColumn)}px, ${padTop + line * lineHeight}px)`
|
|
759
|
+
fragment.appendChild(mark)
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
this.decorations.replaceChildren(fragment)
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
private renderWidgets(first: number, last: number): void {
|
|
767
|
+
const doc = this.core.doc
|
|
768
|
+
const { lineHeight, padTop, padLeft, charWidth } = this.metrics
|
|
769
|
+
const fragment = this.root.ownerDocument.createDocumentFragment()
|
|
770
|
+
/** What follows the end of each line, in the order it was given. */
|
|
771
|
+
const trailing = new Map<number, HTMLElement>()
|
|
772
|
+
|
|
773
|
+
const trail = (line: number): HTMLElement => {
|
|
774
|
+
let holder = trailing.get(line)
|
|
775
|
+
if (!holder) {
|
|
776
|
+
const text = doc.line(line)
|
|
777
|
+
holder = this.root.ownerDocument.createElement('div')
|
|
778
|
+
holder.className = 'stx-ce-trailing'
|
|
779
|
+
holder.style.transform = `translate(${padLeft + this.widthOf(text, text.length) + 2 * charWidth}px, ${padTop + line * lineHeight}px)`
|
|
780
|
+
trailing.set(line, holder)
|
|
781
|
+
fragment.appendChild(holder)
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
return holder
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
const chip = (text: string, kind: string, className: string): HTMLElement => {
|
|
788
|
+
const element = this.root.ownerDocument.createElement('span')
|
|
789
|
+
element.className = className ? `stx-ce-widget ${className}` : 'stx-ce-widget'
|
|
790
|
+
element.dataset.kind = kind
|
|
791
|
+
// Text, never markup: a result is whatever the user's code returned.
|
|
792
|
+
element.textContent = text
|
|
793
|
+
|
|
794
|
+
return element
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
for (const widget of this.widgets) {
|
|
798
|
+
const position = doc.positionAt(widget.offset)
|
|
799
|
+
if (position.line < first || position.line >= last)
|
|
800
|
+
continue
|
|
801
|
+
|
|
802
|
+
if (widget.atEnd) {
|
|
803
|
+
trail(position.line).appendChild(chip(widget.text, widget.kind, widget.className))
|
|
804
|
+
continue
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const element = chip(widget.text, widget.kind, widget.className)
|
|
808
|
+
element.classList.add('stx-ce-widget--placed')
|
|
809
|
+
element.style.transform = `translate(${padLeft + this.widthOf(doc.line(position.line), position.column)}px, ${padTop + position.line * lineHeight}px)`
|
|
810
|
+
fragment.appendChild(element)
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
if (this.options.inlineDiagnostics !== false) {
|
|
814
|
+
const shown = new Set<number>()
|
|
815
|
+
const ordered = [...this.diagnostics].sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity])
|
|
816
|
+
for (const diagnostic of ordered) {
|
|
817
|
+
const line = doc.lineIndexAt(diagnostic.from)
|
|
818
|
+
// One message per line: the worst one. The rest are still underlined.
|
|
819
|
+
if (line < first || line >= last || shown.has(line))
|
|
820
|
+
continue
|
|
821
|
+
|
|
822
|
+
shown.add(line)
|
|
823
|
+
trail(line).appendChild(chip(diagnostic.message.split('\n')[0]!, diagnostic.severity, 'stx-ce-widget--diagnostic'))
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
if (this.ghost) {
|
|
828
|
+
const position = doc.positionAt(this.ghost.offset)
|
|
829
|
+
if (position.line >= first && position.line < last) {
|
|
830
|
+
const [head, ...rest] = this.ghost.text.split('\n')
|
|
831
|
+
const left = padLeft + this.widthOf(doc.line(position.line), position.column)
|
|
832
|
+
const top = padTop + position.line * lineHeight
|
|
833
|
+
|
|
834
|
+
const inline = this.root.ownerDocument.createElement('span')
|
|
835
|
+
inline.className = 'stx-ce-ghost'
|
|
836
|
+
inline.textContent = head ?? ''
|
|
837
|
+
inline.style.transform = `translate(${left}px, ${top}px)`
|
|
838
|
+
fragment.appendChild(inline)
|
|
839
|
+
|
|
840
|
+
if (rest.length > 0) {
|
|
841
|
+
// Later lines start at the margin, over whatever code is below. They
|
|
842
|
+
// are a preview of text that is not in the document yet.
|
|
843
|
+
const block = this.root.ownerDocument.createElement('div')
|
|
844
|
+
block.className = 'stx-ce-ghost stx-ce-ghost--block'
|
|
845
|
+
block.textContent = rest.join('\n')
|
|
846
|
+
block.style.transform = `translate(${padLeft}px, ${top + lineHeight}px)`
|
|
847
|
+
fragment.appendChild(block)
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
if (fragment.childNodes.length === 0 && this.widgetLayer.childElementCount === 0)
|
|
853
|
+
return
|
|
854
|
+
|
|
855
|
+
this.widgetLayer.replaceChildren(fragment)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
private scheduleIdle(): void {
|
|
859
|
+
if (this.idle !== undefined || this.destroyed)
|
|
860
|
+
return
|
|
861
|
+
|
|
862
|
+
this.idle = setTimeout(() => {
|
|
863
|
+
this.idle = undefined
|
|
864
|
+
if (this.destroyed || !this.highlighter?.pending)
|
|
865
|
+
return
|
|
866
|
+
|
|
867
|
+
const pass = this.highlighter.update({ through: -1, maxLines: IDLE_BUDGET })
|
|
868
|
+
const { first, last } = this.visibleRange()
|
|
869
|
+
// Only what is on screen needs drawing. The rest is ready for a scroll.
|
|
870
|
+
if (pass.from < last && pass.to > first)
|
|
871
|
+
this.renderRows(first, last)
|
|
872
|
+
if (this.highlighter.pending)
|
|
873
|
+
this.scheduleIdle()
|
|
874
|
+
}, 0)
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// ------------------------------------------------------------------- caret
|
|
878
|
+
|
|
879
|
+
/** Where the caret is, in the coordinates of the text area. */
|
|
880
|
+
caretAnchor(offset: number = this.core.main.head): CaretAnchor {
|
|
881
|
+
const { lineHeight, padTop, padLeft } = this.metrics
|
|
882
|
+
const position = this.core.doc.positionAt(offset)
|
|
883
|
+
const top = padTop + position.line * lineHeight
|
|
884
|
+
const visibleTop = this.scroller.scrollTop
|
|
885
|
+
const visibleBottom = visibleTop + this.scroller.clientHeight
|
|
886
|
+
|
|
887
|
+
return {
|
|
888
|
+
left: padLeft + this.widthOf(this.core.doc.line(position.line), position.column),
|
|
889
|
+
top,
|
|
890
|
+
bottom: top + lineHeight,
|
|
891
|
+
spaceAbove: top - visibleTop,
|
|
892
|
+
spaceBelow: visibleBottom - (top + lineHeight),
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/** Scroll so the caret is on screen, with a little room around it. */
|
|
897
|
+
revealCaret(): void {
|
|
898
|
+
const { lineHeight, charWidth } = this.metrics
|
|
899
|
+
const anchor = this.caretAnchor()
|
|
900
|
+
const scroller = this.scroller
|
|
901
|
+
const marginY = lineHeight
|
|
902
|
+
const marginX = 4 * charWidth
|
|
903
|
+
|
|
904
|
+
if (anchor.top - marginY < scroller.scrollTop)
|
|
905
|
+
scroller.scrollTop = Math.max(0, anchor.top - marginY)
|
|
906
|
+
else if (anchor.bottom + marginY > scroller.scrollTop + scroller.clientHeight)
|
|
907
|
+
scroller.scrollTop = anchor.bottom + marginY - scroller.clientHeight
|
|
908
|
+
|
|
909
|
+
// The gutter stays put while the text scrolls under it, so the caret's
|
|
910
|
+
// left edge is measured from where the gutter ends.
|
|
911
|
+
const left = anchor.left
|
|
912
|
+
const visibleWidth = scroller.clientWidth - this.gutterWidth
|
|
913
|
+
if (left - marginX < scroller.scrollLeft)
|
|
914
|
+
scroller.scrollLeft = Math.max(0, left - marginX)
|
|
915
|
+
else if (left + marginX > scroller.scrollLeft + visibleWidth)
|
|
916
|
+
scroller.scrollLeft = left + marginX - visibleWidth
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
focus(): void {
|
|
920
|
+
this.textarea.focus()
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
get hasFocus(): boolean {
|
|
924
|
+
return this.focused
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// ------------------------------------------------------------- annotations
|
|
928
|
+
|
|
929
|
+
/** Replace everything shown beside lines. */
|
|
930
|
+
setWidgets(widgets: readonly EditorWidget[]): void {
|
|
931
|
+
const doc = this.core.doc
|
|
932
|
+
this.widgets = widgets.map((widget) => {
|
|
933
|
+
const atEnd = widget.column === undefined || widget.column === 'end'
|
|
934
|
+
const line = Math.max(0, Math.min(doc.lineCount - 1, widget.line))
|
|
935
|
+
const offset = atEnd ? doc.lineInfo(line).to : doc.offsetAt({ line, column: widget.column as number })
|
|
936
|
+
|
|
937
|
+
return { offset, atEnd, text: widget.text, kind: widget.kind ?? 'result', className: widget.className ?? '' }
|
|
938
|
+
})
|
|
939
|
+
this.render()
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/** Replace every diagnostic. */
|
|
943
|
+
setDiagnostics(diagnostics: readonly EditorDiagnostic[]): void {
|
|
944
|
+
const doc = this.core.doc
|
|
945
|
+
this.diagnostics = diagnostics.map((diagnostic) => {
|
|
946
|
+
const from = doc.offsetAt(diagnostic.from)
|
|
947
|
+
|
|
948
|
+
return {
|
|
949
|
+
from,
|
|
950
|
+
to: Math.max(from, doc.offsetAt(diagnostic.to)),
|
|
951
|
+
message: diagnostic.message,
|
|
952
|
+
severity: diagnostic.severity ?? 'error',
|
|
953
|
+
}
|
|
954
|
+
})
|
|
955
|
+
this.announced = ''
|
|
956
|
+
this.render()
|
|
957
|
+
this.announceDiagnostic()
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* Show a suggestion at the caret, or clear it.
|
|
962
|
+
*
|
|
963
|
+
* It belongs to the place it was shown at. Typing its first characters
|
|
964
|
+
* keeps it and shortens it; anything else lets it go.
|
|
965
|
+
*/
|
|
966
|
+
setGhostText(text: string | null, outcome: 'accept' | 'dismiss' | null = null): void {
|
|
967
|
+
const previous = this.ghost
|
|
968
|
+
this.ghost = text && rangeEmpty(this.core.main) ? { offset: this.core.main.head, text } : null
|
|
969
|
+
|
|
970
|
+
if (previous && !this.ghost && outcome)
|
|
971
|
+
this.options.onGhost?.(outcome, previous.text)
|
|
972
|
+
|
|
973
|
+
this.render()
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
get ghostText(): string {
|
|
977
|
+
return this.ghost?.text ?? ''
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** Insert the suggestion, as one undo step. */
|
|
981
|
+
acceptGhost(): boolean {
|
|
982
|
+
const ghost = this.ghost
|
|
983
|
+
if (!ghost || this.core.readOnly)
|
|
984
|
+
return false
|
|
985
|
+
|
|
986
|
+
this.ghost = null
|
|
987
|
+
const end = ghost.offset + ghost.text.length
|
|
988
|
+
this.core.dispatch({
|
|
989
|
+
changes: [{ from: ghost.offset, to: ghost.offset, insert: ghost.text }],
|
|
990
|
+
selection: { anchor: end, head: end },
|
|
991
|
+
kind: 'ghost',
|
|
992
|
+
})
|
|
993
|
+
this.options.onGhost?.('accept', ghost.text)
|
|
994
|
+
|
|
995
|
+
return true
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
private updateGhost(transaction: Transaction): void {
|
|
999
|
+
const ghost = this.ghost
|
|
1000
|
+
if (!ghost)
|
|
1001
|
+
return
|
|
1002
|
+
|
|
1003
|
+
const [change] = transaction.changes
|
|
1004
|
+
const typedThrough = transaction.changes.length === 1
|
|
1005
|
+
&& change!.from === ghost.offset
|
|
1006
|
+
&& change!.to === ghost.offset
|
|
1007
|
+
&& change!.insert !== ''
|
|
1008
|
+
&& ghost.text.startsWith(change!.insert)
|
|
1009
|
+
&& this.core.main.head === ghost.offset + change!.insert.length
|
|
1010
|
+
|
|
1011
|
+
if (typedThrough) {
|
|
1012
|
+
const rest = ghost.text.slice(change!.insert.length)
|
|
1013
|
+
this.ghost = rest === '' ? null : { offset: ghost.offset + change!.insert.length, text: rest }
|
|
1014
|
+
if (!this.ghost)
|
|
1015
|
+
this.options.onGhost?.('accept', ghost.text)
|
|
1016
|
+
return
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
this.ghost = null
|
|
1020
|
+
this.options.onGhost?.('dismiss', ghost.text)
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// ----------------------------------------------------------- announcements
|
|
1024
|
+
|
|
1025
|
+
private announce(message: string): void {
|
|
1026
|
+
if (this.status && this.status.textContent !== message)
|
|
1027
|
+
this.status.textContent = message
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/** Say what is wrong with the line the caret is on, once per line. */
|
|
1031
|
+
private announceDiagnostic(): void {
|
|
1032
|
+
if (!this.status || this.diagnostics.length === 0)
|
|
1033
|
+
return
|
|
1034
|
+
|
|
1035
|
+
const line = this.core.cursor.line
|
|
1036
|
+
const here = this.diagnostics.filter(diagnostic => this.core.doc.lineIndexAt(diagnostic.from) === line)
|
|
1037
|
+
const message = here.length === 0
|
|
1038
|
+
? ''
|
|
1039
|
+
: `Line ${line + 1}: ${here.map(diagnostic => `${diagnostic.severity}: ${diagnostic.message}`).join('. ')}`
|
|
1040
|
+
|
|
1041
|
+
if (message !== this.announced) {
|
|
1042
|
+
this.announced = message
|
|
1043
|
+
this.announce(message)
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// ----------------------------------------------------------------- teardown
|
|
1048
|
+
|
|
1049
|
+
destroy(): void {
|
|
1050
|
+
if (this.destroyed)
|
|
1051
|
+
return
|
|
1052
|
+
|
|
1053
|
+
this.destroyed = true
|
|
1054
|
+
for (const dispose of this.disposers)
|
|
1055
|
+
dispose()
|
|
1056
|
+
this.disposers.length = 0
|
|
1057
|
+
this.resizeObserver?.disconnect()
|
|
1058
|
+
if (this.idle !== undefined)
|
|
1059
|
+
clearTimeout(this.idle)
|
|
1060
|
+
|
|
1061
|
+
const view = this.root.ownerDocument.defaultView
|
|
1062
|
+
if (this.frame !== 0 && view?.cancelAnimationFrame)
|
|
1063
|
+
view.cancelAnimationFrame(this.frame)
|
|
1064
|
+
this.root.removeAttribute('data-ce-ready')
|
|
1065
|
+
}
|
|
1066
|
+
}
|