-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeEditor.svelte
113 lines (105 loc) · 2.85 KB
/
CodeEditor.svelte
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<style>
.container {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: stretch;
flex-grow: 1;
overflow: hidden;
}
.numbers {
font-family: monospace, monospace;
padding: calc(0.25em + 1px);
text-align: right;
user-select: none;
-webkit-user-select: none;
overflow: hidden;
}
textarea {
resize: none;
border: 1px solid var(--fg-color);
padding: 0.25em;
font-family: monospace, monospace;
white-space: pre;
overflow: auto;
flex-grow: 1;
}
</style>
<script>
let { editor = $bindable(), code = $bindable(""), ...rest } = $props();
let lineNumbers = $state();
function indent(s) {
return " " + s.split("\n").join("\n ");
}
function dedent(s) {
return s.replace(/^( |\t)/gm, "");
}
function keydown(e) {
const textarea = e.target;
const { selectionStart: start, selectionEnd: end, value } = textarea;
switch (e.key.toLocaleLowerCase()) {
case "tab":
e.preventDefault();
if (e.shiftKey) {
const lineStart = value.lastIndexOf("\n", start - 1) + 1;
textarea.setRangeText(
dedent(value.slice(lineStart, end)),
lineStart,
end,
start == end ? "end" : "preserve",
);
} else {
if (start == end) {
textarea.setRangeText(" ", start, end, "end");
} else {
const lineStart = value.lastIndexOf("\n", start - 1) + 1;
textarea.setRangeText(
indent(value.slice(lineStart, end)),
lineStart,
end,
"preserve",
);
}
}
break;
case "enter":
const lineStart = value.lastIndexOf("\n", start - 1) + 1;
const numTabs =
(value
.slice(lineStart)
.replace(/\t/g, " ")
.match(/^( )*/g) || [""])[0].length / 2;
textarea.setRangeText("\n" + " ".repeat(numTabs), start, end, "end");
e.preventDefault();
// setRangeText doesn't cause Svelte to automatically update bind:value
// for textareas, so the following line is required to force update the
// code variable (and thereby set the correct line numbering).
code = textarea.value;
break;
}
}
function syncScroll(e) {
if (lineNumbers == null) return;
lineNumbers.scrollTop = e.target.scrollTop;
}
</script>
<div class="container">
<div class="numbers" bind:this={lineNumbers}>
{#each code.split("\n") as _, i}
<div>{i + 1}</div>
{/each}
<div style="min-height: 5em"></div>
</div>
<textarea
bind:this={editor}
bind:value={code}
onkeydown={keydown}
onscroll={syncScroll}
wrap="off"
autocorrect="off"
autocapitalize="none"
autocomplete="off"
spellcheck="false"
{...rest}
></textarea>
</div>