forked from calumk/codecup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeCup.svelte
More file actions
562 lines (492 loc) · 17.6 KB
/
CodeCup.svelte
File metadata and controls
562 lines (492 loc) · 17.6 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
<script lang="ts">
import { onMount, tick } from 'svelte';
import { createLowlight, type LanguageFn } from 'lowlight';
import { Unist } from '@typematter/svelte-unist';
import { components as hastComponents } from '@typematter/svelte-hast';
import type { Root } from 'hast';
import { cssSupports } from './utils/css-supports';
interface Props {
language?: string;
rtl?: boolean;
tabSize?: number;
enableAutocorrect?: boolean;
lineNumbers?: boolean;
defaultTheme?: 'light' | 'dark' | boolean;
areaId?: string | null;
ariaLabelledby?: string | null;
readonly?: boolean;
handleTabs?: boolean;
handleSelfClosingCharacters?: boolean;
handleNewLineIndentation?: boolean;
styleParent?: ShadowRoot;
copyButton?: boolean;
maxLines?: number;
minLines?: number;
code?: string;
onupdate?: (code: string) => void;
grammars: Readonly<Record<string, LanguageFn>>;
}
let {
language = $bindable('html'),
rtl = false,
tabSize = 2,
enableAutocorrect = false,
lineNumbers = $bindable(false),
defaultTheme = true,
areaId = null,
ariaLabelledby = null,
readonly = $bindable(false),
handleTabs = true,
handleSelfClosingCharacters = true,
handleNewLineIndentation = true,
styleParent = undefined,
copyButton = false,
maxLines = 100,
minLines = 1,
code = $bindable(''),
onupdate,
grammars,
}: Props = $props();
const lowlight = $derived(createLowlight(grammars));
let elWrapper: HTMLDivElement;
let elTextarea: HTMLTextAreaElement;
let elPre: HTMLPreElement;
let lineNumber = $derived(code.split('\n').length);
let wrapperHeight = $derived.by(() => {
let limited = lineNumber;
if (limited > maxLines) limited = maxLines;
else if (limited < minLines) limited = minLines;
return `${limited * 20 + 20}px`;
});
let highlightedTree = $state<Root>({ type: 'root', children: [] });
let copyMessageVisible = $state(false);
function doHighlight() {
try {
if (lowlight.registered(language)) {
highlightedTree = lowlight.highlight(language, code);
} else {
highlightedTree = {
type: 'root',
children: [{ type: 'text', value: code }],
};
}
} catch {
highlightedTree = {
type: 'root',
children: [{ type: 'text', value: code }],
};
}
}
$effect(() => {
// Re-highlight when code or language changes
language;
code;
doHighlight();
if (elTextarea && elTextarea.value !== code) {
elTextarea.value = code;
}
});
function fireUpdate() {
onupdate?.(code);
}
function handleInput(e: Event & { currentTarget: HTMLTextAreaElement }) {
if (readonly) return;
code = e.currentTarget.value;
setTimeout(fireUpdate, 1);
}
function handleKeydown(e: KeyboardEvent) {
if (readonly) return;
handleTabsKey(e);
handleSelfClosingChars(e);
handleNewLineIndent(e);
}
function handleScroll(e: Event & { currentTarget: HTMLTextAreaElement }) {
if (elPre) {
elPre.style.transform = `translate3d(-${e.currentTarget.scrollLeft}px, -${e.currentTarget.scrollTop}px, 0)`;
}
}
function handleTabsKey(e: KeyboardEvent) {
if (!handleTabs) return;
if (e.keyCode !== 9) return;
e.preventDefault();
const input = elTextarea;
const selectionDir = input.selectionDirection;
let selStartPos = input.selectionStart;
let selEndPos = input.selectionEnd;
const inputVal = input.value;
let beforeSelection = inputVal.substr(0, selStartPos);
let selectionVal = inputVal.substring(selStartPos, selEndPos);
const afterSelection = inputVal.substring(selEndPos);
const indent = ' '.repeat(tabSize);
if (selStartPos !== selEndPos && selectionVal.length >= indent.length) {
const currentLineStart = selStartPos - beforeSelection.split('\n').pop()!.length;
let startIndentLen = indent.length;
let endIndentLen = indent.length;
if (e.shiftKey) {
const currentLineStartStr = inputVal.substr(currentLineStart, indent.length);
if (currentLineStartStr === indent) {
startIndentLen = -startIndentLen;
if (currentLineStart > selStartPos) {
selectionVal =
selectionVal.substring(0, currentLineStart) +
selectionVal.substring(currentLineStart + indent.length);
endIndentLen = 0;
} else if (currentLineStart === selStartPos) {
startIndentLen = 0;
endIndentLen = 0;
selectionVal = selectionVal.substring(indent.length);
} else {
endIndentLen = -endIndentLen;
beforeSelection =
beforeSelection.substring(0, currentLineStart) +
beforeSelection.substring(currentLineStart + indent.length);
}
} else {
startIndentLen = 0;
endIndentLen = 0;
}
selectionVal = selectionVal.replace(new RegExp(`\n${indent.split('').join('\\')}`, 'g'), '\n');
} else {
beforeSelection =
beforeSelection.substr(0, currentLineStart) +
indent +
beforeSelection.substring(currentLineStart, selStartPos);
selectionVal = selectionVal.replace(/\n/g, `\n${indent}`);
}
input.value = beforeSelection + selectionVal + afterSelection;
input.selectionStart = selStartPos + startIndentLen;
input.selectionEnd = selStartPos + selectionVal.length + endIndentLen;
input.selectionDirection = selectionDir;
} else {
input.value = beforeSelection + indent + afterSelection;
input.selectionStart = selStartPos + indent.length;
input.selectionEnd = selStartPos + indent.length;
}
code = input.value;
doHighlight();
setTimeout(fireUpdate, 1);
elTextarea.selectionEnd = selEndPos + tabSize;
}
function handleSelfClosingChars(e: KeyboardEvent) {
if (!handleSelfClosingCharacters) return;
const openChars = ['(', '[', '{', '<', "'", '"'];
const closeChars = [')', ']', '}', '>', "'", '"'];
const key = e.key;
if (!openChars.includes(key) && !closeChars.includes(key)) return;
closeCharacter(key);
}
function handleNewLineIndent(e: KeyboardEvent) {
if (!handleNewLineIndentation) return;
if (e.key !== 'Enter') return;
e.preventDefault();
const input = elTextarea;
const selStartPos = input.selectionStart;
const selEndPos = input.selectionEnd;
const inputVal = input.value;
const beforeSelection = inputVal.substr(0, selStartPos);
const afterSelection = inputVal.substring(selEndPos);
const lineStart = inputVal.lastIndexOf('\n', selStartPos - 1);
const spaceLast = lineStart + inputVal.slice(lineStart + 1).search(/[^ ]|$/);
const indentSize = spaceLast > lineStart ? spaceLast - lineStart : 0;
const newCode = `${beforeSelection}\n${' '.repeat(indentSize)}${afterSelection}`;
input.value = newCode;
input.selectionStart = selStartPos + indentSize + 1;
input.selectionEnd = selStartPos + indentSize + 1;
code = input.value;
doHighlight();
setTimeout(fireUpdate, 1);
}
function skipCloseChar(char: string): boolean {
const selectionStart = elTextarea.selectionStart;
const selectionEnd = elTextarea.selectionEnd;
const hasSelection = Math.abs(selectionEnd - selectionStart) > 0;
return [')', '}', ']', '>'].includes(char) || (["'", '"'].includes(char) && !hasSelection);
}
function closeCharacter(char: string) {
const selectionStart = elTextarea.selectionStart;
const selectionEnd = elTextarea.selectionEnd;
if (!skipCloseChar(char)) {
let closeChar = char;
switch (char) {
case '(':
closeChar = String.fromCharCode(char.charCodeAt(0) + 1);
break;
case '<':
case '{':
case '[':
closeChar = String.fromCharCode(char.charCodeAt(0) + 2);
break;
}
const selectionText = code.substring(selectionStart, selectionEnd);
const newCode = `${code.substring(0, selectionStart)}${selectionText}${closeChar}${code.substring(selectionEnd)}`;
code = newCode;
elTextarea.value = newCode;
} else {
const skipChar = code.substr(selectionEnd, 1) === char;
const newSelectionEnd = skipChar ? selectionEnd + 1 : selectionEnd;
const closeChar = !skipChar && ["'", '"'].includes(char) ? char : '';
const newCode = `${code.substring(0, selectionStart)}${closeChar}${code.substring(newSelectionEnd)}`;
code = newCode;
elTextarea.value = newCode;
elTextarea.selectionEnd = ++elTextarea.selectionStart;
}
elTextarea.selectionEnd = selectionStart;
doHighlight();
setTimeout(fireUpdate, 1);
}
function copyCode() {
navigator.clipboard.writeText(code).then(() => {
copyMessageVisible = true;
setTimeout(() => {
copyMessageVisible = false;
}, 1000);
});
}
export function updateCode(newCode: string) {
code = newCode;
if (elTextarea) elTextarea.value = newCode;
doHighlight();
setTimeout(fireUpdate, 1);
}
export function updateLanguage(newLanguage: string) {
language = newLanguage;
}
export function getCode(): string {
return code;
}
export function enableReadonlyMode() {
readonly = true;
}
export function disableReadonlyMode() {
readonly = false;
}
export function toggleReadonlyMode() {
readonly = !readonly;
}
export function enableLineNumbers() {
lineNumbers = true;
}
export function disableLineNumbers() {
lineNumbers = false;
}
export function toggleLineNumbers() {
lineNumbers = !lineNumbers;
}
onMount(() => {
if (elTextarea) {
elTextarea.value = code;
}
doHighlight();
});
</script>
<div
class="codecup"
class:codecup--has-line-numbers={lineNumbers}
class:has-caret-color={cssSupports('caret-color', '#000')}
class:default-theme={defaultTheme}
class:dark={defaultTheme === true ? window.matchMedia('(prefers-color-scheme: dark)').matches : defaultTheme === 'dark'}
bind:this={elWrapper}
style:height={wrapperHeight}
>
{#if lineNumbers}
<div class="codecup__lines">
{#each { length: lineNumber } as _, i}
<span class="codecup__lines__line">{i + 1}</span>
{/each}
</div>
{/if}
<textarea
bind:this={elTextarea}
class="codecup__textarea codecup__flatten"
dir={rtl ? 'rtl' : undefined}
spellcheck={enableAutocorrect ? undefined : 'false'}
autocapitalize={enableAutocorrect ? undefined : 'off'}
autocomplete={enableAutocorrect ? undefined : 'off'}
id={areaId}
aria-labelledby={ariaLabelledby}
readonly={readonly || undefined}
oninput={handleInput}
onkeydown={handleKeydown}
onscroll={handleScroll}
></textarea>
<pre bind:this={elPre} class="codecup__pre codecup__flatten" dir={rtl ? 'rtl' : undefined}><code
class="codecup__code hljs language-{language}"
><Unist ast={highlightedTree} components={hastComponents} /></code
></pre>
{#if copyButton}
<div class="codecup__copyMessage" style:display={copyMessageVisible ? 'block' : 'none'}>Copied!</div>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="codecup__copyButton" onclick={copyCode}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"
><rect width="256" height="256" fill="none" /><polygon
points="88 40 88 88 168 88 168 168 216 168 216 40 88 40"
opacity="0.2"
/><polyline
points="168 168 216 168 216 40 88 40 88 88"
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="16"
/><rect
x="40"
y="88"
width="128"
height="128"
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="16"
/></svg
>
</div>
{/if}
</div>
<style lang="scss">
$background-color: #fff;
$line-height: 20px;
$font-size: 13px;
$font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
$color: #ccc;
$line-number-width: 40px;
.codecup {
width: 100%;
height: 100%;
overflow: hidden;
border: 1px solid #eaeefb;
border-radius: 4px;
position: relative;
}
.codecup,
.codecup * {
box-sizing: border-box;
}
.codecup__pre {
pointer-events: none;
z-index: 3;
overflow: hidden;
}
.codecup__textarea {
background: none;
border: none;
color: $color;
.codecup.has-caret-color & {
color: $background-color;
}
z-index: 1;
resize: none;
font-family: $font-family;
-webkit-appearance: pre;
caret-color: #111;
z-index: 2;
width: 100%;
height: 100%;
}
.codecup--has-line-numbers .codecup__textarea {
width: calc(100% - $line-number-width);
}
.codecup__code {
display: block;
font-family: $font-family;
overflow: hidden;
}
.codecup__flatten {
padding: 10px;
font-size: $font-size;
line-height: $line-height;
white-space: pre;
position: absolute;
top: 0;
left: 0;
overflow: auto;
margin: 0 !important;
outline: none;
text-align: left;
}
.codecup--has-line-numbers .codecup__flatten {
width: calc(100% - $line-number-width);
left: $line-number-width;
}
.codecup__line-highlight {
position: absolute;
top: 10px;
left: 0;
width: 100%;
height: $line-height;
background: rgba(0, 0, 0, 0.1);
z-index: 1;
}
.codecup__lines {
padding: 10px 4px;
font-size: 12px;
line-height: $line-height;
font-family: 'Cousine', monospace;
position: absolute;
left: 0;
top: 0;
width: $line-number-width;
height: 100%;
text-align: right;
color: #999;
z-index: 2;
}
.codecup__lines__line {
display: block;
}
.codecup.codecup--has-line-numbers {
padding-left: $line-number-width;
}
.codecup.codecup--has-line-numbers:before {
content: '';
position: absolute;
left: 0;
top: 0;
width: $line-number-width;
height: 100%;
// background: #eee;
background: #dcdfe6;
z-index: 1;
}
.codecup__copyButton {
position: absolute;
right: 5px;
top: 5px;
z-index: 3;
background: #eaeefb;
border: none;
color: #999;
cursor: pointer;
outline: none;
width: 22px;
height: 22px;
border-radius: 4px;
}
.codecup__copyMessage {
position: absolute;
right: 32px;
top: 5px;
z-index: 3;
background: #eaeefb;
border: none;
color: #999;
cursor: pointer;
outline: none;
width: 55px;
height: 22px;
line-height: 22px;
border-radius: 4px;
font-size: 12px;
text-align: center;
font-family: 'Cousine', monospace;
}
.codecup.default-theme {
background: $background-color;
color: #4f559c;
}
.codecup.default-theme.dark {
background: #1e1e1e;
color: #eee;
}
</style>