-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
65 lines (54 loc) · 2.58 KB
/
Copy patheditor.js
File metadata and controls
65 lines (54 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Compartment, EditorState } from 'https://esm.sh/@codemirror/state@6.5.2';
import { EditorView, lineNumbers } from 'https://esm.sh/@codemirror/view@6.41.1?deps=@codemirror/state@6.5.2';
import { defaultHighlightStyle, syntaxHighlighting } from 'https://esm.sh/@codemirror/language@6.12.3?deps=@codemirror/state@6.5.2,@codemirror/view@6.41.1';
import { python } from 'https://esm.sh/@codemirror/lang-python@6.2.1?deps=@codemirror/state@6.5.2,@codemirror/view@6.41.1,@codemirror/language@6.12.3';
import { oneDarkHighlightStyle } from 'https://esm.sh/@codemirror/theme-one-dark@6.1.3?deps=@codemirror/state@6.5.2,@codemirror/view@6.41.1,@codemirror/language@6.12.3';
const themePreference = window.matchMedia('(prefers-color-scheme: dark)');
const highlightStyle = () => themePreference.matches ? oneDarkHighlightStyle : defaultHighlightStyle;
const highlightCompartment = new Compartment();
const textarea = document.getElementById('code-editor');
const form = document.querySelector('form.runner-editor');
if (textarea && form) {
textarea.classList.add('textarea-fallback');
const view = new EditorView({
state: EditorState.create({
doc: textarea.value,
extensions: [
python(),
highlightCompartment.of(syntaxHighlighting(highlightStyle())),
lineNumbers(),
EditorView.lineWrapping,
EditorView.contentAttributes.of({
'aria-label': textarea.getAttribute('aria-label') || 'Editable Python example code',
}),
EditorView.updateListener.of((update) => {
if (update.docChanged) textarea.value = update.state.doc.toString();
}),
],
}),
});
textarea.insertAdjacentElement('afterend', view.dom);
textarea.hidden = true;
themePreference.addEventListener?.('change', () => {
view.dispatch({ effects: highlightCompartment.reconfigure(syntaxHighlighting(highlightStyle())) });
});
function resize() {
view.dom.style.minHeight = '';
const minimum = Number.parseFloat(getComputedStyle(view.dom).minHeight) || 0;
view.dom.style.minHeight = `${Math.max(minimum, view.contentDOM.scrollHeight)}px`;
}
function scheduleResize() {
requestAnimationFrame(resize);
}
function setValue(value) {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
textarea.value = value;
scheduleResize();
}
resize();
function syncTextarea() {
textarea.value = view.state.doc.toString();
}
form.addEventListener('submit', syncTextarea);
window.pythonByExampleEditor = { setValue, syncTextarea, resize: scheduleResize, focus: () => view.focus() };
}