Debian Codegraph @

ivette/src/renderer/Laboratory.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 // --------------------------------------------------------------------------
24 // --- Lab View Component
25 // --------------------------------------------------------------------------
26
27 import _ from 'lodash';
28 import React from 'react';
29 import * as Dome from 'dome';
30 import * as Json from 'dome/data/json';
31 import * as Settings from 'dome/data/settings';
32 import { Catch } from 'dome/errors';
33 import { DnD, DragSource } from 'dome/dnd';
34 import { SideBar, Section, Item } from 'dome/frame/sidebars';
35 import { RSplit } from 'dome/layout/splitters';
36 import * as Grids from 'dome/layout/grids';
37 import { Hbox, Hfill, Vfill } from 'dome/layout/boxes';
38 import { IconButton, Field } from 'dome/controls/buttons';
39 import { Label } from 'dome/controls/labels';
40 import { Icon } from 'dome/controls/icons';
41 import { RenderElement } from 'dome/layout/dispatch';
42
43 import './style.css';
44
45
46 const Debug = new Dome.Debug('labviews');
47
48 // --------------------------------------------------------------------------
49 // --- Types
50 // --------------------------------------------------------------------------
51
52 interface Item {
53 /** Identifier. */
54 id: string;
55 /** Displayed name. */
56 label: string;
57 /** Tooltip description. */
58 title?: string;
59 /** Ordering index. */
60 rank?: number;
61 }
62 interface View extends Item {
63 origin?: string;
64 order?: number[];
65 builtin?: boolean;
66 defaultView?: boolean;
67 }
68
69 type Group = Item
70
71 interface Component extends Item {
72 group?: string;
73 layout?: layout;
74 }
75
76 type layout = 'PLAIN' | 'HPANE' | 'VPANE'
77
78
79 // --------------------------------------------------------------------------
80 // --- Library Class
81 // --------------------------------------------------------------------------
82
83 let RANK = 0;
84 const UPDATE = new Dome.Event('labview.library');
85
86 class Library {
87 modified: boolean;
88 virtual: { [id: string]: (Item & { order?: number }) };
89 collection: { [id: string]: (Item & { order?: number }) };
90 items: Item[];
91
92 constructor() {
93 this.modified = false;
94 this.virtual = {};
95 this.collection = {};
96 this.items = [];
97 }
98
99 commit(): void {
100 if (!_.isEqual(this.collection, this.virtual)) {
101 this.collection = { ...this.virtual };
102 this.items = _.sortBy(this.collection, ['order', 'id']);
103 this.modified = false;
104 UPDATE.emit();
105 }
106 }
107
108 addItem(props: Item): void {
109 if (!this.modified) {
110 this.modified = true;
111 setImmediate(() => this.commit());
112 }
113 const order = props.rank ?? ++RANK;
114 const collection = this.virtual;
115 collection[props.id] = { ...props, order };
116 }
117
118 }
119
120 const LIBRARY = new Library();
121
122 // --------------------------------------------------------------------------
123 // --- Library Components
124 // --------------------------------------------------------------------------
125
126 const isItemId = (fd: string, id: string): boolean =>
127 id.startsWith(fd) && id[fd.length] === '.';
128 const getItemId = (fd: string, id: string): string | undefined =>
129 isItemId(fd, id) ? id.substring(fd.length + 1) : undefined;
130 const getItems = (items: Item[], fd: string): Item[] =>
131 items.filter((item) => isItemId(fd, item.id));
132
133 export function addLibraryItem<A extends Item>(
134 fd: string,
135 { id, ...props }: A
136 ): void {
137 const itemId = `${fd}.${id}`;
138 LIBRARY.addItem({ ...props, id: itemId });
139 }
140
141 // --------------------------------------------------------------------------
142 // --- Grid Item
143 // --------------------------------------------------------------------------
144
145 interface TitleContext {
146 id?: string;
147 label?: string;
148 title?: string;
149 }
150
151 interface GridItemProps extends Item {
152 layout?: 'PLAIN' | 'HPANE' | 'VPANE';
153 children?: React.ReactNode;
154 }
155
156 const TITLE = React.createContext<TitleContext>({});
157
158 export function useTitleContext(): TitleContext {
159 return React.useContext(TITLE);
160 }
161
162 const GRIDITEM = {
163 className: 'dome-container dome-xBoxes-vbox dome-xBoxes-box',
164 handle: '.labview-handle',
165 resize: 'both',
166 fill: 'none',
167 shrink: 'none',
168 minWidth: 40,
169 minHeight: 40,
170 width: 120,
171 height: 120,
172 };
173
174 const GRIDITEM_PLAIN = { fill: 'both' };
175 const GRIDITEM_HPANE = { fill: 'horizontal' };
176 const GRIDITEM_VPANE = { fill: 'vertical' };
177
178 const makeGridItem = (customize: unknown, onClose: (id: string) => void) =>
179 function GridItem<A extends GridItemProps>(comp: A): JSX.Element {
180 const { id: libId, label, title, layout = 'PLAIN', children } = comp;
181 const id = getItemId('components', libId);
182 let properties: { [key: string]: unknown } = { ...GRIDITEM };
183 switch (layout) {
184 case 'PLAIN':
185 properties = { ...properties, ...GRIDITEM_PLAIN };
186 break;
187 case 'HPANE':
188 properties = { ...properties, ...GRIDITEM_HPANE };
189 break;
190 case 'VPANE':
191 properties = { ...properties, ...GRIDITEM_VPANE };
192 break;
193 case undefined:
194 break;
195 default:
196 Debug.warn(`unexpected layout for ${id} component`, layout);
197 break;
198 }
199 Object.keys(properties).forEach((key) => {
200 const prop = (comp as A & { [key: string]: unknown })[key];
201 if (prop) properties[key] = prop;
202 });
203 let CLOSING;
204 if (customize) {
205 CLOSING = (
206 <IconButton
207 className="labview-close"
208 offset={-1}
209 icon="CROSS"
210 onClick={() => onClose(id as string)} // id may actually be undefined
211 />
212 );
213 }
214 return (
215 <Grids.GridItem
216 id={id}
217 className={properties.className}
218 handle={properties.handle}
219 resize={properties.resize}
220 fill={properties.fill}
221 shrink={properties.shrink}
222 minWidth={properties.minWidth}
223 minHeight={properties.minHeight}
224 width={properties.width}
225 height={properties.height}
226 >
227 <Vfill className="labview-content">
228 <Hbox className="labview-titlebar">
229 <Hfill>
230 <Catch label={id}>
231 <RenderElement id={`labview.title.${id}`}>
232 <Label
233 className="labview-handle"
234 label={label}
235 title={title} />
236 </RenderElement>
237 </Catch>
238 </Hfill>
239 {CLOSING}
240 </Hbox>
241 <TITLE.Provider value={{ id, label, title }}>
242 <Catch label={id}>{children}</Catch>
243 </TITLE.Provider>
244 </Vfill>
245 </Grids.GridItem>
246 );
247 };
248
249 // --------------------------------------------------------------------------
250 // --- Customization Views
251 // --------------------------------------------------------------------------
252
253 type Shape = Json.json // Until Grids has a type Shape, use this one instead
254
255 interface CustomViewsProps {
256 settings?: string,
257 shape: Shape,
258 setShape: (shape: Shape) => void,
259 views: React.PropsWithChildren<View>[]
260 }
261
262 interface CustomViewsSettings {
263 current?: string;
264 shapes?: { [k: string]: Shape };
265 }
266
267 function CustomViews(props: CustomViewsProps): JSX.Element {
268 const { settings, shape, setShape, views: libViews } = props;
269 const [local, setLocal] = Settings.useWindowSettings<CustomViewsSettings>(
270 settings,
271 Json.identity as Json.Loose<CustomViewsSettings & Json.json>, // Clearly abusive conversion, a real decoder is needed
272 {},
273 );
274 const [customs, setCustoms] =
275 Settings.useLocalStorage<{ [id: string]: View }>(
276 'frama-c.labview',
277 Json.identity as Json.Loose<{ [id: string]: View } & Json.json>, // Clearly abusive conversion, a real decoder is needed
278 {},
279 );
280 const [edited, setEdited] = React.useState<string>();
281 const triggerDefault = React.useRef<View>();
282 const { current, shapes = {} } = local;
283 const theViews: { [id: string]: View } = {};
284
285 _.forEach(libViews, (view) => {
286 const {
287 id: origin,
288 order,
289 label = '(Stock View)',
290 title, defaultView,
291 } = view;
292 const id = `builtin.${origin}`;
293
294 theViews[id] =
295 { id, order, label, title, builtin: true, defaultView, origin };
296 });
297
298 _.forEach(customs, (view) => {
299 const { id, order, label = '(Custom View)', title, origin } = view;
300 if (id && !theViews[id]) {
301 theViews[id] = { id, order, label, title, builtin: false, origin };
302 }
303 });
304
305 const getStock =
306 (origin: string | undefined): React.PropsWithChildren<View> => (
307 (origin && _.find(libViews, (v) => v.id === origin)) ||
308 _.find(libViews, (v) => !!v.defaultView) ||
309 libViews[0]
310 );
311
312 const getDefaultShape = (view: View): Shape => {
313 const stock = getStock(view && view.origin);
314 return stock && Grids.makeChildrenShape(stock.children);
315 };
316
317 const SELECT = (id: string): void => {
318 if (id && current !== id) {
319 if (current) shapes[current] = shape;
320 setLocal({ current: id, shapes });
321 setShape(shapes[id] || getDefaultShape(theViews[id]));
322 }
323 };
324
325 const POPUP = (id: string): void => {
326 const view = theViews[id];
327 if (!view) return;
328 const isCurrent = current === id;
329 const isCustom = !view.builtin;
330
331 const DEFAULT = (): void => {
332 shapes[id] = undefined;
333 setLocal({ current: id, shapes });
334 setShape(getDefaultShape(view));
335 };
336
337 const RENAME = () => void setEdited(id);
338
339 const DUPLICATE = (): void => {
340 const base = `custom.${view.origin}`;
341 const stock = getStock(view.origin);
342 let k = 1;
343 let newId = base;
344 while (theViews[newId]) {
345 k += 1;
346 newId = `${base}~${k}`;
347 }
348 let newOrder = view.order;
349 if (newOrder && newOrder.concat) newOrder = newOrder.concat([k]);
350 let newLabel = `Custom ${stock.label}`;
351 if (k > 1) newLabel += `~${k}`;
352 customs[newId] = {
353 id: newId,
354 label: newLabel,
355 order: newOrder,
356 title: `Derived from ${stock.label}`,
357 origin: view.origin,
358 builtin: false,
359 };
360 setCustoms(customs);
361 if (current) shapes[current] = shape;
362 setLocal({ current: newId, shapes });
363 setEdited(newId);
364 };
365
366 const REMOVE = (): void => {
367 delete customs[id];
368 delete shapes[id];
369 setCustoms(customs);
370 const newCurrent = current === id ? undefined : current;
371 setLocal({ current: newCurrent, shapes });
372 };
373
374 Dome.popupMenu([
375 { label: 'Rename View', display: (!edited && isCustom), onClick: RENAME },
376 { label: 'Restore Default', display: isCurrent, onClick: DEFAULT },
377 { label: 'Duplicate View', onClick: DUPLICATE },
378 'separator',
379 { label: 'Remove View', display: isCustom, onClick: REMOVE },
380 ]);
381 };
382
383 const makeViewItem = ({ id, label, title, builtin }: View): JSX.Element => {
384 if (edited === id) {
385 const RENAMED = (newLabel: string): void => {
386 if (newLabel) {
387 const custom = Json.jObj(customs[id] as Json.json) || {};
388 if (custom) custom.label = newLabel;
389 setCustoms(customs);
390 }
391 setEdited(undefined);
392 };
393 const FIELD = (
394 <Field
395 className="labview-field"
396 placeholder="View Name"
397 autoFocus
398 value={label}
399 title={title}
400 onChange={RENAMED}
401 />
402 );
403 return (
404 <Item key={id} icon="DISPLAY">
405 {FIELD}
406 </Item>
407 );
408 }
409 const FLAGS = [];
410 if (builtin) FLAGS.push('LOCK');
411 return (
412 <Item
413 key={id}
414 icon="DISPLAY"
415 label={label}
416 title={title}
417 selected={!!id && current === id}
418 onSelection={() => SELECT(id)}
419 onContextMenu={() => POPUP(id)}
420 >
421 {FLAGS.map((icn) => (
422 <Icon
423 key={icn}
424 className="labview-icon"
425 size={9}
426 offset={1}
427 id={icn}
428 />
429 ))}
430 </Item>
431 );
432 };
433
434 if (!current && !triggerDefault.current) {
435 const theDefault = _.find(theViews, (item) => !!item.defaultView);
436 triggerDefault.current = theDefault;
437 if (theDefault) setTimeout(() => { SELECT(theDefault.id); });
438 }
439
440 return (
441 <Section label="Views" defaultUnfold>
442 {_.sortBy(theViews, ['order', 'id']).map(makeViewItem)}
443 </Section>
444 );
445 }
446
447 // --------------------------------------------------------------------------
448 // --- Customization Components
449 // --------------------------------------------------------------------------
450
451 const DRAGOVERLAY = { className: 'labview-stock' };
452
453 export interface CustomGroupProps {
454 settings?: string;
455 dnd?: DnD;
456 shape?: Shape;
457 setDragging: (id?: string) => void;
458 id?: string;
459 title?: string;
460 label: string;
461 components: Component[];
462 }
463
464 function CustomGroup({
465 settings,
466 dnd, shape, setDragging,
467 id: sectionId,
468 title: sectionTitle,
469 label: sectionLabel,
470 components,
471 }: CustomGroupProps): JSX.Element {
472 const makeComponent = ({ id, label, title }: Component): JSX.Element => {
473 const itemId = getItemId('components', id);
474 const disabled = Grids.getShapeItem(shape, itemId) !== undefined;
475 return (
476 <DragSource
477 key={id}
478 dnd={dnd}
479 disabled={disabled}
480 overlay={disabled ? undefined : DRAGOVERLAY}
481 onStart={() => setDragging(itemId)}
482 >
483 <Item
484 icon="COMPONENT"
485 disabled={disabled}
486 label={label}
487 title={title}
488 />
489 </DragSource>
490 );
491 };
492 return (
493 <Section
494 key={sectionId}
495 settings={settings && `${settings}.${sectionId}`}
496 label={sectionLabel}
497 title={sectionTitle}
498 defaultUnfold={sectionId === 'groups.frama-c'}
499 >
500 {components.map(makeComponent)}
501 </Section>
502 );
503 }
504
505 // --------------------------------------------------------------------------
506 // --- Customization Panel
507 // --------------------------------------------------------------------------
508
509 interface CustomPanelProps {
510 dnd?: DnD;
511 settings?: string;
512 shape?: Shape;
513 setShape: (shape: Shape) => void;
514 setDragging: (id?: string) => void;
515 }
516
517 function CustomizePanel(
518 { dnd, settings, shape, setShape, setDragging }: CustomPanelProps,
519 ): JSX.Element {
520 Dome.useUpdate(UPDATE);
521 const { items } = LIBRARY;
522 const views = getItems(items, 'views') as View[];
523 const groups = getItems(items, 'groups') as Group[];
524 const components = getItems(items, 'components') as Component[];
525 const settingFolds = settings && `${settings}.folds`;
526 const settingViews = settings && `${settings}.views`;
527 const contents: { [id: string]: Component[] } = {};
528
529 groups.unshift({ id: 'nogroup', label: 'Components' });
530 groups.forEach((g) => (contents[g.id] = []));
531
532 components.forEach((c) => {
533 const gid = c.group ? `groups.${c.group}` : 'nogroup';
534 let content = contents[gid];
535 if (content === undefined) content = contents.nogroup;
536 content.push(c);
537 });
538
539 return (
540 <SideBar>
541 <CustomViews
542 key="views"
543 settings={settingViews}
544 shape={shape}
545 setShape={setShape}
546 views={views}
547 />
548 {groups.map((g) => (
549 <CustomGroup
550 settings={settingFolds}
551 key={g.id}
552 id={g.id}
553 label={g.label}
554 title={g.title}
555 dnd={dnd}
556 setDragging={setDragging}
557 shape={shape}
558 components={contents[g.id]}
559 />
560 ))}
561 </SideBar>
562 );
563 }
564
565 // --------------------------------------------------------------------------
566 // --- LabView Container
567 // --------------------------------------------------------------------------
568
569 export interface LabViewProps {
570 /** Show component panels. */
571 customize?: boolean;
572 /** Base settings identifier. */
573 settings?: string;
574 }
575
576 /**
577 Reconfigurable Component Display.
578 */
579 export function LabView(props: LabViewProps): JSX.Element {
580 // Parameters
581 const { settings, customize = false } = props;
582 const settingSplit = settings && `${settings}.split`;
583 const settingShape = settings && `${settings}.shape`;
584 const settingPanel = settings && `${settings}.panel`;
585 // Hooks & State
586 Dome.useUpdate(
587 UPDATE,
588 Dome.windowSettings,
589 Dome.globalSettings,
590 );
591 const dnd = React.useMemo(() => new DnD(), []);
592 const [shape, setShape] =
593 Settings.useWindowSettings(settingShape, Json.jAny, undefined);
594 const [dragging, setDragging] = React.useState<string | undefined>();
595 // Preparation
596 const onClose =
597 (id: string): void => setShape(Grids.removeShapeItem(shape, id));
598 const components: Component[] =
599 _.filter(
600 LIBRARY.collection,
601 (item: Item) => isItemId('components', item.id),
602 );
603 const gridItems =
604 components.map(makeGridItem(customize, onClose));
605 const holding =
606 dragging ? gridItems.find((elt) => elt.props.id === dragging) : undefined;
607 // Make view
608 return (
609 <RSplit margin={120} settings={settingSplit} unfold={customize}>
610 <Grids.GridLayout
611 dnd={dnd}
612 padding={2}
613 className="labview-container"
614 items={gridItems}
615 shape={shape}
616 onReshape={setShape}
617 holding={holding}
618 />
619 <CustomizePanel
620 dnd={dnd}
621 settings={settingPanel}
622 shape={shape}
623 setShape={setShape}
624 setDragging={setDragging}
625 />
626 </RSplit>
627 );
628 }
629
630 // --------------------------------------------------------------------------