Debian Codegraph @

ivette/src/dome/renderer/table/arrays.ts

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 // --- Array Models
27 // --------------------------------------------------------------------------
28
29 /**
30 @packageDocumentation
31 @module dome/table/arrays
32 */
33
34 import { Debug } from 'dome';
35 import * as Compare from 'dome/data/compare';
36 import type { ByFields, Order } from 'dome/data/compare';
37 import {
38 SortingInfo, Sorting,
39 Filter, Filtering,
40 Model, Collection, forEach,
41 } from './models';
42
43 const D = new Debug('Dome');
44
45 // --------------------------------------------------------------------------
46 // --- Sorting Utilities
47 // --------------------------------------------------------------------------
48
49 export type ByColumns<Row> = { [dataKey: string]: Compare.Order<Row> };
50
51 export interface PACK<Key, Row> {
52 index: number | undefined;
53 key: Key;
54 row: Row;
55 }
56
57 export type SORT<K, R> = Order<PACK<K, R>>;
58
59 function orderBy<K, R>(
60 columns: ByColumns<R>,
61 ord: SortingInfo,
62 ): SORT<K, R> {
63 const dataKey = ord.sortBy;
64 const byData = columns[dataKey] ?? Compare.equal;
65 const rv = ord.sortDirection === 'DESC';
66 type D = PACK<K, R>;
67 const byEntry = (x: D, y: D) => byData(x.row, y.row);
68 const byIndex = (x: D, y: D) => (x.index ?? 0) - (y.index ?? 0);
69 return Compare.direction(Compare.sequence(byEntry, byIndex), rv);
70 }
71
72 function orderByRing<K, R>(
73 natural: undefined | Order<R>,
74 columns: undefined | ByColumns<R>,
75 ring: SortingInfo[],
76 ): SORT<K, R> {
77 type D = PACK<K, R>;
78 const byRing = columns ? ring.map((ord) => orderBy(columns, ord)) : [];
79 const byData = natural ? ((x: D, y: D) => natural(x.row, y.row)) : undefined;
80 return Compare.sequence(...byRing, byData);
81 }
82
83 // --------------------------------------------------------------------------
84 // --- Filtering Utilities
85 // --------------------------------------------------------------------------
86
87 type INDEX<K, R> = Map<K, PACK<K, R>>;
88
89 // --------------------------------------------------------------------------
90 // --- Array Model
91 // --------------------------------------------------------------------------
92
93 export class ArrayModel<Key, Row>
94 extends Model<Key, Row>
95 implements Sorting, Filtering<Key, Row>
96 {
97
98 // Hold raw data (unsorted, unfiltered)
99 private index: INDEX<Key, Row> = new Map();
100
101 // Hold filtered & sorted data (computed and cached on demand)
102 private table?: PACK<Key, Row>[];
103
104 // Hold filtered & sorted array of data (computed and cached on demand)
105 private array?: Row[];
106
107 // Filtered-out Row Count
108 private filtered = 0;
109
110 // Filtering function
111 private filter?: Filter<Key, Row>;
112
113 // Natural ordering (if any)
114 private natural?: Order<Row>;
115
116 // Sortable columns and associated ordering (if any)
117 private columns?: ByColumns<Row>;
118
119 // Comparison Ring
120 private ring: SortingInfo[] = [];
121
122 // Consolidated order (computed on demand)
123 private order?: SORT<Key, Row>;
124
125 // --------------------------------------------------------------------------
126 // --- Rebuild Array
127 // --------------------------------------------------------------------------
128
129 // Lazily compute order
130 protected sorter(): SORT<Key, Row> {
131 let current = this.order;
132 if (current) return current;
133 current = this.order = // eslint-disable-line no-multi-assign
134 orderByRing(this.natural, this.columns, this.ring);
135 return current;
136 }
137
138 // Lazily compute table ; modifies packed entries in place
139 protected rebuild(): PACK<Key, Row>[] {
140 const current = this.table;
141 let filtered = 0;
142 if (current !== undefined) return current;
143 const table: PACK<Key, Row>[] = [];
144 try {
145 this.index.forEach((packed) => {
146 packed.index = undefined;
147 const phi = this.filter;
148 if (!phi || phi(packed.row, packed.key))
149 table.push(packed);
150 else
151 filtered++;
152 });
153 table.sort(this.sorter());
154 } catch (err) {
155 D.warn('error when rebuilding table:', err);
156 }
157 table.forEach((packed, index) => { packed.index = index; });
158 this.table = table;
159 this.filtered = filtered;
160 return table;
161 }
162
163 // --------------------------------------------------------------------------
164 // --- Proxy
165 // --------------------------------------------------------------------------
166
167 /** Non filtered. */
168 getTotalRowCount() { return this.getRowCount() + this.filtered; }
169
170 getRowCount() { return this.rebuild().length; }
171
172 getRowAt(k: number) { return this.rebuild()[k]?.row; }
173
174 getKeyAt(k: number) {
175 const current = this.table;
176 return current ? current[k]?.key : undefined;
177 }
178
179 getKeyFor(k: number, _: Row) { return this.getKeyAt(k); }
180
181 getIndexOf(key: Key) {
182 const pack = this.index.get(key);
183 if (!pack) return undefined;
184 const k = pack.index;
185 if (k === undefined || k < 0) return undefined;
186 const current = this.table;
187 return (current && k < current.length) ? k : undefined;
188 }
189
190 // --------------------------------------------------------------------------
191 // --- Ordering
192 // --------------------------------------------------------------------------
193
194 /** Sets comparison functions for the specified columns. Previous
195 comparison for un-specified columns are kept unchanged, if any.
196 This will be used to refine
197 [[setNaturalOrder]] in response to user column selection with
198 [[setSorting]] provided you enable by-column sorting from the table view.
199 Finally triggers a reload. */
200 setColumnOrder(columns?: ByColumns<Row>) {
201 this.columns = { ...this.columns, ...columns };
202 this.reload();
203 }
204
205 /** Sets natural ordering of the rows.
206 It defines in which order the entries are rendered in the table. This
207 primary ordering can be refined in response to user column selection with
208 [[setSorting]] provided you enable by-column sorting from the table view.
209 Finally triggers a reload. */
210 setNaturalOrder(order?: Order<Row>) {
211 this.natural = order;
212 this.reload();
213 }
214
215 /**
216 Sets both natural ordering and column ordering with the provided
217 orders by fields. This is a combination of [[setColumnOrder]] and
218 [[setNaturalOrder]] with [[dome/data/compare.byFields]].
219 */
220 setOrderingByFields(byfields: ByFields<Row>) {
221 this.natural = Compare.byFields(byfields);
222 const columns = this.columns ?? {};
223 const keys = Object.keys(byfields);
224 for (let i = 0; i < keys.length; i++) {
225 const dataKey = keys[i] as (string & keyof Row);
226 const fn = byfields[dataKey];
227 if (fn) columns[dataKey] = (x: Row, y: Row) => {
228 const dx = x[dataKey];
229 const dy = y[dataKey];
230 if (dx === dy) return 0;
231 if (dx === undefined) return 1;
232 if (dy === undefined) return -1;
233 return fn(dx, dy);
234 };
235 }
236 this.columns = columns;
237 this.reload();
238 }
239
240 /**
241 Remove the sorting function for the provided column.
242 */
243 deleteColumnOrder(dataKey: string) {
244 const { columns } = this;
245 if (columns) delete columns[dataKey];
246 this.ring = this.ring.filter((ord) => ord.sortBy !== dataKey);
247 this.reload();
248 }
249
250 /** Reorder rows with the provided column and direction.
251 Previous ordering is kept and refined by the new one.
252 Use `undefined` or `null` to reset the natural ordering. */
253 setSorting(ord?: undefined | null | SortingInfo) {
254 if (ord) {
255 const { ring } = this;
256 const cur = ring[0];
257 const fd = ord.sortBy;
258 if (
259 !cur ||
260 cur.sortBy !== fd ||
261 cur.sortDirection !== ord.sortDirection
262 ) {
263 const newRing = ring.filter((o) => o.sortBy !== fd);
264 newRing.unshift(ord);
265 this.ring = newRing;
266 this.reload();
267 }
268 } else if (this.ring.length > 0) {
269 this.ring = [];
270 this.reload();
271 }
272 }
273
274 canSortBy(column: string): boolean {
275 const columns = this.columns;
276 return !!columns && columns[column] !== undefined;
277 }
278
279 getSorting(): SortingInfo | undefined {
280 return this.ring[0];
281 }
282
283 // --------------------------------------------------------------------------
284 // --- Filtering
285 // --------------------------------------------------------------------------
286
287 setFilter(fn?: Filter<Key, Row>) {
288 const phi = this.filter;
289 if (phi !== fn) {
290 this.filter = fn;
291 this.reload();
292 }
293 }
294
295 // --------------------------------------------------------------------------
296 // --- Full Updates
297 // --------------------------------------------------------------------------
298
299 /** Trigger a complete reload of the table. */
300 reload() {
301 this.array = undefined;
302 this.table = undefined;
303 this.order = undefined;
304 super.reload();
305 }
306
307 /** Remove all data and reload. */
308 clear() {
309 this.index.clear();
310 this.reload();
311 }
312
313 // --------------------------------------------------------------------------
314 // --- Checks for Reload vs. Update
315 // --------------------------------------------------------------------------
316
317 private needReloadForUpdate(pack: PACK<Key, Row>): boolean {
318 // Case where reload is already triggered
319 const current = this.table;
320 if (!current) return false;
321 // Case where filtering of key has changed
322 const k = pack.index ?? -1;
323 const n = current ? current.length : 0;
324 const phi = this.filter;
325 const oldOk = 0 <= k && k < n;
326 const nowOk = phi ? phi(pack.row, pack.key) : true;
327 if (oldOk !== nowOk) return true;
328 // Case where element was not displayed and will still not be
329 if (!oldOk) return false;
330 // Detecting if ordering is preserved
331 const order = this.sorter();
332 const prev = k - 1;
333 if (0 <= prev && order(pack, current[prev]) < 0) return true;
334 const next = k + 1;
335 if (next < n && order(current[next], pack) < 0) return true;
336 super.updateIndex(k);
337 return false;
338 }
339
340 private needReloadForInsert(pack: PACK<Key, Row>): boolean {
341 // Case where reload is already triggered
342 const current = this.table;
343 if (!current) return false;
344 // Case where inserted element is filtered out
345 const phi = this.filter;
346 return phi ? phi(pack.row, pack.key) : true;
347 }
348
349 private needReloadForRemoval(pack: PACK<Key, Row>): boolean {
350 // Case where reload is already triggered
351 const current = this.table;
352 if (!current) return false;
353 // Case where inserted element is filtered out
354 const k = pack.index ?? -1;
355 return 0 <= k && k < current.length;
356 }
357
358 // --------------------------------------------------------------------------
359 // --- Update item and optimized reload
360 // --------------------------------------------------------------------------
361
362 /**
363 Update a data entry and signal the views only if needed.
364 Use `undefined` to keep value unchanged, `null` for removal,
365 or the new row data for update. This triggers a full
366 reload if ordering or filtering if modified by the updated value,
367 a update index if the row data is only modified and visible.
368 Otherwise, no rendering is triggered since the modification
369 is not visible.
370 @param key - the entry identifier
371 @param row - new value of `null` for removal
372 */
373 update(key: Key, row?: undefined | null | Row) {
374 if (row === undefined) return;
375 const pack = this.index.get(key);
376 let doReload = false;
377 if (pack) {
378 if (row === null) {
379 // Removal
380 this.index.delete(key);
381 doReload = this.needReloadForRemoval(pack);
382 } else {
383 // Updated
384 pack.row = row;
385 doReload = this.needReloadForUpdate(pack);
386 }
387 } else {
388 if (row === null) {
389 // Nop
390 return;
391 }
392 const newPack = { key, row, index: undefined };
393 this.index.set(key, newPack);
394 doReload = this.needReloadForInsert(newPack);
395
396 }
397 if (doReload) this.reload();
398 }
399
400 // --------------------------------------------------------------------------
401 // --- Batched Updates
402 // --------------------------------------------------------------------------
403
404 /**
405 Silently removes the entry.
406 Modification will be only visible after a final [[reload]].
407 Useful for a large number of batched updates.
408 */
409 removeAllData() {
410 this.index.clear();
411 }
412
413 /**
414 Silently removes the entries.
415 Modification will be only visible after a final [[reload]].
416 Useful for a large number of batched updates.
417 @param key - the removed entry.
418 */
419 removeData(keys: Collection<Key>) {
420 forEach(keys, (k) => this.index.delete(k));
421 }
422
423 /**
424 Silently updates the entry.
425 Modification will be only visible after a final [[reload]].
426 Useful for a large number of batched updates.
427 @param key - the entry to update.
428 @param row - the new row data or `null` for removal.
429 */
430 setData(key: Key, row: null | Row) {
431 if (row !== null) {
432 this.index.set(key, { key, row, index: undefined });
433 } else {
434 this.index.delete(key);
435 }
436 }
437
438 /** Returns the data associated with a key (if any). */
439 getData(key: Key): Row | undefined {
440 return this.index.get(key)?.row;
441 }
442
443 /** Returns an array of filtered and sorted entries.
444 Computed on demand and cached. */
445 getArray(): Row[] {
446 let arr = this.array;
447 if (arr === undefined) {
448 arr = this.array = // eslint-disable-line no-multi-assign
449 this.rebuild().map((e) => e.row);
450 }
451 return arr;
452 }
453
454 }
455
456 // --------------------------------------------------------------------------
457 // --- Compact Array Model
458 // --------------------------------------------------------------------------
459
460 /**
461 @template Row - object data that also contains their « key ».
462 */
463 export class CompactModel<Key, Row> extends ArrayModel<Key, Row> {
464
465 getkey: (d: Row) => Key;
466
467 /** @param key - the key property of `Row` holding an entry identifier. */
468 constructor(getkey: (d: Row) => Key) {
469 super();
470 this.getkey = getkey;
471 }
472
473 /** Use the key getter directly. */
474 getKeyFor(_: number, data: Row) { return this.getkey(data); }
475
476 /** Silently add or update a collection of data.
477 Requires a final trigger to update views. */
478 updateData(data: Collection<Row>) {
479 forEach(data, (row: Row) => this.setData(this.getkey(row), row));
480 }
481
482 /**
483 Replace all previous data with the new ones.
484 Finally triggers a reload.
485 */
486 replaceAllDataWith(data: Collection<Row>) {
487 this.removeAllData();
488 this.updateData(data);
489 this.reload();
490 }
491
492 }
493
494 // --------------------------------------------------------------------------