-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathcode-block.svelte
221 lines (190 loc) · 5.62 KB
/
code-block.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
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
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import { autocompletion, closeBrackets } from '@codemirror/autocomplete';
import { historyKeymap, standardKeymap } from '@codemirror/commands';
import { json } from '@codemirror/lang-json';
import {
bracketMatching,
foldGutter,
indentOnInput,
indentUnit,
StreamLanguage,
syntaxHighlighting,
} from '@codemirror/language';
import { shell } from '@codemirror/legacy-modes/mode/shell';
import { EditorState } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import { createEventDispatcher, onMount } from 'svelte';
import CopyButton from '$lib/holocene/copyable/button.svelte';
import { copyToClipboard } from '$lib/utilities/copy-to-clipboard';
import { useDarkMode } from '$lib/utilities/dark-mode';
import {
parseWithBigInt,
stringifyWithBigInt,
} from '$lib/utilities/parse-with-big-int';
import {
TEMPORAL_SYNTAX,
TEMPORAL_THEME,
} from '$lib/vendor/codemirror/theme';
type BaseProps = HTMLAttributes<HTMLDivElement> & {
content: string;
language?: 'json' | 'text' | 'shell';
editable?: boolean;
inline?: boolean;
testId?: string;
copyable?: boolean;
minHeight?: number;
maxHeight?: number;
label?: string;
};
type CopyableProps = BaseProps & {
copyable: true;
copyIconTitle: string;
copySuccessIconTitle: string;
};
type $$Props = BaseProps | CopyableProps;
const dispatch = createEventDispatcher<{ change: string }>();
export let content: string;
let className: string = null;
export { className as class };
export let editable = false;
export let inline = false;
export let language = 'json';
export let copyable = true;
export let copyIconTitle = '';
export let copySuccessIconTitle = '';
export let minHeight = undefined;
export let maxHeight = undefined;
export let label = '';
const { copy, copied } = copyToClipboard();
const handleCopy = (e: Event) => {
copy(e, content);
};
let editor: HTMLElement;
let view: EditorView;
const formatJSON = (jsonData: string): string => {
if (!jsonData) return;
let parsedData: string;
try {
parsedData = parseWithBigInt(jsonData);
} catch (error) {
parsedData = jsonData;
}
return stringifyWithBigInt(parsedData, undefined, inline ? 0 : 2);
};
const formatValue = ({ value, language }) =>
language === 'json' ? formatJSON(value) : value;
$: value = formatValue({ value: content, language });
const lineBreakReplacer = EditorView.updateListener.of((update) => {
if (editable) return;
const newText = update.state.doc.toString().replace(/\\n/g, '\n');
if (newText !== update.state.doc.toString()) {
update.view.dispatch({
changes: { from: 0, to: update.state.doc.length, insert: newText },
});
}
});
const createEditorView = (isDark: boolean): EditorView => {
return new EditorView({
parent: editor,
state: createEditorState(value, isDark),
dispatch(transaction) {
view.update([transaction]);
if (transaction.docChanged) {
dispatch('change', view.state.doc.toString());
}
},
});
};
const createEditorState = (
value: string | null | undefined,
isDark: boolean,
): EditorState => {
const extensions = [
keymap.of([...standardKeymap, ...historyKeymap]),
TEMPORAL_THEME({ isDark, copyable }),
syntaxHighlighting(TEMPORAL_SYNTAX, { fallback: true }),
indentUnit.of(' '),
closeBrackets(),
autocompletion(),
indentOnInput(),
bracketMatching(),
EditorState.readOnly.of(!editable),
EditorView.editable.of(editable),
EditorView.contentAttributes.of({ 'aria-label': label }),
lineBreakReplacer,
];
if (language === 'json') {
extensions.push(json());
}
if (language === 'shell') {
extensions.push(StreamLanguage.define(shell));
}
if (!inline) {
extensions.push(EditorView.lineWrapping);
}
if (!inline && !editable) {
extensions.push(foldGutter());
}
if (minHeight || maxHeight) {
extensions.push(
EditorView.theme({
'&': {
...(minHeight ? { 'min-height': `${minHeight}px` } : {}),
...(maxHeight ? { 'max-height': `${maxHeight}px` } : {}),
},
}),
);
extensions.push(EditorView.contentAttributes.of({ tabindex: '0' }));
}
return EditorState.create({
doc: value,
extensions,
});
};
onMount(() => {
createView($useDarkMode);
return () => view?.destroy();
});
const createView = (isDark: boolean) => {
if (view) view.destroy();
view = createEditorView(isDark);
};
$: createView($useDarkMode);
const resetView = (value = '', format = true) => {
const formattedValue = format ? formatValue({ value, language }) : value;
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: formattedValue,
},
});
};
const setView = () => {
if (view && (!editable || view.state.doc.toString() !== content)) {
resetView(content);
}
};
$: content, language, setView();
</script>
<div class="relative min-w-[80px] grow">
<div
bind:this={editor}
class={className}
class:inline
data-testid={$$props.testId}
class:editable
class:readOnly={!editable}
{...$$restProps}
/>
{#if copyable}
<CopyButton
{copyIconTitle}
{copySuccessIconTitle}
class="absolute right-1 top-1 text-secondary"
on:click={handleCopy}
copied={$copied}
/>
{/if}
</div>