Debian Codegraph @

ivette/src/dome/renderer/data/library.js

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 // --- Data Collector
25 // --------------------------------------------------------------------------
26
27 /**
28 @packageDocumentation
29 @module dome/data/library
30 @description
31 This module allows to integrate data definitions within React elements.
32
33 Typically, you can use it to define your own structure of logical elements
34 and display them at different places in the GUI. For instance, you may
35 want to define a custom list of elements, where each element
36 will be rendered twice: locally with the currenly selected item, and in a side-bar
37 or in the menu-bar, or for any other purpose than rendering. You want to declare
38 your list like this:
39
40 * ```jsx
41 * <MyList>
42 * <MyItem id={A} ... >...</MyItem>
43 * <MyItem id={B} ... >...</MyItem>
44 * <MyItem id={C} ... >...</MyItem>
45 * </MyList>
46 * ```
47
48 Dome data libraries, as provided by this module, allows you to define such
49 collection of data mixed with rendered elements.
50
51 Data are collected through libraries.
52 You create libraries with `createLibrary()` or `useLocalLibrary()` and
53 then provide them to `<Data.Item>`, `<Data.Component>`, `<Data.Node>` or
54 `<Data.Fragment>` elements.
55
56 At any (other) point of the tree, you can use the collected items
57 with the `useLibrary()` custom React hook.
58
59 Libraries are pushed down the React virtual tree _via_ React context,
60 so you don't need to re-specify it for children of `<Data.Node/>`
61 and `<Data.Fragment/>`.
62
63 Items must be identified with a unique `id` ; they are sorted according
64 to their `order` property, although `<Data.Fragment/>` and `<Data.Node/>`
65 preserve the order of data collected from each of their children. Items are
66 collected when they are actually _mounted_ by React,
67 like any other React element.
68
69 Data elements are normal React element, that might be rendered by
70 visible elements in the DOM. You may think of data elements as having a
71 double rendering: mounted data items are collected into libraries, and normal visible
72 elements are collected into the React virtual DOM. Each kind of data element is
73 rendered differenly with this respect:
74
75 - `<Data.Item>` renders its children within a React fragment;
76 - `<Data.Node>` is like an item, with its data children stored in the registered item;
77 - `<Data.Component>` always renders 'null' and capture its React children elements
78 in the registered item;
79 - `<Data.Fragment>` renders its children within a React fragment, with optional context
80 library and specified order.
81
82 See each component for more details.
83
84 As an example of use, the introductory example can be implemented as follows:
85
86 ```jsx
87 const lib = createLibrary();
88
89 // To be used at any (possibly repeated) place in the hierarchy of react elements
90 // Children items are only added to the library when the list is mounted
91 const MyList = ({ children }) => {
92 // Actually renders nothing if children only contains items.
93 // The fragment makes items keep their declaration ordering.
94 return (
95 <Data.Fragment lib={lib}>{children}</Data.Fragment>
96 );
97 };
98
99 // To be used also at any (possibly repeated) place in the hierarchy
100 const MyItem = (props) => <Data.Item lib={lib} {...props} /> ;
101
102 // To be used for instance at top-level inside a side-bar
103 const MyListIndex = () => {
104 let items = Data.useLibrary(lib);
105 return (
106 <ul>
107 { items.map(({id,label}) => (<li key={id}>{label}</li>)) }
108 </ul>
109 );
110 };
111 ```
112 */
113
114 import _ from 'lodash';
115 import React from 'react';
116 import * as Dome from 'dome';
117 import EventEmitter from 'events';
118
119 // --------------------------------------------------------------------------
120 // --- Libraries
121 // --------------------------------------------------------------------------
122
123 const reOrder = (items) =>
124 _.sortBy(items, ['order', 'id'])
125 .map((item, order) => Object.assign(item, { order }));
126
127 /**
128 @summary Data Collector.
129 @description
130 Libraries are used to collect data through the React virtual DOM.
131 */
132 class Library extends EventEmitter {
133
134 constructor() {
135 super();
136 this.items = {};
137 this.lastItems = {};
138 this._trigger = _.debounce(this._trigger, 10);
139 }
140
141 _trigger() {
142 if (!_.isEqual(this.items, this.lastItems)) {
143 this.lastItems = this.items;
144 this.sorted = undefined;
145 this.emit('trigger');
146 }
147 };
148
149 /**
150 @summary Register Item.
151 @param {object} item - must have an `'id'` property
152 */
153 add(item) {
154 const id = item.id;
155 if (Dome.DEVEL && this.items[id])
156 console.warn(`[dome/data] duplicate item identifier (${id})`);
157 this.items[id] = item;
158 this._trigger();
159 }
160
161 /**
162 @summary Remove Item.
163 @param {string} id - the item identifier to remove
164 */
165 remove(id) {
166 delete this.items[id];
167 this._trigger();
168 }
169
170 /**
171 @summary Bugger Contents.
172 @return {Array<object>} items array sorted by `'order'` and `'id'` properties.
173 */
174 contents() {
175 return this.sorted || (this.sorted = reOrder(this.items));
176 }
177
178 /**
179 @summary Register callback.
180 @param {function} callback - invoked when library contents changes
181 **/
182 on(callback) { this.on('trigger', callback); }
183
184 /**
185 @summary Un-register callback.
186 @param {function} callback - callback to unregister
187 **/
188 off(callback) { this.off('trigger', callback); }
189
190 }
191
192 /**
193 @summary Creates a Data library.
194 @return {Library} a newly created, empty library.
195 @description
196 Same as `new Library()`.
197 */
198 export function createLibrary() { return new Library(); }
199
200 /**
201 @summary Collect living items from the library (Custom React Hook).
202 @param {Library} library - the desired library
203 @return {Array<items>} items currently mounted in the library
204 @description
205 This hook is automatically updated whenever an item is added or removed
206 from the library.
207 */
208 export function useLibrary(library) {
209 const forceUpdate = Dome.useForceUpdate();
210 Dome.useEmitter(library, 'trigger', forceUpdate);
211 return library.contents();
212 }
213
214 /**
215 @summary Use a locally created new library (Custom React Hook).
216 @return {object} `{ library, items }` the local library and its collected items
217 @description
218 This is a combination of a locally created library _and_ its collected items.
219 Same as:
220 ```
221 const library = React.useMemo( createLibrary , [] );
222 const items = useLibrary( library );
223 ```
224 */
225 export function useLocalLibrary() {
226 const library = React.useMemo(createLibrary, []);
227 const items = useLibrary(library);
228 return { library, items };
229 }
230
231 const CurrentLib = React.createContext();
232 const CurrentPath = React.createContext([]);
233
234 const makePath = (path, order) =>
235 order === undefined ? path : path.slice(0, -1).concat(order);
236
237 /**
238 @summary Current library (Custom React Hook).
239 @return {Library} in local context
240 */
241 export function useCurrentLibrary() {
242 return React.useContext(CurrentLib);
243 }
244
245 // --------------------------------------------------------------------------
246 // --- Internals
247 // --------------------------------------------------------------------------
248
249 function useLocalItem({ lib: localLib, id, order, ...itemProps }, children) {
250 const currentLib = React.useContext(CurrentLib);
251 const currentPath = React.useContext(CurrentPath);
252 const path = makePath(currentPath, order);
253 React.useEffect(() => {
254 const library = localLib || currentLib;
255 if (id && library) {
256 const item = { id, order: path, ...itemProps };
257 if (children) item.children = children;
258 library.add(item);
259 return () => library.remove(id);
260 } else
261 return undefined;
262 });
263 return path;
264 };
265
266 function makeChildren(path, children) {
267 const n = React.Children.count(children);
268 if (n == 0) return null;
269 else {
270 const childContext = (elt, k) => {
271 if (elt) {
272 const newPath = path.concat(1 + k);
273 return (
274 <CurrentPath.Provider value={newPath}>
275 {elt}
276 </CurrentPath.Provider>
277 );
278 } else
279 return elt;
280 };
281 return React.Children.map(children, childContext);
282 }
283 }
284
285 // --------------------------------------------------------------------------
286 // --- Item Definition
287 // --------------------------------------------------------------------------
288
289 /**
290 @summary Data Item definition.
291 @property {Library} [lib] - data library collecting the item
292 @property {string} [id] - item identifier
293 @property {number} [order] - item local ordering (default: inherited)
294 @property {any} [...props] - other item properties
295 @property {React.Children} [children] - rendered elements
296 @description
297 Register a new item in the library:
298
299 ```
300 { id, order, props }
301 ```
302
303 If not specified, the current context library is used. If no identifier nor
304 library is actually available, the item definition is skipped.
305
306 An `<Item/>` element rendres its children in a nested, ordered fragment,
307 but with the same current library than the inherited one, if any.
308 */
309 export const Item = ({ children, ...props }) => {
310 let path = useLocalItem(props);
311 return (<React.Fragment>{makeChildren(path, children)}</React.Fragment>);
312 };
313
314 // --------------------------------------------------------------------------
315 // --- Component Definition
316 // --------------------------------------------------------------------------
317
318 /**
319 @summary Data Component definition.
320 @property {Library} [lib] - data library collecting the item (default: inherited)
321 @property {string} id - item identifier (default: skip item definition)
322 @property {number} [order] - item order (default: parent fragment ordering)
323 @property {any} [...props] - registered item properties
324 @property {React.Children} [children] - component _virtual_ elements
325 @description
326 Register a new item in the library. If enabled and not disabled,
327 the collected item data will be:
328
329 ```
330 { id, order, props, children: React.Children }
331 ```
332
333 The specified order property is used to sort this item among its immediate
334 neighbours in the React virtual DOM. The final item order is determined with
335 respect to all the other collected items.
336
337 Children elements of the `<Component/>` are _not_ mounted into the React
338 virtual DOM. However, they are stored in the `children` property of the
339 item, and can be rendered in other parts of the DOM through
340 `useCurrentLibrary()` react hook. The local context will _not_ be propagated
341 to these children.
342
343 The component element itself is rendered as `null` when mounted in the virtual DOM by React.
344 */
345 export const Component = ({ children, ...props }) => {
346 useLocalItem(props, children);
347 return null;
348 };
349
350 // --------------------------------------------------------------------------
351 // --- Node Definition
352 // --------------------------------------------------------------------------
353
354 /**
355 @summary Recursive Data Item definition.
356 @property {Library} [lib] - data library collecting the item (default: inherited)
357 @property {string} id - item identifier (default: skip item definition)
358 @property {number} [order] - item order (default: parent fragment ordering)
359 @property {any} [...props] - registered item properties
360 @property {React.Children} [children] - sub-data and rendering of the item
361 @description
362 Register a new item in the library, as follows:
363
364 ```
365 { id, order, props, children: Array<item> }
366 ```
367
368 The specified order property is used to sort this item among its immediate
369 neighbours in the React virtual DOM. The final item order is determined with
370 respect to all the other collected items.
371
372 A _new_ local library is created and associated to this `<Node/>` element, and propagated
373 in children as the new context library. If necessary, you can obtain this local
374 library with the `useContext()` react hook.
375
376 Hence, children elements of the node item _are_ rendered in the virtual React DOM,
377 but their data elements are collected and stored in the `children` property of the
378 defined `<Node/>` item.
379 */
380 export const Node = ({ children, ...props }) => {
381 let { library, items } = useLocalLibrary();
382 let path = useLocalItem(props, items);
383 return (
384 <CurrentLib.Provider value={library}>
385 {makeChildren(path, children)}
386 </CurrentLib.Provider>
387 );
388 };
389
390 // --------------------------------------------------------------------------
391 // --- Fragment Definition
392 // --------------------------------------------------------------------------
393
394 /**
395 @summary Ordered Data Collection.
396 @property {Library} [lib] - local library to use
397 @property {Sortable} [order] - local order to use (default: inherited)
398 @property {boolean} [enabled] - fragment shall be rendered (default: `true`)
399 @property {boolean} [disabled] - fragment shal not be rendered (default: `false`)
400 @property {React.Children} [children] - sub-data and rendering of the data collection
401 */
402 export const Fragment = ({ lib: localLib, order, enabled = true, disabled = false, children, ...localProps }) => {
403 const currentLib = React.useContext(CurrentLib);
404 const currentPath = React.useContext(CurrentPath);
405 const library = localLib || currentLib;
406 if (enabled && !disabled && React.Children.count(children) > 0) {
407 const path = makePath(currentPath, order);
408 return (
409 <CurrentLib.Provider value={library}>
410 {makeChildren(path, children)}
411 </CurrentLib.Provider>
412 );
413 } else
414 return null;
415 };
416
417 // --------------------------------------------------------------------------