Debian Codegraph @

ivette/src/dome/renderer/text/editors.tsx

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 /* eslint-disable @typescript-eslint/explicit-function-return-type */
24
25 // --------------------------------------------------------------------------
26 // --- Text Documents
27 // --------------------------------------------------------------------------
28
29 /**
30 @packageDocumentation
31 @module dome/text/editors
32 */
33
34 import _ from 'lodash';
35 import React from 'react';
36 import * as Dome from 'dome';
37 import * as Themes from 'dome/themes';
38 import { Vfill } from 'dome/layout/boxes';
39 import CodeMirror, { EditorConfiguration } from 'codemirror/lib/codemirror';
40 import { RichTextBuffer, CSSMarker, Decorator } from './buffers';
41
42 import './style.css';
43 import './dark-code.css';
44 import 'codemirror/lib/codemirror.css';
45
46 const CSS_HOVERED = 'dome-xText-hover';
47 const CSS_SELECTED = 'dome-xText-select';
48
49 const D = new Dome.Debug('Dome');
50
51 /* --------------------------------------------------------------------------*/
52 /* --- View Properties --- */
53 /* --------------------------------------------------------------------------*/
54
55 export interface MarkerCallback {
56 (id: string, meta?: boolean): void;
57 }
58
59 /**
60 Text Editor configuration.
61
62 Inherits CodeMirror
63 [EditorConfiguration](https://codemirror.net/doc/manual.html#config)
64 options.
65 */
66
67 export interface TextProps extends CodeMirror.EditorConfiguration {
68
69 /** The buffer to view. */
70 buffer: RichTextBuffer | undefined;
71
72 /** The currently selected marker identifier. */
73 selection?: string;
74
75 /** Callback on hovered marker, if some. */
76 onHover?: (id?: string) => void;
77
78 /** Callback on identified marker selection. */
79 onSelection?: MarkerCallback;
80
81 /** Callback on identified marker right-click. */
82 onContextMenu?: MarkerCallback;
83
84 /** Font Size. */
85 fontSize?: number;
86
87 /** Additional className for the text container. */
88 className?: string;
89
90 /** Additional style. */
91 style?: React.CSSProperties;
92
93 }
94
95 /* --------------------------------------------------------------------------*/
96 /* --- CodeMirror Configuration Utils ---*/
97 /* --------------------------------------------------------------------------*/
98
99 function getConfig(props: TextProps): CodeMirror.EditorConfiguration {
100 const {
101 buffer,
102 selection,
103 onSelection,
104 onContextMenu,
105 fontSize,
106 ...config
107 } = props;
108 return config;
109 }
110
111 type MouseEvt = React.MouseEvent<HTMLDivElement, MouseEvent>;
112 type CMoption = keyof EditorConfiguration;
113
114 function forEachOption(
115 config: EditorConfiguration,
116 fn: (opt: CMoption) => void,
117 ) {
118 (Object.keys(config) as (keyof EditorConfiguration)[]).forEach(fn);
119 }
120
121 // --------------------------------------------------------------------------
122 // --- Code Mirror Instance Wrapper
123 // --------------------------------------------------------------------------
124
125 class CodeMirrorWrapper extends React.Component<TextProps> {
126
127 private currentParent?: Element | null;
128 private currentHeight?: number;
129 private currentWidth?: number;
130 private rootElement: HTMLDivElement | null = null;
131 private codeMirror?: CodeMirror.Editor;
132 private refreshPolling?: NodeJS.Timeout;
133
134 // Currently hovered 'dome-xHover-nnn'
135 private marker?: CSSMarker;
136
137 // Maps hovered 'dome-xMark-id' to their decorations
138 private decorations = new Map<string, string>();
139
140 constructor(props: TextProps) {
141 super(props);
142 this.mountPoint = this.mountPoint.bind(this);
143 this.refresh = this.refresh.bind(this);
144 this.autoRefresh = this.autoRefresh.bind(this);
145 this.onBlur = this.onBlur.bind(this);
146 this.onFocus = this.onFocus.bind(this);
147 this.onScroll = this.onScroll.bind(this);
148 this.onClick = this.onClick.bind(this);
149 this.onContextMenu = this.onContextMenu.bind(this);
150 this.onMouseMove = this.onMouseMove.bind(this);
151 this.handleKey = this.handleKey.bind(this);
152 this.handleUpdate = this.handleUpdate.bind(this);
153 this.handleHover = _.throttle(this.handleHover, 50);
154 this.handleScrollTo = this.handleScrollTo.bind(this);
155 }
156
157 // --------------------------------------------------------------------------
158 // --- Mounting
159 // --------------------------------------------------------------------------
160
161 mountPoint(elt: HTMLDivElement | null) {
162 this.rootElement = elt;
163 if (elt !== null) {
164 // Mounting...
165 const { buffer } = this.props;
166 const config = getConfig(this.props);
167 this.codeMirror = CodeMirror(elt, { value: '' });
168 if (buffer) {
169 buffer.link(this.codeMirror);
170 buffer.on('decorated', this.handleUpdate);
171 buffer.on('scroll', this.handleScrollTo);
172 }
173 // Passing all options to constructor does not work (Cf. CodeMirror's BTS)
174 forEachOption(
175 config, (opt) => this.codeMirror?.setOption(opt, config[opt]),
176 );
177 // Binding events to view
178 this.codeMirror.on('update', this.handleUpdate);
179 this.codeMirror.on('keyHandled', this.handleKey);
180 Dome.update.on(this.refresh);
181 // Auto refresh
182 this.refreshPolling = setInterval(this.autoRefresh, 250);
183 this.handleUpdate();
184 } else {
185 // Unmounting...
186 if (this.refreshPolling) {
187 clearInterval(this.refreshPolling);
188 this.refreshPolling = undefined;
189 }
190 Dome.update.off(this.refresh);
191 const { buffer } = this.props;
192 if (this.codeMirror && buffer) {
193 buffer.unlink(this.codeMirror);
194 buffer.off('decorated', this.handleUpdate);
195 buffer.off('scroll', this.handleScrollTo);
196 }
197 this.codeMirror = undefined;
198 this.marker = undefined;
199 this.decorations.clear();
200 }
201 }
202
203 // --------------------------------------------------------------------------
204 // --- Auto Refresh
205 // --------------------------------------------------------------------------
206
207 refresh() {
208 const elt = this.rootElement;
209 const cm = this.codeMirror;
210 if (cm && elt) {
211 this.currentWidth = elt.offsetWidth;
212 this.currentHeight = elt.offsetHeight;
213 this.currentParent = elt.offsetParent;
214 cm.refresh();
215 }
216 }
217
218 // Polled every 250ms
219 autoRefresh() {
220 const elt = this.rootElement;
221 const cm = this.codeMirror;
222 if (cm && elt) {
223 const eltW = elt.offsetWidth;
224 const eltH = elt.offsetHeight;
225 const eltP = elt.offsetParent;
226 if (eltW !== this.currentWidth ||
227 eltH !== this.currentHeight ||
228 eltP !== this.currentParent) {
229 this.currentWidth = eltW;
230 this.currentHeight = eltH;
231 this.currentParent = eltP;
232 cm.refresh();
233 }
234 }
235 }
236
237 // --------------------------------------------------------------------------
238 // --- Hover
239 // --------------------------------------------------------------------------
240
241 _findMarker(elt: Element): CSSMarker | undefined {
242 const { buffer } = this.props;
243 if (buffer) {
244 let best: CSSMarker | undefined;
245 elt.classList.forEach((name) => {
246 const marker = buffer.findHover(name);
247 if (marker && (!best || marker.length < best.length)) best = marker;
248 });
249 return best;
250 }
251 return undefined;
252 }
253
254 // eslint-disable-next-line class-methods-use-this
255 _findDecoration(
256 classes: DOMTokenList,
257 buffer: RichTextBuffer,
258 decorator: Decorator,
259 ) {
260 let bestMarker: CSSMarker | undefined;
261 let bestDecorated: CSSMarker | undefined;
262 let bestDecoration: string | undefined;
263 classes.forEach((name) => {
264
265 const marker = buffer.findHover(name);
266 const id = marker && marker.id;
267 const decoration = id && decorator(id);
268
269 if (marker && (!bestMarker || marker.length < bestMarker.length)) {
270 bestMarker = marker;
271 }
272
273 if (marker && decoration &&
274 (!bestDecorated || marker.length < bestDecorated.length)) {
275 bestDecorated = marker;
276 bestDecoration = decoration;
277 }
278
279 });
280 return bestMarker ? {
281 classNameId: bestMarker.classNameId,
282 decoration: bestDecoration,
283 } : undefined;
284 }
285
286 _markElementsWith(classNameId: string, className: string) {
287 const root = this.rootElement;
288 const toMark = root && root.getElementsByClassName(classNameId);
289 if (toMark) {
290 const n = toMark.length;
291 if (n === 0) return;
292 for (let k = 0; k < n; k++) toMark[k].classList.add(className);
293 }
294 }
295
296 _unmarkElementsWith(className: string) {
297 const root = this.rootElement;
298 const toUnmark = root && root.getElementsByClassName(className);
299 if (toUnmark) {
300 const n = toUnmark.length;
301 if (n === 0) return;
302 const elts: Element[] = new Array(n);
303 for (let k = 0; k < n; k++) elts[k] = toUnmark[k];
304 elts.forEach((elt) => elt.classList.remove(className));
305 }
306 }
307
308 handleHover(target: Element) {
309 // Throttled (see constructor)
310 const oldMarker = this.marker;
311 const newMarker = this._findMarker(target);
312 if (oldMarker !== newMarker) {
313 if (oldMarker) this._unmarkElementsWith(CSS_HOVERED);
314 if (newMarker && newMarker.hover)
315 this._markElementsWith(newMarker.classNameId, CSS_HOVERED);
316 this.marker = newMarker;
317 const callback = this.props.onHover;
318 if (callback) callback(newMarker?.id);
319 }
320 }
321
322 handleUpdate() {
323 const root = this.rootElement;
324 const marked = root && root.getElementsByClassName('dome-xMarked');
325 if (!marked) return;
326 const n = marked.length;
327 if (n === 0) return;
328 const { marker } = this;
329 const hovered = (marker && marker.hover) ? marker.classNameId : undefined;
330 const { selection } = this.props;
331 const selected = selection && (`dome-xMark-${selection}`);
332 const { buffer } = this.props;
333 const decorator = buffer?.getDecorator();
334 if (!hovered && !selection && !decorator) return;
335 const newDecorations = new Map<string, string>();
336 for (let k = 0; k < n; k++) {
337 const elt = marked[k];
338 const classes = elt.classList;
339 if (hovered && classes.contains(hovered)) classes.add(CSS_HOVERED);
340 if (selected && classes.contains(selected)) classes.add(CSS_SELECTED);
341 if (buffer && decorator) {
342 const deco = this._findDecoration(classes, buffer, decorator);
343 if (deco) {
344 const prev = this.decorations.get(deco.classNameId);
345 const curr = deco.decoration;
346 if (prev && prev !== curr) classes.remove(prev);
347 if (curr) {
348 classes.add(curr);
349 newDecorations.set(deco.classNameId, curr);
350 }
351 }
352 }
353 }
354 this.decorations = newDecorations;
355 }
356
357 onMouseMove(evt: MouseEvt) {
358 // Not throttled (can not leak Synthetic Events)
359 const tgt = evt.target;
360 if (tgt instanceof Element) this.handleHover(tgt);
361 }
362
363 onMouseClick(evt: MouseEvt, callback: MarkerCallback | undefined) {
364 // No need for throttling
365 if (callback) {
366 const { target } = evt;
367 if (target instanceof Element) {
368 const marker = this._findMarker(target);
369 if (marker && marker.id) callback(marker.id, evt.altKey);
370 }
371 }
372 this.props.buffer?.setFocused(true);
373 }
374
375 onClick(evt: MouseEvt) {
376 this.onMouseClick(evt, this.props.onSelection);
377 }
378
379 onContextMenu(evt: MouseEvt) {
380 this.onMouseClick(evt, this.props.onContextMenu);
381 }
382
383 // --------------------------------------------------------------------------
384 // --- Scrolling
385 // --------------------------------------------------------------------------
386
387 handleScrollTo(line: number) {
388 try {
389 const cm = this.codeMirror;
390 return cm && cm.scrollIntoView({ line, ch: 0 });
391 } catch (_error) {
392 D.warn(`unable to scroll to line ${line}: out of range.`);
393 }
394 }
395
396 // --------------------------------------------------------------------------
397 // --- Focus
398 // --------------------------------------------------------------------------
399
400 handleKey(_cm: CodeMirror.Editor, key: string, _evt: Event) {
401 switch (key) {
402 case 'Esc':
403 this.props.buffer?.setFocused(false);
404 break;
405 default:
406 this.props.buffer?.setFocused(true);
407 break;
408 }
409 }
410
411 onFocus() { this.props.buffer?.setFocused(true); }
412 onBlur() { this.props.buffer?.setFocused(false); }
413 onScroll() {
414 const cm = this.codeMirror;
415 const { buffer } = this.props;
416 if (cm && buffer) {
417 const rect = cm.getScrollInfo();
418 const delta = rect.height - rect.top - rect.clientHeight;
419 buffer.setFocused(delta > 0);
420 }
421 }
422
423 // --------------------------------------------------------------------------
424 // --- Rendering
425 // --------------------------------------------------------------------------
426
427 shouldComponentUpdate(newProps: TextProps) {
428 const cm = this.codeMirror;
429 if (cm) {
430 // Swap documents if necessary
431 const {
432 buffer: oldBuffer,
433 selection: oldSelect,
434 fontSize: oldFont,
435 } = this.props;
436 const {
437 buffer: newBuffer,
438 selection: newSelect,
439 fontSize: newFont,
440 } = newProps;
441 if (oldBuffer !== newBuffer) {
442 if (oldBuffer) oldBuffer.unlink(cm);
443 if (newBuffer) newBuffer.link(cm);
444 else cm.setValue('');
445 }
446 const oldConfig = getConfig(this.props);
447 const newConfig = getConfig(newProps);
448 // Incremental update options
449 forEachOption(oldConfig, (opt) => {
450 if (!(opt in newConfig)) {
451 const defValue = CodeMirror.defaults[opt];
452 if (defValue)
453 cm.setOption(opt, defValue);
454 }
455 });
456 forEachOption(newConfig, (opt) => {
457 const oldValue = oldConfig[opt];
458 const newValue = newConfig[opt];
459 if (newValue !== oldValue) {
460 cm.setOption(opt, newValue);
461 }
462 });
463 // Update selection
464 if (oldSelect !== newSelect) {
465 const selected = `dome-xMark-${newSelect}`;
466 if (oldSelect) this._unmarkElementsWith(CSS_SELECTED);
467 if (newSelect) this._markElementsWith(selected, CSS_SELECTED);
468 }
469 // Refresh on new font
470 if (oldFont !== newFont) setImmediate(this.refresh);
471 }
472 // Keep mounted node unchanged
473 return false;
474 }
475
476 render() {
477 return (
478 <div
479 className="dome-xText"
480 ref={this.mountPoint}
481 onClick={this.onClick}
482 onContextMenu={this.onContextMenu}
483 onBlur={this.onBlur}
484 onFocus={this.onFocus}
485 onScroll={this.onScroll}
486 onMouseMove={this.onMouseMove}
487 onMouseLeave={this.onMouseMove}
488 />
489 );
490 }
491
492 }
493
494 // --------------------------------------------------------------------------
495 // --- Text View
496 // --------------------------------------------------------------------------
497
498 /** #### Text Editor.
499
500 A component rendering the content of a text buffer, that shall be instances
501 of the `Buffer` base class.
502
503 The view is based on a [CodeMirror](https://codemirror.net) component linked
504 with the internal Code Mirror Document from the associated buffer.
505
506 Multiple views might share the same buffer as source content. The buffer will
507 be kept in sync with all its linked views.
508
509 The Text component never update its mounted NODE element, however, all
510 property modifications (including buffer) are propagated to the internal
511 CodeMirror instance. Undefined properties are set (or reset) to the
512 CodeMirror defaults.
513
514 #### Themes
515
516 The CodeMirror `theme` option allow you to style your document, especially
517 when using modes.
518
519 By default, CodeMirror uses the `'default'` theme in _light_ theme and the
520 `'dark-code'` theme in _dark_ theme. The `'dark-code'` is provided by Dome,
521 Cf. `./dark-mode.css` in the source distribution.
522
523 To use other custom themes, you shall load the associated CSS style
524 sheet. For instance, to use the `'ambiance'` theme provided with CodeMirror,
525 you shall import `'codemirror/theme/ambiance.css'` somewhere in your
526 application.
527
528 #### Modes & Adds-On
529
530 You can install modes and adds-on provided by the CodeMirror distribution by
531 simply importing (once, before being used) the associated modules in your
532 application. For instance, to use the `'javascript'` mode option, you shall
533 import `'codemirror/mode/javascript/javascript.js'` file in your application.
534
535 #### Further Customization
536
537 You can register your own extensions directly into the global `CodeMirror`
538 class instance. However, the correct instance must be retrieved by using
539 `import CodeMirror from 'codemirror/lib/codemirror.js'` ; using `from
540 'codemirror'` returns a different instance of `CodeMirror` class and will not
541 work. */
542 export function Text(props: TextProps) {
543 const [appTheme] = Themes.useColorTheme();
544 let { className, style, fontSize, theme: usrTheme, ...cmprops } = props;
545 if (fontSize !== undefined && fontSize < 4) fontSize = 4;
546 if (fontSize !== undefined && fontSize > 48) fontSize = 48;
547 const theme = usrTheme ?? (appTheme === 'dark' ? 'dark-code' : 'default');
548 return (
549 <Vfill className={className} style={{ ...style, fontSize }}>
550 <CodeMirrorWrapper fontSize={fontSize} theme={theme} {...cmprops} />
551 </Vfill>
552 );
553 }
554
555 // --------------------------------------------------------------------------