forked from lucko/paste
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorTextArea.tsx
More file actions
348 lines (306 loc) · 8.87 KB
/
EditorTextArea.tsx
File metadata and controls
348 lines (306 loc) · 8.87 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
import Editor, {
BeforeMount,
Monaco,
OnChange,
OnMount,
} from '@monaco-editor/react';
import history from 'history/browser';
import {
MutableRefObject,
RefObject,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import styled from 'styled-components';
import themes, { Theme } from '../style/themes';
import type { editor } from 'monaco-editor';
import { diffLanguage } from '../util/languages/diff';
import { logLanguage } from '../util/languages/log';
import { ResetFunction } from './Editor';
import { loader } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
self.MonacoEnvironment = {
getWorker(_: string, label: string): Promise<Worker> | Worker {
switch (label) {
case 'json':
return new jsonWorker();
case 'css':
case 'scss':
case 'less':
return new cssWorker();
case 'html':
case 'handlebars':
case 'razor':
return new htmlWorker();
case 'typescript':
case 'javascript':
return new tsWorker();
default:
return new editorWorker();
}
},
};
loader.config({ monaco });
export interface EditorTextAreaProps {
forcedContent: string;
actualContent: string;
setActualContent: (value: string) => void;
theme: Theme;
language: string;
fontSize: number;
readOnly: boolean;
wordWrap: boolean;
resetFunction: MutableRefObject<ResetFunction | null>;
}
export default function EditorTextArea({
forcedContent,
actualContent,
setActualContent,
theme,
language,
fontSize,
readOnly,
wordWrap,
resetFunction,
}: EditorTextAreaProps) {
const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>();
const [monaco, setMonaco] = useState<Monaco>();
const [selected, toggleSelected] = useSelectedLine();
const editorAreaRef = useRef<HTMLDivElement>(null);
useLineNumberMagic(
editorAreaRef,
selected,
toggleSelected,
forcedContent,
editor,
monaco
);
usePlaceholderText(actualContent, editor, monaco);
const beforeMount: BeforeMount = monaco => {
for (const theme of Object.values(themes) as Theme[]) {
monaco.editor.defineTheme(theme.id, theme.editor);
}
monaco.languages.register({ id: 'log' });
monaco.languages.setMonarchTokensProvider('log', logLanguage);
monaco.languages.register({ id: 'diff' });
monaco.languages.setMonarchTokensProvider('diff', diffLanguage);
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: true,
});
};
const onMount: OnMount = (editor, monaco) => {
editor.addAction({
id: 'search',
label: 'Search with Google',
contextMenuGroupId: '9_cutcopypaste',
contextMenuOrder: 5,
run: editor => {
const selection = editor.getSelection();
if (selection && !selection.isEmpty()) {
const model = editor.getModel();
if (model) {
const query = model.getValueInRange(selection);
window.open('https://www.google.com/search?q=' + query, '_blank');
}
}
},
});
setEditor(editor);
setMonaco(monaco);
resetFunction.current = () => {
editor.setValue('');
editor.focus();
};
editor.focus();
};
const onChange: OnChange = useCallback(
value => {
setActualContent(value as string);
},
[setActualContent]
);
// detect indentation whenever new forced content is set
useEffect(() => {
if (!editor) {
return;
}
const model = editor.getModel();
if (!model) {
return;
}
model.detectIndentation(true, 2);
}, [editor, forcedContent]);
return (
<EditorArea ref={editorAreaRef}>
<Editor
theme={theme.id}
language={language === 'plain' ? 'plaintext' : language}
options={{
fontFamily: 'JetBrains Mono',
fontSize: fontSize,
fontLigatures: true,
wordWrap: wordWrap ? 'on' : 'off',
renderLineHighlight: 'none',
renderValidationDecorations: 'off',
readOnly,
domReadOnly: readOnly,
}}
beforeMount={beforeMount}
onMount={onMount}
onChange={onChange}
value={forcedContent}
/>
</EditorArea>
);
}
const EditorArea = styled.main`
margin-top: 2.5em;
height: 100%;
.line-numbers {
cursor: pointer !important;
}
.highlighted-line + div {
color: ${props => props.theme.highlightedLine.color};
background-color: ${props => props.theme.highlightedLine.backgroundColor};
font-weight: bold;
}
.placeholder-text {
position: absolute;
opacity: 0.5;
font-weight: lighter;
&::after {
content: 'Paste (or type) some code...';
}
}
`;
function usePlaceholderText(
actualContent: string,
editor: editor.IStandaloneCodeEditor | undefined,
monaco: Monaco | undefined
) {
useEffect(() => {
if (!editor || !monaco || actualContent) {
return;
}
const decoration = {
range: new monaco.Range(1, 0, 1, 1),
options: {
after: {
content: '\u200B',
inlineClassName: 'placeholder-text',
},
},
};
const decorations = editor.deltaDecorations([], [decoration]);
return () => {
editor.deltaDecorations(decorations, []);
};
}, [editor, monaco, actualContent]);
}
type SelectedLine = [number, number];
type ToggleSelectedFunction = (lineNo: number, e: MouseEvent) => void;
function useSelectedLine(): [SelectedLine, ToggleSelectedFunction] {
// extract highlighted lines from window hash
const [selected, setSelected] = useState<[number, number]>(() => {
const hash = window.location.hash;
if (/^#L\d+(-\d+)?$/.test(hash)) {
const [start, end] = hash.substring(2).split('-').map(Number);
return [start, isNaN(end) ? start : end];
} else {
return [-1, -1];
}
});
// update window hash when a new line is highlighted
useEffect(() => {
let hash = '';
if (selected[0] !== -1) {
if (selected[1] !== selected[0]) {
const start = Math.min(...selected);
const end = Math.max(...selected);
hash = `#L${start}-${end}`;
} else {
hash = `#L${selected[0]}`;
}
}
history.replace({ hash });
}, [selected]);
// toggle the highlighting for a given line
const toggleSelected = useCallback(
(lineNo: number, e: MouseEvent) => {
const shift = e.shiftKey;
if (selected[0] === lineNo && selected[1] === lineNo) {
setSelected([-1, -1]);
} else if (selected[0] === -1 || !shift) {
setSelected([lineNo, lineNo]);
} else {
setSelected([selected[0], lineNo]);
}
},
[selected, setSelected]
);
return [selected, toggleSelected];
}
function useLineNumberMagic(
editorAreaRef: RefObject<HTMLDivElement | null>,
selected: SelectedLine,
toggleSelected: ToggleSelectedFunction,
forcedContent: string,
editor: editor.IStandaloneCodeEditor | undefined,
monaco: Monaco | undefined
) {
// add an event listener for clicking on line numbers
useEffect(() => {
const node = editorAreaRef.current;
if (!node) {
return;
}
const handler = (click: MouseEvent) => {
const element = document.elementFromPoint(click.x, click.y);
if (
element &&
element.classList.contains('line-numbers') &&
element.textContent
) {
toggleSelected(parseInt(element.textContent), click);
}
};
node.addEventListener('click', handler);
return () => node.removeEventListener('click', handler);
}, [editorAreaRef, toggleSelected]);
// apply a 'highlighed' decoration to the selected lines
// and scroll them into view if not already
useEffect(() => {
if (!editor || !monaco || selected[0] === -1) {
return;
}
// apply a decoration
const newDecorations = [
{
range: new monaco.Range(selected[0], 1, selected[1], 1),
options: {
isWholeLine: true,
linesDecorationsClassName: 'highlighted-line',
},
},
];
const decorations = editor.deltaDecorations([], newDecorations);
// scroll the selected line into view
if (selected[0] === selected[1]) {
editor.revealLineInCenterIfOutsideViewport(selected[0]);
} else {
editor.revealLinesInCenterIfOutsideViewport(selected[0], selected[1]);
}
// cleanup by removing the decorations
return () => {
editor.deltaDecorations(decorations, []);
};
}, [editor, monaco, selected, forcedContent]);
}