Debian Codegraph @

templates/lib/extra/wunderbaum/wunderbaum.umd.js

raw
1 (function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.mar10 = {}));
5 })(this, (function (exports) { 'use strict';
6
7 /*!
8 * Wunderbaum - debounce.ts
9 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
10 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
11 */
12 /*
13 * debounce & throttle, taken from https://github.com/lodash/lodash v4.17.21
14 * MIT License: https://raw.githubusercontent.com/lodash/lodash/4.17.21-npm/LICENSE
15 * Modified for TypeScript type annotations.
16 */
17 /* --- */
18 /** Detect free variable `global` from Node.js. */
19 const freeGlobal = typeof global === "object" &&
20 global !== null &&
21 global.Object === Object &&
22 global;
23 /** Detect free variable `globalThis` */
24 const freeGlobalThis = typeof globalThis === "object" &&
25 globalThis !== null &&
26 globalThis.Object == Object &&
27 globalThis;
28 /** Detect free variable `self`. */
29 const freeSelf = typeof self === "object" && self !== null && self.Object === Object && self;
30 /** Used as a reference to the global object. */
31 const root = freeGlobalThis || freeGlobal || freeSelf || Function("return this")();
32 /**
33 * Checks if `value` is the
34 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
35 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
36 *
37 * @since 0.1.0
38 * @category Lang
39 * @param {*} value The value to check.
40 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
41 * @example
42 *
43 * isObject({})
44 * // => true
45 *
46 * isObject([1, 2, 3])
47 * // => true
48 *
49 * isObject(Function)
50 * // => true
51 *
52 * isObject(null)
53 * // => false
54 */
55 function isObject(value) {
56 const type = typeof value;
57 return value != null && (type === "object" || type === "function");
58 }
59 /**
60 * Creates a debounced function that delays invoking `func` until after `wait`
61 * milliseconds have elapsed since the last time the debounced function was
62 * invoked, or until the next browser frame is drawn. The debounced function
63 * comes with a `cancel` method to cancel delayed `func` invocations and a
64 * `flush` method to immediately invoke them. Provide `options` to indicate
65 * whether `func` should be invoked on the leading and/or trailing edge of the
66 * `wait` timeout. The `func` is invoked with the last arguments provided to the
67 * debounced function. Subsequent calls to the debounced function return the
68 * result of the last `func` invocation.
69 *
70 * **Note:** If `leading` and `trailing` options are `true`, `func` is
71 * invoked on the trailing edge of the timeout only if the debounced function
72 * is invoked more than once during the `wait` timeout.
73 *
74 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
75 * until the next tick, similar to `setTimeout` with a timeout of `0`.
76 *
77 * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
78 * invocation will be deferred until the next frame is drawn (typically about
79 * 16ms).
80 *
81 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
82 * for details over the differences between `debounce` and `throttle`.
83 *
84 * @since 0.1.0
85 * @category Function
86 * @param {Function} func The function to debounce.
87 * @param {number} [wait=0]
88 * The number of milliseconds to delay; if omitted, `requestAnimationFrame` is
89 * used (if available).
90 * @param [options={}] The options object.
91 * @returns {Function} Returns the new debounced function.
92 * @example
93 *
94 * // Avoid costly calculations while the window size is in flux.
95 * jQuery(window).on('resize', debounce(calculateLayout, 150))
96 *
97 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
98 * jQuery(element).on('click', debounce(sendMail, 300, {
99 * 'leading': true,
100 * 'trailing': false
101 * }))
102 *
103 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
104 * const debounced = debounce(batchLog, 250, { 'maxWait': 1000 })
105 * const source = new EventSource('/stream')
106 * jQuery(source).on('message', debounced)
107 *
108 * // Cancel the trailing debounced invocation.
109 * jQuery(window).on('popstate', debounced.cancel)
110 *
111 * // Check for pending invocations.
112 * const status = debounced.pending() ? "Pending..." : "Ready"
113 */
114 function debounce(func, wait = 0, options = {}) {
115 let lastArgs, lastThis, maxWait, result, timerId, lastCallTime;
116 let lastInvokeTime = 0;
117 let leading = false;
118 let maxing = false;
119 let trailing = true;
120 // Bypass `requestAnimationFrame` by explicitly setting `wait=0`.
121 const useRAF = !wait && wait !== 0 && typeof root.requestAnimationFrame === "function";
122 if (typeof func !== "function") {
123 throw new TypeError("Expected a function");
124 }
125 wait = +wait || 0;
126 if (isObject(options)) {
127 leading = !!options.leading;
128 maxing = "maxWait" in options;
129 maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : maxWait;
130 trailing = "trailing" in options ? !!options.trailing : trailing;
131 }
132 function invokeFunc(time) {
133 const args = lastArgs;
134 const thisArg = lastThis;
135 lastArgs = lastThis = undefined;
136 lastInvokeTime = time;
137 result = func.apply(thisArg, args);
138 return result;
139 }
140 function startTimer(pendingFunc, wait) {
141 if (useRAF) {
142 root.cancelAnimationFrame(timerId);
143 return root.requestAnimationFrame(pendingFunc);
144 }
145 return setTimeout(pendingFunc, wait);
146 }
147 function cancelTimer(id) {
148 if (useRAF) {
149 return root.cancelAnimationFrame(id);
150 }
151 clearTimeout(id);
152 }
153 function leadingEdge(time) {
154 // Reset any `maxWait` timer.
155 lastInvokeTime = time;
156 // Start the timer for the trailing edge.
157 timerId = startTimer(timerExpired, wait);
158 // Invoke the leading edge.
159 return leading ? invokeFunc(time) : result;
160 }
161 function remainingWait(time) {
162 const timeSinceLastCall = time - lastCallTime;
163 const timeSinceLastInvoke = time - lastInvokeTime;
164 const timeWaiting = wait - timeSinceLastCall;
165 return maxing
166 ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)
167 : timeWaiting;
168 }
169 function shouldInvoke(time) {
170 const timeSinceLastCall = time - lastCallTime;
171 const timeSinceLastInvoke = time - lastInvokeTime;
172 // Either this is the first call, activity has stopped and we're at the
173 // trailing edge, the system time has gone backwards and we're treating
174 // it as the trailing edge, or we've hit the `maxWait` limit.
175 return (lastCallTime === undefined ||
176 timeSinceLastCall >= wait ||
177 timeSinceLastCall < 0 ||
178 (maxing && timeSinceLastInvoke >= maxWait));
179 }
180 function timerExpired() {
181 const time = Date.now();
182 if (shouldInvoke(time)) {
183 return trailingEdge(time);
184 }
185 // Restart the timer.
186 timerId = startTimer(timerExpired, remainingWait(time));
187 }
188 function trailingEdge(time) {
189 timerId = undefined;
190 // Only invoke if we have `lastArgs` which means `func` has been
191 // debounced at least once.
192 if (trailing && lastArgs) {
193 return invokeFunc(time);
194 }
195 lastArgs = lastThis = undefined;
196 return result;
197 }
198 function cancel() {
199 if (timerId !== undefined) {
200 cancelTimer(timerId);
201 }
202 lastInvokeTime = 0;
203 lastArgs = lastCallTime = lastThis = timerId = undefined;
204 }
205 function flush() {
206 return timerId === undefined ? result : trailingEdge(Date.now());
207 }
208 function pending() {
209 return timerId !== undefined;
210 }
211 function debounced(...args) {
212 const time = Date.now();
213 const isInvoking = shouldInvoke(time);
214 lastArgs = args;
215 // eslint-disable-next-line @typescript-eslint/no-this-alias
216 lastThis = this;
217 lastCallTime = time;
218 if (isInvoking) {
219 if (timerId === undefined) {
220 return leadingEdge(lastCallTime);
221 }
222 if (maxing) {
223 // Handle invocations in a tight loop.
224 timerId = startTimer(timerExpired, wait);
225 return invokeFunc(lastCallTime);
226 }
227 }
228 if (timerId === undefined) {
229 timerId = startTimer(timerExpired, wait);
230 }
231 return result;
232 }
233 debounced.cancel = cancel;
234 debounced.flush = flush;
235 debounced.pending = pending;
236 return debounced;
237 }
238 /**
239 * Creates a throttled function that only invokes `func` at most once per
240 * every `wait` milliseconds (or once per browser frame). The throttled function
241 * comes with a `cancel` method to cancel delayed `func` invocations and a
242 * `flush` method to immediately invoke them. Provide `options` to indicate
243 * whether `func` should be invoked on the leading and/or trailing edge of the
244 * `wait` timeout. The `func` is invoked with the last arguments provided to the
245 * throttled function. Subsequent calls to the throttled function return the
246 * result of the last `func` invocation.
247 *
248 * **Note:** If `leading` and `trailing` options are `true`, `func` is
249 * invoked on the trailing edge of the timeout only if the throttled function
250 * is invoked more than once during the `wait` timeout.
251 *
252 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
253 * until the next tick, similar to `setTimeout` with a timeout of `0`.
254 *
255 * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
256 * invocation will be deferred until the next frame is drawn (typically about
257 * 16ms).
258 *
259 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
260 * for details over the differences between `throttle` and `debounce`.
261 *
262 * @since 0.1.0
263 * @category Function
264 * @param {Function} func The function to throttle.
265 * @param {number} [wait=0]
266 * The number of milliseconds to throttle invocations to; if omitted,
267 * `requestAnimationFrame` is used (if available).
268 * @param [options={}] The options object.
269 * @returns {Function} Returns the new throttled function.
270 * @example
271 *
272 * // Avoid excessively updating the position while scrolling.
273 * jQuery(window).on('scroll', throttle(updatePosition, 100))
274 *
275 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
276 * const throttled = throttle(renewToken, 300000, { 'trailing': false })
277 * jQuery(element).on('click', throttled)
278 *
279 * // Cancel the trailing throttled invocation.
280 * jQuery(window).on('popstate', throttled.cancel)
281 */
282 function throttle(func, wait = 0, options = {}) {
283 let leading = true;
284 let trailing = true;
285 if (typeof func !== "function") {
286 throw new TypeError("Expected a function");
287 }
288 if (isObject(options)) {
289 leading = "leading" in options ? !!options.leading : leading;
290 trailing = "trailing" in options ? !!options.trailing : trailing;
291 }
292 return debounce(func, wait, {
293 leading,
294 trailing,
295 maxWait: wait,
296 });
297 }
298
299 /*!
300 * Wunderbaum - util
301 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
302 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
303 */
304 /** @module util */
305 /** Readable names for `MouseEvent.button` */
306 const MOUSE_BUTTONS = {
307 0: "",
308 1: "left",
309 2: "middle",
310 3: "right",
311 4: "back",
312 5: "forward",
313 };
314 const MAX_INT = 9007199254740991;
315 const userInfo = _getUserInfo();
316 /**True if the client is using a macOS platform. */
317 const isMac = userInfo.isMac;
318 const REX_HTML = /[&<>"'/]/g; // Escape those characters
319 const REX_TOOLTIP = /[<>"'/]/g; // Don't escape `&` in tooltips
320 const ENTITY_MAP = {
321 "&": "&amp;",
322 "<": "&lt;",
323 ">": "&gt;",
324 '"': "&quot;",
325 "'": "&#39;",
326 "/": "&#x2F;",
327 };
328 /** A generic error that can be thrown to indicate a validation error when
329 * handling the `apply` event for a node title or the `change` event for a
330 * grid cell.
331 */
332 class ValidationError extends Error {
333 constructor(message) {
334 super(message);
335 this.name = "ValidationError";
336 }
337 }
338 /**
339 * A ES6 Promise, that exposes the resolve()/reject() methods.
340 *
341 * TODO: See [Promise.withResolvers()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers#description)
342 * , a proposed standard, but not yet implemented in any browser.
343 */
344 let Deferred$1 = class Deferred {
345 constructor() {
346 this.thens = [];
347 this.catches = [];
348 this.status = "";
349 }
350 resolve(value) {
351 if (this.status) {
352 throw new Error("already settled");
353 }
354 this.status = "resolved";
355 this.resolvedValue = value;
356 this.thens.forEach((t) => t(value));
357 this.thens = []; // Avoid memleaks.
358 }
359 reject(error) {
360 if (this.status) {
361 throw new Error("already settled");
362 }
363 this.status = "rejected";
364 this.rejectedError = error;
365 this.catches.forEach((c) => c(error));
366 this.catches = []; // Avoid memleaks.
367 }
368 then(cb) {
369 if (status === "resolved") {
370 cb(this.resolvedValue);
371 }
372 else {
373 this.thens.unshift(cb);
374 }
375 }
376 catch(cb) {
377 if (this.status === "rejected") {
378 cb(this.rejectedError);
379 }
380 else {
381 this.catches.unshift(cb);
382 }
383 }
384 promise() {
385 return {
386 then: this.then,
387 catch: this.catch,
388 };
389 }
390 };
391 /**Throw an `Error` if `cond` is falsey. */
392 function assert(cond, msg) {
393 if (!cond) {
394 msg = msg || "Assertion failed.";
395 throw new Error(msg);
396 }
397 }
398 function _getUserInfo() {
399 const nav = navigator;
400 // const ua = nav.userAgentData;
401 const res = {
402 isMac: /Mac/.test(nav.platform),
403 };
404 return res;
405 }
406 /** Run `callback` when document was loaded. */
407 function documentReady(callback) {
408 if (document.readyState === "loading") {
409 document.addEventListener("DOMContentLoaded", callback);
410 }
411 else {
412 callback();
413 }
414 }
415 /** Resolve when document was loaded. */
416 function documentReadyPromise() {
417 return new Promise((resolve) => {
418 documentReady(resolve);
419 });
420 }
421 /**
422 * Iterate over Object properties or array elements.
423 *
424 * @param obj `Object`, `Array` or null
425 * @param callback called for every item.
426 * `this` also contains the item.
427 * Return `false` to stop the iteration.
428 */
429 function each(obj, callback) {
430 if (obj == null) {
431 // accept `null` or `undefined`
432 return obj;
433 }
434 const length = obj.length;
435 let i = 0;
436 if (typeof length === "number") {
437 for (; i < length; i++) {
438 if (callback.call(obj[i], i, obj[i]) === false) {
439 break;
440 }
441 }
442 }
443 else {
444 for (const k in obj) {
445 if (callback.call(obj[i], k, obj[k]) === false) {
446 break;
447 }
448 }
449 }
450 return obj;
451 }
452 /** Shortcut for `throw new Error(msg)`.*/
453 function error(msg) {
454 throw new Error(msg);
455 }
456 /** Convert `<`, `>`, `&`, `"`, `'`, and `/` to the equivalent entities. */
457 function escapeHtml(s) {
458 return ("" + s).replace(REX_HTML, function (s) {
459 return ENTITY_MAP[s];
460 });
461 }
462 // export function escapeRegExp(s: string) {
463 // return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
464 // }
465 /**Convert a regular expression string by escaping special characters (e.g. `"$"` -> `"\$"`) */
466 function escapeRegex(s) {
467 return ("" + s).replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
468 }
469 /** Convert `<`, `>`, `"`, `'`, and `/` (but not `&`) to the equivalent entities. */
470 function escapeTooltip(s) {
471 return ("" + s).replace(REX_TOOLTIP, function (s) {
472 return ENTITY_MAP[s];
473 });
474 }
475 /** TODO */
476 function extractHtmlText(s) {
477 if (s.indexOf(">") >= 0) {
478 error("Not implemented");
479 // return $("<div/>").html(s).text();
480 }
481 return s;
482 }
483 /**
484 * Read the value from an HTML input element.
485 *
486 * If a `<span class="wb-col">` is passed, the first child input is used.
487 * Depending on the target element type, `value` is interpreted accordingly.
488 * For example for a checkbox, a value of true, false, or null is returned if
489 * the element is checked, unchecked, or indeterminate.
490 * For datetime input control a numerical value is assumed, etc.
491 *
492 * Common use case: store the new user input in a `change` event handler:
493 *
494 * ```ts
495 * change: (e) => {
496 * const tree = e.tree;
497 * const node = e.node;
498 * // Read the value from the input control that triggered the change event:
499 * let value = tree.getValueFromElem(e.element);
500 * // and store it to the node model (assuming the column id matches the property name)
501 * node.data[e.info.colId] = value;
502 * },
503 * ```
504 * @param elem `<input>` or `<select>` element. Also a parent `span.wb-col` is accepted.
505 * @param coerce pass true to convert date/time inputs to `Date`.
506 * @returns the value
507 */
508 function getValueFromElem(elem, coerce = false) {
509 const tag = elem.tagName;
510 let value = null;
511 if (tag === "SPAN" && elem.classList.contains("wb-col")) {
512 const span = elem;
513 const embeddedInput = span.querySelector("input,select");
514 if (embeddedInput) {
515 return getValueFromElem(embeddedInput, coerce);
516 }
517 span.innerText = "" + value;
518 }
519 else if (tag === "INPUT") {
520 const input = elem;
521 const type = input.type;
522 switch (type) {
523 case "button":
524 case "reset":
525 case "submit":
526 case "image":
527 break;
528 case "checkbox":
529 value = input.indeterminate ? null : input.checked;
530 break;
531 case "date":
532 case "datetime":
533 case "datetime-local":
534 case "month":
535 case "time":
536 case "week":
537 value = coerce ? input.valueAsDate : input.value;
538 break;
539 case "number":
540 case "range":
541 value = input.valueAsNumber;
542 break;
543 case "radio":
544 {
545 const name = input.name;
546 const checked = input.parentElement.querySelector(`input[name="${name}"]:checked`);
547 value = checked ? checked.value : undefined;
548 }
549 break;
550 case "text":
551 default:
552 value = input.value;
553 }
554 }
555 else if (tag === "SELECT") {
556 const select = elem;
557 value = select.value;
558 }
559 return value;
560 }
561 /**
562 * Set the value of an HTML input element.
563 *
564 * If a `<span class="wb-col">` is passed, the first child input is used.
565 * Depending on the target element type, `value` is interpreted accordingly.
566 * For example a checkbox is set to checked, unchecked, or indeterminate if the
567 * value is truethy, falsy, or `null`.
568 * For datetime input control a numerical value is assumed, etc.
569 *
570 * Common use case: update embedded input controls in a `render` event handler:
571 *
572 * ```ts
573 * render: (e) => {
574 * // e.node.log(e.type, e, e.node.data);
575 *
576 * for (const col of Object.values(e.renderColInfosById)) {
577 * switch (col.id) {
578 * default:
579 * // Assumption: we named column.id === node.data.NAME
580 * util.setValueToElem(col.elem, e.node.data[col.id]);
581 * break;
582 * }
583 * }
584 * },
585 * ```
586 *
587 * @param elem `<input>` or `<select>` element Also a parent `span.wb-col` is accepted.
588 * @param value a value that matches the target element.
589 */
590 function setValueToElem(elem, value) {
591 const tag = elem.tagName;
592 if (tag === "SPAN" && elem.classList.contains("wb-col")) {
593 const span = elem;
594 const embeddedInput = span.querySelector("input,select");
595 if (embeddedInput) {
596 return setValueToElem(embeddedInput, value);
597 }
598 // No embedded input: simply write as escaped html
599 span.innerText = "" + value;
600 }
601 else if (tag === "INPUT") {
602 const input = elem;
603 const type = input.type;
604 switch (type) {
605 case "checkbox":
606 // An explicit `null` value is interpreted as 'indeterminate'.
607 // `undefined` is interpreted as 'unchecked'
608 input.indeterminate = value === null;
609 input.checked = !!value;
610 break;
611 case "date":
612 case "month":
613 case "time":
614 case "week":
615 case "datetime":
616 case "datetime-local":
617 input.valueAsDate = new Date(value);
618 break;
619 case "number":
620 case "range":
621 if (value == null) {
622 input.value = value;
623 }
624 else {
625 input.valueAsNumber = value;
626 }
627 break;
628 case "radio":
629 error(`Not yet implemented: ${type}`);
630 // const name = input.name;
631 // const checked = input.parentElement!.querySelector(
632 // `input[name="${name}"]:checked`
633 // );
634 // value = checked ? (<HTMLInputElement>checked).value : undefined;
635 break;
636 case "button":
637 case "reset":
638 case "submit":
639 case "image":
640 break;
641 case "text":
642 default:
643 input.value = value !== null && value !== void 0 ? value : "";
644 }
645 }
646 else if (tag === "SELECT") {
647 const select = elem;
648 if (value == null) {
649 select.selectedIndex = -1;
650 }
651 else {
652 select.value = value;
653 }
654 }
655 }
656 /** Show/hide element by setting the `display` style to 'none'. */
657 function setElemDisplay(elem, flag) {
658 const style = elemFromSelector(elem).style;
659 if (flag) {
660 if (style.display === "none") {
661 style.display = "";
662 }
663 }
664 else if (style.display === "") {
665 style.display = "none";
666 }
667 }
668 /** Create and return an unconnected `HTMLElement` from a HTML string. */
669 function elemFromHtml(html) {
670 const t = document.createElement("template");
671 t.innerHTML = html.trim();
672 return t.content.firstElementChild;
673 }
674 const _IGNORE_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
675 /** Return a HtmlElement from selector or cast an existing element. */
676 function elemFromSelector(obj) {
677 if (!obj) {
678 return null; //(null as unknown) as HTMLElement;
679 }
680 if (typeof obj === "string") {
681 return document.querySelector(obj);
682 }
683 return obj;
684 }
685 /**
686 * Return a canonical descriptive string for a keyboard or mouse event.
687 *
688 * The result also contains a prefix for modifiers if any, for example
689 * `"x"`, `"F2"`, `"Control+Home"`, or `"Shift+clickright"`.
690 * This is especially useful in `switch` statements, to make sure that modifier
691 * keys are considered and handled correctly:
692 * ```ts
693 * const eventName = util.eventToString(e);
694 * switch (eventName) {
695 * case "+":
696 * case "Add":
697 * ...
698 * break;
699 * case "Enter":
700 * case "End":
701 * case "Control+End":
702 * case "Meta+ArrowDown":
703 * case "PageDown":
704 * ...
705 * break;
706 * }
707 * ```
708 */
709 function eventToString(event) {
710 const key = event.key;
711 const et = event.type;
712 const s = [];
713 if (event.altKey) {
714 s.push("Alt");
715 }
716 if (event.ctrlKey) {
717 s.push("Control");
718 }
719 if (event.metaKey) {
720 s.push("Meta");
721 }
722 if (event.shiftKey) {
723 s.push("Shift");
724 }
725 if (et === "click" || et === "dblclick") {
726 s.push(MOUSE_BUTTONS[event.button] + et);
727 }
728 else if (et === "wheel") {
729 s.push(et);
730 // } else if (!IGNORE_KEYCODES[key]) {
731 // s.push(
732 // SPECIAL_KEYCODES[key] ||
733 // String.fromCharCode(key).toLowerCase()
734 // );
735 }
736 else if (!_IGNORE_KEYS.has(key)) {
737 s.push(key);
738 }
739 return s.join("+");
740 }
741 /**
742 * Copy allproperties from one or more source objects to a target object.
743 *
744 * @returns the modified target object.
745 */
746 // TODO: use Object.assign()? --> https://stackoverflow.com/a/42740894
747 // TODO: support deep merge --> https://stackoverflow.com/a/42740894
748 function extend(...args) {
749 for (let i = 1; i < args.length; i++) {
750 const arg = args[i];
751 if (arg == null) {
752 continue;
753 }
754 for (const key in arg) {
755 if (Object.prototype.hasOwnProperty.call(arg, key)) {
756 args[0][key] = arg[key];
757 }
758 }
759 }
760 return args[0];
761 }
762 /** Return true if `obj` is of type `array`. */
763 function isArray(obj) {
764 return Array.isArray(obj);
765 }
766 /** Return true if `obj` is of type `Object` and has no properties. */
767 function isEmptyObject(obj) {
768 return Object.keys(obj).length === 0 && obj.constructor === Object;
769 }
770 /** Return true if `obj` is of type `function`. */
771 function isFunction(obj) {
772 return typeof obj === "function";
773 }
774 /** Return true if `obj` is of type `Object`. */
775 function isPlainObject(obj) {
776 return Object.prototype.toString.call(obj) === "[object Object]";
777 }
778 /** A dummy function that does nothing ('no operation'). */
779 function noop(...args) { }
780 function onEvent(rootTarget, eventNames, selectorOrHandler, handlerOrNone) {
781 let selector, handler;
782 rootTarget = elemFromSelector(rootTarget);
783 // rootTarget = eventTargetFromSelector<EventTarget>(rootTarget)!;
784 if (handlerOrNone) {
785 selector = selectorOrHandler;
786 handler = handlerOrNone;
787 }
788 else {
789 selector = "";
790 handler = selectorOrHandler;
791 }
792 eventNames.split(" ").forEach((evn) => {
793 rootTarget.addEventListener(evn, function (e) {
794 if (!selector) {
795 return handler(e); // no event delegation
796 }
797 else if (e.target) {
798 let elem = e.target;
799 if (elem.matches(selector)) {
800 return handler(e);
801 }
802 elem = elem.closest(selector);
803 if (elem) {
804 return handler(e);
805 }
806 }
807 });
808 });
809 }
810 /** Return a wrapped handler method, that provides `this._super` and `this._superApply`.
811 *
812 * ```ts
813 // Implement `opts.createNode` event to add the 'draggable' attribute
814 overrideMethod(ctx.options, "createNode", (event, data) => {
815 // Default processing if any
816 this._super.apply(this, event, data);
817 // Add 'draggable' attribute
818 data.node.span.draggable = true;
819 });
820 ```
821 */
822 function overrideMethod(instance, methodName, handler, ctx) {
823 let prevSuper, prevSuperApply;
824 const self = ctx || instance;
825 const prevFunc = instance[methodName];
826 const _super = (...args) => {
827 return prevFunc.apply(self, args);
828 };
829 const _superApply = (argsArray) => {
830 return prevFunc.apply(self, argsArray);
831 };
832 const wrapper = (...args) => {
833 try {
834 prevSuper = self._super;
835 prevSuperApply = self._superApply;
836 self._super = _super;
837 self._superApply = _superApply;
838 return handler.apply(self, args);
839 }
840 finally {
841 self._super = prevSuper;
842 self._superApply = prevSuperApply;
843 }
844 };
845 instance[methodName] = wrapper;
846 }
847 /** Run function after ms milliseconds and return a promise that resolves when done. */
848 function setTimeoutPromise(callback, ms) {
849 return new Promise((resolve, reject) => {
850 setTimeout(() => {
851 try {
852 resolve(callback.apply(this));
853 }
854 catch (err) {
855 reject(err);
856 }
857 }, ms);
858 });
859 }
860 /**
861 * Wait `ms` microseconds.
862 *
863 * Example:
864 * ```js
865 * await sleep(1000);
866 * ```
867 * @param ms duration
868 * @returns
869 */
870 async function sleep(ms) {
871 return new Promise((resolve) => setTimeout(resolve, ms));
872 }
873 /**
874 * Set or rotate checkbox status with support for tri-state.
875 *
876 * An initial 'indeterminate' state becomes 'checked' on the first call.
877 *
878 * If the input element has the class 'wb-tristate' assigned, the sequence is:<br>
879 * 'indeterminate' -> 'checked' -> 'unchecked' -> 'indeterminate' -> ...<br>
880 * Otherwise we toggle like <br>
881 * 'checked' -> 'unchecked' -> 'checked' -> ...
882 */
883 function toggleCheckbox(element, value, tristate) {
884 const input = elemFromSelector(element);
885 assert(input.type === "checkbox", `Expected a checkbox: ${input.type}`);
886 tristate !== null && tristate !== void 0 ? tristate : (tristate = input.classList.contains("wb-tristate") || input.indeterminate);
887 if (value === undefined) {
888 const curValue = input.indeterminate ? null : input.checked;
889 switch (curValue) {
890 case true:
891 value = false;
892 break;
893 case false:
894 value = tristate ? null : true;
895 break;
896 case null:
897 value = true;
898 break;
899 }
900 }
901 input.indeterminate = value == null;
902 input.checked = !!value;
903 }
904 /**
905 * Return `opts.NAME` if opts is valid and
906 *
907 * @param opts dict, object, or null
908 * @param name option name (use dot notation to access extension option, e.g. `filter.mode`)
909 * @param defaultValue returned when `opts` is not an object, or does not have a NAME property
910 */
911 function getOption(opts, name, defaultValue = undefined) {
912 let ext;
913 // Lookup `name` in options dict
914 if (opts && name.indexOf(".") >= 0) {
915 [ext, name] = name.split(".");
916 opts = opts[ext];
917 }
918 const value = opts ? opts[name] : null;
919 // Use value from value options dict, fallback do default
920 return value !== null && value !== void 0 ? value : defaultValue;
921 }
922 /** Return the next value from a list of values (rotating). @since 0.11 */
923 function rotate(value, values) {
924 const idx = values.indexOf(value);
925 return values[(idx + 1) % values.length];
926 }
927 /** Convert an Array or space-separated string to a Set. */
928 function toSet(val) {
929 if (val instanceof Set) {
930 return val;
931 }
932 if (typeof val === "string") {
933 const set = new Set();
934 for (const c of val.split(" ")) {
935 set.add(c.trim());
936 }
937 return set;
938 }
939 if (Array.isArray(val)) {
940 return new Set(val);
941 }
942 throw new Error("Cannot convert to Set<string>: " + val);
943 }
944 /** Convert a pixel string to number.
945 * We accept a number or a string like '123px'. If undefined, the first default
946 * value that is a number or a string ending with 'px' is returned.
947 *
948 * Example:
949 * ```js
950 * let x = undefined;
951 * let y = "123px";
952 * const width = util.toPixel(x, y, 100); // returns 123
953 * ```
954 */
955 function toPixel(...defaults) {
956 for (const d of defaults) {
957 if (typeof d === "number") {
958 return d;
959 }
960 if (typeof d === "string" && d.endsWith("px")) {
961 return parseInt(d, 10);
962 }
963 assert(d == null, `Expected a number or string like '123px': ${d}`);
964 }
965 throw new Error(`Expected a string like '123px': ${defaults}`);
966 }
967 /** Return the the boolean value of the first non-null element.
968 * Example:
969 * ```js
970 * const opts = { flag: true };
971 * const value = util.toBool(opts.foo, opts.flag, false); // returns true
972 * ```
973 */
974 function toBool(...boolDefaults) {
975 for (const d of boolDefaults) {
976 if (d != null) {
977 return !!d;
978 }
979 }
980 throw new Error("No default boolean value provided");
981 }
982 /**
983 * Return `val` unless `val` is a number in which case we convert to boolean.
984 * This is useful when a boolean value is stored as a 0/1 (e.g. in JSON) and
985 * we still want to maintain string values. null and undefined are returned as
986 * is. E.g. `checkbox` may be boolean or 'radio'.
987 */
988 function intToBool(val) {
989 return typeof val === "number" ? !!val : val;
990 }
991 // /** Check if a string is contained in an Array or Set. */
992 // export function isAnyOf(s: string, items: Array<string>|Set<string>): boolean {
993 // return Array.prototype.includes.call(items, s)
994 // }
995 // /** Check if an Array or Set has at least one matching entry. */
996 // export function hasAnyOf(container: Array<string>|Set<string>, items: Array<string>): boolean {
997 // if (Array.isArray(container)) {
998 // return container.some(v => )
999 // }
1000 // return container.some(v => {})
1001 // // const container = toSet(items);
1002 // // const itemSet = toSet(items);
1003 // // Array.prototype.includes
1004 // // throw new Error("Cannot convert to Set<string>: " + val);
1005 // }
1006 /** Return a canonical string representation for an object's type (e.g. 'array', 'number', ...). */
1007 function type(obj) {
1008 return Object.prototype.toString
1009 .call(obj)
1010 .replace(/^\[object (.+)\]$/, "$1")
1011 .toLowerCase();
1012 }
1013 /**
1014 * Return a function that can be called instead of `callback`, but guarantees
1015 * a limited execution rate.
1016 * The execution rate is calculated based on the runtime duration of the
1017 * previous call.
1018 * Example:
1019 * ```js
1020 * throttledFoo = util.adaptiveThrottle(foo.bind(this), {});
1021 * throttledFoo();
1022 * throttledFoo();
1023 * ```
1024 */
1025 function adaptiveThrottle(callback, options) {
1026 const opts = Object.assign({
1027 minDelay: 16,
1028 defaultDelay: 200,
1029 maxDelay: 5000,
1030 delayFactor: 2.0,
1031 }, options);
1032 const minDelay = Math.max(16, +opts.minDelay);
1033 const maxDelay = +opts.maxDelay;
1034 let waiting = 0; // Initially, we're not waiting
1035 let pendingArgs = null;
1036 let pendingTimer = null;
1037 const throttledFn = (...args) => {
1038 if (waiting) {
1039 pendingArgs = args;
1040 // console.log(`adaptiveThrottle() queing request #${waiting}...`, args);
1041 waiting += 1;
1042 }
1043 else {
1044 // Prevent invocations while running or blocking
1045 waiting = 1;
1046 const useArgs = args; // pendingArgs || args;
1047 pendingArgs = null;
1048 // console.log(`adaptiveThrottle() execute...`, useArgs);
1049 const start = Date.now();
1050 try {
1051 callback.apply(this, useArgs);
1052 }
1053 catch (error) {
1054 console.error(error); // eslint-disable-line no-console
1055 }
1056 const elap = Date.now() - start;
1057 const curDelay = Math.min(Math.max(minDelay, elap * opts.delayFactor), maxDelay);
1058 const useDelay = Math.max(minDelay, curDelay - elap);
1059 // console.log(
1060 // `adaptiveThrottle() calling worker took ${elap}ms. delay = ${curDelay}ms, using ${useDelay}ms`,
1061 // pendingArgs
1062 // );
1063 pendingTimer = setTimeout(() => {
1064 // Unblock, and trigger pending requests if any
1065 // const skipped = waiting - 1;
1066 pendingTimer = null;
1067 waiting = 0; // And allow future invocations
1068 if (pendingArgs != null) {
1069 // There was another request while running or waiting
1070 // console.log(
1071 // `adaptiveThrottle() re-trigger (missed ${skipped})...`,
1072 // pendingArgs
1073 // );
1074 throttledFn.apply(this, pendingArgs);
1075 }
1076 }, useDelay);
1077 }
1078 };
1079 throttledFn.cancel = () => {
1080 if (pendingTimer) {
1081 clearTimeout(pendingTimer);
1082 pendingTimer = null;
1083 }
1084 pendingArgs = null;
1085 waiting = 0;
1086 };
1087 throttledFn.pending = () => {
1088 return !!pendingTimer;
1089 };
1090 throttledFn.flush = () => {
1091 throw new Error("Not implemented");
1092 };
1093 return throttledFn;
1094 }
1095
1096 var util = /*#__PURE__*/Object.freeze({
1097 __proto__: null,
1098 Deferred: Deferred$1,
1099 MAX_INT: MAX_INT,
1100 MOUSE_BUTTONS: MOUSE_BUTTONS,
1101 ValidationError: ValidationError,
1102 adaptiveThrottle: adaptiveThrottle,
1103 assert: assert,
1104 debounce: debounce,
1105 documentReady: documentReady,
1106 documentReadyPromise: documentReadyPromise,
1107 each: each,
1108 elemFromHtml: elemFromHtml,
1109 elemFromSelector: elemFromSelector,
1110 error: error,
1111 escapeHtml: escapeHtml,
1112 escapeRegex: escapeRegex,
1113 escapeTooltip: escapeTooltip,
1114 eventToString: eventToString,
1115 extend: extend,
1116 extractHtmlText: extractHtmlText,
1117 getOption: getOption,
1118 getValueFromElem: getValueFromElem,
1119 intToBool: intToBool,
1120 isArray: isArray,
1121 isEmptyObject: isEmptyObject,
1122 isFunction: isFunction,
1123 isMac: isMac,
1124 isPlainObject: isPlainObject,
1125 noop: noop,
1126 onEvent: onEvent,
1127 overrideMethod: overrideMethod,
1128 rotate: rotate,
1129 setElemDisplay: setElemDisplay,
1130 setTimeoutPromise: setTimeoutPromise,
1131 setValueToElem: setValueToElem,
1132 sleep: sleep,
1133 throttle: throttle,
1134 toBool: toBool,
1135 toPixel: toPixel,
1136 toSet: toSet,
1137 toggleCheckbox: toggleCheckbox,
1138 type: type
1139 });
1140
1141 /*!
1142 * Wunderbaum - types
1143 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
1144 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
1145 */
1146 /**
1147 * Possible values for {@link WunderbaumNode.update} and {@link Wunderbaum.update}.
1148 */
1149 var ChangeType;
1150 (function (ChangeType) {
1151 /** Re-render the whole viewport, headers, and all rows. */
1152 ChangeType["any"] = "any";
1153 /** A node's title, icon, columns, or status have changed. Update the existing row markup. */
1154 ChangeType["data"] = "data";
1155 /** The `tree.columns` definition has changed beyond simple width adjustments. */
1156 ChangeType["colStructure"] = "colStructure";
1157 /** The viewport/window was resized. Adjust layout attributes for all elements. */
1158 ChangeType["resize"] = "resize";
1159 /** A node's definition has changed beyond status and data. Re-render the whole row's markup. */
1160 ChangeType["row"] = "row";
1161 /** Nodes have been added, removed, etc. Update markup. */
1162 ChangeType["structure"] = "structure";
1163 /** A node's status has changed. Update current row's classes, to reflect active, selected, ... */
1164 ChangeType["status"] = "status";
1165 /** Vertical scroll event. Update the 'top' property of all rows. */
1166 ChangeType["scroll"] = "scroll";
1167 })(ChangeType || (ChangeType = {}));
1168 /** @internal */
1169 var RenderFlag;
1170 (function (RenderFlag) {
1171 RenderFlag["clearMarkup"] = "clearMarkup";
1172 RenderFlag["header"] = "header";
1173 RenderFlag["redraw"] = "redraw";
1174 RenderFlag["scroll"] = "scroll";
1175 })(RenderFlag || (RenderFlag = {}));
1176 /** Possible values for {@link WunderbaumNode.setStatus}. */
1177 var NodeStatusType;
1178 (function (NodeStatusType) {
1179 NodeStatusType["ok"] = "ok";
1180 NodeStatusType["loading"] = "loading";
1181 NodeStatusType["error"] = "error";
1182 NodeStatusType["noData"] = "noData";
1183 NodeStatusType["paging"] = "paging";
1184 })(NodeStatusType || (NodeStatusType = {}));
1185 /** Define the subregion of a node, where an event occurred. */
1186 var NodeRegion;
1187 (function (NodeRegion) {
1188 NodeRegion["unknown"] = "";
1189 NodeRegion["checkbox"] = "checkbox";
1190 NodeRegion["column"] = "column";
1191 NodeRegion["expander"] = "expander";
1192 NodeRegion["icon"] = "icon";
1193 NodeRegion["prefix"] = "prefix";
1194 NodeRegion["title"] = "title";
1195 })(NodeRegion || (NodeRegion = {}));
1196 /** Initial navigation mode and possible transition. */
1197 var NavModeEnum;
1198 (function (NavModeEnum) {
1199 /** Start with row mode, but allow cell-nav mode */
1200 NavModeEnum["startRow"] = "startRow";
1201 /** Cell-nav mode only */
1202 NavModeEnum["cell"] = "cell";
1203 /** Start in cell-nav mode, but allow row mode */
1204 NavModeEnum["startCell"] = "startCell";
1205 /** Row mode only */
1206 NavModeEnum["row"] = "row";
1207 })(NavModeEnum || (NavModeEnum = {}));
1208
1209 /*!
1210 * Wunderbaum - wb_extension_base
1211 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
1212 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
1213 */
1214 class WunderbaumExtension {
1215 constructor(tree, id, defaults) {
1216 this.enabled = true;
1217 this.tree = tree;
1218 this.id = id;
1219 this.treeOpts = tree.options;
1220 const opts = tree.options;
1221 if (this.treeOpts[id] === undefined) {
1222 opts[id] = this.extensionOpts = extend({}, defaults);
1223 }
1224 else {
1225 // TODO: do we break existing object instance references here?
1226 this.extensionOpts = extend({}, defaults, opts[id]);
1227 opts[id] = this.extensionOpts;
1228 }
1229 this.enabled = this.getPluginOption("enabled", true);
1230 }
1231 /** Called on tree (re)init after all extensions are added, but before loading.*/
1232 init() {
1233 this.tree.element.classList.add("wb-ext-" + this.id);
1234 }
1235 // protected callEvent(type: string, extra?: any): any {
1236 // let func = this.extensionOpts[type];
1237 // if (func) {
1238 // return func.call(
1239 // this.tree,
1240 // util.extend(
1241 // {
1242 // event: this.id + "." + type,
1243 // },
1244 // extra
1245 // )
1246 // );
1247 // }
1248 // }
1249 getPluginOption(name, defaultValue) {
1250 var _a;
1251 return (_a = this.extensionOpts[name]) !== null && _a !== void 0 ? _a : defaultValue;
1252 }
1253 setPluginOption(name, value) {
1254 this.extensionOpts[name] = value;
1255 }
1256 setEnabled(flag = true) {
1257 return this.setPluginOption("enabled", !!flag);
1258 // this.enabled = !!flag;
1259 }
1260 onKeyEvent(data) {
1261 return;
1262 }
1263 onRender(data) {
1264 return;
1265 }
1266 }
1267
1268 /*!
1269 * Wunderbaum - ext-filter
1270 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
1271 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
1272 */
1273 const START_MARKER = "\uFFF7";
1274 const END_MARKER = "\uFFF8";
1275 const RE_START_MARKER = new RegExp(escapeRegex(START_MARKER), "g");
1276 const RE_END_MARTKER = new RegExp(escapeRegex(END_MARKER), "g");
1277 class FilterExtension extends WunderbaumExtension {
1278 constructor(tree) {
1279 super(tree, "filter", {
1280 autoApply: true, // Re-apply last filter if lazy data is loaded
1281 autoExpand: false, // Expand all branches that contain matches while filtered
1282 matchBranch: false, // Whether to implicitly match all children of matched nodes
1283 connect: null, // Element or selector of an input control for filter query strings
1284 fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'
1285 hideExpanders: false, // Hide expanders if all child nodes are hidden by filter
1286 highlight: true, // Highlight matches by wrapping inside <mark> tags
1287 leavesOnly: false, // Match end nodes only
1288 mode: "dim", // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)
1289 noData: true, // Display a 'no data' status node if result is empty
1290 });
1291 this.queryInput = null;
1292 this.prevButton = null;
1293 this.nextButton = null;
1294 this.modeButton = null;
1295 this.matchInfoElem = null;
1296 this.lastFilterArgs = null;
1297 }
1298 init() {
1299 super.init();
1300 const connect = this.getPluginOption("connect");
1301 if (connect) {
1302 this._connectControls();
1303 }
1304 }
1305 setPluginOption(name, value) {
1306 super.setPluginOption(name, value);
1307 switch (name) {
1308 case "mode":
1309 this.tree.filterMode =
1310 value === "hide" ? "hide" : value === "mark" ? "mark" : "dim";
1311 this.tree.updateFilter();
1312 break;
1313 }
1314 }
1315 _updatedConnectedControls() {
1316 var _a;
1317 const filterActive = this.tree.filterMode !== null;
1318 const activeNode = this.tree.getActiveNode();
1319 const matchCount = filterActive ? this.countMatches() : 0;
1320 const strings = this.treeOpts.strings;
1321 let matchIdx = "?";
1322 if (this.matchInfoElem) {
1323 if (filterActive) {
1324 let info;
1325 if (matchCount === 0) {
1326 info = strings.noMatch;
1327 }
1328 else if (activeNode && activeNode.match >= 1) {
1329 matchIdx = (_a = activeNode.match) !== null && _a !== void 0 ? _a : "?";
1330 info = strings.matchIndex;
1331 }
1332 else {
1333 info = strings.queryResult;
1334 }
1335 info = info
1336 .replace("${count}", this.tree.count().toLocaleString())
1337 .replace("${match}", "" + matchIdx)
1338 .replace("${matches}", matchCount.toLocaleString());
1339 this.matchInfoElem.textContent = info;
1340 }
1341 else {
1342 this.matchInfoElem.textContent = "";
1343 }
1344 }
1345 if (this.nextButton instanceof HTMLButtonElement) {
1346 this.nextButton.disabled = !matchCount;
1347 }
1348 if (this.prevButton instanceof HTMLButtonElement) {
1349 this.prevButton.disabled = !matchCount;
1350 }
1351 if (this.modeButton) {
1352 this.modeButton.disabled = !filterActive;
1353 this.modeButton.classList.toggle("wb-filter-hide", this.tree.filterMode === "hide");
1354 }
1355 }
1356 _connectControls() {
1357 const tree = this.tree;
1358 const connect = this.getPluginOption("connect");
1359 if (!connect) {
1360 return;
1361 }
1362 this.queryInput = elemFromSelector(connect.inputElem);
1363 if (!this.queryInput) {
1364 throw new Error(`Invalid 'filter.connect' option: ${connect.inputElem}.`);
1365 }
1366 this.prevButton = elemFromSelector(connect.prevButton);
1367 this.nextButton = elemFromSelector(connect.nextButton);
1368 this.modeButton = elemFromSelector(connect.modeButton);
1369 this.matchInfoElem = elemFromSelector(connect.matchInfoElem);
1370 if (this.prevButton) {
1371 onEvent(this.prevButton, "click", () => {
1372 tree.findRelatedNode(tree.getActiveNode() || tree.getFirstChild(), "prevMatch");
1373 this._updatedConnectedControls();
1374 });
1375 }
1376 if (this.nextButton) {
1377 onEvent(this.nextButton, "click", () => {
1378 tree.findRelatedNode(tree.getActiveNode() || tree.getFirstChild(), "nextMatch");
1379 this._updatedConnectedControls();
1380 });
1381 }
1382 if (this.modeButton) {
1383 onEvent(this.modeButton, "click", (e) => {
1384 if (!this.tree.filterMode) {
1385 return;
1386 }
1387 this.setPluginOption("mode", tree.filterMode === "dim" ? "hide" : "dim");
1388 });
1389 }
1390 onEvent(this.queryInput, "input", debounce((e) => {
1391 this.filterNodes(this.queryInput.value.trim(), {});
1392 }, 700));
1393 this._updatedConnectedControls();
1394 }
1395 _applyFilterNoUpdate(filter, _opts) {
1396 return this.tree.runWithDeferredUpdate(() => {
1397 return this._applyFilterImpl(filter, _opts);
1398 });
1399 }
1400 _applyFilterImpl(filter, _opts) {
1401 var _a;
1402 let //temp,
1403 count = 0;
1404 const start = Date.now();
1405 const tree = this.tree;
1406 const treeOpts = tree.options;
1407 const prevAutoCollapse = treeOpts.autoCollapse;
1408 // Use default options from `tree.options.filter`, but allow to override them
1409 const opts = extend({}, treeOpts.filter, _opts);
1410 const hideMode = opts.mode === "hide";
1411 const matchBranch = !!opts.matchBranch;
1412 const leavesOnly = !!opts.leavesOnly && !matchBranch;
1413 let filterRegExp;
1414 let highlightRegExp;
1415 // Default to 'match title substring (case insensitive)'
1416 if (typeof filter === "string" || filter instanceof RegExp) {
1417 if (filter === "") {
1418 tree.logInfo("Passing an empty string as a filter is handled as clearFilter().");
1419 this.clearFilter();
1420 return 0;
1421 }
1422 if (opts.fuzzy) {
1423 assert(typeof filter === "string", "fuzzy filter must be a string");
1424 // See https://codereview.stackexchange.com/questions/23899/faster-javascript-fuzzy-string-matching-function/23905#23905
1425 // and http://www.quora.com/How-is-the-fuzzy-search-algorithm-in-Sublime-Text-designed
1426 // and http://www.dustindiaz.com/autocomplete-fuzzy-matching
1427 const matchReString = filter
1428 .split("")
1429 // Escaping the `filter` will not work because,
1430 // it gets further split into individual characters. So,
1431 // escape each character after splitting
1432 .map(escapeRegex)
1433 .reduce(function (a, b) {
1434 // create capture groups for parts that comes before
1435 // the character
1436 return a + "([^" + b + "]*)" + b;
1437 }, "");
1438 filterRegExp = new RegExp(matchReString, "i");
1439 // highlightRegExp = new RegExp(escapeRegex(filter), "gi");
1440 }
1441 else if (filter instanceof RegExp) {
1442 filterRegExp = filter;
1443 highlightRegExp = filter;
1444 }
1445 else {
1446 const matchReString = escapeRegex(filter); // make sure a '.' is treated literally
1447 filterRegExp = new RegExp(matchReString, "i");
1448 highlightRegExp = new RegExp(matchReString, "gi");
1449 }
1450 tree.logDebug(`Filtering nodes by '${filterRegExp}'`);
1451 // const re = new RegExp(match, "i");
1452 // const reHighlight = new RegExp(escapeRegex(filter), "gi");
1453 filter = (node) => {
1454 if (!node.title) {
1455 return false;
1456 }
1457 // let text = escapeTitles ? node.title : extractHtmlText(node.title);
1458 const text = node.title;
1459 // `.match` instead of `.test` to get the capture groups
1460 // const res = text.match(filterRegExp);
1461 const res = filterRegExp.exec(text);
1462 if (res && opts.highlight) {
1463 let highlightString;
1464 if (opts.fuzzy) {
1465 highlightString = _markFuzzyMatchedChars(text, res, true);
1466 }
1467 else {
1468 // #740: we must not apply the marks to escaped entity names, e.g. `&quot;`
1469 // Use some exotic characters to mark matches:
1470 highlightString = text.replace(highlightRegExp, function (s) {
1471 return START_MARKER + s + END_MARKER;
1472 });
1473 }
1474 // now we can escape the title...
1475 node.titleWithHighlight = escapeHtml(highlightString)
1476 // ... and finally insert the desired `<mark>` tags
1477 .replace(RE_START_MARKER, "<mark>")
1478 .replace(RE_END_MARTKER, "</mark>");
1479 }
1480 return !!res;
1481 };
1482 }
1483 tree.filterMode = (_a = opts.mode) !== null && _a !== void 0 ? _a : "dim";
1484 // eslint-disable-next-line prefer-rest-params
1485 this.lastFilterArgs = arguments;
1486 tree.element.classList.toggle("wb-ext-filter-hide", !!hideMode);
1487 tree.element.classList.toggle("wb-ext-filter-dim", opts.mode === "dim");
1488 tree.element.classList.toggle("wb-ext-filter-hide-expanders", !!opts.hideExpanders);
1489 // Reset current filter
1490 tree.root.subMatchCount = 0;
1491 tree.visit((node) => {
1492 delete node.match;
1493 delete node.titleWithHighlight;
1494 node.subMatchCount = 0;
1495 });
1496 tree.setStatus(NodeStatusType.ok);
1497 // Adjust node.hide, .match, and .subMatchCount properties
1498 treeOpts.autoCollapse = false; // #528
1499 tree.visit((node) => {
1500 if (leavesOnly && node.children != null) {
1501 return;
1502 }
1503 let res = filter(node);
1504 if (res === "skip") {
1505 node.visit(function (c) {
1506 c.match = undefined;
1507 }, true);
1508 return "skip";
1509 }
1510 let matchedByBranch = false;
1511 if ((matchBranch || res === "branch") && node.parent.match) {
1512 res = true;
1513 matchedByBranch = true;
1514 }
1515 if (res) {
1516 count++;
1517 node.match = count;
1518 node.visitParents((p) => {
1519 if (p !== node) {
1520 p.subMatchCount += 1;
1521 }
1522 // Expand match (unless this is no real match, but only a node in a matched branch)
1523 if (opts.autoExpand && !matchedByBranch && !p.expanded) {
1524 p.setExpanded(true, {
1525 noAnimation: true,
1526 noEvents: true,
1527 });
1528 p._filterAutoExpanded = true;
1529 }
1530 }, true);
1531 }
1532 });
1533 treeOpts.autoCollapse = prevAutoCollapse;
1534 if (count === 0 && opts.noData && hideMode) {
1535 if (typeof opts.noData === "string") {
1536 tree.root.setStatus(NodeStatusType.noData, { message: opts.noData });
1537 }
1538 else {
1539 tree.root.setStatus(NodeStatusType.noData);
1540 }
1541 }
1542 // Redraw whole tree
1543 tree.logDebug(`Filter '${filter}' found ${count} nodes in ${Date.now() - start} ms.`);
1544 this._updatedConnectedControls();
1545 return count;
1546 }
1547 /**
1548 * [ext-filter] Dim or hide nodes.
1549 */
1550 filterNodes(filter, options) {
1551 return this._applyFilterNoUpdate(filter, options);
1552 }
1553 /**
1554 * [ext-filter] Dim or hide whole branches.
1555 * @deprecated Use {@link filterNodes} instead and set `options.matchBranch: true`.
1556 */
1557 filterBranches(filter, options) {
1558 assert(options.matchBranch === undefined, "filterBranches() is deprecated.");
1559 options.matchBranch = true;
1560 return this._applyFilterNoUpdate(filter, options);
1561 }
1562 /**
1563 * [ext-filter] Return the number of matched nodes.
1564 */
1565 countMatches() {
1566 let n = 0;
1567 this.tree.visit((node) => {
1568 if (node.match && !node.statusNodeType) {
1569 n++;
1570 }
1571 });
1572 return n;
1573 }
1574 /**
1575 * [ext-filter] Re-apply current filter.
1576 */
1577 updateFilter() {
1578 var _a;
1579 const tree = this.tree;
1580 if (tree.filterMode &&
1581 this.lastFilterArgs &&
1582 ((_a = tree.options.filter) === null || _a === void 0 ? void 0 : _a.autoApply)) {
1583 // eslint-disable-next-line prefer-spread
1584 this._applyFilterNoUpdate.apply(this, this.lastFilterArgs);
1585 }
1586 else {
1587 tree.logWarn("updateFilter(): no filter active.");
1588 }
1589 this._updatedConnectedControls();
1590 }
1591 /**
1592 * [ext-filter] Reset the filter.
1593 */
1594 clearFilter() {
1595 const tree = this.tree;
1596 tree.enableUpdate(false);
1597 tree.setStatus(NodeStatusType.ok);
1598 // we also counted root node's subMatchCount
1599 delete tree.root.match;
1600 delete tree.root.subMatchCount;
1601 tree.visit((node) => {
1602 delete node.match;
1603 delete node.subMatchCount;
1604 delete node.titleWithHighlight;
1605 if (node._filterAutoExpanded && node.expanded) {
1606 node.setExpanded(false, {
1607 noAnimation: true,
1608 noEvents: true,
1609 });
1610 }
1611 delete node._filterAutoExpanded;
1612 });
1613 tree.filterMode = null;
1614 this.lastFilterArgs = null;
1615 tree.element.classList.remove(
1616 // "wb-ext-filter",
1617 "wb-ext-filter-dim", "wb-ext-filter-hide");
1618 this._updatedConnectedControls();
1619 tree.enableUpdate(true);
1620 }
1621 }
1622 /**
1623 * @description Marks the matching charecters of `text` either by `mark` or
1624 * by exotic*Chars (if `escapeTitles` is `true`) based on `matches`
1625 * which is an array of matching groups.
1626 * @param {string} text
1627 * @param {RegExpMatchArray} matches
1628 */
1629 function _markFuzzyMatchedChars(text, matches, escapeTitles = true) {
1630 const matchingIndices = [];
1631 // get the indices of matched characters (Iterate through `RegExpMatchArray`)
1632 for (let _matchingArrIdx = 1; _matchingArrIdx < matches.length; _matchingArrIdx++) {
1633 const _mIdx =
1634 // get matching char index by cumulatively adding
1635 // the matched group length
1636 matches[_matchingArrIdx].length +
1637 (_matchingArrIdx === 1 ? 0 : 1) +
1638 (matchingIndices[matchingIndices.length - 1] || 0);
1639 matchingIndices.push(_mIdx);
1640 }
1641 // Map each `text` char to its position and store in `textPoses`.
1642 const textPoses = text.split("");
1643 if (escapeTitles) {
1644 // If escaping the title, then wrap the matching char within exotic chars
1645 matchingIndices.forEach(function (v) {
1646 textPoses[v] = START_MARKER + textPoses[v] + END_MARKER;
1647 });
1648 }
1649 else {
1650 // Otherwise, Wrap the matching chars within `mark`.
1651 matchingIndices.forEach(function (v) {
1652 textPoses[v] = "<mark>" + textPoses[v] + "</mark>";
1653 });
1654 }
1655 // Join back the modified `textPoses` to create final highlight markup.
1656 return textPoses.join("");
1657 }
1658
1659 /*!
1660 * Wunderbaum - ext-keynav
1661 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
1662 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
1663 */
1664 const QUICKSEARCH_DELAY = 500;
1665 class KeynavExtension extends WunderbaumExtension {
1666 constructor(tree) {
1667 super(tree, "keynav", {});
1668 }
1669 _getEmbeddedInputElem(elem) {
1670 var _a;
1671 let input = null;
1672 if (elem && elem.type != null) {
1673 input = elem;
1674 }
1675 else {
1676 // ,[contenteditable]
1677 const ace = (_a = this.tree.getActiveColElem()) === null || _a === void 0 ? void 0 : _a.querySelector("input,select");
1678 if (ace) {
1679 input = ace;
1680 }
1681 }
1682 return input;
1683 }
1684 // /* Return the current cell's embedded input that has keyboard focus. */
1685 // protected _getFocusedInputElem(): HTMLInputElement | null {
1686 // const ace = this.tree
1687 // .getActiveColElem()
1688 // ?.querySelector<HTMLInputElement>("input:focus,select:focus");
1689 // return ace || null;
1690 // }
1691 /* Return true if the current cell's embedded input has keyboard focus. */
1692 _isCurInputFocused() {
1693 var _a;
1694 const ace = (_a = this.tree
1695 .getActiveColElem()) === null || _a === void 0 ? void 0 : _a.querySelector("input:focus,select:focus");
1696 return !!ace;
1697 }
1698 onKeyEvent(data) {
1699 const event = data.event;
1700 const tree = this.tree;
1701 const opts = data.options;
1702 const activate = !event.ctrlKey || opts.autoActivate;
1703 const curInput = this._getEmbeddedInputElem(event.target);
1704 const inputHasFocus = curInput && this._isCurInputFocused();
1705 const navModeOption = opts.navigationModeOption;
1706 let focusNode, eventName = eventToString(event), node = data.node, handled = true;
1707 // tree.log(`onKeyEvent: ${eventName}, curInput`, curInput);
1708 if (!tree.isEnabled()) {
1709 // tree.logDebug(`onKeyEvent ignored for disabled tree: ${eventName}`);
1710 return false;
1711 }
1712 // Let callback prevent default processing
1713 if (tree._callEvent("keydown", data) === false) {
1714 return false;
1715 }
1716 // Let ext-edit trigger editing
1717 if (tree._callMethod("edit._preprocessKeyEvent", data) === false) {
1718 return false;
1719 }
1720 // Set focus to active (or first node) if no other node has the focus yet
1721 if (!node) {
1722 const currentNode = tree.getFocusNode() || tree.getActiveNode();
1723 const firstNode = tree.getFirstChild();
1724 if (!currentNode && firstNode && eventName === "ArrowDown") {
1725 firstNode.logInfo("Keydown: activate first node.");
1726 firstNode.setActive();
1727 return;
1728 }
1729 focusNode = currentNode || firstNode;
1730 if (focusNode) {
1731 focusNode.setFocus();
1732 node = tree.getFocusNode();
1733 node.logInfo("Keydown: force focus on active node.");
1734 }
1735 }
1736 const isColspan = node.isColspan();
1737 if (tree.isRowNav()) {
1738 // -----------------------------------------------------------------------
1739 // --- Row Mode ---
1740 // -----------------------------------------------------------------------
1741 if (inputHasFocus) {
1742 // If editing an embedded input control, let the control handle all
1743 // keys. Only Enter and Escape should apply / discard, but keep the
1744 // keyboard focus.
1745 switch (eventName) {
1746 case "Enter":
1747 curInput.blur();
1748 tree.setFocus();
1749 break;
1750 case "Escape":
1751 node._render();
1752 tree.setFocus();
1753 break;
1754 }
1755 return;
1756 }
1757 // --- Quick-Search
1758 if (opts.quicksearch &&
1759 eventName.length === 1 &&
1760 /^\w$/.test(eventName) &&
1761 !curInput) {
1762 // Allow to search for longer streaks if typed in quickly
1763 const stamp = Date.now();
1764 if (stamp - tree.lastQuicksearchTime > QUICKSEARCH_DELAY) {
1765 tree.lastQuicksearchTerm = "";
1766 }
1767 tree.lastQuicksearchTime = stamp;
1768 tree.lastQuicksearchTerm += eventName;
1769 const matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode());
1770 if (matchNode) {
1771 matchNode.setActive(true, { event: event });
1772 }
1773 event.preventDefault();
1774 return;
1775 }
1776 // Pre-Evaluate expand/collapse action for LEFT/RIGHT
1777 switch (eventName) {
1778 case "Enter":
1779 if (node.isActive()) {
1780 if (node.isExpanded()) {
1781 eventName = "Subtract"; // callapse
1782 }
1783 else if (node.isExpandable(true)) {
1784 eventName = "Add"; // expand
1785 }
1786 }
1787 break;
1788 case "ArrowLeft":
1789 if (node.expanded) {
1790 eventName = "Subtract"; // collapse
1791 }
1792 break;
1793 case "ArrowRight":
1794 if (!node.expanded && node.isExpandable(true)) {
1795 eventName = "Add"; // expand
1796 }
1797 else if (navModeOption === NavModeEnum.startCell ||
1798 navModeOption === NavModeEnum.startRow) {
1799 event.preventDefault();
1800 tree.setCellNav();
1801 return false;
1802 }
1803 break;
1804 }
1805 // Standard navigation (row mode)
1806 switch (eventName) {
1807 case "+":
1808 case "Add":
1809 // case "=": // 187: '+' @ Chrome, Safari
1810 node.setExpanded(true);
1811 break;
1812 case "-":
1813 case "Subtract":
1814 node.setExpanded(false);
1815 break;
1816 case " ": // Space
1817 // if (node.isPagingNode()) {
1818 // tree._triggerNodeEvent("clickPaging", ctx, event);
1819 // } else
1820 if (node.getOption("checkbox")) {
1821 node.toggleSelected();
1822 }
1823 else {
1824 node.setActive(true, { event: event });
1825 }
1826 break;
1827 case "Enter":
1828 node.setActive(true, { event: event });
1829 break;
1830 case "ArrowDown":
1831 case "ArrowLeft":
1832 case "ArrowRight":
1833 case "ArrowUp":
1834 case "Backspace":
1835 case "End":
1836 case "Home":
1837 case "Control+End":
1838 case "Control+Home":
1839 case "Meta+ArrowDown":
1840 case "Meta+ArrowUp":
1841 case "PageDown":
1842 case "PageUp":
1843 node.navigate(eventName, { activate: activate, event: event });
1844 break;
1845 default:
1846 handled = false;
1847 }
1848 }
1849 else {
1850 // -----------------------------------------------------------------------
1851 // --- Cell Mode ---
1852 // -----------------------------------------------------------------------
1853 // // Standard navigation (cell mode)
1854 // if (isCellEditMode && INPUT_BREAKOUT_KEYS.has(eventName)) {
1855 // }
1856 // const curInput = this._getEmbeddedInputElem(null);
1857 const curInputType = curInput ? curInput.type || curInput.tagName : "";
1858 // const inputHasFocus = curInput && this._isCurInputFocused();
1859 const inputCanFocus = curInput && curInputType !== "checkbox";
1860 if (inputHasFocus) {
1861 if (eventName === "Escape") {
1862 node.logDebug(`Reset focused input on Escape`);
1863 // Discard changes and reset input validation state
1864 curInput.setCustomValidity("");
1865 node._render();
1866 // Keep cell-nav mode
1867 tree.setFocus();
1868 tree.setColumn(tree.activeColIdx);
1869 return;
1870 // } else if (!INPUT_BREAKOUT_KEYS.has(eventName)) {
1871 }
1872 else if (eventName !== "Enter") {
1873 if (curInput && curInput.checkValidity && !curInput.checkValidity()) {
1874 // Invalid input: ignore all keys except Enter and Escape
1875 node.logDebug(`Ignored ${eventName} inside invalid input`);
1876 return false;
1877 }
1878 // Let current `<input>` handle it
1879 node.logDebug(`Ignored ${eventName} inside focused input`);
1880 return;
1881 }
1882 // const curInputType = curInput.type || curInput.tagName;
1883 // const breakoutKeys = INPUT_KEYS[curInputType];
1884 // if (!breakoutKeys.includes(eventName)) {
1885 // node.logDebug(`Ignored ${eventName} inside ${curInputType} input`);
1886 // return;
1887 // }
1888 }
1889 else if (curInput) {
1890 // On a cell that has an embedded, unfocused <input>
1891 if (eventName.length === 1 && inputCanFocus) {
1892 // Typing a single char
1893 curInput.focus();
1894 curInput.value = "";
1895 node.logDebug(`Focus input: ${eventName}`);
1896 return false;
1897 }
1898 }
1899 if (eventName === "Tab") {
1900 eventName = "ArrowRight";
1901 handled = true;
1902 }
1903 else if (eventName === "Shift+Tab") {
1904 eventName = tree.activeColIdx > 0 ? "ArrowLeft" : "";
1905 handled = true;
1906 }
1907 switch (eventName) {
1908 case "+":
1909 case "Add":
1910 // case "=": // 187: '+' @ Chrome, Safari
1911 node.setExpanded(true);
1912 break;
1913 case "-":
1914 case "Subtract":
1915 node.setExpanded(false);
1916 break;
1917 case " ": // Space
1918 if (tree.activeColIdx === 0 && node.getOption("checkbox")) {
1919 node.toggleSelected();
1920 handled = true;
1921 }
1922 else if (curInput && curInputType === "checkbox") {
1923 curInput.click();
1924 // toggleCheckbox(curInput)
1925 // new Event("change")
1926 // curInput.change
1927 handled = true;
1928 }
1929 break;
1930 case "F2":
1931 if (curInput && !inputHasFocus && inputCanFocus) {
1932 curInput.focus();
1933 handled = true;
1934 }
1935 break;
1936 case "Enter":
1937 tree.setFocus(); // Blur prev. input if any
1938 if ((tree.activeColIdx === 0 || isColspan) && node.isExpandable()) {
1939 node.setExpanded(!node.isExpanded());
1940 handled = true;
1941 }
1942 else if (curInput && !inputHasFocus && inputCanFocus) {
1943 curInput.focus();
1944 handled = true;
1945 }
1946 break;
1947 case "Escape":
1948 tree.setFocus(); // Blur prev. input if any
1949 node.log(`keynav: focus tree...`);
1950 if (tree.isCellNav() && navModeOption !== NavModeEnum.cell) {
1951 node.log(`keynav: setCellNav(false)`);
1952 tree.setCellNav(false); // row-nav mode
1953 tree.setFocus(); //
1954 handled = true;
1955 }
1956 break;
1957 case "ArrowLeft":
1958 tree.setFocus(); // Blur prev. input if any
1959 if (isColspan && node.isExpanded()) {
1960 node.setExpanded(false);
1961 }
1962 else if (!isColspan && tree.activeColIdx > 0) {
1963 tree.setColumn(tree.activeColIdx - 1);
1964 }
1965 else if (navModeOption !== NavModeEnum.cell) {
1966 tree.setCellNav(false); // row-nav mode
1967 }
1968 handled = true;
1969 break;
1970 case "ArrowRight":
1971 tree.setFocus(); // Blur prev. input if any
1972 if (isColspan && !node.isExpanded()) {
1973 node.setExpanded();
1974 }
1975 else if (!isColspan &&
1976 tree.activeColIdx < tree.columns.length - 1) {
1977 tree.setColumn(tree.activeColIdx + 1);
1978 }
1979 handled = true;
1980 break;
1981 case "Home": // Generated by [Fn] + ArrowLeft on Mac
1982 // case "Meta+ArrowLeft":
1983 tree.setFocus(); // Blur prev. input if any
1984 if (!isColspan && tree.activeColIdx > 0) {
1985 tree.setColumn(0);
1986 }
1987 handled = true;
1988 break;
1989 case "End": // Generated by [Fn] + ArrowRight on Mac
1990 // case "Meta+ArrowRight":
1991 tree.setFocus(); // Blur prev. input if any
1992 if (!isColspan && tree.activeColIdx < tree.columns.length - 1) {
1993 tree.setColumn(tree.columns.length - 1);
1994 }
1995 handled = true;
1996 break;
1997 case "ArrowDown":
1998 case "ArrowUp":
1999 case "Backspace":
2000 case "Control+End": // Generated by Control + [Fn] + ArrowRight on Mac
2001 case "Control+Home": // Generated by Control + [Fn] + Arrowleft on Mac
2002 case "Meta+ArrowDown": // [⌘] + ArrowDown on Mac
2003 case "Meta+ArrowUp": // [⌘] + ArrowUp on Mac
2004 case "PageDown": // Generated by [Fn] + ArrowDown on Mac
2005 case "PageUp": // Generated by [Fn] + ArrowUp on Mac
2006 node.navigate(eventName, { activate: activate, event: event });
2007 // if (isCellEditMode) {
2008 // this._getEmbeddedInputElem(null, true); // set focus to input
2009 // }
2010 handled = true;
2011 break;
2012 default:
2013 handled = false;
2014 }
2015 }
2016 if (handled) {
2017 event.preventDefault();
2018 }
2019 return;
2020 }
2021 }
2022
2023 /*!
2024 * Wunderbaum - ext-logger
2025 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
2026 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
2027 */
2028 class LoggerExtension extends WunderbaumExtension {
2029 constructor(tree) {
2030 super(tree, "logger", {});
2031 this.ignoreEvents = new Set([
2032 "iconBadge",
2033 // "enhanceTitle",
2034 "render",
2035 "discard",
2036 ]);
2037 this.prefix = tree + ".ext-logger";
2038 }
2039 init() {
2040 const tree = this.tree;
2041 // this.ignoreEvents.add();
2042 if (tree.getOption("debugLevel") >= 4) {
2043 // const self = this;
2044 const ignoreEvents = this.ignoreEvents;
2045 const prefix = this.prefix;
2046 overrideMethod(tree, "callEvent", function (name, extra) {
2047 /* eslint-disable prefer-rest-params */
2048 if (ignoreEvents.has(name)) {
2049 return tree._superApply(arguments);
2050 }
2051 const start = Date.now();
2052 const res = tree._superApply(arguments);
2053 tree.logDebug(`${prefix}: callEvent('${name}') took ${Date.now() - start} ms.`, arguments[1]);
2054 return res;
2055 });
2056 }
2057 }
2058 onKeyEvent(data) {
2059 // this.tree.logInfo("onKeyEvent", eventToString(data.event), data);
2060 this.tree.logDebug(`${this.prefix}: onKeyEvent()`, data);
2061 return;
2062 }
2063 }
2064
2065 /*!
2066 * Wunderbaum - ext-dnd
2067 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
2068 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
2069 */
2070 const nodeMimeType = "application/x-wunderbaum-node";
2071 class DndExtension extends WunderbaumExtension {
2072 constructor(tree) {
2073 super(tree, "dnd", {
2074 autoExpandMS: 1500, // Expand nodes after n milliseconds of hovering
2075 // dropMarkerInsertOffsetX: -16, // Additional offset for drop-marker with hitMode = "before"/"after"
2076 // dropMarkerOffsetX: -24, // Absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
2077 // #1021 `document.body` is not available yet
2078 // dropMarkerParent: "body", // Root Container used for drop marker (could be a shadow root)
2079 multiSource: false, // true: Drag multiple (i.e. selected) nodes. Also a callback() is allowed
2080 effectAllowed: "all", // Restrict the possible cursor shapes and modifier operations (can also be set in the dragStart event)
2081 dropEffectDefault: "move", // Default dropEffect ('copy', 'link', or 'move') when no modifier is pressed (override in drag, dragOver).
2082 guessDropEffect: true, // Calculate from `effectAllowed` and modifier keys)
2083 preventForeignNodes: false, // Prevent dropping nodes from different Wunderbaum trees
2084 preventLazyParents: true, // Prevent dropping items on unloaded lazy Wunderbaum tree nodes
2085 preventNonNodes: false, // Prevent dropping items other than Wunderbaum tree nodes
2086 preventRecursion: true, // Prevent dropping nodes on own descendants
2087 preventSameParent: false, // Prevent dropping nodes under same direct parent
2088 preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. (move only)
2089 serializeClipboardData: true, // Serialize node data to dataTransfer object
2090 scroll: true, // Enable auto-scrolling while dragging
2091 scrollSensitivity: 20, // Active top/bottom margin in pixel
2092 // scrollnterval: 50, // Generate event every 50 ms
2093 scrollSpeed: 5, // Scroll pixel per 50 ms
2094 // setTextTypeJson: false, // Allow dragging of nodes to different IE windows
2095 sourceCopyHook: null, // Optional callback passed to `toDict` on dragStart @since 2.38
2096 // Events (drag support)
2097 dragStart: null, // Callback(sourceNode, data), return true, to enable dnd drag
2098 drag: null, // Callback(sourceNode, data)
2099 dragEnd: null, // Callback(sourceNode, data)
2100 // Events (drop support)
2101 dragEnter: null, // Callback(targetNode, data), return true, to enable dnd drop
2102 dragOver: null, // Callback(targetNode, data)
2103 dragExpand: null, // Callback(targetNode, data), return false to prevent autoExpand
2104 drop: null, // Callback(targetNode, data)
2105 dragLeave: null, // Callback(targetNode, data)
2106 });
2107 // public dropMarkerElem?: HTMLElement;
2108 this.srcNode = null;
2109 this.lastTargetNode = null;
2110 this.lastEnterStamp = 0;
2111 this.lastAllowedDropRegions = null;
2112 this.lastDropEffect = null;
2113 this.lastDropRegion = false;
2114 this.currentScrollDir = 0;
2115 this.applyScrollDirThrottled = throttle(this._applyScrollDir, 50);
2116 }
2117 init() {
2118 super.init();
2119 // Store the current scroll parent, which may be the tree
2120 // container, any enclosing div, or the document.
2121 // #761: scrollParent() always needs a container child
2122 // $temp = $("<span>").appendTo(this.$container);
2123 // this.$scrollParent = $temp.scrollParent();
2124 // $temp.remove();
2125 const tree = this.tree;
2126 const dndOpts = tree.options.dnd;
2127 // Enable drag support if dragStart() is specified:
2128 if (dndOpts.dragStart) {
2129 onEvent(tree.element, "dragstart drag dragend", this.onDragEvent.bind(this));
2130 }
2131 // Enable drop support if dragEnter() is specified:
2132 if (dndOpts.dragEnter) {
2133 onEvent(tree.element, "dragenter dragover dragleave drop", this.onDropEvent.bind(this));
2134 }
2135 }
2136 /** Cleanup classes after target node is no longer hovered. */
2137 _leaveNode() {
2138 // We remove the marker on dragenter from the previous target:
2139 const ltn = this.lastTargetNode;
2140 this.lastEnterStamp = 0;
2141 if (ltn) {
2142 ltn.setClass("wb-drop-target wb-drop-over wb-drop-after wb-drop-before", false);
2143 this.lastTargetNode = null;
2144 }
2145 }
2146 /** */
2147 unifyDragover(res) {
2148 if (res === false) {
2149 return false;
2150 }
2151 else if (res instanceof Set) {
2152 return res.size > 0 ? res : false;
2153 }
2154 else if (res === true) {
2155 return new Set(["over", "before", "after"]);
2156 }
2157 else if (typeof res === "string" || isArray(res)) {
2158 res = toSet(res);
2159 return res.size > 0 ? res : false;
2160 }
2161 throw new Error("Unsupported drop region definition: " + res);
2162 }
2163 /**
2164 * Calculates the drop region based on the drag event and the allowed drop regions.
2165 */
2166 _calcDropRegion(e, allowed) {
2167 const rowHeight = this.tree.options.rowHeightPx;
2168 const dy = e.offsetY;
2169 if (!allowed) {
2170 return false;
2171 }
2172 else if (allowed.size === 3) {
2173 return dy < 0.25 * rowHeight
2174 ? "before"
2175 : dy > 0.75 * rowHeight
2176 ? "after"
2177 : "over";
2178 }
2179 else if (allowed.size === 1 && allowed.has("over")) {
2180 return "over";
2181 }
2182 else {
2183 // Only 'before' and 'after':
2184 return dy > rowHeight / 2 ? "after" : "before";
2185 }
2186 // return "over";
2187 }
2188 /**
2189 * Guess drop effect (copy/link/move) using opinionated conventions.
2190 *
2191 * Default: dnd.dropEffectDefault
2192 */
2193 _guessDropEffect(e) {
2194 // const nativeDropEffect = e.dataTransfer?.dropEffect;
2195 var _a;
2196 // if (nativeDropEffect && nativeDropEffect !== "none") {
2197 // return nativeDropEffect;
2198 // }
2199 const dndOpts = this.treeOpts.dnd;
2200 const ea = (_a = dndOpts.effectAllowed) !== null && _a !== void 0 ? _a : "all";
2201 const canCopy = ["all", "copy", "copyLink", "copyMove"].includes(ea);
2202 const canLink = ["all", "link", "copyLink", "linkMove"].includes(ea);
2203 const canMove = ["all", "move", "copyMove", "linkMove"].includes(ea);
2204 let res = dndOpts.dropEffectDefault;
2205 if (dndOpts.guessDropEffect) {
2206 if (isMac) {
2207 if (e.altKey && canCopy) {
2208 res = "copy";
2209 }
2210 if (e.metaKey && canMove) {
2211 res = "move"; // command key
2212 }
2213 if (e.altKey && e.metaKey && canLink) {
2214 res = "link";
2215 }
2216 }
2217 else {
2218 if (e.ctrlKey && canCopy) {
2219 res = "copy";
2220 }
2221 if (e.shiftKey && canMove) {
2222 res = "move";
2223 }
2224 if (e.altKey && canLink) {
2225 res = "link";
2226 }
2227 }
2228 }
2229 return res;
2230 }
2231 /** Don't allow void operation ('drop on self').*/
2232 _isVoidDrop(targetNode, srcNode, dropRegion) {
2233 // this.tree.logDebug(
2234 // `_isVoidDrop: ${srcNode} -> ${dropRegion} ${targetNode}`
2235 // );
2236 // TODO: should be checked on move only
2237 if (!this.treeOpts.dnd.preventVoidMoves || !srcNode) {
2238 return false;
2239 }
2240 if ((dropRegion === "before" && targetNode === srcNode.getNextSibling()) ||
2241 (dropRegion === "after" && targetNode === srcNode.getPrevSibling())) {
2242 // this.tree.logDebug("Prevented before/after self");
2243 return true;
2244 }
2245 // Don't allow dropping nodes on own parent (or self)
2246 return srcNode === targetNode || srcNode.parent === targetNode;
2247 }
2248 /* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */
2249 _applyScrollDir() {
2250 if (this.isDragging() && this.currentScrollDir) {
2251 const dndOpts = this.tree.options.dnd;
2252 const sp = this.tree.element; // scroll parent
2253 const scrollTop = sp.scrollTop;
2254 if (this.currentScrollDir < 0) {
2255 sp.scrollTop = Math.max(0, scrollTop - dndOpts.scrollSpeed);
2256 }
2257 else if (this.currentScrollDir > 0) {
2258 sp.scrollTop = scrollTop + dndOpts.scrollSpeed;
2259 }
2260 }
2261 }
2262 /* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */
2263 _autoScroll(viewportY) {
2264 const tree = this.tree;
2265 const dndOpts = tree.options.dnd;
2266 const sensitivity = dndOpts.scrollSensitivity;
2267 const sp = tree.element; // scroll parent
2268 const headerHeight = tree.headerElement.clientHeight; // May be 0
2269 // const height = sp.clientHeight - headerHeight;
2270 // const height = sp.offsetHeight + headerHeight;
2271 const height = sp.offsetHeight;
2272 const scrollTop = sp.scrollTop;
2273 // tree.logDebug(
2274 // `autoScroll: height=${height}, scrollTop=${scrollTop}, viewportY=${viewportY}`
2275 // );
2276 this.currentScrollDir = 0;
2277 if (scrollTop > 0 &&
2278 viewportY > 0 &&
2279 viewportY <= sensitivity + headerHeight) {
2280 // Mouse in top 20px area: scroll up
2281 // sp.scrollTop = Math.max(0, scrollTop - dndOpts.scrollSpeed);
2282 this.currentScrollDir = -1;
2283 }
2284 else if (scrollTop < sp.scrollHeight - height &&
2285 viewportY >= height - sensitivity) {
2286 // Mouse in bottom 20px area: scroll down
2287 // sp.scrollTop = scrollTop + dndOpts.scrollSpeed;
2288 this.currentScrollDir = 1;
2289 }
2290 if (this.currentScrollDir) {
2291 this.applyScrollDirThrottled();
2292 }
2293 return sp.scrollTop - scrollTop;
2294 }
2295 /** Return true if a drag operation currently in progress. */
2296 isDragging() {
2297 return !!this.srcNode;
2298 }
2299 /**
2300 * Handle dragstart, drag and dragend events for the source node.
2301 */
2302 onDragEvent(e) {
2303 var _a;
2304 // const tree = this.tree;
2305 const dndOpts = this.treeOpts.dnd;
2306 const srcNode = Wunderbaum.getNode(e);
2307 if (!srcNode) {
2308 this.tree.logWarn(`onDragEvent.${e.type}: no node`);
2309 return;
2310 }
2311 if (["dragstart", "dragend"].includes(e.type)) {
2312 this.tree.logDebug(`onDragEvent.${e.type} srcNode: ${srcNode}`, e);
2313 }
2314 // --- dragstart ---
2315 if (e.type === "dragstart") {
2316 // Set a default definition of allowed effects
2317 e.dataTransfer.effectAllowed = dndOpts.effectAllowed; //"copyMove"; // "all";
2318 if (srcNode.isEditingTitle()) {
2319 srcNode.logDebug("Prevented dragging node in edit mode.");
2320 e.preventDefault();
2321 return false;
2322 }
2323 // Let user cancel the drag operation, override effectAllowed, etc.:
2324 const res = srcNode._callEvent("dnd.dragStart", { event: e });
2325 if (!res) {
2326 e.preventDefault();
2327 return false;
2328 }
2329 const nodeData = srcNode.toDict(true, (n) => {
2330 // We don't want to re-use the key on drop:
2331 n._orgKey = n.key;
2332 delete n.key;
2333 });
2334 nodeData._treeId = srcNode.tree.id;
2335 if (dndOpts.serializeClipboardData) {
2336 if (typeof dndOpts.serializeClipboardData === "function") {
2337 e.dataTransfer.setData(nodeMimeType, dndOpts.serializeClipboardData(nodeData, srcNode));
2338 }
2339 else {
2340 e.dataTransfer.setData(nodeMimeType, JSON.stringify(nodeData));
2341 }
2342 }
2343 // e.dataTransfer!.setData("text/html", $(node.span).html());
2344 if (!((_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.types.includes("text/plain"))) {
2345 e.dataTransfer.setData("text/plain", srcNode.title);
2346 }
2347 this.srcNode = srcNode;
2348 setTimeout(() => {
2349 // Decouple this call, so the CSS is applied to the node, but not to
2350 // the system generated drag image
2351 srcNode.setClass("wb-drag-source");
2352 }, 0);
2353 // --- drag ---
2354 }
2355 else if (e.type === "drag") {
2356 if (dndOpts.drag) {
2357 srcNode._callEvent("dnd.drag", { event: e });
2358 }
2359 // --- dragend ---
2360 }
2361 else if (e.type === "dragend") {
2362 srcNode.setClass("wb-drag-source", false);
2363 this.srcNode = null;
2364 if (this.lastTargetNode) {
2365 this._leaveNode();
2366 }
2367 srcNode._callEvent("dnd.dragEnd", { event: e });
2368 }
2369 return true;
2370 }
2371 /**
2372 * Handle dragenter, dragover, dragleave, drop events.
2373 */
2374 onDropEvent(e) {
2375 var _a;
2376 // const isLink = event.dataTransfer.types.includes("text/uri-list");
2377 const srcNode = this.srcNode;
2378 const srcTree = srcNode ? srcNode.tree : null;
2379 const targetNode = Wunderbaum.getNode(e);
2380 const dndOpts = this.treeOpts.dnd;
2381 const dt = e.dataTransfer;
2382 const dropRegion = this._calcDropRegion(e, this.lastAllowedDropRegions);
2383 /** Helper to log a message if predicate is false. */
2384 const _t = (pred, msg) => {
2385 if (pred) {
2386 this.tree.log(`Prevented drop operation (${msg}).`);
2387 }
2388 return pred;
2389 };
2390 if (!targetNode) {
2391 this._leaveNode();
2392 return;
2393 }
2394 if (["drop"].includes(e.type)) {
2395 this.tree.logDebug(`onDropEvent.${e.type} targetNode: ${targetNode}, ea: ${dt === null || dt === void 0 ? void 0 : dt.effectAllowed}, ` +
2396 `de: ${dt === null || dt === void 0 ? void 0 : dt.dropEffect}, cy: ${e.offsetY}, r: ${dropRegion}, srcNode: ${srcNode}`, e);
2397 }
2398 // --- dragenter ---
2399 if (e.type === "dragenter") {
2400 // this.tree.logWarn(` onDropEvent.${e.type} targetNode: ${targetNode}`, e);
2401 this.lastAllowedDropRegions = null;
2402 // `dragleave` is not reliable with event delegation, so we generate it
2403 // from dragenter:
2404 if (this.lastTargetNode && this.lastTargetNode !== targetNode) {
2405 this._leaveNode();
2406 }
2407 this.lastTargetNode = targetNode;
2408 this.lastEnterStamp = Date.now();
2409 if (
2410 // Don't drop on status node:
2411 _t(targetNode.isStatusNode(), "is status node") ||
2412 // Prevent dropping nodes from different Wunderbaum trees:
2413 _t(dndOpts.preventForeignNodes && targetNode.tree !== srcTree, "preventForeignNodes") ||
2414 // Prevent dropping items on unloaded lazy Wunderbaum tree nodes:
2415 _t(dndOpts.preventLazyParents && !targetNode.isLoaded(), "preventLazyParents") ||
2416 // Prevent dropping items other than Wunderbaum tree nodes:
2417 _t(dndOpts.preventNonNodes && !srcNode, "preventNonNodes") ||
2418 // Prevent dropping nodes on own descendants:
2419 _t(dndOpts.preventRecursion && (srcNode === null || srcNode === void 0 ? void 0 : srcNode.isAncestorOf(targetNode)), "preventRecursion") ||
2420 // Prevent dropping nodes under same direct parent:
2421 _t(dndOpts.preventSameParent &&
2422 srcNode &&
2423 targetNode.parent === srcNode.parent, "preventSameParent") ||
2424 // Don't allow void operation ('drop on self'): TODO: should be checked on move only
2425 _t(dndOpts.preventVoidMoves && targetNode === srcNode, "preventVoidMoves")) {
2426 dt.dropEffect = "none";
2427 // this.tree.log("Prevented drop operation");
2428 return true; // Prevent drop operation
2429 }
2430 // User may return a set of regions (or `false` to prevent drop)
2431 // Figure out a drop effect (copy/link/move) using opinated conventions.
2432 dt.dropEffect = this._guessDropEffect(e) || "none";
2433 let regionSet = targetNode._callEvent("dnd.dragEnter", {
2434 event: e,
2435 sourceNode: srcNode,
2436 });
2437 //
2438 regionSet = this.unifyDragover(regionSet);
2439 if (!regionSet) {
2440 dt.dropEffect = "none";
2441 return true; // Prevent drop operation
2442 }
2443 this.lastAllowedDropRegions = regionSet;
2444 this.lastDropEffect = dt.dropEffect;
2445 const region = this._calcDropRegion(e, this.lastAllowedDropRegions);
2446 targetNode.setClass("wb-drop-target");
2447 targetNode.setClass("wb-drop-over", region === "over");
2448 targetNode.setClass("wb-drop-before", region === "before");
2449 targetNode.setClass("wb-drop-after", region === "after");
2450 e.preventDefault(); // Allow drop (Drop operation is denied by default)
2451 return false;
2452 // --- dragover ---
2453 }
2454 else if (e.type === "dragover") {
2455 const viewportY = e.clientY - this.tree.element.offsetTop;
2456 this._autoScroll(viewportY);
2457 dt.dropEffect = this._guessDropEffect(e) || "none";
2458 targetNode._callEvent("dnd.dragOver", { event: e, sourceNode: srcNode });
2459 const region = this._calcDropRegion(e, this.lastAllowedDropRegions);
2460 this.lastDropRegion = region;
2461 this.lastDropEffect = dt.dropEffect;
2462 if (dndOpts.autoExpandMS > 0 &&
2463 targetNode.isExpandable(true) &&
2464 !targetNode._isLoading &&
2465 Date.now() - this.lastEnterStamp > dndOpts.autoExpandMS &&
2466 targetNode._callEvent("dnd.dragExpand", {
2467 event: e,
2468 sourceNode: srcNode,
2469 }) !== false) {
2470 targetNode.setExpanded();
2471 }
2472 if (!region || this._isVoidDrop(targetNode, srcNode, region)) {
2473 return; // We already rejected in dragenter
2474 }
2475 targetNode.setClass("wb-drop-over", region === "over");
2476 targetNode.setClass("wb-drop-before", region === "before");
2477 targetNode.setClass("wb-drop-after", region === "after");
2478 e.preventDefault(); // Allow drop (Drop operation is denied by default)
2479 return false;
2480 // --- dragleave ---
2481 }
2482 else if (e.type === "dragleave") {
2483 // NOTE: we cannot trust this event, since it is always fired,
2484 // Instead we remove the marker on dragenter
2485 targetNode._callEvent("dnd.dragLeave", { event: e, sourceNode: srcNode });
2486 // --- drop ---
2487 }
2488 else if (e.type === "drop") {
2489 e.stopPropagation(); // prevent browser from opening links?
2490 e.preventDefault(); // #69 prevent iOS browser from opening links
2491 this._leaveNode();
2492 const region = this.lastDropRegion;
2493 let nodeData = (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.getData(nodeMimeType);
2494 nodeData = nodeData ? JSON.parse(nodeData) : null;
2495 const srcNode = this.srcNode;
2496 const lastDropEffect = this.lastDropEffect;
2497 setTimeout(() => {
2498 // Decouple this call, because drop actions may prevent the dragend event
2499 // from being fired on some browsers
2500 targetNode._callEvent("dnd.drop", {
2501 event: e,
2502 region: region,
2503 suggestedDropMode: region === "over" ? "appendChild" : region,
2504 suggestedDropEffect: lastDropEffect,
2505 // suggestedDropEffect: e.dataTransfer?.dropEffect,
2506 sourceNode: srcNode,
2507 sourceNodeData: nodeData,
2508 });
2509 }, 10);
2510 }
2511 return false;
2512 }
2513 }
2514
2515 /*!
2516 * Wunderbaum - drag_observer
2517 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
2518 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
2519 */
2520 /**
2521 * Convert mouse- and touch events to 'dragstart', 'drag', and 'dragstop'.
2522 */
2523 class DragObserver {
2524 constructor(opts) {
2525 this.start = {
2526 event: null,
2527 x: 0,
2528 y: 0,
2529 altKey: false,
2530 ctrlKey: false,
2531 metaKey: false,
2532 shiftKey: false,
2533 };
2534 this.dragElem = null;
2535 this.dragging = false;
2536 this.customData = {};
2537 // TODO: touch events
2538 this.events = ["mousedown", "mouseup", "mousemove", "keydown"];
2539 if (!opts.root) {
2540 throw new Error("Missing `root` option.");
2541 }
2542 this.opts = Object.assign({ thresh: 5 }, opts);
2543 this.root = opts.root;
2544 this._handler = this.handleEvent.bind(this);
2545 this.events.forEach((type) => {
2546 this.root.addEventListener(type, this._handler);
2547 });
2548 }
2549 /** Unregister all event listeners. */
2550 disconnect() {
2551 this.events.forEach((type) => {
2552 this.root.removeEventListener(type, this._handler);
2553 });
2554 }
2555 getDragElem() {
2556 return this.dragElem;
2557 }
2558 isDragging() {
2559 return this.dragging;
2560 }
2561 stopDrag(cb_event) {
2562 if (this.dragging && this.opts.dragstop && cb_event) {
2563 cb_event.type = "dragstop";
2564 try {
2565 this.opts.dragstop(cb_event);
2566 }
2567 catch (err) {
2568 console.error("dragstop error", err); // eslint-disable-line no-console
2569 }
2570 }
2571 this.dragElem = null;
2572 this.dragging = false;
2573 this.start.event = null;
2574 this.customData = {};
2575 }
2576 handleEvent(e) {
2577 const type = e.type;
2578 const opts = this.opts;
2579 const cb_event = {
2580 type: e.type,
2581 startEvent: type === "mousedown" ? e : this.start.event,
2582 event: e,
2583 customData: this.customData,
2584 dragElem: this.dragElem,
2585 dx: e.pageX - this.start.x,
2586 dy: e.pageY - this.start.y,
2587 apply: undefined,
2588 };
2589 // console.log("handleEvent", type, cb_event);
2590 switch (type) {
2591 case "keydown":
2592 this.stopDrag(cb_event);
2593 break;
2594 case "mousedown":
2595 if (this.dragElem) {
2596 this.stopDrag(cb_event);
2597 break;
2598 }
2599 if (opts.selector) {
2600 let elem = e.target;
2601 if (elem.matches(opts.selector)) {
2602 this.dragElem = elem;
2603 }
2604 else {
2605 elem = elem.closest(opts.selector);
2606 if (elem) {
2607 this.dragElem = elem;
2608 }
2609 else {
2610 break; // no event delegation selector matched
2611 }
2612 }
2613 }
2614 this.start.event = e;
2615 this.start.x = e.pageX;
2616 this.start.y = e.pageY;
2617 this.start.altKey = e.altKey;
2618 this.start.ctrlKey = e.ctrlKey;
2619 this.start.metaKey = e.metaKey;
2620 this.start.shiftKey = e.shiftKey;
2621 break;
2622 case "mousemove":
2623 // TODO: debounce/throttle?
2624 // TODO: horizontal mode: ignore if dx unchanged
2625 if (!this.dragElem) {
2626 break;
2627 }
2628 if (!this.dragging) {
2629 if (opts.thresh) {
2630 const dist2 = cb_event.dx * cb_event.dx + cb_event.dy * cb_event.dy;
2631 if (dist2 < opts.thresh * opts.thresh) {
2632 break;
2633 }
2634 }
2635 cb_event.type = "dragstart";
2636 if (opts.dragstart(cb_event) === false) {
2637 this.stopDrag(cb_event);
2638 break;
2639 }
2640 this.dragging = true;
2641 }
2642 if (this.dragging && this.opts.drag) {
2643 cb_event.type = "drag";
2644 this.opts.drag(cb_event);
2645 }
2646 break;
2647 case "mouseup":
2648 if (!this.dragging) {
2649 this.stopDrag(cb_event);
2650 break;
2651 }
2652 if (e.button === 0) {
2653 cb_event.apply = true;
2654 }
2655 else {
2656 cb_event.apply = false;
2657 }
2658 this.stopDrag(cb_event);
2659 break;
2660 }
2661 }
2662 }
2663
2664 /*!
2665 * Wunderbaum - common
2666 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
2667 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
2668 */
2669 const DEFAULT_DEBUGLEVEL = 3; // Replaced by rollup script
2670 /**
2671 * Fixed height of a row in pixel. Must match the SCSS variable `$row-outer-height`.
2672 */
2673 const DEFAULT_ROW_HEIGHT = 22;
2674 /**
2675 * Fixed width of node icons in pixel. Must match the SCSS variable `$icon-outer-width`.
2676 */
2677 const ICON_WIDTH = 20;
2678 /**
2679 * Adjust the width of the title span, so overflow ellipsis work.
2680 * (2 x `$col-padding-x` + 3px rounding errors).
2681 */
2682 const TITLE_SPAN_PAD_Y = 7;
2683 /** Render row markup for N nodes above and below the visible viewport. */
2684 const RENDER_MAX_PREFETCH = 5;
2685 /** Minimum column width if not set otherwise. */
2686 const DEFAULT_MIN_COL_WIDTH = 4;
2687 /** Regular expression to detect if a string describes an image URL (in contrast
2688 * to a class name). Strings are considered image urls if they contain '.' or '/'.
2689 */
2690 const TEST_IMG = new RegExp(/\.|\//);
2691 // export const RECURSIVE_REQUEST_ERROR = "$recursive_request";
2692 // export const INVALID_REQUEST_TARGET_ERROR = "$request_target_invalid";
2693 /**
2694 * Default node icons for icon libraries
2695 *
2696 * - 'bootstrap': {@link https://icons.getbootstrap.com}
2697 * - 'fontawesome6' {@link https://fontawesome.com/icons}
2698 *
2699 */
2700 const iconMaps = {
2701 bootstrap: {
2702 error: "bi bi-exclamation-triangle",
2703 // loading: "bi bi-hourglass-split wb-busy",
2704 loading: "bi bi-chevron-right wb-busy",
2705 // loading: "bi bi-arrow-repeat wb-spin",
2706 // loading: '<div class="spinner-border spinner-border-sm" role="status"> <span class="visually-hidden">Loading...</span> </div>',
2707 // noData: "bi bi-search",
2708 noData: "bi bi-question-circle",
2709 expanderExpanded: "bi bi-chevron-down",
2710 // expanderExpanded: "bi bi-dash-square",
2711 expanderCollapsed: "bi bi-chevron-right",
2712 // expanderCollapsed: "bi bi-plus-square",
2713 expanderLazy: "bi bi-chevron-right wb-helper-lazy-expander",
2714 // expanderLazy: "bi bi-chevron-bar-right",
2715 checkChecked: "bi bi-check-square",
2716 checkUnchecked: "bi bi-square",
2717 checkUnknown: "bi bi-dash-square-dotted",
2718 radioChecked: "bi bi-circle-fill",
2719 radioUnchecked: "bi bi-circle",
2720 radioUnknown: "bi bi-record-circle",
2721 folder: "bi bi-folder2",
2722 folderOpen: "bi bi-folder2-open",
2723 folderLazy: "bi bi-folder-symlink",
2724 doc: "bi bi-file-earmark",
2725 colSortable: "bi bi-chevron-expand",
2726 // colSortable: "bi bi-arrow-down-up",
2727 // colSortAsc: "bi bi-chevron-down",
2728 // colSortDesc: "bi bi-chevron-up",
2729 colSortAsc: "bi bi-arrow-down",
2730 colSortDesc: "bi bi-arrow-up",
2731 colFilter: "bi bi-filter-circle",
2732 colFilterActive: "bi bi-filter-circle-fill wb-helper-invalid",
2733 colMenu: "bi bi-three-dots-vertical",
2734 },
2735 fontawesome6: {
2736 error: "fa-solid fa-triangle-exclamation",
2737 loading: "fa-solid fa-chevron-right fa-beat",
2738 noData: "fa-solid fa-circle-question",
2739 expanderExpanded: "fa-solid fa-chevron-down",
2740 expanderCollapsed: "fa-solid fa-chevron-right",
2741 expanderLazy: "fa-solid fa-chevron-right wb-helper-lazy-expander",
2742 checkChecked: "fa-regular fa-square-check",
2743 checkUnchecked: "fa-regular fa-square",
2744 checkUnknown: "fa-regular fa-square-minus",
2745 radioChecked: "fa-solid fa-circle",
2746 radioUnchecked: "fa-regular fa-circle",
2747 radioUnknown: "fa-regular fa-circle-question",
2748 folder: "fa-solid fa-folder-closed",
2749 folderOpen: "fa-regular fa-folder-open",
2750 folderLazy: "fa-solid fa-folder-plus",
2751 doc: "fa-regular fa-file",
2752 colSortable: "fa-solid fa-fw fa-sort",
2753 colSortAsc: "fa-solid fa-fw fa-sort-up",
2754 colSortDesc: "fa-solid fa-fw fa-sort-down",
2755 colFilter: "fa-solid fa-fw fa-filter",
2756 colFilterActive: "fa-solid fa-fw fa-filter wb-helper-invalid",
2757 colMenu: "fa-solid fa-fw fa-ellipsis-v",
2758 },
2759 };
2760 /** Dict keys that are evaluated by source loader (others are added to `tree.data` instead). */
2761 const RESERVED_TREE_SOURCE_KEYS = new Set([
2762 "_format", // reserved for future use
2763 "_keyMap", // Used for compressed data format
2764 "_positional", // Used for compressed data format
2765 "_typeList", // Used for compressed data format @deprecated
2766 "_valueMap", // Used for compressed data format
2767 "_version", // reserved for future use
2768 "children",
2769 "columns",
2770 "types",
2771 ]);
2772 // /** Key codes that trigger grid navigation, even when inside an input element. */
2773 // export const INPUT_BREAKOUT_KEYS: Set<string> = new Set([
2774 // // "ArrowDown",
2775 // // "ArrowUp",
2776 // "Enter",
2777 // "Escape",
2778 // ]);
2779 /** Map `KeyEvent.key` to navigation action. */
2780 const KEY_TO_NAVIGATION_MAP = {
2781 ArrowDown: "down",
2782 ArrowLeft: "left",
2783 ArrowRight: "right",
2784 ArrowUp: "up",
2785 Backspace: "parent",
2786 End: "lastCol",
2787 Home: "firstCol",
2788 "Control+End": "last",
2789 "Control+Home": "first",
2790 "Meta+ArrowDown": "last", // macOs
2791 "Meta+ArrowUp": "first", // macOs
2792 PageDown: "pageDown",
2793 PageUp: "pageUp",
2794 };
2795 /** Return a callback that returns true if the node title matches the string
2796 * or regular expression.
2797 * @see {@link WunderbaumNode.findAll}
2798 */
2799 function makeNodeTitleMatcher(match) {
2800 if (match instanceof RegExp) {
2801 return function (node) {
2802 return match.test(node.title);
2803 };
2804 }
2805 assert(typeof match === "string", `Expected a string or RegExp: ${match}`);
2806 // s = escapeRegex(s.toLowerCase());
2807 return function (node) {
2808 return node.title === match;
2809 // console.log("match " + node, node.title.toLowerCase().indexOf(match))
2810 // return node.title.toLowerCase().indexOf(match) >= 0;
2811 };
2812 }
2813 /** Return a callback that returns true if the node title starts with a string (case-insensitive). */
2814 function makeNodeTitleStartMatcher(s) {
2815 s = escapeRegex(s);
2816 const reMatch = new RegExp("^" + s, "i");
2817 return function (node) {
2818 return reMatch.test(node.title);
2819 };
2820 }
2821 /** Compare two nodes by title (case-insensitive). */
2822 function nodeTitleSorter(a, b) {
2823 const x = a.title.toLowerCase();
2824 const y = b.title.toLowerCase();
2825 return x === y ? 0 : x > y ? 1 : -1;
2826 }
2827 /**
2828 * Convert 'flat' to 'nested' format.
2829 *
2830 * Flat node entry format:
2831 * [PARENT_IDX, {KEY_VALUE_ARGS}]
2832 * or, if N _positional re defined:
2833 * [PARENT_IDX, POSITIONAL_ARG_1, POSITIONAL_ARG_2, ..., POSITIONAL_ARG_N]
2834 * Even if _positional additional are defined, KEY_VALUE_ARGS can be appended:
2835 * [PARENT_IDX, POSITIONAL_ARG_1, ..., {KEY_VALUE_ARGS}]
2836 *
2837 * 1. Parent-referencing list is converted to a list of nested dicts with
2838 * optional `children` properties.
2839 * 2. `[POSITIONAL_ARGS]` are added as dict attributes.
2840 */
2841 function unflattenSource(source) {
2842 var _a, _b, _c;
2843 const { _format, _keyMap = {}, _positional = [], children } = source;
2844 const _positionalCount = _positional.length;
2845 if (_format !== "flat") {
2846 throw new Error(`Expected source._format: "flat", but got ${_format}`);
2847 }
2848 if (_positionalCount && _positional.includes("children")) {
2849 throw new Error(`source._positional must not include "children": ${_positional}`);
2850 }
2851 let longToShort = _keyMap;
2852 if (_keyMap.t) {
2853 // Inverse keyMap was used (pre 0.7.0)
2854 // TODO: raise Error on final 1.x release
2855 const msg = `source._keyMap maps from long to short since v0.7.0. Flip key/value!`;
2856 console.warn(msg); // eslint-disable-line no-console
2857 longToShort = {};
2858 for (const [key, value] of Object.entries(_keyMap)) {
2859 longToShort[value] = key;
2860 }
2861 }
2862 const positionalShort = _positional.map((e) => { var _a; return (_a = longToShort[e]) !== null && _a !== void 0 ? _a : e; });
2863 const newChildren = [];
2864 const keyToNodeMap = {};
2865 const indexToNodeMap = {};
2866 const keyAttrName = (_a = longToShort["key"]) !== null && _a !== void 0 ? _a : "key";
2867 const childrenAttrName = (_b = longToShort["children"]) !== null && _b !== void 0 ? _b : "children";
2868 for (const [index, nodeTuple] of children.entries()) {
2869 // Node entry format:
2870 // [PARENT_ID, [POSITIONAL_ARGS]]
2871 // or
2872 // [PARENT_ID, POSITIONAL_ARG_1, POSITIONAL_ARG_2, ..., {KEY_VALUE_ARGS}]
2873 let kwargs;
2874 const [parentId, ...args] = nodeTuple;
2875 if (args.length === _positionalCount) {
2876 kwargs = {};
2877 }
2878 else if (args.length === _positionalCount + 1) {
2879 kwargs = args.pop();
2880 if (typeof kwargs !== "object") {
2881 throw new Error(`unflattenSource: Expected dict as last tuple element: ${nodeTuple}`);
2882 }
2883 }
2884 else {
2885 throw new Error(`unflattenSource: unexpected tuple length: ${nodeTuple}`);
2886 }
2887 // Free up some memory as we go
2888 nodeTuple[1] = null;
2889 if (nodeTuple[2] != null) {
2890 nodeTuple[2] = null;
2891 }
2892 // We keep `kwargs` as our new node definition. Then we add all positional
2893 // values to this object:
2894 args.forEach((val, positionalIdx) => {
2895 kwargs[positionalShort[positionalIdx]] = val;
2896 });
2897 args.length = 0;
2898 // Find the parent node. `null` means 'toplevel'. PARENT_ID may be the numeric
2899 // index of the source.children list. If PARENT_ID is a string, we search
2900 // a parent with node.key of this value.
2901 indexToNodeMap[index] = kwargs;
2902 const key = kwargs[keyAttrName];
2903 if (key != null) {
2904 keyToNodeMap[key] = kwargs;
2905 }
2906 let parentNode = null;
2907 if (parentId === null) ;
2908 else if (typeof parentId === "number") {
2909 parentNode = indexToNodeMap[parentId];
2910 if (parentNode === undefined) {
2911 throw new Error(`unflattenSource: Could not find parent node by index: ${parentId}.`);
2912 }
2913 }
2914 else {
2915 parentNode = keyToNodeMap[parentId];
2916 if (parentNode === undefined) {
2917 throw new Error(`unflattenSource: Could not find parent node by key: ${parentId}`);
2918 }
2919 }
2920 if (parentNode) {
2921 (_c = parentNode[childrenAttrName]) !== null && _c !== void 0 ? _c : (parentNode[childrenAttrName] = []);
2922 parentNode[childrenAttrName].push(kwargs);
2923 }
2924 else {
2925 newChildren.push(kwargs);
2926 }
2927 }
2928 source.children = newChildren;
2929 }
2930 /**
2931 * Decompresses the source data by
2932 * - converting from 'flat' to 'nested' format
2933 * - expanding short alias names to long names (if defined in _keyMap)
2934 * - resolving value indexes to value strings (if defined in _valueMap)
2935 *
2936 * @param source - The source object to be decompressed.
2937 * @returns void
2938 */
2939 function decompressSourceData(source) {
2940 let { _format, _version = 1, _keyMap, _valueMap } = source;
2941 assert(_version === 1, `Expected file version 1 instead of ${_version}`);
2942 let longToShort = _keyMap;
2943 let shortToLong = {};
2944 if (longToShort) {
2945 for (const [key, value] of Object.entries(longToShort)) {
2946 shortToLong[value] = key;
2947 }
2948 }
2949 // Fallback for old format (pre 0.7.0, using _keyMap in reverse direction)
2950 // TODO: raise Error on final 1.x release
2951 if (longToShort && longToShort.t) {
2952 const msg = `source._keyMap maps from long to short since v0.7.0. Flip key/value!`;
2953 console.warn(msg); // eslint-disable-line no-console
2954 [longToShort, shortToLong] = [shortToLong, longToShort];
2955 }
2956 // Fallback for old format (pre 0.7.0, using _typeList instead of _valueMap)
2957 // TODO: raise Error on final 1.x release
2958 if (source._typeList != null) {
2959 const msg = `source._typeList is deprecated since v0.7.0: use source._valueMap: {"type": [...]} instead.`;
2960 if (_valueMap != null) {
2961 throw new Error(msg);
2962 }
2963 else {
2964 console.warn(msg); // eslint-disable-line no-console
2965 _valueMap = { type: source._typeList };
2966 delete source._typeList;
2967 }
2968 }
2969 if (_format === "flat") {
2970 unflattenSource(source);
2971 }
2972 delete source._format;
2973 delete source._version;
2974 delete source._keyMap;
2975 delete source._valueMap;
2976 delete source._positional;
2977 function _iter(childList) {
2978 for (const node of childList) {
2979 // Iterate over a list of names, because we modify inside the loop
2980 // (for ... of ... does not allow this)
2981 Object.getOwnPropertyNames(node).forEach((propName) => {
2982 const value = node[propName];
2983 // Replace short names with long names if defined in _keyMap
2984 let longName = propName;
2985 if (_keyMap && shortToLong[propName] != null) {
2986 longName = shortToLong[propName];
2987 if (longName !== propName) {
2988 node[longName] = value;
2989 delete node[propName];
2990 }
2991 }
2992 // Replace type index with type name if defined in _valueMap
2993 if (_valueMap &&
2994 typeof value === "number" &&
2995 _valueMap[longName] != null) {
2996 const newValue = _valueMap[longName][value];
2997 if (newValue == null) {
2998 throw new Error(`Expected valueMap[${longName}][${value}] entry in [${_valueMap[longName]}]`);
2999 }
3000 node[longName] = newValue;
3001 }
3002 });
3003 // Recursion
3004 if (node.children) {
3005 _iter(node.children);
3006 }
3007 }
3008 }
3009 if (_keyMap || _valueMap) {
3010 _iter(source.children);
3011 }
3012 }
3013
3014 /*!
3015 * Wunderbaum - ext-grid
3016 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
3017 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
3018 */
3019 class GridExtension extends WunderbaumExtension {
3020 constructor(tree) {
3021 super(tree, "grid", {
3022 // throttle: 200,
3023 });
3024 this.observer = new DragObserver({
3025 root: window.document,
3026 selector: "span.wb-col-resizer-active",
3027 thresh: 4,
3028 // throttle: 400,
3029 dragstart: (e) => {
3030 const info = Wunderbaum.getEventInfo(e.startEvent);
3031 const colDef = info.colDef;
3032 const allow = colDef &&
3033 this.tree.element.contains(e.dragElem) &&
3034 toBool(colDef.resizable, tree.options.columnsResizable, false);
3035 // this.tree.log("dragstart", colDef, e, info);
3036 this.tree.element.classList.toggle("wb-col-resizing", !!allow);
3037 info.colElem.classList.toggle("wb-col-resizing", !!allow);
3038 // We start dagging, so we remember the actual width in *pixels*
3039 // (which may be 'auto' or '100%').
3040 // Since we we re-create the markup on each update, we also cannot store
3041 // the original event or DOM element, but only the colDef object.
3042 if (allow) {
3043 // Store initial target column infos in customData
3044 e.customData.colDef = colDef;
3045 e.customData.orgCustomWidthPx = colDef.customWidthPx;
3046 const curWidthPx = Number.parseInt(info.colElem.style.width, 10);
3047 e.customData.orgWidthPx = curWidthPx;
3048 // Set custom width to current width, so that we can modify it
3049 colDef.customWidthPx = curWidthPx;
3050 // this.tree.log(
3051 // `dragstart customWidthPx=${colDef.customWidthPx}`,
3052 // e,
3053 // info
3054 // );
3055 this.tree.update(ChangeType.colStructure);
3056 // this.tree.log(
3057 // `dragstart 2 customWidthPx=${colDef.customWidthPx}`,
3058 // e,
3059 // info
3060 // );
3061 }
3062 return allow;
3063 },
3064 drag: (e) => {
3065 // TODO: throttle
3066 return this.handleDrag(e);
3067 },
3068 dragstop: (e) => {
3069 return this.handleDrag(e);
3070 },
3071 });
3072 }
3073 init() {
3074 super.init();
3075 }
3076 /**
3077 * Hanldes drag and sragstop events for column resizing.
3078 */
3079 handleDrag(e) {
3080 const custom = e.customData;
3081 const colDef = custom.colDef;
3082 // this.tree.log(`${e.type} (dx=${e.dx})`, e, info);
3083 if (e.type === "dragstop" || e.type === "drag") {
3084 this.tree.element.classList.remove("wb-col-resizing");
3085 // info.colElem!.classList.remove("wb-col-resizing");
3086 if (e.apply || e.type === "drag") {
3087 const minWidth = toPixel(colDef.minWidth, DEFAULT_MIN_COL_WIDTH);
3088 const newWidth = Math.max(minWidth, custom.orgWidthPx + e.dx);
3089 colDef.customWidthPx = newWidth;
3090 // this.tree.log(
3091 // `${e.type} minWidth=${minWidth}, newWidth=${newWidth}`,
3092 // colDef
3093 // );
3094 }
3095 else {
3096 // Drag was cancelled
3097 this.tree.log("Column resize cancelled", e);
3098 colDef.customWidthPx = custom.orgCustomWidthPx; // Restore original width or undefined
3099 }
3100 this.tree.update(ChangeType.colStructure);
3101 }
3102 }
3103 }
3104
3105 /*!
3106 * Wunderbaum - deferred
3107 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
3108 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
3109 */
3110 /**
3111 * Implement a ES6 Promise, that exposes a resolve() and reject() method.
3112 *
3113 * Loosely mimics {@link https://api.jquery.com/category/deferred-object/ | jQuery.Deferred}.
3114 * Example:
3115 * ```js
3116 * function foo() {
3117 * let dfd = new Deferred(),
3118 * ...
3119 * dfd.resolve('foo')
3120 * ...
3121 * return dfd.promise();
3122 * }
3123 * ```
3124 */
3125 class Deferred {
3126 constructor() {
3127 this._promise = new Promise((resolve, reject) => {
3128 this._resolve = resolve;
3129 this._reject = reject;
3130 });
3131 }
3132 /** Resolve the Promise. */
3133 resolve(value) {
3134 this._resolve(value);
3135 }
3136 /** Reject the Promise. */
3137 reject(reason) {
3138 this._reject(reason);
3139 }
3140 /** Return the native Promise instance.*/
3141 promise() {
3142 return this._promise;
3143 }
3144 /** Call Promise.then on the embedded promise instance.*/
3145 then(cb) {
3146 return this._promise.then(cb);
3147 }
3148 /** Call Promise.catch on the embedded promise instance.*/
3149 catch(cb) {
3150 return this._promise.catch(cb);
3151 }
3152 /** Call Promise.finally on the embedded promise instance.*/
3153 finally(cb) {
3154 return this._promise.finally(cb);
3155 }
3156 }
3157
3158 /*!
3159 * Wunderbaum - wunderbaum_node
3160 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
3161 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
3162 */
3163 /** WunderbaumNode properties that can be passed with source data.
3164 * (Any other source properties will be stored as `node.data.PROP`.)
3165 */
3166 const NODE_PROPS = new Set([
3167 "checkbox",
3168 "classes",
3169 "expanded",
3170 "icon",
3171 "iconTooltip",
3172 "key",
3173 "lazy",
3174 "_partsel",
3175 "radiogroup",
3176 "refKey",
3177 "selected",
3178 "statusNodeType",
3179 "title",
3180 "tooltip",
3181 "type",
3182 "unselectable",
3183 ]);
3184 /** WunderbaumNode properties that will be returned by `node.toDict()`.)
3185 */
3186 const NODE_DICT_PROPS = new Set(NODE_PROPS);
3187 NODE_DICT_PROPS.delete("_partsel");
3188 NODE_DICT_PROPS.delete("unselectable");
3189 // /** Node properties that are of type bool (or boolean & string).
3190 // * When parsing, we accept 0 for false and 1 for true for better JSON compression.
3191 // */
3192 // export const NODE_BOOL_PROPS: Set<string> = new Set([
3193 // "checkbox",
3194 // "colspan",
3195 // "expanded",
3196 // "icon",
3197 // "iconTooltip",
3198 // "radiogroup",
3199 // "selected",
3200 // "tooltip",
3201 // "unselectable",
3202 // ]);
3203 /**
3204 * A single tree node.
3205 *
3206 * **NOTE:** <br>
3207 * Generally you should not modify properties directly, since this may break
3208 * the internal bookkeeping.
3209 */
3210 class WunderbaumNode {
3211 constructor(tree, parent, data) {
3212 var _a, _b;
3213 /** Reference key. Unlike {@link key}, a `refKey` may occur multiple
3214 * times within a tree (in this case we have 'clone nodes').
3215 * @see Use {@link setKey} to modify.
3216 */
3217 this.refKey = undefined;
3218 /**
3219 * Array of child nodes (null for leaf nodes).
3220 * For lazy nodes, this is `null` or ùndefined` until the children are loaded
3221 * and leaf nodes may be `[]` (empty array).
3222 * @see {@link hasChildren}, {@link addChildren}, {@link lazy}.
3223 */
3224 this.children = null;
3225 /** Additional classes added to `div.wb-row`.
3226 * @see {@link hasClass}, {@link setClass}. */
3227 this.classes = null; //new Set<string>();
3228 /** Custom data that was passed to the constructor */
3229 this.data = {};
3230 this._isLoading = false;
3231 this._requestId = 0;
3232 this._errorInfo = null;
3233 this._partsel = false;
3234 this._partload = false;
3235 this.subMatchCount = 0;
3236 this._rowIdx = 0;
3237 this._rowElem = undefined;
3238 assert(!parent || parent.tree === tree, `Invalid parent: ${parent}`);
3239 assert(!data.children, "'children' not allowed here");
3240 this.tree = tree;
3241 this.parent = parent;
3242 this.key = "" + ((_a = data.key) !== null && _a !== void 0 ? _a : ++WunderbaumNode.sequence);
3243 this.title = "" + ((_b = data.title) !== null && _b !== void 0 ? _b : "<" + this.key + ">");
3244 this.expanded = !!data.expanded;
3245 this.lazy = !!data.lazy;
3246 // We set the following node properties only if a matching data value is
3247 // passed
3248 data.refKey != null ? (this.refKey = "" + data.refKey) : 0;
3249 data.type != null ? (this.type = "" + data.type) : 0;
3250 data.icon != null ? (this.icon = intToBool(data.icon)) : 0;
3251 data.tooltip != null ? (this.tooltip = intToBool(data.tooltip)) : 0;
3252 data.iconTooltip != null
3253 ? (this.iconTooltip = intToBool(data.iconTooltip))
3254 : 0;
3255 data.statusNodeType != null
3256 ? (this.statusNodeType = ("" + data.statusNodeType))
3257 : 0;
3258 data.colspan != null ? (this.colspan = !!data.colspan) : 0;
3259 // Selection
3260 data.checkbox != null ? intToBool(data.checkbox) : 0;
3261 data.radiogroup != null ? (this.radiogroup = !!data.radiogroup) : 0;
3262 data.selected != null ? (this.selected = !!data.selected) : 0;
3263 data.unselectable != null ? (this.unselectable = !!data.unselectable) : 0;
3264 if (data.classes) {
3265 this.setClass(data.classes);
3266 }
3267 // Store custom fields as `node.data`
3268 for (const [key, value] of Object.entries(data)) {
3269 if (!NODE_PROPS.has(key)) {
3270 this.data[key] = value;
3271 }
3272 }
3273 if (parent && !this.statusNodeType) {
3274 // Don't register root node or status nodes
3275 tree._registerNode(this);
3276 }
3277 }
3278 /**
3279 * Return readable string representation for this instance.
3280 * @internal
3281 */
3282 toString() {
3283 return `WunderbaumNode@${this.key}<'${this.title}'>`;
3284 }
3285 /**
3286 * Iterate all descendant nodes depth-first, pre-order using `for ... of ...` syntax.
3287 * More concise, but slightly slower than {@link WunderbaumNode.visit}.
3288 *
3289 * Example:
3290 * ```js
3291 * for(const n of node) {
3292 * ...
3293 * }
3294 * ```
3295 */
3296 *[Symbol.iterator]() {
3297 // let node: WunderbaumNode | null = this;
3298 const cl = this.children;
3299 if (cl) {
3300 for (let i = 0, l = cl.length; i < l; i++) {
3301 const n = cl[i];
3302 yield n;
3303 if (n.children) {
3304 yield* n;
3305 }
3306 }
3307 // Slower:
3308 // for (let node of this.children) {
3309 // yield node;
3310 // yield* node : 0;
3311 // }
3312 }
3313 }
3314 // /** Return an option value. */
3315 // protected _getOpt(
3316 // name: string,
3317 // nodeObject: any = null,
3318 // treeOptions: any = null,
3319 // defaultValue: any = null
3320 // ): any {
3321 // return evalOption(
3322 // name,
3323 // this,
3324 // nodeObject || this,
3325 // treeOptions || this.tree.options,
3326 // defaultValue
3327 // );
3328 // }
3329 /** Call event handler if defined in tree.options.
3330 * Example:
3331 * ```js
3332 * node._callEvent("edit.beforeEdit", {foo: 42})
3333 * ```
3334 */
3335 _callEvent(type, extra) {
3336 var _a;
3337 return (_a = this.tree) === null || _a === void 0 ? void 0 : _a._callEvent(type, extend({
3338 node: this,
3339 typeInfo: this.type ? this.tree.types[this.type] : {},
3340 }, extra));
3341 }
3342 /**
3343 * Append (or insert) a list of child nodes.
3344 *
3345 * Tip: pass `{ before: 0 }` to prepend new nodes as first children.
3346 *
3347 * @returns first child added
3348 */
3349 addChildren(nodeData, options) {
3350 const tree = this.tree;
3351 let { before = null, applyMinExpanLevel = true, _level } = options !== null && options !== void 0 ? options : {};
3352 // let { before, loadLazy=true, _level } = options ?? {};
3353 // const isTopCall = _level == null;
3354 _level !== null && _level !== void 0 ? _level : (_level = this.getLevel());
3355 const nodeList = [];
3356 try {
3357 tree.enableUpdate(false);
3358 if (isPlainObject(nodeData)) {
3359 nodeData = [nodeData];
3360 }
3361 const forceExpand = applyMinExpanLevel && _level < tree.options.minExpandLevel;
3362 for (const child of nodeData) {
3363 const subChildren = child.children;
3364 delete child.children;
3365 const n = new WunderbaumNode(tree, this, child);
3366 if (forceExpand && !n.isUnloaded()) {
3367 n.expanded = true;
3368 }
3369 nodeList.push(n);
3370 if (subChildren) {
3371 n.addChildren(subChildren, { _level: _level + 1 });
3372 }
3373 }
3374 if (!this.children) {
3375 this.children = nodeList;
3376 }
3377 else if (before == null || this.children.length === 0) {
3378 this.children = this.children.concat(nodeList);
3379 }
3380 else {
3381 // Returns null if before is not a direct child:
3382 before = this.findDirectChild(before);
3383 const pos = this.children.indexOf(before);
3384 assert(pos >= 0, `options.before must be a direct child of ${this}`);
3385 // insert nodeList after children[pos]
3386 this.children.splice(pos, 0, ...nodeList);
3387 }
3388 // this.triggerModifyChild("add", nodeList.length === 1 ? nodeList[0] : null);
3389 tree.update(ChangeType.structure);
3390 }
3391 finally {
3392 // if (tree.options.selectMode === "hier") {
3393 // if (this.parent && this.parent.children) {
3394 // this.fixSelection3FromEndNodes();
3395 // } else {
3396 // // may happen when loading __root__;
3397 // }
3398 // }
3399 tree.enableUpdate(true);
3400 }
3401 // if(isTopCall && loadLazy){
3402 // this.logWarn("addChildren(): loadLazy is not yet implemented.")
3403 // }
3404 return nodeList[0];
3405 }
3406 /**
3407 * Append or prepend a node, or append a child node.
3408 *
3409 * This a convenience function that calls addChildren()
3410 *
3411 * @param nodeData node definition
3412 * @param [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
3413 * @returns new node
3414 */
3415 addNode(nodeData, mode = "appendChild") {
3416 if (mode === "over") {
3417 mode = "appendChild"; // compatible with drop region
3418 }
3419 switch (mode) {
3420 case "after":
3421 return this.parent.addChildren(nodeData, {
3422 before: this.getNextSibling(),
3423 });
3424 case "before":
3425 return this.parent.addChildren(nodeData, { before: this });
3426 case "prependChild":
3427 // Insert before the first child if any
3428 // let insertBefore = this.children ? this.children[0] : undefined;
3429 return this.addChildren(nodeData, { before: 0 });
3430 case "appendChild":
3431 return this.addChildren(nodeData);
3432 }
3433 assert(false, `Invalid mode: ${mode}`);
3434 return undefined;
3435 }
3436 /**
3437 * Apply a modification (or navigation) operation.
3438 *
3439 * @see {@link Wunderbaum.applyCommand}
3440 */
3441 applyCommand(cmd, options) {
3442 return this.tree.applyCommand(cmd, this, options);
3443 }
3444 /**
3445 * Collapse all expanded sibling nodes if any.
3446 * (Automatically called when `autoCollapse` is true.)
3447 */
3448 collapseSiblings(options) {
3449 for (const node of this.parent.children) {
3450 if (node !== this && node.expanded) {
3451 node.setExpanded(false, options);
3452 }
3453 }
3454 }
3455 /**
3456 * Add/remove one or more classes to `<div class='wb-row'>`.
3457 *
3458 * This also maintains `node.classes`, so the class will survive a re-render.
3459 *
3460 * @param className one or more class names. Multiple classes can be passed
3461 * as space-separated string, array of strings, or set of strings.
3462 */
3463 setClass(className, flag = true) {
3464 const cnSet = toSet(className);
3465 if (flag) {
3466 if (this.classes === null) {
3467 this.classes = new Set();
3468 }
3469 cnSet.forEach((cn) => {
3470 var _a;
3471 this.classes.add(cn);
3472 (_a = this._rowElem) === null || _a === void 0 ? void 0 : _a.classList.toggle(cn, flag);
3473 });
3474 }
3475 else {
3476 if (this.classes === null) {
3477 return;
3478 }
3479 cnSet.forEach((cn) => {
3480 var _a;
3481 this.classes.delete(cn);
3482 (_a = this._rowElem) === null || _a === void 0 ? void 0 : _a.classList.toggle(cn, flag);
3483 });
3484 if (this.classes.size === 0) {
3485 this.classes = null;
3486 }
3487 }
3488 }
3489 /** Start editing this node's title. */
3490 startEditTitle() {
3491 this.tree._callMethod("edit.startEditTitle", this);
3492 }
3493 /**
3494 * Call `setExpanded()` on all descendant nodes.
3495 *
3496 * @param flag true to expand, false to collapse.
3497 * @param options Additional options.
3498 * @see {@link Wunderbaum.expandAll}
3499 * @see {@link WunderbaumNode.setExpanded}
3500 */
3501 async expandAll(flag = true, options) {
3502 const tree = this.tree;
3503 const { collapseOthers, deep, depth, force, keepActiveNodeVisible = true, loadLazy, resetLazy, } = options !== null && options !== void 0 ? options : {};
3504 // limit expansion level to `depth` (or tree.minExpandLevel). Default: unlimited
3505 const treeLevel = this.tree.options.minExpandLevel || null; // 0 -> null
3506 const minLevel = depth !== null && depth !== void 0 ? depth : (force ? null : treeLevel);
3507 const expandOpts = {
3508 deep: deep,
3509 force: force,
3510 loadLazy: loadLazy,
3511 resetLazy: resetLazy,
3512 scrollIntoView: false, // don't scroll every node while iterating
3513 };
3514 this.logInfo(`expandAll(${flag}, depth=${depth}, minLevel=${minLevel})`);
3515 assert(!(flag && deep != null && !collapseOthers), "Expanding with `deep` option is not supported (implied by the `depth` option).");
3516 // Expand all direct children in parallel:
3517 async function _iter(n, level) {
3518 var _a;
3519 // n.logInfo(` _iter(level=${level})`);
3520 const promises = [];
3521 (_a = n.children) === null || _a === void 0 ? void 0 : _a.forEach((cn) => {
3522 if (flag) {
3523 if (!cn.expanded &&
3524 (minLevel == null || level < minLevel) &&
3525 (cn.children || (loadLazy && cn.lazy))) {
3526 // Node is collapsed and may be expanded (i.e. has children or is lazy)
3527 // Expanding may be async, so we store the promise.
3528 // Also the recursion is delayed until expansion finished.
3529 const p = cn.setExpanded(true, expandOpts);
3530 promises.push(p);
3531 if (depth == null) {
3532 p.then(async () => {
3533 await _iter(cn, level + 1);
3534 });
3535 }
3536 }
3537 else {
3538 // We don't expand the node, but still visit descendants.
3539 // There we may find lazy nodes, so we
3540 promises.push(_iter(cn, level + 1));
3541 }
3542 }
3543 else {
3544 // Collapsing is always synchronous, so no promises required
3545 // Do not collapse until minExpandLevel
3546 if (minLevel == null || level >= minLevel) {
3547 cn.setExpanded(false, expandOpts);
3548 }
3549 if ((minLevel != null && level < minLevel) || deep) {
3550 _iter(cn, level + 1); // recursion, even if cn was already collapsed
3551 }
3552 }
3553 });
3554 return new Promise((resolve) => {
3555 Promise.all(promises).then(() => {
3556 resolve(true);
3557 });
3558 });
3559 }
3560 const tag = tree.logTime(`${this}.expandAll(${flag}, depth=${depth})`);
3561 try {
3562 tree.enableUpdate(false);
3563 await _iter(this, 0);
3564 if (collapseOthers) {
3565 assert(flag, "Option `collapseOthers` requires flag=true");
3566 assert(minLevel != null, "Option `collapseOthers` requires `depth` or `minExpandLevel`");
3567 this.expandAll(false, { depth: minLevel });
3568 }
3569 }
3570 finally {
3571 tree.enableUpdate(true);
3572 tree.logTimeEnd(tag);
3573 }
3574 if (tree.activeNode && keepActiveNodeVisible) {
3575 tree.activeNode.scrollIntoView();
3576 }
3577 }
3578 /**
3579 * Find all descendant nodes that match condition (excluding self).
3580 *
3581 * If `match` is a string, search for exact node title.
3582 * If `match` is a RegExp expression, apply it to node.title, using
3583 * [RegExp.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test).
3584 * If `match` is a callback, match all nodes for that the callback(node) returns true.
3585 *
3586 * Returns an empty array if no nodes were found.
3587 *
3588 * Examples:
3589 * ```js
3590 * // Match all node titles that match exactly 'Joe':
3591 * nodeList = node.findAll("Joe")
3592 * // Match all node titles that start with 'Joe' case sensitive:
3593 * nodeList = node.findAll(/^Joe/)
3594 * // Match all node titles that contain 'oe', case insensitive:
3595 * nodeList = node.findAll(/oe/i)
3596 * // Match all nodes with `data.price` >= 99:
3597 * nodeList = node.findAll((n) => {
3598 * return n.data.price >= 99;
3599 * })
3600 * ```
3601 */
3602 findAll(match) {
3603 const matcher = typeof match === "function" ? match : makeNodeTitleMatcher(match);
3604 const res = [];
3605 this.visit((n) => {
3606 if (matcher(n)) {
3607 res.push(n);
3608 }
3609 });
3610 return res;
3611 }
3612 /** Return the direct child with a given key, index or null. */
3613 findDirectChild(ptr) {
3614 const cl = this.children;
3615 if (!cl) {
3616 return null;
3617 }
3618 if (typeof ptr === "string") {
3619 for (let i = 0, l = cl.length; i < l; i++) {
3620 if (cl[i].key === ptr) {
3621 return cl[i];
3622 }
3623 }
3624 }
3625 else if (typeof ptr === "number") {
3626 return cl[ptr];
3627 }
3628 else if (ptr.parent === this) {
3629 // Return null if `ptr` is not a direct child
3630 return ptr;
3631 }
3632 return null;
3633 }
3634 /**
3635 * Find first descendant node that matches condition (excluding self) or null.
3636 *
3637 * @see {@link WunderbaumNode.findAll} for examples.
3638 */
3639 findFirst(match) {
3640 const matcher = typeof match === "function" ? match : makeNodeTitleMatcher(match);
3641 let res = null;
3642 this.visit((n) => {
3643 if (matcher(n)) {
3644 res = n;
3645 return false;
3646 }
3647 });
3648 return res;
3649 }
3650 /** Find a node relative to self.
3651 *
3652 * @see {@link Wunderbaum.findRelatedNode|tree.findRelatedNode()}
3653 */
3654 findRelatedNode(where, includeHidden = false) {
3655 return this.tree.findRelatedNode(this, where, includeHidden);
3656 }
3657 /**
3658 * Iterator version of {@link WunderbaumNode.format}.
3659 */
3660 *format_iter(name_cb, connectors) {
3661 connectors !== null && connectors !== void 0 ? connectors : (connectors = [" ", " | ", " ╰─ ", " ├─ "]);
3662 name_cb !== null && name_cb !== void 0 ? name_cb : (name_cb = (node) => "" + node);
3663 function _is_last(node) {
3664 const ca = node.parent.children;
3665 return node === ca[ca.length - 1];
3666 }
3667 const _format_line = (node) => {
3668 // https://www.measurethat.net/Benchmarks/Show/12196/0/arr-unshift-vs-push-reverse-small-array
3669 const parts = [name_cb(node)];
3670 parts.unshift(connectors[_is_last(node) ? 2 : 3]);
3671 let p = node.parent;
3672 while (p && p !== this) {
3673 // `this` is the top node
3674 parts.unshift(connectors[_is_last(p) ? 0 : 1]);
3675 p = p.parent;
3676 }
3677 return parts.join("");
3678 };
3679 yield name_cb(this);
3680 for (const node of this) {
3681 yield _format_line(node);
3682 }
3683 }
3684 /**
3685 * Return a multiline string representation of a node/subnode hierarchy.
3686 * Mostly useful for debugging.
3687 *
3688 * Example:
3689 * ```js
3690 * console.info(tree.getActiveNode().format((n)=>n.title));
3691 * ```
3692 * logs
3693 * ```
3694 * Books
3695 * ├─ Art of War
3696 * ╰─ Don Quixote
3697 * ```
3698 * @see {@link WunderbaumNode.format_iter}
3699 */
3700 format(name_cb, connectors) {
3701 const a = [];
3702 for (const line of this.format_iter(name_cb, connectors)) {
3703 a.push(line);
3704 }
3705 return a.join("\n");
3706 }
3707 /** Return the `<span class='wb-col'>` element with a given index or id.
3708 * @returns {WunderbaumNode | null}
3709 */
3710 getColElem(colIdx) {
3711 var _a;
3712 if (typeof colIdx === "string") {
3713 colIdx = this.tree.columns.findIndex((value) => value.id === colIdx);
3714 }
3715 const colElems = (_a = this._rowElem) === null || _a === void 0 ? void 0 : _a.querySelectorAll("span.wb-col");
3716 return colElems ? colElems[colIdx] : null;
3717 }
3718 /**
3719 * Return all nodes with the same refKey.
3720 *
3721 * @param includeSelf Include this node itself.
3722 * @see {@link Wunderbaum.findByRefKey}
3723 */
3724 getCloneList(includeSelf = false) {
3725 if (!this.refKey) {
3726 return [];
3727 }
3728 const clones = this.tree.findByRefKey(this.refKey);
3729 if (includeSelf) {
3730 return clones;
3731 }
3732 return [...clones].filter((n) => n !== this);
3733 }
3734 /** Return the first child node or null.
3735 * @returns {WunderbaumNode | null}
3736 */
3737 getFirstChild() {
3738 return this.children ? this.children[0] : null;
3739 }
3740 /** Return the last child node or null.
3741 * @returns {WunderbaumNode | null}
3742 */
3743 getLastChild() {
3744 return this.children ? this.children[this.children.length - 1] : null;
3745 }
3746 /** Return node depth (starting with 1 for top level nodes). */
3747 getLevel() {
3748 let i = 0, p = this.parent;
3749 while (p) {
3750 i++;
3751 p = p.parent;
3752 }
3753 return i;
3754 }
3755 /** Return the successive node (under the same parent) or null. */
3756 getNextSibling() {
3757 const ac = this.parent.children;
3758 const idx = ac.indexOf(this);
3759 return ac[idx + 1] || null;
3760 }
3761 /** Return the parent node (null for the system root node). */
3762 getParent() {
3763 // TODO: return null for top-level nodes?
3764 return this.parent;
3765 }
3766 /** Return an array of all parent nodes (top-down).
3767 * @param includeRoot Include the invisible system root node.
3768 * @param includeSelf Include the node itself.
3769 */
3770 getParentList(includeRoot = false, includeSelf = false) {
3771 const l = [];
3772 let dtn = includeSelf ? this : this.parent;
3773 while (dtn) {
3774 if (includeRoot || dtn.parent) {
3775 l.unshift(dtn);
3776 }
3777 dtn = dtn.parent;
3778 }
3779 return l;
3780 }
3781 /** Return a string representing the hierachical node path, e.g. "a/b/c".
3782 * @param includeSelf
3783 * @param part property name or callback
3784 * @param separator
3785 */
3786 getPath(includeSelf = true, part = "title", separator = "/") {
3787 // includeSelf = includeSelf !== false;
3788 // part = part || "title";
3789 // separator = separator || "/";
3790 let val;
3791 const path = [];
3792 const isFunc = typeof part === "function";
3793 this.visitParents((n) => {
3794 if (n.parent) {
3795 val = isFunc
3796 ? part(n)
3797 : n[part];
3798 path.unshift(val);
3799 }
3800 return undefined; // TODO remove this line
3801 }, includeSelf);
3802 return path.join(separator);
3803 }
3804 /** Return the preceeding node (under the same parent) or null. */
3805 getPrevSibling() {
3806 const ac = this.parent.children;
3807 const idx = ac.indexOf(this);
3808 return ac[idx - 1] || null;
3809 }
3810 /** Return true if node has children.
3811 * Return undefined if not sure, i.e. the node is lazy and not yet loaded.
3812 */
3813 hasChildren() {
3814 if (this.lazy) {
3815 if (this.children == null) {
3816 return undefined; // null or undefined: Not yet loaded
3817 }
3818 else if (this.children.length === 0) {
3819 return false; // Loaded, but response was empty
3820 }
3821 else if (this.children.length === 1 &&
3822 this.children[0].isStatusNode()) {
3823 return undefined; // Currently loading or load error
3824 }
3825 return true; // One or more child nodes
3826 }
3827 return !!(this.children && this.children.length);
3828 }
3829 /** Return true if node has className set. */
3830 hasClass(className) {
3831 return this.classes ? this.classes.has(className) : false;
3832 }
3833 /** Return true if node ist the currently focused node. @since 0.9.0 */
3834 hasFocus() {
3835 return this.tree.focusNode === this;
3836 }
3837 /** Return true if this node is the currently active tree node. */
3838 isActive() {
3839 return this.tree.activeNode === this;
3840 }
3841 /** Return true if this node is a direct or indirect parent of `other`.
3842 * @see {@link WunderbaumNode.isParentOf}
3843 */
3844 isAncestorOf(other) {
3845 return other && other.isDescendantOf(this);
3846 }
3847 /** Return true if this node is a **direct** subnode of `other`.
3848 * @see {@link WunderbaumNode.isDescendantOf}
3849 */
3850 isChildOf(other) {
3851 return other && this.parent === other;
3852 }
3853 /** Return true if this node's refKey is used by at least one other node.
3854 */
3855 isClone() {
3856 return !!this.refKey && this.tree.findByRefKey(this.refKey).length > 1;
3857 }
3858 /** Return true if this node's title spans all columns, i.e. the node has no
3859 * grid cells.
3860 */
3861 isColspan() {
3862 return !!this.getOption("colspan");
3863 }
3864 /** Return true if this node is a direct or indirect subnode of `other`.
3865 * @see {@link WunderbaumNode.isChildOf}
3866 */
3867 isDescendantOf(other) {
3868 if (!other || other.tree !== this.tree) {
3869 return false;
3870 }
3871 let p = this.parent;
3872 while (p) {
3873 if (p === other) {
3874 return true;
3875 }
3876 if (p === p.parent) {
3877 error(`Recursive parent link: ${p}`);
3878 }
3879 p = p.parent;
3880 }
3881 return false;
3882 }
3883 /** Return true if this node has children, i.e. the node is generally expandable.
3884 * If `andCollapsed` is set, we also check if this node is collapsed, i.e.
3885 * an expand operation is currently possible.
3886 */
3887 isExpandable(andCollapsed = false) {
3888 // `false` is never expandable (unoffical)
3889 if ((andCollapsed && this.expanded) || this.children === false) {
3890 return false;
3891 }
3892 if (this.children == null) {
3893 return !!this.lazy; // null or undefined can trigger lazy load
3894 }
3895 if (this.children.length === 0) {
3896 return !!this.tree.options.emptyChildListExpandable;
3897 }
3898 return true;
3899 }
3900 /** Return true if _this_ node is currently in edit-title mode.
3901 *
3902 * See {@link WunderbaumNode.startEditTitle}.
3903 */
3904 isEditingTitle() {
3905 return this.tree._callMethod("edit.isEditingTitle", this);
3906 }
3907 /** Return true if this node is currently expanded. */
3908 isExpanded() {
3909 return !!this.expanded;
3910 }
3911 /** Return true if this node is the first node of its parent's children. */
3912 isFirstSibling() {
3913 const p = this.parent;
3914 return !p || p.children[0] === this;
3915 }
3916 /** Return true if this node is the last node of its parent's children. */
3917 isLastSibling() {
3918 const p = this.parent;
3919 return !p || p.children[p.children.length - 1] === this;
3920 }
3921 /** Return true if this node is lazy (even if data was already loaded) */
3922 isLazy() {
3923 return !!this.lazy;
3924 }
3925 /** Return true if node is lazy and loaded. For non-lazy nodes always return true. */
3926 isLoaded() {
3927 return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
3928 }
3929 /** Return true if node is currently loading, i.e. a GET request is pending. */
3930 isLoading() {
3931 return this._isLoading;
3932 }
3933 /** Return true if this node is a temporarily generated status node of type 'paging'. */
3934 isPagingNode() {
3935 return this.statusNodeType === "paging";
3936 }
3937 /** Return true if this node is a **direct** parent of `other`.
3938 * @see {@link WunderbaumNode.isAncestorOf}
3939 */
3940 isParentOf(other) {
3941 return other && other.parent === this;
3942 }
3943 /** Return true if this node is partially loaded. @experimental */
3944 isPartload() {
3945 return !!this._partload;
3946 }
3947 /** Return true if this node is partially selected (tri-state). */
3948 isPartsel() {
3949 return !this.selected && !!this._partsel;
3950 }
3951 /** Return true if this node has DOM representaion, i.e. is displayed in the viewport. */
3952 isRadio() {
3953 return !!this.parent.radiogroup || this.getOption("checkbox") === "radio";
3954 }
3955 /** Return true if this node has DOM representaion, i.e. is displayed in the viewport. */
3956 isRendered() {
3957 return !!this._rowElem;
3958 }
3959 /** Return true if this node is the (invisible) system root node.
3960 * @see {@link WunderbaumNode.isTopLevel}
3961 */
3962 isRootNode() {
3963 return this.tree.root === this;
3964 }
3965 /** Return true if this node is selected, i.e. the checkbox is set.
3966 * `undefined` if partly selected (tri-state), false otherwise.
3967 */
3968 isSelected() {
3969 return this.selected ? true : this._partsel ? undefined : false;
3970 }
3971 /** Return true if this node is a temporarily generated system node like
3972 * 'loading', 'paging', or 'error' (node.statusNodeType contains the type).
3973 */
3974 isStatusNode() {
3975 return !!this.statusNodeType;
3976 }
3977 /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node. */
3978 isTopLevel() {
3979 return this.tree.root === this.parent;
3980 }
3981 /** Return true if node is marked lazy but not yet loaded.
3982 * For non-lazy nodes always return false.
3983 */
3984 isUnloaded() {
3985 // Also checks if the only child is a status node:
3986 return this.hasChildren() === undefined;
3987 }
3988 /** Return true if all parent nodes are expanded. Note: this does not check
3989 * whether the node is scrolled into the visible part of the screen or viewport.
3990 */
3991 isVisible() {
3992 const hasFilter = this.tree.filterMode === "hide";
3993 const parents = this.getParentList(false, false);
3994 // TODO: check $(n.span).is(":visible")
3995 // i.e. return false for nodes (but not parents) that are hidden
3996 // by a filter
3997 if (hasFilter && !this.match && !this.subMatchCount) {
3998 // this.debug( "isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")" );
3999 return false;
4000 }
4001 for (let i = 0, l = parents.length; i < l; i++) {
4002 const n = parents[i];
4003 if (!n.expanded) {
4004 // this.debug("isVisible: HIDDEN (parent collapsed)");
4005 return false;
4006 }
4007 // if (hasFilter && !n.match && !n.subMatchCount) {
4008 // this.debug("isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")");
4009 // return false;
4010 // }
4011 }
4012 // this.debug("isVisible: VISIBLE");
4013 return true;
4014 }
4015 _loadSourceObject(source, level) {
4016 var _a;
4017 const tree = this.tree;
4018 level !== null && level !== void 0 ? level : (level = this.getLevel());
4019 // Let caller modify the parsed JSON response:
4020 const res = this._callEvent("receive", { response: source });
4021 if (res != null) {
4022 source = res;
4023 }
4024 if (isArray(source)) {
4025 source = { children: source };
4026 }
4027 assert(isPlainObject(source), `Expected an array or plain object: ${source}`);
4028 const format = (_a = source.format) !== null && _a !== void 0 ? _a : "nested";
4029 assert(format === "nested" || format === "flat", `Expected source.format = 'nested' or 'flat': ${format}`);
4030 // Pre-rocess for 'nested' or 'flat' format
4031 decompressSourceData(source);
4032 assert(source.children, "If `source` is an object, it must have a `children` property");
4033 if (source.types) {
4034 tree.logInfo("Redefine types", source.columns);
4035 tree.setTypes(source.types, false);
4036 delete source.types;
4037 }
4038 if (source.columns) {
4039 tree.logInfo("Redefine columns", source.columns);
4040 tree.columns = source.columns;
4041 delete source.columns;
4042 tree.update(ChangeType.colStructure);
4043 }
4044 this.addChildren(source.children);
4045 // Add extra data to `tree.data`
4046 for (const [key, value] of Object.entries(source)) {
4047 if (!RESERVED_TREE_SOURCE_KEYS.has(key)) {
4048 tree.data[key] = value;
4049 // tree.logDebug(`Add source.${key} to tree.data.${key}`);
4050 }
4051 }
4052 if (tree.options.selectMode === "hier") {
4053 this.fixSelection3FromEndNodes();
4054 }
4055 // Allow to un-sort nodes after sorting
4056 this.resetNativeChildOrder();
4057 this._callEvent("load");
4058 }
4059 async _fetchWithOptions(source) {
4060 var _a, _b;
4061 // Either a URL string or an object with a `.url` property.
4062 let url, params, body, options, rest;
4063 let fetchOpts = {};
4064 if (typeof source === "string") {
4065 // source is a plain URL string: assume GET request
4066 url = source;
4067 fetchOpts.method = "GET";
4068 }
4069 else if (isPlainObject(source)) {
4070 // source is a plain object with `.url` property.
4071 ({ url, params, body, options, ...rest } = source);
4072 assert(!rest || Object.keys(rest).length === 0, `Unexpected source properties: ${Object.keys(rest)}. Use 'options' instead.`);
4073 assert(typeof url === "string", `expected source.url as string`);
4074 if (isPlainObject(options)) {
4075 fetchOpts = options;
4076 }
4077 if (isPlainObject(body)) {
4078 // we also accept 'body' as object...
4079 assert(!fetchOpts.body, "options.body should be passed as source.body");
4080 fetchOpts.body = JSON.stringify(fetchOpts.body);
4081 (_a = fetchOpts.method) !== null && _a !== void 0 ? _a : (fetchOpts.method = "POST"); // set default
4082 }
4083 if (isPlainObject(params)) {
4084 url += "?" + new URLSearchParams(params);
4085 (_b = fetchOpts.method) !== null && _b !== void 0 ? _b : (fetchOpts.method = "GET"); // set default
4086 }
4087 }
4088 else {
4089 url = ""; // keep linter happy
4090 error(`Unsupported source format: ${source}`);
4091 }
4092 this.setStatus(NodeStatusType.loading);
4093 const response = await fetch(url, fetchOpts);
4094 if (!response.ok) {
4095 error(`GET ${url} returned ${response.status}, ${response}`);
4096 }
4097 return await response.json();
4098 }
4099 /** Download data from the cloud, then call `.update()`. */
4100 async load(source) {
4101 const tree = this.tree;
4102 const requestId = Date.now();
4103 const prevParent = this.parent;
4104 const start = Date.now();
4105 let elap = 0, elapLoad = 0, elapProcess = 0;
4106 // Check for overlapping requests
4107 if (this._requestId) {
4108 this.logWarn(`Recursive load request #${requestId} while #${this._requestId} is pending. ` +
4109 "The previous request will be ignored.");
4110 }
4111 this._requestId = requestId;
4112 // const timerLabel = tree.logTime(this + ".load()");
4113 try {
4114 const url = typeof source === "string" ? source : source.url;
4115 if (!url) {
4116 // An array or a plain object (that does NOT contain a `.url` property)
4117 // will be treated as native Wunderbaum data
4118 if (typeof source.then === "function") {
4119 const msg = tree.logTime(`Resolve thenable ${source}`);
4120 source = await Promise.resolve(source);
4121 tree.logTimeEnd(msg);
4122 }
4123 this._loadSourceObject(source);
4124 elapProcess = Date.now() - start;
4125 }
4126 else {
4127 // Either a URL string or an object with a `.url` property.
4128 const data = await this._fetchWithOptions(source);
4129 elapLoad = Date.now() - start;
4130 if (this._requestId && this._requestId > requestId) {
4131 this.logWarn(`Ignored load response #${requestId} because #${this._requestId} is pending.`);
4132 return;
4133 }
4134 else {
4135 this.logDebug(`Received response for load request #${requestId}`);
4136 }
4137 if (this.parent === null && prevParent !== null) {
4138 this.logWarn("Lazy parent node was removed while loading: discarding response.");
4139 return;
4140 }
4141 this.setStatus(NodeStatusType.ok);
4142 // if (data.columns) {
4143 // tree.logInfo("Re-define columns", data.columns);
4144 // util.assert(!this.parent);
4145 // tree.columns = data.columns;
4146 // delete data.columns;
4147 // tree.updateColumns({ calculateCols: false });
4148 // }
4149 const startProcess = Date.now();
4150 this._loadSourceObject(data);
4151 elapProcess = Date.now() - startProcess;
4152 }
4153 }
4154 catch (error) {
4155 this.logError("Error during load()", source, error);
4156 this._callEvent("error", { error: error });
4157 this.setStatus(NodeStatusType.error, { message: "" + error });
4158 throw error;
4159 }
4160 finally {
4161 this._requestId = 0;
4162 elap = Date.now() - start;
4163 if (tree.options.debugLevel >= 3) {
4164 tree.logInfo(`Load source took ${elap / 1000} seconds ` +
4165 `(transfer: ${elapLoad / 1000}s, ` +
4166 `processing: ${elapProcess / 1000}s)`);
4167 }
4168 }
4169 }
4170 /**
4171 * Load content of a lazy node.
4172 * If the node is already loaded, nothing happens.
4173 * @param [forceReload=false] If true, reload even if already loaded.
4174 */
4175 async loadLazy(forceReload = false) {
4176 const wasExpanded = this.expanded;
4177 assert(this.lazy, "load() requires a lazy node");
4178 if (!forceReload && !this.isUnloaded()) {
4179 return; // Already loaded: nothing to do
4180 }
4181 if (this.isLoading()) {
4182 this.logWarn("loadLazy() called while already loading: ignored.");
4183 return; // Already loading: prevent duplicate requests
4184 }
4185 if (this.isLoaded()) {
4186 this.resetLazy(); // Also collapses if currently expanded
4187 }
4188 // `lazyLoad` may be long-running, so mark node as loading now. `this.load()`
4189 // will reset the status later.
4190 this.setStatus(NodeStatusType.loading);
4191 try {
4192 const source = await this._callEvent("lazyLoad");
4193 if (source === false) {
4194 this.setStatus(NodeStatusType.ok);
4195 return;
4196 }
4197 assert(isArray(source) || (source && source.url), "The lazyLoad event must return a node list, `{url: ...}`, or false.");
4198 await this.load(source);
4199 this.setStatus(NodeStatusType.ok); // Also resets `this._isLoading`
4200 if (wasExpanded) {
4201 this.expanded = true;
4202 this.tree.update(ChangeType.structure);
4203 }
4204 else {
4205 this.update(); // Fix expander icon to 'loaded'
4206 }
4207 }
4208 catch (e) {
4209 this.logError("Error during loadLazy()", e);
4210 this._callEvent("error", { error: e });
4211 // Also resets `this._isLoading`:
4212 this.setStatus(NodeStatusType.error, { message: "" + e });
4213 }
4214 return;
4215 }
4216 /** Write to `console.log` with node name as prefix if opts.debugLevel >= 4.
4217 * @see {@link WunderbaumNode.logDebug}
4218 */
4219 log(...args) {
4220 if (this.tree.options.debugLevel >= 4) {
4221 console.log(this.toString(), ...args); // eslint-disable-line no-console
4222 }
4223 }
4224 /** Write to `console.debug` with node name as prefix if opts.debugLevel >= 4
4225 * and browser console level includes debug/verbose messages.
4226 * @see {@link WunderbaumNode.log}
4227 */
4228 logDebug(...args) {
4229 if (this.tree.options.debugLevel >= 4) {
4230 console.debug(this.toString(), ...args); // eslint-disable-line no-console
4231 }
4232 }
4233 /** Write to `console.error` with node name as prefix if opts.debugLevel >= 1. */
4234 logError(...args) {
4235 if (this.tree.options.debugLevel >= 1) {
4236 console.error(this.toString(), ...args); // eslint-disable-line no-console
4237 }
4238 }
4239 /** Write to `console.info` with node name as prefix if opts.debugLevel >= 3. */
4240 logInfo(...args) {
4241 if (this.tree.options.debugLevel >= 3) {
4242 console.info(this.toString(), ...args); // eslint-disable-line no-console
4243 }
4244 }
4245 /** Write to `console.warn` with node name as prefix if opts.debugLevel >= 2. */
4246 logWarn(...args) {
4247 if (this.tree.options.debugLevel >= 2) {
4248 console.warn(this.toString(), ...args); // eslint-disable-line no-console
4249 }
4250 }
4251 /** Expand all parents and optionally scroll into visible area as neccessary.
4252 * Promise is resolved, when lazy loading and animations are done.
4253 * @param {object} [options] passed to `setExpanded()`.
4254 * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
4255 */
4256 async makeVisible(options) {
4257 let i;
4258 const dfd = new Deferred();
4259 const deferreds = [];
4260 const parents = this.getParentList(false, false);
4261 const len = parents.length;
4262 const noAnimation = getOption(options, "noAnimation", false);
4263 const scroll = getOption(options, "scrollIntoView", true);
4264 // Expand bottom-up, so only the top node is animated
4265 for (i = len - 1; i >= 0; i--) {
4266 // self.debug("pushexpand" + parents[i]);
4267 const seOpts = { noAnimation: noAnimation };
4268 deferreds.push(parents[i].setExpanded(true, seOpts));
4269 }
4270 Promise.all(deferreds).then(() => {
4271 // All expands have finished
4272 // self.debug("expand DONE", scroll);
4273 // Note: this.tree may be none when switching demo trees
4274 if (scroll && this.tree) {
4275 // Make sure markup and _rowIdx is updated before we do the scroll calculations
4276 this.tree.updatePendingModifications();
4277 this.scrollIntoView().then(() => {
4278 // self.debug("scroll DONE");
4279 dfd.resolve();
4280 });
4281 }
4282 else {
4283 dfd.resolve();
4284 }
4285 });
4286 return dfd.promise();
4287 }
4288 /** Move this node to targetNode. */
4289 moveTo(targetNode, mode = "appendChild", map) {
4290 if (mode === "over") {
4291 mode = "appendChild"; // compatible with drop region
4292 }
4293 if (mode === "prependChild") {
4294 if (targetNode.children && targetNode.children.length) {
4295 mode = "before";
4296 targetNode = targetNode.children[0];
4297 }
4298 else {
4299 mode = "appendChild";
4300 }
4301 }
4302 let pos;
4303 const tree = this.tree;
4304 const prevParent = this.parent;
4305 const targetParent = mode === "appendChild" ? targetNode : targetNode.parent;
4306 if (this === targetNode) {
4307 return;
4308 }
4309 else if (!this.parent) {
4310 error("Cannot move system root");
4311 }
4312 else if (targetParent.isDescendantOf(this)) {
4313 error("Cannot move a node to its own descendant");
4314 }
4315 if (targetParent !== prevParent) {
4316 prevParent.triggerModifyChild("remove", this);
4317 }
4318 // Unlink this node from current parent
4319 if (this.parent.children.length === 1) {
4320 if (this.parent === targetParent) {
4321 return; // #258
4322 }
4323 this.parent.children = this.parent.lazy ? [] : null;
4324 this.parent.expanded = false;
4325 }
4326 else {
4327 pos = this.parent.children.indexOf(this);
4328 assert(pos >= 0, "invalid source parent");
4329 this.parent.children.splice(pos, 1);
4330 }
4331 // Insert this node to target parent's child list
4332 this.parent = targetParent;
4333 if (targetParent.hasChildren()) {
4334 switch (mode) {
4335 case "appendChild":
4336 // Append to existing target children
4337 targetParent.children.push(this);
4338 break;
4339 case "before":
4340 // Insert this node before target node
4341 pos = targetParent.children.indexOf(targetNode);
4342 assert(pos >= 0, "invalid target parent");
4343 targetParent.children.splice(pos, 0, this);
4344 break;
4345 case "after":
4346 // Insert this node after target node
4347 pos = targetParent.children.indexOf(targetNode);
4348 assert(pos >= 0, "invalid target parent");
4349 targetParent.children.splice(pos + 1, 0, this);
4350 break;
4351 default:
4352 error(`Invalid mode '${mode}'.`);
4353 }
4354 }
4355 else {
4356 targetParent.children = [this];
4357 }
4358 // Let caller modify the nodes
4359 if (map) {
4360 targetNode.visit(map, true);
4361 }
4362 if (targetParent === prevParent) {
4363 targetParent.triggerModifyChild("move", this);
4364 }
4365 else {
4366 // prevParent.triggerModifyChild("remove", this);
4367 targetParent.triggerModifyChild("add", this);
4368 }
4369 // Handle cross-tree moves
4370 if (tree !== targetNode.tree) {
4371 // Fix node.tree for all source nodes
4372 // util.assert(false, "Cross-tree move is not yet implemented.");
4373 this.logWarn("Cross-tree moveTo is experimental!");
4374 this.visit((n) => {
4375 // TODO: fix selection state and activation, ...
4376 n.tree = targetNode.tree;
4377 }, true);
4378 }
4379 // Make sure we update async, because discarding the markup would prevent
4380 // DragAndDrop to generate a dragend event on the source node
4381 setTimeout(() => {
4382 // Even indentation may have changed:
4383 tree.update(ChangeType.any);
4384 }, 0);
4385 // TODO: fix selection state
4386 // TODO: fix active state
4387 }
4388 /** Set focus relative to this node and optionally activate.
4389 *
4390 * 'left' collapses the node if it is expanded, or move to the parent
4391 * otherwise.
4392 * 'right' expands the node if it is collapsed, or move to the first
4393 * child otherwise.
4394 *
4395 * @param where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'.
4396 * (Alternatively the `event.key` that would normally trigger this move,
4397 * e.g. `ArrowLeft` = 'left'.
4398 * @param options
4399 */
4400 async navigate(where, options) {
4401 var _a;
4402 // Allow to pass 'ArrowLeft' instead of 'left'
4403 const navType = ((_a = KEY_TO_NAVIGATION_MAP[where]) !== null && _a !== void 0 ? _a : where);
4404 // Otherwise activate or focus the related node
4405 const node = this.findRelatedNode(navType);
4406 if (!node) {
4407 this.logWarn(`Could not find related node '${where}'.`);
4408 return Promise.resolve(this);
4409 }
4410 // setFocus/setActive will scroll later (if autoScroll is specified)
4411 try {
4412 node.makeVisible({ scrollIntoView: false });
4413 }
4414 catch (e) {
4415 // ignore
4416 }
4417 node.setFocus();
4418 if ((options === null || options === void 0 ? void 0 : options.activate) === false) {
4419 return Promise.resolve(this);
4420 }
4421 return node.setActive(true, { event: options === null || options === void 0 ? void 0 : options.event });
4422 }
4423 /** Delete this node and all descendants. */
4424 remove() {
4425 const tree = this.tree;
4426 const pos = this.parent.children.indexOf(this);
4427 this.triggerModify("remove");
4428 this.parent.children.splice(pos, 1);
4429 this.visit((n) => {
4430 n.removeMarkup();
4431 tree._unregisterNode(n);
4432 }, true);
4433 tree.update(ChangeType.structure);
4434 }
4435 /** Remove all descendants of this node. */
4436 removeChildren() {
4437 var _a, _b;
4438 const tree = this.tree;
4439 if (!this.children) {
4440 return;
4441 }
4442 if ((_a = tree.activeNode) === null || _a === void 0 ? void 0 : _a.isDescendantOf(this)) {
4443 tree.activeNode.setActive(false); // TODO: don't fire events
4444 }
4445 if ((_b = tree.focusNode) === null || _b === void 0 ? void 0 : _b.isDescendantOf(this)) {
4446 tree._setFocusNode(null);
4447 }
4448 // TODO: persist must take care to clear select and expand cookies
4449 // Unlink children to support GC
4450 // TODO: also delete this.children (not possible using visit())
4451 this.triggerModifyChild("remove", null);
4452 this.visit((n) => {
4453 tree._unregisterNode(n);
4454 });
4455 if (this.lazy) {
4456 // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
4457 this.children = [];
4458 }
4459 else {
4460 this.children = null;
4461 }
4462 // util.assert(this.parent); // don't call this for root node
4463 if (!this.isRootNode()) {
4464 this.expanded = false;
4465 }
4466 this.tree.update(ChangeType.structure);
4467 }
4468 /** Remove all HTML markup from the DOM. */
4469 removeMarkup() {
4470 if (this._rowElem) {
4471 delete this._rowElem._wb_node;
4472 this._rowElem.remove();
4473 this._rowElem = undefined;
4474 }
4475 }
4476 _getRenderInfo() {
4477 const allColInfosById = {};
4478 const renderColInfosById = {};
4479 const isColspan = this.isColspan();
4480 const colElems = this._rowElem
4481 ? (this._rowElem.querySelectorAll("span.wb-col"))
4482 : null;
4483 let idx = 0;
4484 for (const col of this.tree.columns) {
4485 allColInfosById[col.id] = {
4486 id: col.id,
4487 idx: idx,
4488 elem: colElems ? colElems[idx] : null,
4489 info: col,
4490 };
4491 // renderColInfosById only contains columns that need rendering:
4492 if (!isColspan && col.id !== "*") {
4493 renderColInfosById[col.id] = allColInfosById[col.id];
4494 }
4495 idx++;
4496 }
4497 return {
4498 allColInfosById: allColInfosById,
4499 renderColInfosById: renderColInfosById,
4500 };
4501 }
4502 _createIcon(parentElem, replaceChild, showLoading) {
4503 const iconElem = this.tree._createNodeIcon(this, showLoading, true);
4504 if (iconElem) {
4505 if (replaceChild) {
4506 parentElem.replaceChild(iconElem, replaceChild);
4507 }
4508 else {
4509 parentElem.appendChild(iconElem);
4510 }
4511 }
4512 return iconElem;
4513 }
4514 /**
4515 * Create a whole new `<div class="wb-row">` element.
4516 * @see {@link WunderbaumNode._render}
4517 */
4518 _render_markup(opts) {
4519 const tree = this.tree;
4520 const treeOptions = tree.options;
4521 const rowHeight = treeOptions.rowHeightPx;
4522 const checkbox = this.getOption("checkbox");
4523 const columns = tree.columns;
4524 const level = this.getLevel();
4525 const activeColIdx = tree.isRowNav() ? null : tree.activeColIdx;
4526 let elem;
4527 let rowDiv = this._rowElem;
4528 let checkboxSpan = null;
4529 let expanderSpan = null;
4530 const isNew = !rowDiv;
4531 assert(isNew, "Expected unrendered node");
4532 assert(!isNew || (opts && opts.after), "opts.after expected, unless updating");
4533 assert(!this.isRootNode(), "Root node not allowed");
4534 rowDiv = document.createElement("div");
4535 rowDiv.classList.add("wb-row");
4536 rowDiv.style.top = this._rowIdx * rowHeight + "px";
4537 this._rowElem = rowDiv;
4538 // Attach a node reference to the DOM Element:
4539 rowDiv._wb_node = this;
4540 const nodeElem = document.createElement("span");
4541 nodeElem.classList.add("wb-node", "wb-col");
4542 rowDiv.appendChild(nodeElem);
4543 let ofsTitlePx = 0;
4544 if (checkbox) {
4545 checkboxSpan = document.createElement("i");
4546 checkboxSpan.classList.add("wb-checkbox");
4547 if (checkbox === "radio" || this.parent.radiogroup) {
4548 checkboxSpan.classList.add("wb-radio");
4549 }
4550 nodeElem.appendChild(checkboxSpan);
4551 ofsTitlePx += ICON_WIDTH;
4552 }
4553 for (let i = level - 1; i > 0; i--) {
4554 elem = document.createElement("i");
4555 elem.classList.add("wb-indent");
4556 nodeElem.appendChild(elem);
4557 ofsTitlePx += ICON_WIDTH;
4558 }
4559 if (!treeOptions.minExpandLevel || level > treeOptions.minExpandLevel) {
4560 expanderSpan = document.createElement("i");
4561 expanderSpan.classList.add("wb-expander");
4562 nodeElem.appendChild(expanderSpan);
4563 ofsTitlePx += ICON_WIDTH;
4564 }
4565 // Render the icon (show a 'loading' icon if we do not have an expander that
4566 // we would prefer).
4567 const iconSpan = this._createIcon(nodeElem, null, !expanderSpan);
4568 if (iconSpan) {
4569 ofsTitlePx += ICON_WIDTH;
4570 }
4571 const titleSpan = document.createElement("span");
4572 titleSpan.classList.add("wb-title");
4573 nodeElem.appendChild(titleSpan);
4574 // this._callEvent("enhanceTitle", { titleSpan: titleSpan });
4575 // Store the width of leading icons with the node, so we can calculate
4576 // the width of the embedded title span later
4577 nodeElem._ofsTitlePx = ofsTitlePx;
4578 // Support HTML5 drag-n-drop
4579 if (tree.options.dnd.dragStart) {
4580 nodeElem.draggable = true;
4581 }
4582 // Render columns
4583 const isColspan = this.isColspan();
4584 if (!isColspan && columns.length > 1) {
4585 let colIdx = 0;
4586 for (const col of columns) {
4587 colIdx++;
4588 let colElem;
4589 if (col.id === "*") {
4590 colElem = nodeElem;
4591 }
4592 else {
4593 colElem = document.createElement("span");
4594 colElem.classList.add("wb-col");
4595 rowDiv.appendChild(colElem);
4596 }
4597 if (colIdx === activeColIdx) {
4598 colElem.classList.add("wb-active");
4599 }
4600 // Add classes from `columns` definition to `<div.wb-col>` cells
4601 col.classes ? colElem.classList.add(...col.classes.split(" ")) : 0;
4602 colElem.style.left = col._ofsPx + "px";
4603 colElem.style.width = col._widthPx + "px";
4604 if (isNew && col.html) {
4605 if (typeof col.html === "string") {
4606 colElem.innerHTML = col.html;
4607 }
4608 }
4609 }
4610 }
4611 // Attach to DOM as late as possible
4612 const after = opts ? opts.after : "last";
4613 switch (after) {
4614 case "first":
4615 tree.nodeListElement.prepend(rowDiv);
4616 break;
4617 case "last":
4618 tree.nodeListElement.appendChild(rowDiv);
4619 break;
4620 default:
4621 opts.after.after(rowDiv);
4622 }
4623 // Now go on and fill in data and update classes
4624 opts.isNew = true;
4625 this._render_data(opts);
4626 }
4627 /**
4628 * Render `node.title`, `.icon` into an existing row.
4629 *
4630 * @see {@link WunderbaumNode._render}
4631 */
4632 _render_data(opts) {
4633 assert(this._rowElem, "No _rowElem");
4634 const tree = this.tree;
4635 const treeOptions = tree.options;
4636 const rowDiv = this._rowElem;
4637 const isNew = !!opts.isNew; // Called by _render_markup()?
4638 const preventScroll = !!opts.preventScroll;
4639 const columns = tree.columns;
4640 const isColspan = this.isColspan();
4641 // Row markup already exists
4642 const nodeElem = rowDiv.querySelector("span.wb-node");
4643 const titleSpan = nodeElem.querySelector("span.wb-title");
4644 const scrollTop = tree.element.scrollTop;
4645 if (this.titleWithHighlight) {
4646 titleSpan.innerHTML = this.titleWithHighlight;
4647 }
4648 else {
4649 titleSpan.textContent = this.title; // TODO: this triggers scroll events
4650 }
4651 const tooltip = this.getOption("tooltip", false);
4652 if (tooltip) {
4653 titleSpan.title = tooltip === true ? this.title : tooltip;
4654 }
4655 // NOTE: At least on Safari, this render call triggers a scroll event
4656 // probably when a focused input is replaced.
4657 if (preventScroll) {
4658 tree.element.scrollTop = scrollTop;
4659 }
4660 // Set the width of the title span, so overflow ellipsis work
4661 if (!treeOptions.skeleton) {
4662 if (isColspan) {
4663 const vpWidth = tree.element.clientWidth;
4664 titleSpan.style.width =
4665 vpWidth - nodeElem._ofsTitlePx - TITLE_SPAN_PAD_Y + "px";
4666 }
4667 else {
4668 titleSpan.style.width =
4669 columns[0]._widthPx -
4670 nodeElem._ofsTitlePx -
4671 TITLE_SPAN_PAD_Y +
4672 "px";
4673 }
4674 }
4675 // Update row classes
4676 opts.isDataChange = true;
4677 this._render_status(opts);
4678 // Let user modify the result
4679 if (this.statusNodeType) {
4680 this._callEvent("renderStatusNode", {
4681 isNew: isNew,
4682 nodeElem: nodeElem,
4683 isColspan: isColspan,
4684 });
4685 }
4686 else if (this.parent) {
4687 // Skip root node
4688 const renderInfo = this._getRenderInfo();
4689 this._callEvent("render", {
4690 isNew: isNew,
4691 nodeElem: nodeElem,
4692 isColspan: isColspan,
4693 allColInfosById: renderInfo.allColInfosById,
4694 renderColInfosById: renderInfo.renderColInfosById,
4695 });
4696 }
4697 }
4698 /**
4699 * Update row classes to reflect active, focuses, etc.
4700 * @see {@link WunderbaumNode._render}
4701 */
4702 _render_status(opts) {
4703 // this.log("_render_status", opts);
4704 const tree = this.tree;
4705 const iconMap = tree.iconMap;
4706 const treeOptions = tree.options;
4707 const typeInfo = this.type ? tree.types[this.type] : null;
4708 const rowDiv = this._rowElem;
4709 // Row markup already exists
4710 const nodeElem = rowDiv.querySelector("span.wb-node");
4711 const expanderSpan = nodeElem.querySelector("i.wb-expander");
4712 const checkboxSpan = nodeElem.querySelector("i.wb-checkbox");
4713 const rowClasses = ["wb-row"];
4714 this.expanded ? rowClasses.push("wb-expanded") : 0;
4715 this.lazy ? rowClasses.push("wb-lazy") : 0;
4716 this.selected ? rowClasses.push("wb-selected") : 0;
4717 this._partsel ? rowClasses.push("wb-partsel") : 0;
4718 this === tree.activeNode ? rowClasses.push("wb-active") : 0;
4719 this === tree.focusNode ? rowClasses.push("wb-focus") : 0;
4720 this._errorInfo ? rowClasses.push("wb-error") : 0;
4721 this._isLoading ? rowClasses.push("wb-loading") : 0;
4722 this.isColspan() ? rowClasses.push("wb-colspan") : 0;
4723 this.statusNodeType
4724 ? rowClasses.push("wb-status-" + this.statusNodeType)
4725 : 0;
4726 this.match ? rowClasses.push("wb-match") : 0;
4727 this.subMatchCount ? rowClasses.push("wb-submatch") : 0;
4728 treeOptions.skeleton ? rowClasses.push("wb-skeleton") : 0;
4729 // Replace previous classes:
4730 rowDiv.className = rowClasses.join(" ");
4731 // Add classes from `node.classes`
4732 this.classes ? rowDiv.classList.add(...this.classes) : 0;
4733 // Add classes from `tree.types[node.type]`
4734 if (typeInfo && typeInfo.classes) {
4735 rowDiv.classList.add(...typeInfo.classes);
4736 }
4737 if (expanderSpan) {
4738 let image = null;
4739 if (this._isLoading) {
4740 image = iconMap.loading;
4741 }
4742 else if (this.isExpandable(false)) {
4743 if (this.expanded) {
4744 image = iconMap.expanderExpanded;
4745 }
4746 else {
4747 image = iconMap.expanderCollapsed;
4748 }
4749 }
4750 else if (this.lazy && this.children == null) {
4751 image = iconMap.expanderLazy;
4752 }
4753 if (image == null) {
4754 expanderSpan.classList.add("wb-indent");
4755 }
4756 else if (TEST_IMG.test(image)) {
4757 expanderSpan.style.backgroundImage = `url('${image}')`;
4758 }
4759 else {
4760 expanderSpan.className = "wb-expander " + image;
4761 }
4762 }
4763 if (checkboxSpan) {
4764 let cbclass = "wb-checkbox ";
4765 if (this.isRadio()) {
4766 cbclass += "wb-radio ";
4767 if (this.selected) {
4768 cbclass += iconMap.radioChecked;
4769 // } else if (this._partsel) {
4770 // cbclass += iconMap.radioUnknown;
4771 }
4772 else {
4773 cbclass += iconMap.radioUnchecked;
4774 }
4775 }
4776 else {
4777 if (this.selected) {
4778 cbclass += iconMap.checkChecked;
4779 }
4780 else if (this._partsel) {
4781 cbclass += iconMap.checkUnknown;
4782 }
4783 else {
4784 cbclass += iconMap.checkUnchecked;
4785 }
4786 }
4787 checkboxSpan.className = cbclass;
4788 }
4789 // Fix active cell in cell-nav mode
4790 if (!opts.isNew) {
4791 let i = 0;
4792 for (const colSpan of rowDiv.children) {
4793 colSpan.classList.toggle("wb-active", i++ === tree.activeColIdx);
4794 colSpan.classList.remove("wb-error", "wb-invalid");
4795 }
4796 // Update icon (if not opts.isNew, which would rebuild markup anyway)
4797 const iconSpan = nodeElem.querySelector("i.wb-icon");
4798 if (iconSpan) {
4799 this._createIcon(nodeElem, iconSpan, !expanderSpan);
4800 }
4801 }
4802 // Adjust column width
4803 if (opts.resizeCols !== false && !this.isColspan()) {
4804 const colElems = rowDiv.querySelectorAll("span.wb-col");
4805 let idx = 0;
4806 let ofs = 0;
4807 for (const colDef of this.tree.columns) {
4808 const colElem = colElems[idx];
4809 colElem.style.left = `${ofs}px`;
4810 colElem.style.width = `${colDef._widthPx}px`;
4811 idx++;
4812 ofs += colDef._widthPx;
4813 }
4814 }
4815 }
4816 /*
4817 * Create or update node's markup.
4818 *
4819 * `options.change` defaults to ChangeType.data, which updates the title,
4820 * icon, and status. It also triggers the `render` event, that lets the user
4821 * create or update the content of embeded cell elements.
4822 *
4823 * If only the status or other class-only modifications have changed,
4824 * `options.change` should be set to ChangeType.status instead for best
4825 * efficiency.
4826 *
4827 * Calling `update()` is almost always a better alternative.
4828 * @see {@link WunderbaumNode.update}
4829 */
4830 _render(options) {
4831 // this.log("render", options);
4832 const opts = Object.assign({ change: ChangeType.data }, options);
4833 if (!this._rowElem) {
4834 opts.change = ChangeType.row;
4835 }
4836 switch (opts.change) {
4837 case "status":
4838 this._render_status(opts);
4839 break;
4840 case "data":
4841 this._render_data(opts);
4842 break;
4843 case "row":
4844 // _rowElem is not yet created (asserted in _render_markup)
4845 this._render_markup(opts);
4846 break;
4847 default:
4848 error(`Invalid change type '${opts.change}'.`);
4849 }
4850 }
4851 /**
4852 * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
4853 * event is triggered on next expand.
4854 */
4855 resetLazy() {
4856 this.removeChildren();
4857 this.expanded = false;
4858 this.lazy = true;
4859 this.children = null;
4860 this.tree.update(ChangeType.structure);
4861 }
4862 /** Convert node (or whole branch) into a plain object.
4863 *
4864 * The result is compatible with node.addChildren().
4865 *
4866 * @param recursive include child nodes
4867 * @param callback is called for every node, in order to allow
4868 * modifications.
4869 * Return `false` to ignore this node or `"skip"` to include this node
4870 * without its children.
4871 * @see {@link Wunderbaum.toDictArray}.
4872 */
4873 toDict(recursive = false, callback) {
4874 const dict = {};
4875 NODE_DICT_PROPS.forEach((propName) => {
4876 const val = this[propName];
4877 if (val instanceof Set) {
4878 // Convert Set to string (or skip if set is empty)
4879 val.size
4880 ? (dict[propName] = Array.prototype.join.call(val.keys(), " "))
4881 : 0;
4882 }
4883 else if (val || val === false || val === 0) {
4884 dict[propName] = val;
4885 }
4886 });
4887 if (!isEmptyObject(this.data)) {
4888 dict.data = extend({}, this.data);
4889 if (isEmptyObject(dict.data)) {
4890 delete dict.data;
4891 }
4892 }
4893 if (callback) {
4894 const res = callback(dict, this);
4895 if (res === false) {
4896 // Note: a return value of `false` is only used internally
4897 return false; // Don't include this node nor its children
4898 }
4899 if (res === "skip") {
4900 recursive = false; // Include this node, but not the children
4901 }
4902 }
4903 if (recursive) {
4904 if (isArray(this.children)) {
4905 dict.children = [];
4906 for (let i = 0, l = this.children.length; i < l; i++) {
4907 const node = this.children[i];
4908 if (!node.isStatusNode()) {
4909 // Note: a return value of `false` is only used internally
4910 const res = node.toDict(true, callback);
4911 if (res !== false) {
4912 dict.children.push(res);
4913 }
4914 }
4915 }
4916 }
4917 }
4918 return dict;
4919 }
4920 /** Return an option value that has a default, but may be overridden by a
4921 * callback or a node instance attribute.
4922 *
4923 * Evaluation sequence:
4924 *
4925 * - If `tree.options.<name>` is a callback that returns something, use that.
4926 * - Else if `node.<name>` is defined, use that.
4927 * - Else if `tree.types[<node.type>]` is a value, use that.
4928 * - Else if `tree.options.<name>` is a value, use that.
4929 * - Else use `defaultValue`.
4930 *
4931 * @param name name of the option property (on node and tree)
4932 * @param defaultValue return this if nothing else matched
4933 * {@link Wunderbaum.getOption|Wunderbaum.getOption}
4934 */
4935 getOption(name, defaultValue) {
4936 const tree = this.tree;
4937 let opts = tree.options;
4938 // Lookup `name` in options dict
4939 if (name.indexOf(".") >= 0) {
4940 [opts, name] = name.split(".");
4941 }
4942 const value = opts[name]; // ?? defaultValue;
4943 // A callback resolver always takes precedence
4944 if (typeof value === "function") {
4945 const res = value.call(tree, {
4946 type: "resolve",
4947 tree: tree,
4948 node: this,
4949 // typeInfo: this.type ? tree.types[this.type] : {},
4950 });
4951 if (res !== undefined) {
4952 return res;
4953 }
4954 }
4955 // If this node has an explicit local setting, use it:
4956 if (this[name] !== undefined) {
4957 return this[name];
4958 }
4959 // Use value from type definition if defined
4960 const typeInfo = this.type ? tree.types[this.type] : undefined;
4961 const res = typeInfo ? typeInfo[name] : undefined;
4962 if (res !== undefined) {
4963 return res;
4964 }
4965 // Use value from value options dict, fallback do default
4966 return value !== null && value !== void 0 ? value : defaultValue;
4967 }
4968 /** Make sure that this node is visible in the viewport.
4969 * @see {@link Wunderbaum.scrollTo|Wunderbaum.scrollTo}
4970 */
4971 async scrollIntoView(options) {
4972 const opts = Object.assign({ node: this }, options);
4973 return this.tree.scrollTo(opts);
4974 }
4975 /**
4976 * Activate this node, deactivate previous, send events, activate column and
4977 * scroll into viewport.
4978 */
4979 async setActive(flag = true, options) {
4980 const tree = this.tree;
4981 const prev = tree.getActiveNode();
4982 const retrigger = options === null || options === void 0 ? void 0 : options.retrigger; // Default: false
4983 const focusTree = options === null || options === void 0 ? void 0 : options.focusTree; // Default: false
4984 // const focusNode = options?.focusNode !== false; // Default: true
4985 const noEvents = options === null || options === void 0 ? void 0 : options.noEvents; // Default: false
4986 const orgEvent = options === null || options === void 0 ? void 0 : options.event; // Default: null
4987 const colIdx = options === null || options === void 0 ? void 0 : options.colIdx; // Default: null
4988 const edit = options === null || options === void 0 ? void 0 : options.edit; // Default: false
4989 // util.assert(!colIdx || tree.isCellNav(), "colIdx requires cellNav");
4990 assert(!edit || colIdx != null, "edit requires colIdx");
4991 if (!noEvents) {
4992 if (flag) {
4993 if (prev !== this || retrigger) {
4994 if ((prev === null || prev === void 0 ? void 0 : prev._callEvent("deactivate", {
4995 nextNode: this,
4996 event: orgEvent,
4997 })) === false ||
4998 this._callEvent("beforeActivate", {
4999 prevNode: prev,
5000 event: orgEvent,
5001 }) === false) {
5002 return;
5003 }
5004 tree._setActiveNode(null);
5005 prev === null || prev === void 0 ? void 0 : prev.update(ChangeType.status);
5006 }
5007 }
5008 else if (prev === this || retrigger) {
5009 this._callEvent("deactivate", { nextNode: null, event: orgEvent });
5010 }
5011 }
5012 if (prev !== this) {
5013 if (flag) {
5014 tree._setActiveNode(this);
5015 }
5016 prev === null || prev === void 0 ? void 0 : prev.update(ChangeType.status);
5017 this.update(ChangeType.status);
5018 }
5019 return this.makeVisible().then(() => {
5020 if (flag) {
5021 if (focusTree || edit) {
5022 tree.setFocus();
5023 tree._setFocusNode(this);
5024 tree.focusNode.setFocus();
5025 }
5026 // if (focusNode || edit) {
5027 // tree.focusNode = this;
5028 // tree.focusNode.setFocus();
5029 // }
5030 if (colIdx != null && tree.isCellNav()) {
5031 tree.setColumn(colIdx, { edit: edit });
5032 }
5033 if (!noEvents) {
5034 this._callEvent("activate", { prevNode: prev, event: orgEvent });
5035 }
5036 }
5037 });
5038 }
5039 /**
5040 * Expand or collapse this node.
5041 */
5042 async setExpanded(flag = true, options) {
5043 const { force, scrollIntoView, immediate, resetLazy } = options !== null && options !== void 0 ? options : {};
5044 const sendEvents = !(options === null || options === void 0 ? void 0 : options.noEvents); // Default: send events
5045 if (!flag &&
5046 this.isExpanded() &&
5047 this.getLevel() <= this.tree.getOption("minExpandLevel") &&
5048 !force) {
5049 this.logDebug("Ignored collapse request below minExpandLevel.");
5050 return;
5051 }
5052 if (!flag === !this.expanded) {
5053 return; // Nothing to do
5054 }
5055 if (sendEvents &&
5056 this._callEvent("beforeExpand", { flag: flag }) === false) {
5057 return;
5058 }
5059 // this.log("setExpanded()");
5060 if (flag && this.getOption("autoCollapse")) {
5061 this.collapseSiblings(options);
5062 }
5063 if (flag && this.lazy && this.children == null) {
5064 await this.loadLazy();
5065 }
5066 else if (!flag && resetLazy && this.lazy && this.children) {
5067 this.resetLazy();
5068 }
5069 this.expanded = flag;
5070 const updateOpts = { immediate: immediate };
5071 // const updateOpts = { immediate: !!util.getOption(options, "immediate") };
5072 this.tree.update(ChangeType.structure, updateOpts);
5073 if (flag && scrollIntoView) {
5074 const lastChild = this.getLastChild();
5075 if (lastChild) {
5076 this.tree.updatePendingModifications();
5077 lastChild.scrollIntoView({ topNode: this });
5078 }
5079 }
5080 if (sendEvents) {
5081 this._callEvent("expand", { flag: flag });
5082 }
5083 }
5084 /**
5085 * Set keyboard focus here.
5086 * @see {@link setActive}
5087 */
5088 setFocus(flag = true) {
5089 assert(!!flag, "Blur is not yet implemented");
5090 const prev = this.tree.focusNode;
5091 this.tree._setFocusNode(this);
5092 prev === null || prev === void 0 ? void 0 : prev.update();
5093 this.update();
5094 }
5095 /** Set a new icon path or class. */
5096 setIcon(icon) {
5097 this.icon = icon;
5098 this.update();
5099 }
5100 /** Change node's {@link key} and/or {@link refKey}. */
5101 setKey(key, refKey) {
5102 throw new Error("Not yet implemented");
5103 }
5104 /**
5105 * Trigger a repaint, typically after a status or data change.
5106 *
5107 * `change` defaults to 'data', which handles modifcations of title, icon,
5108 * and column content. It can be reduced to 'ChangeType.status' if only
5109 * active/focus/selected state has changed.
5110 *
5111 * This method will eventually call {@link WunderbaumNode._render} with
5112 * default options, but may be more consistent with the tree's
5113 * {@link Wunderbaum.update} API.
5114 */
5115 update(change = ChangeType.data) {
5116 assert(change === ChangeType.status || change === ChangeType.data, `Invalid change type ${change}`);
5117 this.tree.update(change, this);
5118 }
5119 /**
5120 * Return an array of selected nodes.
5121 * @param stopOnParents only return the topmost selected node (useful with selectMode 'hier')
5122 */
5123 getSelectedNodes(stopOnParents = false) {
5124 const nodeList = [];
5125 this.visit((node) => {
5126 if (node.selected) {
5127 nodeList.push(node);
5128 if (stopOnParents === true) {
5129 return "skip"; // stop processing this branch
5130 }
5131 }
5132 });
5133 return nodeList;
5134 }
5135 /** Toggle the check/uncheck state. */
5136 toggleSelected(options) {
5137 let flag = this.isSelected();
5138 if (flag === undefined && !this.isRadio()) {
5139 flag = this._anySelectable();
5140 }
5141 else {
5142 flag = !flag;
5143 }
5144 return this.setSelected(flag, options);
5145 }
5146 /** Return true if at least on selectable descendant end-node is unselected. @internal */
5147 _anySelectable() {
5148 let found = false;
5149 this.visit((node) => {
5150 if (node.selected === false &&
5151 !node.unselectable &&
5152 !node.hasChildren() &&
5153 !node.parent.radiogroup) {
5154 found = true;
5155 return false; // Stop iteration
5156 }
5157 });
5158 return found;
5159 }
5160 /* Apply selection state to a single node. */
5161 _changeSelectStatusProps(state) {
5162 let changed = false;
5163 switch (state) {
5164 case false:
5165 changed = this.selected || this._partsel;
5166 this.selected = false;
5167 this._partsel = false;
5168 break;
5169 case true:
5170 changed = !this.selected || !this._partsel;
5171 this.selected = true;
5172 this._partsel = true;
5173 break;
5174 case undefined:
5175 changed = this.selected || !this._partsel;
5176 this.selected = false;
5177 // #110: end nodess cannot have a `_partsel` flag
5178 this._partsel = this.hasChildren() ? true : false;
5179 break;
5180 default:
5181 error(`Invalid state: ${state}`);
5182 }
5183 if (changed) {
5184 this.update();
5185 }
5186 return changed;
5187 }
5188 /**
5189 * Fix selection status, after this node was (de)selected in `selectMode: 'hier'`.
5190 * This includes (de)selecting all descendants.
5191 */
5192 fixSelection3AfterClick(opts) {
5193 const force = !!(opts === null || opts === void 0 ? void 0 : opts.force);
5194 const flag = this.isSelected();
5195 this.visit((node) => {
5196 if (node.radiogroup) {
5197 return "skip"; // Don't (de)select this branch
5198 }
5199 if (force || !node.getOption("unselectable")) {
5200 node._changeSelectStatusProps(flag);
5201 }
5202 });
5203 this.fixSelection3FromEndNodes();
5204 }
5205 /**
5206 * Fix selection status for multi-hier mode.
5207 * Only end-nodes are considered to update the descendants branch and parents.
5208 * Should be called after this node has loaded new children or after
5209 * children have been modified using the API.
5210 */
5211 fixSelection3FromEndNodes(opts) {
5212 const force = !!(opts === null || opts === void 0 ? void 0 : opts.force);
5213 assert(this.tree.options.selectMode === "hier", "expected selectMode 'hier'");
5214 // Visit all end nodes and adjust their parent's `selected` and `_partsel`
5215 // attributes. Return selection state true, false, or undefined.
5216 const _walk = (node) => {
5217 let state;
5218 const children = node.children;
5219 if (children && children.length) {
5220 // check all children recursively
5221 let allSelected = true;
5222 let someSelected = false;
5223 for (let i = 0, l = children.length; i < l; i++) {
5224 const child = children[i];
5225 // the selection state of a node is not relevant; we need the end-nodes
5226 const s = _walk(child);
5227 if (s !== false) {
5228 someSelected = true;
5229 }
5230 if (s !== true) {
5231 allSelected = false;
5232 }
5233 }
5234 state = allSelected ? true : someSelected ? undefined : false;
5235 }
5236 else {
5237 // This is an end-node: simply report the status
5238 state = !!node.selected;
5239 }
5240 // #939: Keep a `_partsel` flag that was explicitly set on a lazy node
5241 if (node._partsel &&
5242 !node.selected &&
5243 node.lazy &&
5244 node.children == null) {
5245 state = undefined;
5246 }
5247 if (force || !node.getOption("unselectable")) {
5248 node._changeSelectStatusProps(state);
5249 }
5250 return state;
5251 };
5252 _walk(this);
5253 // Update parent's state
5254 this.visitParents((node) => {
5255 let state;
5256 const children = node.children;
5257 let allSelected = true;
5258 let someSelected = false;
5259 for (let i = 0, l = children.length; i < l; i++) {
5260 const child = children[i];
5261 state = !!child.selected;
5262 // When fixing the parents, we trust the sibling status (i.e. we don't recurse)
5263 if (state || child._partsel) {
5264 someSelected = true;
5265 }
5266 if (!state) {
5267 allSelected = false;
5268 }
5269 }
5270 state = allSelected ? true : someSelected ? undefined : false;
5271 node._changeSelectStatusProps(state);
5272 });
5273 }
5274 /** Modify the check/uncheck state. */
5275 setSelected(flag = true, options) {
5276 const tree = this.tree;
5277 const sendEvents = !(options === null || options === void 0 ? void 0 : options.noEvents); // Default: send events
5278 const prev = this.isSelected();
5279 const isRadio = this.parent && this.parent.radiogroup;
5280 const selectMode = tree.options.selectMode;
5281 const canSelect = (options === null || options === void 0 ? void 0 : options.force) || !this.getOption("unselectable");
5282 flag = !!flag;
5283 // this.logDebug(`setSelected(${flag})`, this);
5284 if (!canSelect) {
5285 return prev;
5286 }
5287 if ((options === null || options === void 0 ? void 0 : options.propagateDown) && selectMode === "multi") {
5288 tree.runWithDeferredUpdate(() => {
5289 this.visit((node) => {
5290 node.setSelected(flag);
5291 });
5292 });
5293 return prev;
5294 }
5295 if (flag === prev ||
5296 (sendEvents && this._callEvent("beforeSelect", { flag: flag }) === false)) {
5297 return prev;
5298 }
5299 tree.runWithDeferredUpdate(() => {
5300 if (isRadio) {
5301 // Radiobutton Group
5302 if (!flag && !(options === null || options === void 0 ? void 0 : options.force)) {
5303 return prev; // don't uncheck radio buttons
5304 }
5305 for (const sibling of this.parent.children) {
5306 sibling.selected = sibling === this;
5307 }
5308 }
5309 else {
5310 this.selected = flag;
5311 if (selectMode === "hier") {
5312 this.fixSelection3AfterClick();
5313 }
5314 else if (selectMode === "single") {
5315 tree.visit((n) => {
5316 n.selected = false;
5317 });
5318 }
5319 }
5320 });
5321 if (sendEvents) {
5322 this._callEvent("select", { flag: flag });
5323 }
5324 return prev;
5325 }
5326 /** Display node status (ok, loading, error, noData) using styles and a dummy child node. */
5327 setStatus(status, options) {
5328 const tree = this.tree;
5329 const message = options === null || options === void 0 ? void 0 : options.message;
5330 const details = options === null || options === void 0 ? void 0 : options.details;
5331 let statusNode = null;
5332 const _clearStatusNode = () => {
5333 // Remove dedicated dummy node, if any
5334 const children = this.children;
5335 if (children && children.length && children[0].isStatusNode()) {
5336 children[0].remove();
5337 }
5338 };
5339 const _setStatusNode = (data) => {
5340 // Create/modify the dedicated dummy node for 'loading...' or
5341 // 'error!' status. (only called for direct child of the invisible
5342 // system root)
5343 const children = this.children;
5344 const firstChild = children ? children[0] : null;
5345 assert(data.statusNodeType, "Not a status node");
5346 assert(!firstChild || !firstChild.isStatusNode(), "Child must not be a status node");
5347 statusNode = this.addNode(data, "prependChild");
5348 statusNode.match = -1; // Mark as 'match' to avoid hiding
5349 tree.update(ChangeType.structure);
5350 return statusNode;
5351 };
5352 _clearStatusNode();
5353 switch (status) {
5354 case "ok":
5355 this._isLoading = false;
5356 this._errorInfo = null;
5357 break;
5358 case "loading":
5359 this._isLoading = true;
5360 this._errorInfo = null;
5361 if (this.parent) {
5362 this.update(ChangeType.status);
5363 }
5364 else {
5365 // If this is the invisible root, add a visible top-level node
5366 _setStatusNode({
5367 statusNodeType: status,
5368 title: tree.options.strings.loading +
5369 (message ? " (" + message + ")" : ""),
5370 checkbox: false,
5371 colspan: true,
5372 tooltip: details,
5373 });
5374 }
5375 // this.update();
5376 break;
5377 case "error":
5378 _setStatusNode({
5379 statusNodeType: status,
5380 title: tree.options.strings.loadError +
5381 (message ? " (" + message + ")" : ""),
5382 checkbox: false,
5383 colspan: true,
5384 // classes: "wb-center",
5385 tooltip: details,
5386 });
5387 this._isLoading = false;
5388 this._errorInfo = { message: message, details: details };
5389 break;
5390 case "noData":
5391 _setStatusNode({
5392 statusNodeType: status,
5393 title: message || tree.options.strings.noData,
5394 checkbox: false,
5395 colspan: true,
5396 tooltip: details,
5397 });
5398 this._isLoading = false;
5399 this._errorInfo = null;
5400 break;
5401 default:
5402 error("invalid node status " + status);
5403 }
5404 tree.update(ChangeType.structure);
5405 return statusNode;
5406 }
5407 /** Rename this node. */
5408 setTitle(title) {
5409 this.title = title;
5410 this.update();
5411 // this.triggerModify("rename"); // TODO
5412 }
5413 /** Set the node tooltip. */
5414 setTooltip(tooltip) {
5415 this.tooltip = tooltip;
5416 this.update();
5417 }
5418 _sortChildren(cmp, deep) {
5419 const cl = this.children;
5420 if (!cl) {
5421 return;
5422 }
5423 cl.sort(cmp);
5424 if (deep) {
5425 for (let i = 0, l = cl.length; i < l; i++) {
5426 if (cl[i].children) {
5427 cl[i]._sortChildren(cmp, deep);
5428 }
5429 }
5430 }
5431 }
5432 /**
5433 * Sort child list by title or custom criteria.
5434 * @param {function} cmp custom compare function(a, b) that returns -1, 0, or 1
5435 * (defaults to sorting by title).
5436 * @param {boolean} deep pass true to sort all descendant nodes recursively
5437 */
5438 sortChildren(cmp = nodeTitleSorter, deep = false) {
5439 this._sortChildren(cmp || nodeTitleSorter, deep);
5440 this.tree.update(ChangeType.structure);
5441 // this.triggerModify("sort"); // TODO
5442 }
5443 /**
5444 * Renumber nodes `_nativeIndex`. This is useful to allow to restore the
5445 * order after sorting a column.
5446 * This method is automatically called after loading new child nodes.
5447 * @since 0.11.0
5448 */
5449 resetNativeChildOrder(options) {
5450 const { recursive = true, propName = "_nativeIndex" } = options !== null && options !== void 0 ? options : {};
5451 if (this.children) {
5452 this.children.forEach((child, i) => {
5453 child.data[propName] = i;
5454 if (recursive && child.children) {
5455 child.resetNativeChildOrder(options);
5456 }
5457 });
5458 }
5459 }
5460 /**
5461 * Convenience method to implement column sorting.
5462 * @since 0.11.0
5463 */
5464 sortByProperty(options) {
5465 var _a, _b, _c;
5466 const { caseInsensitive = true, deep = true, nativeOrderPropName = "_nativeIndex", updateColInfo = false, } = options;
5467 let order;
5468 let colDef;
5469 if (updateColInfo) {
5470 colDef = this.tree["_columnsById"][options.colId];
5471 assert(colDef, `Invalid colId specified: ${options.colId}`);
5472 order =
5473 (_a = options.order) !== null && _a !== void 0 ? _a : rotate(colDef.sortOrder, ["asc", "desc", undefined]);
5474 for (const col of this.tree.columns) {
5475 col.sortOrder = col === colDef ? order : undefined;
5476 }
5477 this.tree.update(ChangeType.colStructure);
5478 }
5479 else {
5480 order = (_b = options.order) !== null && _b !== void 0 ? _b : "asc";
5481 }
5482 let propName = (_c = options.propName) !== null && _c !== void 0 ? _c : (options.colId || "");
5483 if (propName === "*") {
5484 propName = "title";
5485 }
5486 if (order == null) {
5487 propName = nativeOrderPropName;
5488 order = "asc";
5489 }
5490 this.logDebug(`sortByProperty(), propName=${propName}, ${order}`, options);
5491 assert(propName, "No property name specified");
5492 const cmp = (a, b) => {
5493 let av, bv;
5494 if (NODE_DICT_PROPS.has(propName)) {
5495 av = a[propName];
5496 bv = b[propName];
5497 }
5498 else {
5499 av = a.data[propName];
5500 bv = b.data[propName];
5501 }
5502 if (av == null && bv == null) {
5503 return 0;
5504 }
5505 if (av == null) {
5506 av = typeof bv === "string" ? "" : 0;
5507 }
5508 else if (typeof av === "boolean") {
5509 av = av ? 1 : 0;
5510 }
5511 if (bv == null) {
5512 bv = typeof av === "string" ? "" : 0;
5513 }
5514 else if (typeof bv === "boolean") {
5515 bv = bv ? 1 : 0;
5516 }
5517 if (caseInsensitive) {
5518 if (typeof av === "string") {
5519 av = av.toLowerCase();
5520 }
5521 if (typeof bv === "string") {
5522 bv = bv.toLowerCase();
5523 }
5524 }
5525 if (order === "desc") {
5526 return av === bv ? 0 : av > bv ? -1 : 1;
5527 }
5528 return av === bv ? 0 : av > bv ? 1 : -1;
5529 };
5530 return this.sortChildren(cmp, deep);
5531 }
5532 /**
5533 * Trigger `modifyChild` event on a parent to signal that a child was modified.
5534 * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
5535 */
5536 triggerModifyChild(operation, child, extra) {
5537 this.logDebug(`modifyChild(${operation})`, extra, child);
5538 if (!this.tree.options.modifyChild) {
5539 return;
5540 }
5541 if (child && child.parent !== this) {
5542 error("child " + child + " is not a child of " + this);
5543 }
5544 this._callEvent("modifyChild", extend({ operation: operation, child: child }, extra));
5545 }
5546 /**
5547 * Trigger `modifyChild` event on node.parent(!).
5548 * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
5549 * @param {object} [extra]
5550 */
5551 triggerModify(operation, extra) {
5552 // if (!this.parent) {
5553 // return;
5554 // }
5555 this.parent.triggerModifyChild(operation, this, extra);
5556 }
5557 /**
5558 * Call `callback(node)` for all descendant nodes in hierarchical order (depth-first, pre-order).
5559 *
5560 * Stop iteration, if fn() returns false. Skip current branch, if fn()
5561 * returns "skip".<br>
5562 * Return false if iteration was stopped.
5563 *
5564 * @param {function} callback the callback function.
5565 * Return false to stop iteration, return "skip" to skip this node and
5566 * its children only.
5567 * @see {@link IterableIterator<WunderbaumNode>}, {@link Wunderbaum.visit}.
5568 */
5569 visit(callback, includeSelf = false) {
5570 let res = true;
5571 const children = this.children;
5572 if (includeSelf === true) {
5573 res = callback(this);
5574 if (res === false || res === "skip") {
5575 return res;
5576 }
5577 }
5578 if (children) {
5579 for (let i = 0, l = children.length; i < l; i++) {
5580 res = children[i].visit(callback, true);
5581 if (res === false) {
5582 break;
5583 }
5584 }
5585 }
5586 return res;
5587 }
5588 /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
5589 * Stop iteration, if callback() returns false.<br>
5590 * Return false if iteration was stopped.
5591 *
5592 * @param callback the callback function. Return false to stop iteration
5593 */
5594 visitParents(callback, includeSelf = false) {
5595 if (includeSelf && callback(this) === false) {
5596 return false;
5597 }
5598 let p = this.parent;
5599 while (p) {
5600 if (callback(p) === false) {
5601 return false;
5602 }
5603 p = p.parent;
5604 }
5605 return true;
5606 }
5607 /**
5608 * Call fn(node) for all sibling nodes.<br>
5609 * Stop iteration, if fn() returns false.<br>
5610 * Return false if iteration was stopped.
5611 *
5612 * @param callback the callback function.
5613 * Return false to stop iteration.
5614 * @param includeSelf include this node in the iteration.
5615 */
5616 visitSiblings(callback, includeSelf = false) {
5617 const ac = this.parent.children;
5618 for (let i = 0, l = ac.length; i < l; i++) {
5619 const n = ac[i];
5620 if (includeSelf || n !== this) {
5621 if (callback(n) === false) {
5622 return false;
5623 }
5624 }
5625 }
5626 return true;
5627 }
5628 /**
5629 * [ext-filter] Return true if this node is matched by current filter (or no filter is active).
5630 */
5631 isMatched() {
5632 return !(this.tree.filterMode && !this.match);
5633 }
5634 }
5635 WunderbaumNode.sequence = 0;
5636
5637 /*!
5638 * Wunderbaum - ext-edit
5639 * Copyright (c) 2021-2025, Martin Wendt. Released under the MIT license.
5640 * v0.13.0, Sat, 08 Mar 2025 14:16:31 GMT (https://github.com/mar10/wunderbaum)
5641 */
5642 // const START_MARKER = "\uFFF7";
5643 class EditExtension extends WunderbaumExtension {
5644 constructor(tree) {
5645 super(tree, "edit", {
5646 debounce: 100,
5647 minlength: 1,
5648 maxlength: null,
5649 trigger: [], //["clickActive", "F2", "macEnter"],
5650 trim: true,
5651 select: true,
5652 slowClickDelay: 1000, // Handle 'clickActive' only if last click is less than this old (0: always)
5653 validity: true, //"Please enter a title",
5654 // --- Events ---
5655 // (note: there is also the `tree.change` event.)
5656 beforeEdit: null,
5657 edit: null,
5658 apply: null,
5659 });
5660 this.curEditNode = null;
5661 this.relatedNode = null;
5662 this.debouncedOnChange = debounce(this._onChange.bind(this), this.getPluginOption("debounce"));
5663 }
5664 /*
5665 * Call an event handler, while marking the current node cell 'busy'.
5666 * Deal with returned promises and ValidationError.
5667 * Convert a ValidationError into a input.setCustomValidity() call and vice versa.
5668 */
5669 async _applyChange(eventName, node, colElem, inputElem, extra) {
5670 node.log(`_applyChange(${eventName})`, extra);
5671 colElem.classList.add("wb-busy");
5672 colElem.classList.remove("wb-error", "wb-invalid");
5673 inputElem.setCustomValidity("");
5674 // Call event handler either ('change' or 'edit.appy'), which may return a
5675 // promise or a scalar value or throw a ValidationError.
5676 return new Promise((resolve, reject) => {
5677 const res = node._callEvent(eventName, extra);
5678 // normalize to promise, even if a scalar value was returned and await it
5679 Promise.resolve(res)
5680 .then((res) => {
5681 resolve(res);
5682 })
5683 .catch((err) => {
5684 reject(err);
5685 });
5686 })
5687 .then((res) => {
5688 if (!inputElem.checkValidity()) {
5689 // Native validation failed or handler called 'inputElem.setCustomValidity()'
5690 node.logWarn("inputElem.checkValidity() failed: throwing....");
5691 throw new ValidationError(inputElem.validationMessage);
5692 }
5693 return res;
5694 })
5695 .catch((err) => {
5696 if (err instanceof ValidationError) {
5697 node.logWarn("catched ", err);
5698 colElem.classList.add("wb-invalid");
5699 if (inputElem.setCustomValidity && !inputElem.validationMessage) {
5700 inputElem.setCustomValidity(err.message);
5701 }
5702 if (inputElem.validationMessage) {
5703 inputElem.reportValidity();
5704 }
5705 // throw err;
5706 }
5707 else {
5708 node.logError(`Error in ${eventName} event handler (throw e.util.ValidationError instead if this was intended)`, err);
5709 colElem.classList.add("wb-error");
5710 throw err;
5711 }
5712 })
5713 .finally(() => {
5714 colElem.classList.remove("wb-busy");
5715 });
5716 }
5717 /*
5718 * Called for when a control that is embedded in a cell fires a `change` event.
5719 */
5720 _onChange(e) {
5721 const info = Wunderbaum.getEventInfo(e);
5722 const node = info.node;
5723 const colElem = info.colElem;
5724 if (!node || info.colIdx === 0) {
5725 this.tree.log("Ignored change event for removed element or node title");
5726 return;
5727 }
5728 // See also WbChangeEventType
5729 this._applyChange("change", node, colElem, e.target, {
5730 info: info,
5731 event: e,
5732 inputElem: e.target,
5733 inputValue: Wunderbaum.util.getValueFromElem(e.target),
5734 inputValid: e.target.checkValidity(),
5735 });
5736 }
5737 init() {
5738 super.init();
5739 onEvent(this.tree.element, "change", //"change input",
5740 ".contenteditable,input,textarea,select",
5741 // #61: we must not debounce the `change`, event.target may be reset to null
5742 // when the debounced handler is called.
5743 // (e) => {
5744 // this.debouncedOnChange(e);
5745 // }
5746 (e) => this._onChange(e));
5747 }
5748 /* Called by ext_keynav to pre-process input. */
5749 _preprocessKeyEvent(data) {
5750 const event = data.event;
5751 const eventName = eventToString(event);
5752 const tree = this.tree;
5753 const trigger = this.getPluginOption("trigger");
5754 // const inputElem =
5755 // event.target && event.target.closest("input,[contenteditable]");
5756 // tree.logDebug(`_preprocessKeyEvent: ${eventName}, editing:${this.isEditingTitle()}`);
5757 // --- Title editing: apply/discard ---
5758 // if (inputElem) {
5759 if (this.isEditingTitle()) {
5760 switch (eventName) {
5761 case "Enter":
5762 this._stopEditTitle(true, { event: event });
5763 return false;
5764 case "Escape":
5765 this._stopEditTitle(false, { event: event });
5766 return false;
5767 }
5768 // If the event target is an input element or `contenteditable="true"`,
5769 // we ignore it as navigation command
5770 return false;
5771 }
5772 // --- Trigger title editing
5773 if (tree.isRowNav() || tree.activeColIdx === 0) {
5774 switch (eventName) {
5775 case "Enter":
5776 if (trigger.indexOf("macEnter") >= 0 && isMac) {
5777 this.startEditTitle();
5778 return false;
5779 }
5780 break;
5781 case "F2":
5782 if (trigger.indexOf("F2") >= 0) {
5783 this.startEditTitle();
5784 return false;
5785 }
5786 break;
5787 }
5788 return true;
5789 }
5790 return true;
5791 }
5792 /** Return true if a title is currently being edited. */
5793 isEditingTitle(node) {
5794 return node ? this.curEditNode === node : !!this.curEditNode;
5795 }
5796 /** Start renaming, i.e. replace the title with an embedded `<input>`. */
5797 startEditTitle(node) {
5798 node = node !== null && node !== void 0 ? node : this.tree.getActiveNode();
5799 const validity = this.getPluginOption("validity");
5800 const select = this.getPluginOption("select");
5801 if (!node) {
5802 return;
5803 }
5804 if (node.isStatusNode()) {
5805 node.logWarn("Cannot edit status node.");
5806 return;
5807 }
5808 this.tree.logDebug(`startEditTitle(node=${node})`);
5809 let inputHtml = node._callEvent("edit.beforeEdit");
5810 if (inputHtml === false) {
5811 node.logDebug("beforeEdit canceled operation.");
5812 return;
5813 }
5814 // `beforeEdit(e)` may return an input HTML string. Otherwise use a default
5815 // (we also treat a `true` return value as 'use default'):
5816 if (inputHtml === true || !inputHtml) {
5817 const title = escapeHtml(node.title);
5818 let opt = this.getPluginOption("maxlength");
5819 const maxlength = opt ? ` maxlength="${opt}"` : "";
5820 opt = this.getPluginOption("minlength");
5821 const minlength = opt ? ` minlength="${opt}"` : "";
5822 const required = opt > 0 ? " required" : "";
5823 inputHtml =
5824 `<input type=text class="wb-input-edit" tabindex=-1 value="${title}" ` +
5825 `autocorrect="off"${required}${minlength}${maxlength} >`;
5826 }
5827 const titleSpan = node
5828 .getColElem(0)
5829 .querySelector(".wb-title");
5830 titleSpan.innerHTML = inputHtml;
5831 const inputElem = titleSpan.firstElementChild;
5832 if (validity) {
5833 // Permanently apply input validations (CSS and tooltip)
5834 inputElem.addEventListener("keydown", (e) => {
5835 inputElem.setCustomValidity("");
5836 if (!inputElem.reportValidity()) {
5837 node.logWarn(`Invalid input: '${inputElem.value}'`);
5838 }
5839 });
5840 }
5841 inputElem.focus();
5842 if (select) {
5843 inputElem.select();
5844 }
5845 this.curEditNode = node;
5846 node._callEvent("edit.edit", {
5847 inputElem: inputElem,
5848 });
5849 }
5850 /**
5851 *
5852 * @param apply
5853 * @returns
5854 */
5855 stopEditTitle(apply) {
5856 return this._stopEditTitle(apply, {});
5857 }
5858 /*
5859 *
5860 * @param apply
5861 * @param opts.canKeepOpen
5862 */
5863 _stopEditTitle(apply, options) {
5864 var _a;
5865 options !== null && options !== void 0 ? options : (options = {});
5866 const focusElem = document.activeElement;
5867 let newValue = focusElem ? getValueFromElem(focusElem) : null;
5868 const node = this.curEditNode;
5869 const forceClose = !!options.forceClose;
5870 const validity = this.getPluginOption("validity");
5871 if (newValue && this.getPluginOption("trim")) {
5872 newValue = newValue.trim();
5873 }
5874 if (!node) {
5875 this.tree.logDebug("stopEditTitle: not in edit mode.");
5876 return;
5877 }
5878 node.logDebug(`stopEditTitle(${apply})`, options, focusElem, newValue);
5879 if (apply && newValue !== null && newValue !== node.title) {
5880 const errMsg = focusElem.validationMessage;
5881 if (errMsg) {
5882 // input element's native validation failed
5883 throw new Error(`Input validation failed for "${newValue}": ${errMsg}.`);
5884 }
5885 const colElem = node.getColElem(0);
5886 this._applyChange("edit.apply", node, colElem, focusElem, {
5887 oldValue: node.title,
5888 newValue: newValue,
5889 inputElem: focusElem,
5890 inputValid: focusElem.checkValidity(),
5891 }).then((value) => {
5892 var _a;
5893 const errMsg = focusElem.validationMessage;
5894 if (validity && errMsg && value !== false) {
5895 // Handler called 'inputElem.setCustomValidity()' to signal error
5896 throw new Error(`Edit apply validation failed for "${newValue}": ${errMsg}.`);
5897 }
5898 // Discard the embedded `<input>`
5899 // node.logDebug("applyChange:", value, forceClose)
5900 if (!forceClose && value === false) {
5901 // Keep open
5902 return;
5903 }
5904 node === null || node === void 0 ? void 0 : node.setTitle(newValue);
5905 // NOTE: At least on Safari, this render call triggers a scroll event
5906 // probably because the focused input is replaced.
5907 (_a = this.curEditNode) === null || _a === void 0 ? void 0 : _a._render({ preventScroll: true });
5908 this.curEditNode = null;
5909 this.relatedNode = null;
5910 this.tree.setFocus(); // restore focus that was in the input element
5911 });
5912 // .catch((err) => {
5913 // node.logError(err);
5914 // });
5915 // Trigger 'change' event for embedded `<input>`
5916 // focusElem.blur();
5917 }
5918 else {
5919 // Discard the embedded `<input>`
5920 // NOTE: At least on Safari, this render call triggers a scroll event
5921 // probably because the focused input is replaced.
5922 (_a = this.curEditNode) === null || _a === void 0 ? void 0 : _a._render({ preventScroll: true });
5923 this.curEditNode = null;
5924 this.relatedNode = null;
5925 // We discarded the <input>, so we have to acquire keyboard focus again
5926 this.tree.setFocus();
5927 }
5928 }
5929 /**
5930 * Create a new child or sibling node and start edit mode.
5931 */
5932 createNode(mode = "after", node, init) {
5933 const tree = this.tree;
5934 node = node !== null && node !== void 0 ? node : tree.getActiveNode();
5935 assert(node, "No node was passed, or no node is currently active.");
5936 // const validity = this.getPluginOption("validity");
5937 mode = mode || "prependChild";
5938 if (init == null) {
5939 init = { title: "" };
5940 }
5941 else if (typeof init === "string") {
5942 init = { title: init };
5943 }
5944 else {
5945 assert(isPlainObject(init), `Expected a plain object: ${init}`);
5946 }
5947 // Make sure node is expanded (and loaded) in 'child' mode
5948 if ((mode === "prependChild" || mode === "appendChild") &&
5949 (node === null || node === void 0 ? void 0 : node.isExpandable(true))) {
5950 node.setExpanded().then(() => {
5951 this.createNode(mode, node, init);
5952 });
5953 return;
5954 }
5955 const newNode = node.addNode(init, mode);
5956 newNode.setClass("wb-edit-new");
5957 this.relatedNode = node;
5958 // Don't filter new nodes:
5959 newNode.match = -1;
5960 newNode.makeVisible({ noAnimation: true }).then(() => {
5961 this.startEditTitle(newNode);
5962 });
5963 }
5964 }
5965
5966 /*!
5967 * wunderbaum.ts
5968 *
5969 * A treegrid control.
5970 *
5971 * Copyright (c) 2021-2025, Martin Wendt (https://wwWendt.de).
5972 * https://github.com/mar10/wunderbaum
5973 *
5974 * Released under the MIT license.
5975 * @version v0.13.0
5976 * @date Sat, 08 Mar 2025 14:16:31 GMT
5977 */
5978 // import "./wunderbaum.scss";
5979 class WbSystemRoot extends WunderbaumNode {
5980 constructor(tree) {
5981 super(tree, null, {
5982 key: "__root__",
5983 title: tree.id,
5984 });
5985 }
5986 toString() {
5987 return `WbSystemRoot@${this.key}<'${this.tree.id}'>`;
5988 }
5989 }
5990 /**
5991 * A persistent plain object or array.
5992 *
5993 * See also {@link WunderbaumOptions}.
5994 */
5995 class Wunderbaum {
5996 /** Currently active node if any.
5997 * Use {@link WunderbaumNode.setActive|setActive} to modify.
5998 */
5999 get activeNode() {
6000 var _a;
6001 // Check for deleted node, i.e. node.tree === null
6002 return ((_a = this._activeNode) === null || _a === void 0 ? void 0 : _a.tree) ? this._activeNode : null;
6003 }
6004 /** Current node hat has keyboard focus if any.
6005 * Use {@link WunderbaumNode.setFocus|setFocus()} to modify.
6006 */
6007 get focusNode() {
6008 var _a;
6009 // Check for deleted node, i.e. node.tree === null
6010 return ((_a = this._focusNode) === null || _a === void 0 ? void 0 : _a.tree) ? this._focusNode : null;
6011 }
6012 constructor(options) {
6013 this.enabled = true;
6014 /** Contains additional data that was sent as response to an Ajax source load request. */
6015 this.data = {};
6016 this.extensionList = [];
6017 this.extensions = {};
6018 this.keyMap = new Map();
6019 this.refKeyMap = new Map();
6020 this.treeRowCount = 0;
6021 this._disableUpdateCount = 0;
6022 this._disableUpdateIgnoreCount = 0;
6023 this._activeNode = null;
6024 this._focusNode = null;
6025 /** Shared properties, referenced by `node.type`. */
6026 this.types = {};
6027 /** List of column definitions. */
6028 this.columns = []; // any[] = [];
6029 this._columnsById = {};
6030 // Modification Status
6031 this.pendingChangeTypes = new Set();
6032 /** Expose some useful methods of the util.ts module as `tree._util`. */
6033 this._util = util;
6034 // --- SELECT ---
6035 // /** @internal */
6036 // public selectRangeAnchor: WunderbaumNode | null = null;
6037 // --- BREADCRUMB ---
6038 /** Filter options (used as defaults for calls to {@link Wunderbaum.filterNodes} ) */
6039 this.breadcrumb = null;
6040 // --- FILTER ---
6041 /** Filter options (used as defaults for calls to {@link Wunderbaum.filterNodes} ) */
6042 this.filterMode = null;
6043 // --- KEYNAV ---
6044 /** @internal Use `setColumn()`/`getActiveColElem()` to access. */
6045 this.activeColIdx = 0;
6046 /** @internal */
6047 this._cellNavMode = false;
6048 /** @internal */
6049 this.lastQuicksearchTime = 0;
6050 /** @internal */
6051 this.lastQuicksearchTerm = "";
6052 // --- EDIT ---
6053 this.lastClickTime = 0;
6054 const opts = (this.options = extend({
6055 id: null,
6056 source: null, // URL for GET/PUT, Ajax options, or callback
6057 element: null, // <div class="wunderbaum">
6058 debugLevel: DEFAULT_DEBUGLEVEL, // 0:quiet, 1:errors, 2:warnings, 3:info, 4:verbose
6059 header: null, // Show/hide header (pass bool or string)
6060 // headerHeightPx: ROW_HEIGHT,
6061 rowHeightPx: DEFAULT_ROW_HEIGHT,
6062 iconMap: "bootstrap",
6063 columns: null,
6064 types: null,
6065 // escapeTitles: true,
6066 enabled: true,
6067 fixedCol: false,
6068 showSpinner: false,
6069 checkbox: false,
6070 minExpandLevel: 0,
6071 emptyChildListExpandable: false,
6072 // updateThrottleWait: 200,
6073 skeleton: false,
6074 connectTopBreadcrumb: null,
6075 selectMode: "multi", // SelectModeType
6076 // --- KeyNav ---
6077 navigationModeOption: null, // NavModeEnum,
6078 quicksearch: true,
6079 // --- Events ---
6080 iconBadge: null,
6081 change: null,
6082 // enhanceTitle: null,
6083 error: null,
6084 receive: null,
6085 // --- Strings ---
6086 strings: {
6087 loadError: "Error",
6088 loading: "Loading...",
6089 noData: "No data",
6090 breadcrumbDelimiter: " » ",
6091 queryResult: "Found ${matches} of ${count}",
6092 noMatch: "No results",
6093 matchIndex: "${match} of ${matches}",
6094 },
6095 }, options));
6096 const readyDeferred = new Deferred();
6097 this.ready = readyDeferred.promise();
6098 let readyOk = false;
6099 this.ready
6100 .then(() => {
6101 readyOk = true;
6102 try {
6103 this._callEvent("init");
6104 }
6105 catch (error) {
6106 // We re-raise in the reject handler, but Chrome resets the stack
6107 // frame then, so we log it here:
6108 this.logError("Exception inside `init(e)` event:", error);
6109 }
6110 })
6111 .catch((err) => {
6112 if (readyOk) {
6113 // Error occurred in `init` handler. We can re-raise, but Chrome
6114 // resets the stack frame.
6115 throw err;
6116 }
6117 else {
6118 // Error in load process
6119 this._callEvent("init", { error: err });
6120 }
6121 });
6122 this.id = opts.id || "wb_" + ++Wunderbaum.sequence;
6123 this.root = new WbSystemRoot(this);
6124 this._registerExtension(new KeynavExtension(this));
6125 this._registerExtension(new EditExtension(this));
6126 this._registerExtension(new FilterExtension(this));
6127 this._registerExtension(new DndExtension(this));
6128 this._registerExtension(new GridExtension(this));
6129 this._registerExtension(new LoggerExtension(this));
6130 this._updateViewportThrottled = adaptiveThrottle(this._updateViewportImmediately.bind(this), {});
6131 // --- Evaluate options
6132 this.columns = opts.columns;
6133 delete opts.columns;
6134 if (!this.columns || !this.columns.length) {
6135 const title = typeof opts.header === "string" ? opts.header : this.id;
6136 this.columns = [{ id: "*", title: title, width: "*" }];
6137 }
6138 if (opts.types) {
6139 this.setTypes(opts.types, true);
6140 }
6141 delete opts.types;
6142 // --- Create Markup
6143 this.element = elemFromSelector(opts.element);
6144 assert(!!this.element, `Invalid 'element' option: ${opts.element}`);
6145 this.element.classList.add("wunderbaum");
6146 if (!this.element.getAttribute("tabindex")) {
6147 this.element.tabIndex = 0;
6148 }
6149 if (opts.rowHeightPx !== DEFAULT_ROW_HEIGHT) {
6150 this.element.style.setProperty("--wb-row-outer-height", opts.rowHeightPx + "px");
6151 this.element.style.setProperty("--wb-row-inner-height", opts.rowHeightPx - 2 + "px");
6152 }
6153 // Attach tree instance to <div>
6154 this.element._wb_tree = this;
6155 // Create header markup, or take it from the existing html
6156 this.headerElement =
6157 this.element.querySelector("div.wb-header");
6158 const wantHeader = opts.header == null ? this.columns.length > 1 : !!opts.header;
6159 if (this.headerElement) {
6160 // User existing header markup to define `this.columns`
6161 assert(!this.columns, "`opts.columns` must not be set if table markup already contains a header");
6162 this.columns = [];
6163 const rowElement = this.headerElement.querySelector("div.wb-row");
6164 for (const colDiv of rowElement.querySelectorAll("div")) {
6165 this.columns.push({
6166 id: colDiv.dataset.id || `col_${this.columns.length}`,
6167 // id: colDiv.dataset.id || null,
6168 title: "" + colDiv.textContent,
6169 // text: "" + colDiv.textContent,
6170 width: "*", // TODO: read from header span
6171 });
6172 }
6173 }
6174 else {
6175 // We need a row div, the rest will be computed from `this.columns`
6176 const coldivs = "<span class='wb-col'></span>".repeat(this.columns.length);
6177 this.element.innerHTML = `
6178 <div class='wb-header'>
6179 <div class='wb-row'>
6180 ${coldivs}
6181 </div>
6182 </div>`;
6183 if (!wantHeader) {
6184 const he = this.element.querySelector("div.wb-header");
6185 he.style.display = "none";
6186 }
6187 }
6188 //
6189 this.element.innerHTML += `
6190 <div class="wb-list-container">
6191 <div class="wb-node-list"></div>
6192 </div>`;
6193 this.listContainerElement = this.element.querySelector("div.wb-list-container");
6194 this.nodeListElement =
6195 this.listContainerElement.querySelector("div.wb-node-list");
6196 this.headerElement =
6197 this.element.querySelector("div.wb-header");
6198 this.element.classList.toggle("wb-grid", this.columns.length > 1);
6199 if (this.options.connectTopBreadcrumb) {
6200 this.breadcrumb = elemFromSelector(this.options.connectTopBreadcrumb);
6201 assert(!this.breadcrumb || this.breadcrumb.innerHTML != null, `Invalid 'connectTopBreadcrumb' option: ${this.breadcrumb}.`);
6202 this.breadcrumb.addEventListener("click", (e) => {
6203 // const node = Wunderbaum.getNode(e)!;
6204 const elem = e.target;
6205 if (elem && elem.matches("a.wb-breadcrumb")) {
6206 const node = this.keyMap.get(elem.dataset.key);
6207 node === null || node === void 0 ? void 0 : node.setActive();
6208 e.preventDefault();
6209 }
6210 });
6211 }
6212 this._initExtensions();
6213 // --- apply initial options
6214 ["enabled", "fixedCol"].forEach((optName) => {
6215 if (opts[optName] != null) {
6216 this.setOption(optName, opts[optName]);
6217 }
6218 });
6219 // --- Load initial data
6220 if (opts.source) {
6221 if (opts.showSpinner) {
6222 this.nodeListElement.innerHTML = `<progress class='spinner'>${opts.strings.loading}</progress>`;
6223 }
6224 this.load(opts.source)
6225 .then(() => {
6226 // The source may have defined columns, so we may adjust the nav mode
6227 if (opts.navigationModeOption == null) {
6228 if (this.isGrid()) {
6229 this.setNavigationOption(NavModeEnum.cell);
6230 }
6231 else {
6232 this.setNavigationOption(NavModeEnum.row);
6233 }
6234 }
6235 else {
6236 this.setNavigationOption(opts.navigationModeOption);
6237 }
6238 this.update(ChangeType.structure, { immediate: true });
6239 readyDeferred.resolve();
6240 })
6241 .catch((error) => {
6242 readyDeferred.reject(error);
6243 })
6244 .finally(() => {
6245 var _a;
6246 (_a = this.element.querySelector("progress.spinner")) === null || _a === void 0 ? void 0 : _a.remove();
6247 this.element.classList.remove("wb-initializing");
6248 });
6249 }
6250 else {
6251 readyDeferred.resolve();
6252 }
6253 // Async mode is sometimes required, because this.element.clientWidth
6254 // has a wrong value at start???
6255 this.update(ChangeType.any);
6256 // --- Bind listeners
6257 this.element.addEventListener("scroll", (e) => {
6258 // this.log(`scroll, scrollTop:${e.target.scrollTop}`, e);
6259 this.update(ChangeType.scroll);
6260 });
6261 this.resizeObserver = new ResizeObserver((entries) => {
6262 // this.log("ResizeObserver: Size changed", entries);
6263 this.update(ChangeType.resize);
6264 });
6265 this.resizeObserver.observe(this.element);
6266 onEvent(this.element, "click", ".wb-button,.wb-col-icon", (e) => {
6267 var _a, _b;
6268 const info = Wunderbaum.getEventInfo(e);
6269 const command = (_b = (_a = e.target) === null || _a === void 0 ? void 0 : _a.dataset) === null || _b === void 0 ? void 0 : _b.command;
6270 this._callEvent("buttonClick", {
6271 event: e,
6272 info: info,
6273 command: command,
6274 });
6275 });
6276 onEvent(this.nodeListElement, "click", "div.wb-row", (e) => {
6277 const info = Wunderbaum.getEventInfo(e);
6278 const node = info.node;
6279 const mouseEvent = e;
6280 // this.log("click", info);
6281 // if (this._selectRange(info) === false) {
6282 // return;
6283 // }
6284 if (this._callEvent("click", { event: e, node: node, info: info }) === false) {
6285 this.lastClickTime = Date.now();
6286 return false;
6287 }
6288 if (node) {
6289 if (mouseEvent.ctrlKey) {
6290 node.toggleSelected();
6291 return;
6292 }
6293 // Edit title if 'clickActive' is triggered:
6294 const trigger = this.getOption("edit.trigger");
6295 const slowClickDelay = this.getOption("edit.slowClickDelay");
6296 if (trigger.indexOf("clickActive") >= 0 &&
6297 info.region === "title" &&
6298 node.isActive() &&
6299 (!slowClickDelay || Date.now() - this.lastClickTime < slowClickDelay)) {
6300 node.startEditTitle();
6301 }
6302 if (info.colIdx >= 0) {
6303 node.setActive(true, { colIdx: info.colIdx, event: e });
6304 }
6305 else {
6306 node.setActive(true, { event: e });
6307 }
6308 if (info.region === NodeRegion.expander) {
6309 node.setExpanded(!node.isExpanded(), {
6310 scrollIntoView: options.scrollIntoViewOnExpandClick !== false,
6311 });
6312 }
6313 else if (info.region === NodeRegion.checkbox) {
6314 node.toggleSelected();
6315 }
6316 }
6317 this.lastClickTime = Date.now();
6318 });
6319 onEvent(this.nodeListElement, "dblclick", "div.wb-row", (e) => {
6320 const info = Wunderbaum.getEventInfo(e);
6321 const node = info.node;
6322 // this.log("dblclick", info, e);
6323 if (this._callEvent("dblclick", { event: e, node: node, info: info }) ===
6324 false) {
6325 return false;
6326 }
6327 if (node &&
6328 info.colIdx === 0 &&
6329 node.isExpandable() &&
6330 info.region !== NodeRegion.expander) {
6331 this._callMethod("edit._stopEditTitle");
6332 node.setExpanded(!node.isExpanded());
6333 }
6334 });
6335 onEvent(this.element, "keydown", (e) => {
6336 const info = Wunderbaum.getEventInfo(e);
6337 const eventName = eventToString(e);
6338 const node = info.node || this.getFocusNode();
6339 this._callHook("onKeyEvent", {
6340 event: e,
6341 node: node,
6342 info: info,
6343 eventName: eventName,
6344 });
6345 });
6346 onEvent(this.element, "focusin focusout", (e) => {
6347 const flag = e.type === "focusin";
6348 const targetNode = Wunderbaum.getNode(e);
6349 this._callEvent("focus", { flag: flag, event: e });
6350 if (flag && this.isRowNav() && !this.isEditingTitle()) {
6351 if (opts.navigationModeOption === NavModeEnum.row) {
6352 targetNode === null || targetNode === void 0 ? void 0 : targetNode.setActive();
6353 }
6354 else {
6355 this.setCellNav();
6356 }
6357 }
6358 if (!flag) {
6359 this._callMethod("edit._stopEditTitle", true, {
6360 event: e,
6361 forceClose: true,
6362 });
6363 }
6364 });
6365 }
6366 /**
6367 * Return a Wunderbaum instance, from element, id, index, or event.
6368 *
6369 * ```js
6370 * getTree(); // Get first Wunderbaum instance on page
6371 * getTree(1); // Get second Wunderbaum instance on page
6372 * getTree(event); // Get tree for this mouse- or keyboard event
6373 * getTree("foo"); // Get tree for this `tree.options.id`
6374 * getTree("#tree"); // Get tree for first matching element selector
6375 * ```
6376 */
6377 static getTree(el) {
6378 if (el instanceof Wunderbaum) {
6379 return el;
6380 }
6381 else if (el instanceof WunderbaumNode) {
6382 return el.tree;
6383 }
6384 if (el === undefined) {
6385 el = 0; // get first tree
6386 }
6387 if (typeof el === "number") {
6388 el = document.querySelectorAll(".wunderbaum")[el]; // el was an integer: return nth element
6389 }
6390 else if (typeof el === "string") {
6391 // Search all trees for matching ID
6392 for (const treeElem of document.querySelectorAll(".wunderbaum")) {
6393 const tree = treeElem._wb_tree;
6394 if (tree && tree.id === el) {
6395 return tree;
6396 }
6397 }
6398 // Search by selector
6399 el = document.querySelector(el);
6400 if (!el) {
6401 return null;
6402 }
6403 }
6404 else if (el.target) {
6405 el = el.target;
6406 }
6407 assert(el instanceof Element, `Invalid el type: ${el}`);
6408 if (!el.matches(".wunderbaum")) {
6409 el = el.closest(".wunderbaum");
6410 }
6411 if (el && el._wb_tree) {
6412 return el._wb_tree;
6413 }
6414 return null;
6415 }
6416 /**
6417 * Return the icon-function -> icon-definition mapping.
6418 */
6419 get iconMap() {
6420 const map = this.options.iconMap;
6421 if (typeof map === "string") {
6422 return iconMaps[map];
6423 }
6424 return map;
6425 }
6426 /**
6427 * Return a WunderbaumNode instance from element or event.
6428 */
6429 static getNode(el) {
6430 if (!el) {
6431 return null;
6432 }
6433 else if (el instanceof WunderbaumNode) {
6434 return el;
6435 }
6436 else if (el.target !== undefined) {
6437 el = el.target; // el was an Event
6438 }
6439 // `el` is a DOM element
6440 // let nodeElem = obj.closest("div.wb-row");
6441 while (el) {
6442 if (el._wb_node) {
6443 return el._wb_node;
6444 }
6445 el = el.parentElement; //.parentNode;
6446 }
6447 return null;
6448 }
6449 /**
6450 * Iterate all descendant nodes depth-first, pre-order using `for ... of ...` syntax.
6451 * More concise, but slightly slower than {@link Wunderbaum.visit}.
6452 *
6453 * Example:
6454 * ```js
6455 * for(const node of tree) {
6456 * ...
6457 * }
6458 * ```
6459 */
6460 *[Symbol.iterator]() {
6461 yield* this.root;
6462 }
6463 /** @internal */
6464 _registerExtension(extension) {
6465 this.extensionList.push(extension);
6466 this.extensions[extension.id] = extension;
6467 // this.extensionMap.set(extension.id, extension);
6468 }
6469 /** Called on tree (re)init after markup is created, before loading. */
6470 _initExtensions() {
6471 for (const ext of this.extensionList) {
6472 ext.init();
6473 }
6474 }
6475 /** Add node to tree's bookkeeping data structures. */
6476 _registerNode(node) {
6477 const key = node.key;
6478 assert(key != null, `Missing key: '${node}'.`);
6479 assert(!this.keyMap.has(key), `Duplicate key: '${key}': ${node}.`);
6480 this.keyMap.set(key, node);
6481 const rk = node.refKey;
6482 if (rk != null) {
6483 const rks = this.refKeyMap.get(rk); // Set of nodes with this refKey
6484 if (rks) {
6485 rks.add(node);
6486 }
6487 else {
6488 this.refKeyMap.set(rk, new Set([node]));
6489 }
6490 }
6491 }
6492 /** Remove node from tree's bookkeeping data structures. */
6493 _unregisterNode(node) {
6494 // Remove refKey reference from map (if any)
6495 const rk = node.refKey;
6496 if (rk != null) {
6497 const rks = this.refKeyMap.get(rk);
6498 if (rks && rks.delete(node) && !rks.size) {
6499 // We just removed the last element
6500 this.refKeyMap.delete(rk);
6501 }
6502 }
6503 // Remove key reference from map
6504 this.keyMap.delete(node.key);
6505 // Mark as disposed
6506 node.tree = null;
6507 node.parent = null;
6508 // Remove HTML markup
6509 node.removeMarkup();
6510 }
6511 /** Call all hook methods of all registered extensions.*/
6512 _callHook(hook, data = {}) {
6513 let res;
6514 const d = extend({}, { tree: this, options: this.options, result: undefined }, data);
6515 for (const ext of this.extensionList) {
6516 res = ext[hook].call(ext, d);
6517 if (res === false) {
6518 break;
6519 }
6520 if (d.result !== undefined) {
6521 res = d.result;
6522 }
6523 }
6524 return res;
6525 }
6526 /**
6527 * Call tree method or extension method if defined.
6528 *
6529 * Example:
6530 * ```js
6531 * tree._callMethod("edit.startEdit", "arg1", "arg2")
6532 * ```
6533 */
6534 _callMethod(name, ...args) {
6535 const [p, n] = name.split(".");
6536 const obj = n ? this.extensions[p] : this;
6537 const func = obj[n];
6538 if (func) {
6539 return func.apply(obj, args);
6540 }
6541 else {
6542 this.logError(`Calling undefined method '${name}()'.`);
6543 }
6544 }
6545 /**
6546 * Call event handler if defined in tree or tree.EXTENSION options.
6547 *
6548 * Example:
6549 * ```js
6550 * tree._callEvent("edit.beforeEdit", {foo: 42})
6551 * ```
6552 */
6553 _callEvent(type, extra) {
6554 const [p, n] = type.split(".");
6555 const opts = this.options;
6556 const func = n ? opts[p][n] : opts[p];
6557 if (func) {
6558 return func.call(this, extend({ type: type, tree: this, util: this._util }, extra));
6559 // } else {
6560 // this.logError(`Triggering undefined event '${type}'.`)
6561 }
6562 }
6563 /** Return the node for given row index. */
6564 _getNodeByRowIdx(idx) {
6565 // TODO: start searching from active node (reverse)
6566 let node = null;
6567 this.visitRows((n) => {
6568 if (n._rowIdx === idx) {
6569 node = n;
6570 return false;
6571 }
6572 });
6573 return node;
6574 }
6575 /** Return the topmost visible node in the viewport.
6576 * @param complete If `false`, the node is considered visible if at least one
6577 * pixel is visible.
6578 */
6579 getTopmostVpNode(complete = true) {
6580 const rowHeight = this.options.rowHeightPx;
6581 const gracePx = 1; // ignore subpixel scrolling
6582 const scrollParent = this.element;
6583 // const headerHeight = this.headerElement.clientHeight; // May be 0
6584 const scrollTop = scrollParent.scrollTop; // + headerHeight;
6585 let topIdx;
6586 if (complete) {
6587 topIdx = Math.ceil((scrollTop - gracePx) / rowHeight);
6588 }
6589 else {
6590 topIdx = Math.floor(scrollTop / rowHeight);
6591 }
6592 return this._getNodeByRowIdx(topIdx);
6593 }
6594 /** Return the lowest visible node in the viewport. */
6595 getLowestVpNode(complete = true) {
6596 const rowHeight = this.options.rowHeightPx;
6597 const scrollParent = this.element;
6598 const headerHeight = this.headerElement.clientHeight; // May be 0
6599 const scrollTop = scrollParent.scrollTop;
6600 const clientHeight = scrollParent.clientHeight - headerHeight;
6601 let bottomIdx;
6602 if (complete) {
6603 bottomIdx = Math.floor((scrollTop + clientHeight) / rowHeight) - 1;
6604 }
6605 else {
6606 bottomIdx = Math.ceil((scrollTop + clientHeight) / rowHeight) - 1;
6607 }
6608 bottomIdx = Math.min(bottomIdx, this.count(true) - 1);
6609 return this._getNodeByRowIdx(bottomIdx);
6610 }
6611 /** Return following visible node in the viewport. */
6612 _getNextNodeInView(node, options) {
6613 let ofs = (options === null || options === void 0 ? void 0 : options.ofs) || 1;
6614 const reverse = !!(options === null || options === void 0 ? void 0 : options.reverse);
6615 this.visitRows((n) => {
6616 node = n;
6617 if ((options === null || options === void 0 ? void 0 : options.cb) && options.cb(n)) {
6618 return false;
6619 }
6620 if (ofs-- <= 0) {
6621 return false;
6622 }
6623 }, { reverse: reverse, start: node || this.getActiveNode() });
6624 return node;
6625 }
6626 /**
6627 * Append (or insert) a list of toplevel nodes.
6628 *
6629 * @see {@link WunderbaumNode.addChildren}
6630 */
6631 addChildren(nodeData, options) {
6632 return this.root.addChildren(nodeData, options);
6633 }
6634 /**
6635 * Apply a modification or navigation operation.
6636 *
6637 * Most of these commands simply map to a node or tree method.
6638 * This method is especially useful when implementing keyboard mapping,
6639 * context menus, or external buttons.
6640 *
6641 * Valid commands:
6642 * - 'moveUp', 'moveDown'
6643 * - 'indent', 'outdent'
6644 * - 'remove'
6645 * - 'edit', 'addChild', 'addSibling': (reqires ext-edit extension)
6646 * - 'cut', 'copy', 'paste': (use an internal singleton 'clipboard')
6647 * - 'down', 'first', 'last', 'left', 'parent', 'right', 'up': navigate
6648 *
6649 */
6650 applyCommand(cmd, nodeOrOpts, options) {
6651 let // clipboard,
6652 node, refNode;
6653 // options = $.extend(
6654 // { setActive: true, clipboard: CLIPBOARD },
6655 // options_
6656 // );
6657 if (nodeOrOpts instanceof WunderbaumNode) {
6658 node = nodeOrOpts;
6659 }
6660 else {
6661 node = this.getActiveNode();
6662 assert(options === undefined, `Unexpected options: ${options}`);
6663 options = nodeOrOpts;
6664 }
6665 // clipboard = options.clipboard;
6666 switch (cmd) {
6667 // Sorting and indentation:
6668 case "moveUp":
6669 refNode = node.getPrevSibling();
6670 if (refNode) {
6671 node.moveTo(refNode, "before");
6672 node.setActive();
6673 }
6674 break;
6675 case "moveDown":
6676 refNode = node.getNextSibling();
6677 if (refNode) {
6678 node.moveTo(refNode, "after");
6679 node.setActive();
6680 }
6681 break;
6682 case "indent":
6683 refNode = node.getPrevSibling();
6684 if (refNode) {
6685 node.moveTo(refNode, "appendChild");
6686 refNode.setExpanded();
6687 node.setActive();
6688 }
6689 break;
6690 case "outdent":
6691 if (!node.isTopLevel()) {
6692 node.moveTo(node.getParent(), "after");
6693 node.setActive();
6694 }
6695 break;
6696 // Remove:
6697 case "remove":
6698 refNode = node.getPrevSibling() || node.getParent();
6699 node.remove();
6700 if (refNode) {
6701 refNode.setActive();
6702 }
6703 break;
6704 // Add, edit (requires ext-edit):
6705 case "addChild":
6706 this._callMethod("edit.createNode", "prependChild");
6707 break;
6708 case "addSibling":
6709 this._callMethod("edit.createNode", "after");
6710 break;
6711 case "rename":
6712 node.startEditTitle();
6713 break;
6714 // Simple clipboard simulation:
6715 // case "cut":
6716 // clipboard = { mode: cmd, data: node };
6717 // break;
6718 // case "copy":
6719 // clipboard = {
6720 // mode: cmd,
6721 // data: node.toDict(function(d, n) {
6722 // delete d.key;
6723 // }),
6724 // };
6725 // break;
6726 // case "clear":
6727 // clipboard = null;
6728 // break;
6729 // case "paste":
6730 // if (clipboard.mode === "cut") {
6731 // // refNode = node.getPrevSibling();
6732 // clipboard.data.moveTo(node, "child");
6733 // clipboard.data.setActive();
6734 // } else if (clipboard.mode === "copy") {
6735 // node.addChildren(clipboard.data).setActive();
6736 // }
6737 // break;
6738 // Navigation commands:
6739 case "down":
6740 case "first":
6741 case "last":
6742 case "left":
6743 case "nextMatch":
6744 case "pageDown":
6745 case "pageUp":
6746 case "parent":
6747 case "prevMatch":
6748 case "right":
6749 case "up":
6750 return node.navigate(cmd);
6751 default:
6752 error(`Unhandled command: '${cmd}'`);
6753 }
6754 }
6755 /** Delete all nodes. */
6756 clear() {
6757 this.root.removeChildren();
6758 this.root.children = null;
6759 this.keyMap.clear();
6760 this.refKeyMap.clear();
6761 this.treeRowCount = 0;
6762 this._activeNode = null;
6763 this._focusNode = null;
6764 // this.types = {};
6765 // this. columns =[];
6766 // this._columnsById = {};
6767 // Modification Status
6768 // this.changedSince = 0;
6769 // this.changes.clear();
6770 // this.changedNodes.clear();
6771 // // --- FILTER ---
6772 // public filterMode: FilterModeType = null;
6773 // // --- KEYNAV ---
6774 // public activeColIdx = 0;
6775 // public cellNavMode = false;
6776 // public lastQuicksearchTime = 0;
6777 // public lastQuicksearchTerm = "";
6778 this.update(ChangeType.structure);
6779 }
6780 /**
6781 * Clear nodes and markup and detach events and observers.
6782 *
6783 * This method may be useful to free up resources before re-creating a tree
6784 * on an existing div, for example in unittest suites.
6785 * Note that this Wunderbaum instance becomes unusable afterwards.
6786 */
6787 destroy() {
6788 this.logInfo("destroy()...");
6789 this.clear();
6790 this.resizeObserver.disconnect();
6791 this.element.innerHTML = "";
6792 // Remove all event handlers
6793 this.element.outerHTML = this.element.outerHTML; // eslint-disable-line
6794 }
6795 /**
6796 * Return `tree.option.NAME` (also resolving if this is a callback).
6797 *
6798 * See also {@link WunderbaumNode.getOption|WunderbaumNode.getOption()}
6799 * to evaluate `node.NAME` setting and `tree.types[node.type].NAME`.
6800 *
6801 * @param name option name (use dot notation to access extension option, e.g.
6802 * `filter.mode`)
6803 */
6804 getOption(name, defaultValue) {
6805 let ext;
6806 let opts = this.options;
6807 // Lookup `name` in options dict
6808 if (name.indexOf(".") >= 0) {
6809 [ext, name] = name.split(".");
6810 opts = opts[ext];
6811 }
6812 let value = opts[name];
6813 // A callback resolver always takes precedence
6814 if (typeof value === "function") {
6815 value = value({ type: "resolve", tree: this });
6816 }
6817 // Use value from value options dict, fallback do default
6818 // console.info(name, value, opts)
6819 return value !== null && value !== void 0 ? value : defaultValue;
6820 }
6821 /**
6822 * Set tree option.
6823 * Use dot notation to set plugin option, e.g. "filter.mode".
6824 */
6825 setOption(name, value) {
6826 // this.log(`setOption(${name}, ${value})`);
6827 if (name.indexOf(".") >= 0) {
6828 const parts = name.split(".");
6829 const ext = this.extensions[parts[0]];
6830 ext.setPluginOption(parts[1], value);
6831 return;
6832 }
6833 this.options[name] = value;
6834 switch (name) {
6835 case "checkbox":
6836 this.update(ChangeType.any);
6837 break;
6838 case "enabled":
6839 this.setEnabled(!!value);
6840 break;
6841 case "fixedCol":
6842 this.element.classList.toggle("wb-fixed-col", !!value);
6843 break;
6844 }
6845 }
6846 /** Return true if the tree (or one of its nodes) has the input focus. */
6847 hasFocus() {
6848 return this.element.contains(document.activeElement);
6849 }
6850 /**
6851 * Return true if the tree displays a header. Grids have a header unless the
6852 * `header` option is set to `false`. Plain trees have a header if the `header`
6853 * option is a string or `true`.
6854 */
6855 hasHeader() {
6856 const header = this.options.header;
6857 return this.isGrid() ? header !== false : !!header;
6858 }
6859 /** Run code, but defer rendering of viewport until done.
6860 *
6861 * ```js
6862 * tree.runWithDeferredUpdate(() => {
6863 * return someFuncThatWouldUpdateManyNodes();
6864 * });
6865 * ```
6866 */
6867 runWithDeferredUpdate(func, hint = null) {
6868 try {
6869 this.enableUpdate(false);
6870 const res = func();
6871 assert(!(res instanceof Promise), `Promise return not allowed: ${res}`);
6872 return res;
6873 }
6874 finally {
6875 this.enableUpdate(true);
6876 }
6877 }
6878 /** Recursively expand all expandable nodes (triggers lazy load if needed). */
6879 async expandAll(flag = true, options) {
6880 await this.root.expandAll(flag, options);
6881 }
6882 /** Recursively select all nodes. */
6883 selectAll(flag = true) {
6884 return this.root.setSelected(flag, { propagateDown: true });
6885 }
6886 /** Toggle select all nodes. */
6887 toggleSelect() {
6888 this.selectAll(this.root._anySelectable());
6889 }
6890 /**
6891 * Return an array of selected nodes.
6892 * @param stopOnParents only return the topmost selected node (useful with selectMode 'hier')
6893 */
6894 getSelectedNodes(stopOnParents = false) {
6895 return this.root.getSelectedNodes(stopOnParents);
6896 }
6897 /*
6898 * Return an array of selected nodes.
6899 */
6900 _selectRange(eventInfo) {
6901 this.logDebug("_selectRange", eventInfo);
6902 error("Not yet implemented.");
6903 // const mode = this.options.selectMode!;
6904 // if (mode !== "multi") {
6905 // this.logDebug(`Range selection only available for selectMode 'multi'`);
6906 // return;
6907 // }
6908 // if (eventInfo.canonicalName === "Meta+click") {
6909 // eventInfo.node?.toggleSelected();
6910 // return false; // don't
6911 // } else if (eventInfo.canonicalName === "Shift+click") {
6912 // let from = this.activeNode;
6913 // let to = eventInfo.node;
6914 // if (!from || !to || from === to) {
6915 // return;
6916 // }
6917 // this.runWithDeferredUpdate(() => {
6918 // this.visitRows(
6919 // (node) => {
6920 // node.setSelected();
6921 // },
6922 // {
6923 // includeHidden: true,
6924 // includeSelf: false,
6925 // start: from,
6926 // reverse: from!._rowIdx! > to!._rowIdx!,
6927 // }
6928 // );
6929 // });
6930 // return false;
6931 // }
6932 }
6933 /** Return the number of nodes in the data model.
6934 * @param visible if true, nodes that are hidden due to collapsed parents are ignored.
6935 */
6936 count(visible = false) {
6937 return visible ? this.treeRowCount : this.keyMap.size;
6938 }
6939 /** Return the number of *unique* nodes in the data model, i.e. unique `node.refKey`.
6940 */
6941 countUnique() {
6942 return this.refKeyMap.size;
6943 }
6944 /** @internal sanity check. */
6945 _check() {
6946 let i = 0;
6947 this.visit((n) => {
6948 i++;
6949 });
6950 if (this.keyMap.size !== i) {
6951 this.logWarn(`_check failed: ${this.keyMap.size} !== ${i}`);
6952 }
6953 // util.assert(this.keyMap.size === i);
6954 }
6955 /**
6956 * Find all nodes that match condition.
6957 *
6958 * @param match title string to search for, or a
6959 * callback function that returns `true` if a node is matched.
6960 * @see {@link WunderbaumNode.findAll}
6961 */
6962 findAll(match) {
6963 return this.root.findAll(match);
6964 }
6965 /**
6966 * Find all nodes with a given _refKey_ (aka a list of clones).
6967 *
6968 * @param refKey a `node.refKey` value to search for.
6969 * @returns an array of matching nodes with at least two element or `[]`
6970 * if nothing found.
6971 *
6972 * @see {@link WunderbaumNode.getCloneList}
6973 */
6974 findByRefKey(refKey) {
6975 const clones = this.refKeyMap.get(refKey);
6976 return clones ? Array.from(clones) : [];
6977 }
6978 /**
6979 * Find first node that matches condition.
6980 *
6981 * @param match title string to search for, or a
6982 * callback function that returns `true` if a node is matched.
6983 * @see {@link WunderbaumNode.findFirst}
6984 */
6985 findFirst(match) {
6986 return this.root.findFirst(match);
6987 }
6988 /**
6989 * Find first node that matches condition.
6990 *
6991 * @see {@link WunderbaumNode.findFirst}
6992 *
6993 */
6994 findKey(key) {
6995 return this.keyMap.get(key) || null;
6996 }
6997 /**
6998 * Find the next visible node that starts with `match`, starting at `startNode`
6999 * and wrap-around at the end.
7000 * Used by quicksearch and keyboard navigation.
7001 */
7002 findNextNode(match, startNode, reverse = false) {
7003 //, visibleOnly) {
7004 let res = null;
7005 const firstNode = this.getFirstChild();
7006 // Last visible node (calculation is expensive, so do only if we need it):
7007 const lastNode = reverse ? this.findRelatedNode(firstNode, "last") : null;
7008 const matcher = typeof match === "string" ? makeNodeTitleStartMatcher(match) : match;
7009 startNode = startNode || (reverse ? lastNode : firstNode);
7010 function _checkNode(n) {
7011 // console.log("_check " + n)
7012 if (matcher(n)) {
7013 res = n;
7014 }
7015 if (res || n === startNode) {
7016 return false;
7017 }
7018 }
7019 this.visitRows(_checkNode, {
7020 start: startNode,
7021 includeSelf: false,
7022 reverse: reverse,
7023 });
7024 // Wrap around search
7025 if (!res && startNode !== firstNode) {
7026 this.visitRows(_checkNode, {
7027 start: reverse ? lastNode : firstNode,
7028 includeSelf: true,
7029 reverse: reverse,
7030 });
7031 }
7032 return res;
7033 }
7034 /**
7035 * Find a node relative to another node.
7036 *
7037 * @param node
7038 * @param where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'.
7039 * (Alternatively the keyCode that would normally trigger this move,
7040 * e.g. `$.ui.keyCode.LEFT` = 'left'.
7041 * @param includeHidden Not yet implemented
7042 */
7043 findRelatedNode(node, where, includeHidden = false) {
7044 const rowHeight = this.options.rowHeightPx;
7045 let res = null;
7046 const pageSize = Math.floor(this.listContainerElement.clientHeight / rowHeight);
7047 switch (where) {
7048 case "parent":
7049 if (node.parent && node.parent.parent) {
7050 res = node.parent;
7051 }
7052 break;
7053 case "first":
7054 // First visible node
7055 this.visit((n) => {
7056 if (n.isVisible()) {
7057 res = n;
7058 return false;
7059 }
7060 });
7061 break;
7062 case "last":
7063 this.visit((n) => {
7064 // last visible node
7065 if (n.isVisible()) {
7066 res = n;
7067 }
7068 });
7069 break;
7070 case "left":
7071 if (node.parent && node.parent.parent) {
7072 res = node.parent;
7073 }
7074 // if (node.expanded) {
7075 // node.setExpanded(false);
7076 // } else if (node.parent && node.parent.parent) {
7077 // res = node.parent;
7078 // }
7079 break;
7080 case "right":
7081 if (node.children && node.children.length) {
7082 res = node.children[0];
7083 }
7084 // if (this.cellNavMode) {
7085 // throw new Error("Not implemented");
7086 // } else {
7087 // if (!node.expanded && (node.children || node.lazy)) {
7088 // node.setExpanded();
7089 // res = node;
7090 // } else if (node.children && node.children.length) {
7091 // res = node.children[0];
7092 // }
7093 // }
7094 break;
7095 case "up":
7096 res = this._getNextNodeInView(node, { reverse: true });
7097 break;
7098 case "down":
7099 res = this._getNextNodeInView(node);
7100 break;
7101 case "pageDown":
7102 {
7103 const bottomNode = this.getLowestVpNode();
7104 // this.logDebug(`${where}(${node}) -> ${bottomNode}`);
7105 if (node._rowIdx < bottomNode._rowIdx) {
7106 res = bottomNode;
7107 }
7108 else {
7109 res = this._getNextNodeInView(node, {
7110 reverse: false,
7111 ofs: pageSize,
7112 });
7113 }
7114 }
7115 break;
7116 case "pageUp":
7117 if (node._rowIdx === 0) {
7118 res = node;
7119 }
7120 else {
7121 const topNode = this.getTopmostVpNode();
7122 // this.logDebug(`${where}(${node}) -> ${topNode}`);
7123 if (node._rowIdx > topNode._rowIdx) {
7124 res = topNode;
7125 }
7126 else {
7127 res = this._getNextNodeInView(node, {
7128 reverse: true,
7129 ofs: pageSize,
7130 });
7131 }
7132 }
7133 break;
7134 case "prevMatch":
7135 // fallthrough
7136 case "nextMatch":
7137 if (!this.isFilterActive) {
7138 this.logWarn(`${where}: Filter is not active.`);
7139 break;
7140 }
7141 res = this.findNextNode((n) => n.isMatched(), node, where === "prevMatch");
7142 res === null || res === void 0 ? void 0 : res.setActive();
7143 break;
7144 default:
7145 this.logWarn("Unknown relation '" + where + "'.");
7146 }
7147 return res;
7148 }
7149 /**
7150 * Iterator version of {@link Wunderbaum.format}.
7151 */
7152 *format_iter(name_cb, connectors) {
7153 yield* this.root.format_iter(name_cb, connectors);
7154 }
7155 /**
7156 * Return multiline string representation of the node hierarchy.
7157 * Mostly useful for debugging.
7158 *
7159 * Example:
7160 * ```js
7161 * console.info(tree.format((n)=>n.title));
7162 * ```
7163 * logs
7164 * ```
7165 * Playground
7166 * ├─ Books
7167 * | ├─ Art of War
7168 * | ╰─ Don Quixote
7169 * ├─ Music
7170 * ...
7171 * ```
7172 *
7173 * @see {@link Wunderbaum.format_iter} and {@link WunderbaumNode.format}.
7174 */
7175 format(name_cb, connectors) {
7176 return this.root.format(name_cb, connectors);
7177 }
7178 /**
7179 * Return the active cell (`span.wb-col`) of the currently active node or null.
7180 */
7181 getActiveColElem() {
7182 if (this.activeNode && this.activeColIdx >= 0) {
7183 return this.activeNode.getColElem(this.activeColIdx);
7184 }
7185 return null;
7186 }
7187 /**
7188 * Return the currently active node or null (alias for `tree.activeNode`).
7189 * Alias for {@link Wunderbaum.activeNode}.
7190 *
7191 * @see {@link WunderbaumNode.setActive}
7192 * @see {@link WunderbaumNode.isActive}
7193 * @see {@link Wunderbaum.activeNode}
7194 * @see {@link Wunderbaum.focusNode}
7195 */
7196 getActiveNode() {
7197 return this.activeNode;
7198 }
7199 /**
7200 * Return the first top level node if any (not the invisible root node).
7201 */
7202 getFirstChild() {
7203 return this.root.getFirstChild();
7204 }
7205 /**
7206 * Return the last top level node if any (not the invisible root node).
7207 */
7208 getLastChild() {
7209 return this.root.getLastChild();
7210 }
7211 /**
7212 * Return the node that currently has keyboard focus or null.
7213 * Alias for {@link Wunderbaum.focusNode}.
7214 * @see {@link WunderbaumNode.setFocus}
7215 * @see {@link WunderbaumNode.hasFocus}
7216 * @see {@link Wunderbaum.activeNode}
7217 * @see {@link Wunderbaum.focusNode}
7218 */
7219 getFocusNode() {
7220 return this.focusNode;
7221 }
7222 /** Return a {node: WunderbaumNode, region: TYPE} object for a mouse event.
7223 *
7224 * @param {Event} event Mouse event, e.g. click, ...
7225 * @returns {object} Return a {node: WunderbaumNode, region: TYPE} object
7226 * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
7227 */
7228 static getEventInfo(event) {
7229 const target = event.target;
7230 const cl = target.classList;
7231 const parentCol = target.closest("span.wb-col");
7232 const node = Wunderbaum.getNode(target);
7233 const tree = node ? node.tree : Wunderbaum.getTree(event);
7234 const res = {
7235 event: event,
7236 canonicalName: eventToString(event),
7237 tree: tree,
7238 node: node,
7239 region: NodeRegion.unknown,
7240 colDef: undefined,
7241 colIdx: -1,
7242 colId: undefined,
7243 colElem: parentCol,
7244 };
7245 if (cl.contains("wb-title")) {
7246 res.region = NodeRegion.title;
7247 }
7248 else if (cl.contains("wb-expander")) {
7249 res.region = node.isExpandable()
7250 ? NodeRegion.expander
7251 : NodeRegion.prefix;
7252 }
7253 else if (cl.contains("wb-checkbox")) {
7254 res.region = NodeRegion.checkbox;
7255 }
7256 else if (cl.contains("wb-icon")) {
7257 //|| cl.contains("wb-custom-icon")) {
7258 res.region = NodeRegion.icon;
7259 }
7260 else if (cl.contains("wb-node")) {
7261 res.region = NodeRegion.title;
7262 }
7263 else if (parentCol) {
7264 res.region = NodeRegion.column;
7265 const idx = Array.prototype.indexOf.call(parentCol.parentNode.children, parentCol);
7266 res.colIdx = idx;
7267 }
7268 else if (cl.contains("wb-row")) {
7269 // Plain tree
7270 res.region = NodeRegion.title;
7271 }
7272 else {
7273 // Somewhere near the title
7274 if (event.type !== "mousemove" && !(event instanceof KeyboardEvent)) {
7275 tree === null || tree === void 0 ? void 0 : tree.logWarn("getEventInfo(): not found", event, res);
7276 }
7277 return res;
7278 }
7279 if (res.colIdx === -1) {
7280 res.colIdx = 0;
7281 }
7282 res.colDef = tree === null || tree === void 0 ? void 0 : tree.columns[res.colIdx];
7283 res.colDef != null ? (res.colId = res.colDef.id) : 0;
7284 // this.log("Event", event, res);
7285 return res;
7286 }
7287 /**
7288 * Return readable string representation for this instance.
7289 * @internal
7290 */
7291 toString() {
7292 return `Wunderbaum<'${this.id}'>`;
7293 }
7294 /** Return true if any node title or grid cell is currently beeing edited.
7295 *
7296 * See also {@link Wunderbaum.isEditingTitle}.
7297 */
7298 isEditing() {
7299 const focusElem = this.nodeListElement.querySelector("input:focus,select:focus");
7300 return !!focusElem;
7301 }
7302 /** Return true if any node is currently in edit-title mode.
7303 *
7304 * See also {@link WunderbaumNode.isEditingTitle} and {@link Wunderbaum.isEditing}.
7305 */
7306 isEditingTitle() {
7307 return this._callMethod("edit.isEditingTitle");
7308 }
7309 /**
7310 * Return true if any node is currently beeing loaded, i.e. a Ajax request is pending.
7311 */
7312 isLoading() {
7313 let res = false;
7314 this.root.visit((n) => {
7315 // also visit rootNode
7316 if (n._isLoading || n._requestId) {
7317 res = true;
7318 return false;
7319 }
7320 }, true);
7321 return res;
7322 }
7323 /** Write to `console.log` with tree name as prefix if opts.debugLevel >= 4.
7324 * @see {@link Wunderbaum.logDebug}
7325 */
7326 log(...args) {
7327 if (this.options.debugLevel >= 4) {
7328 console.log(this.toString(), ...args); // eslint-disable-line no-console
7329 }
7330 }
7331 /** Write to `console.debug` with tree name as prefix if opts.debugLevel >= 4.
7332 * and browser console level includes debug/verbose messages.
7333 * @see {@link Wunderbaum.log}
7334 */
7335 logDebug(...args) {
7336 if (this.options.debugLevel >= 4) {
7337 console.debug(this.toString(), ...args); // eslint-disable-line no-console
7338 }
7339 }
7340 /** Write to `console.error` with tree name as prefix. */
7341 logError(...args) {
7342 if (this.options.debugLevel >= 1) {
7343 console.error(this.toString(), ...args); // eslint-disable-line no-console
7344 }
7345 }
7346 /** Write to `console.info` with tree name as prefix if opts.debugLevel >= 3. */
7347 logInfo(...args) {
7348 if (this.options.debugLevel >= 3) {
7349 console.info(this.toString(), ...args); // eslint-disable-line no-console
7350 }
7351 }
7352 /** @internal */
7353 logTime(label) {
7354 if (this.options.debugLevel >= 4) {
7355 console.time(this + ": " + label); // eslint-disable-line no-console
7356 }
7357 return label;
7358 }
7359 /** @internal */
7360 logTimeEnd(label) {
7361 if (this.options.debugLevel >= 4) {
7362 console.timeEnd(this + ": " + label); // eslint-disable-line no-console
7363 }
7364 }
7365 /** Write to `console.warn` with tree name as prefix with if opts.debugLevel >= 2. */
7366 logWarn(...args) {
7367 if (this.options.debugLevel >= 2) {
7368 console.warn(this.toString(), ...args); // eslint-disable-line no-console
7369 }
7370 }
7371 /** Reset column widths to default. @since 0.10.0 */
7372 resetColumns() {
7373 this.columns.forEach((col) => {
7374 delete col.customWidthPx;
7375 });
7376 this.update(ChangeType.colStructure);
7377 }
7378 // /** Renumber nodes `_nativeIndex`. @see {@link WunderbaumNode.resetNativeChildOrder} */
7379 // resetNativeChildOrder(options?: ResetOrderOptions) {
7380 // this.root.resetNativeChildOrder(options);
7381 // }
7382 /**
7383 * Make sure that this node is vertically scrolled into the viewport.
7384 *
7385 * Nodes that are above the visible area become the top row, nodes that are
7386 * below the viewport become the bottom row.
7387 */
7388 scrollTo(nodeOrOpts) {
7389 const PADDING = 2; // leave some pixels between viewport bounds
7390 let node;
7391 // WunderbaumNode;
7392 let options;
7393 if (nodeOrOpts instanceof WunderbaumNode) {
7394 node = nodeOrOpts;
7395 }
7396 else {
7397 options = nodeOrOpts;
7398 node = options.node;
7399 }
7400 assert(node && node._rowIdx != null, `Invalid node: ${node}`);
7401 const rowHeight = this.options.rowHeightPx;
7402 const scrollParent = this.element;
7403 const headerHeight = this.headerElement.clientHeight; // May be 0
7404 const scrollTop = scrollParent.scrollTop;
7405 const vpHeight = scrollParent.clientHeight;
7406 const rowTop = node._rowIdx * rowHeight + headerHeight;
7407 const vpTop = headerHeight;
7408 const vpRowTop = rowTop - scrollTop;
7409 const vpRowBottom = vpRowTop + rowHeight;
7410 const topNode = options === null || options === void 0 ? void 0 : options.topNode;
7411 // this.log( `scrollTo(${node.title}), vpTop:${vpTop}px, scrollTop:${scrollTop}, vpHeight:${vpHeight}, rowTop:${rowTop}, vpRowTop:${vpRowTop}`, nodeOrOpts , options);
7412 let newScrollTop = null;
7413 if (vpRowTop >= vpTop) {
7414 if (vpRowBottom <= vpHeight) ;
7415 else {
7416 // Node is below viewport
7417 // this.log("Below viewport");
7418 newScrollTop = rowTop + rowHeight - vpHeight + PADDING; // leave some pixels between viewport bounds
7419 }
7420 }
7421 else {
7422 // Node is above viewport
7423 // this.log("Above viewport");
7424 newScrollTop = rowTop - vpTop - PADDING; // leave some pixels between viewport bounds
7425 }
7426 if (newScrollTop != null) {
7427 this.log(`scrollTo(${rowTop}): ${scrollTop} => ${newScrollTop}`);
7428 scrollParent.scrollTop = newScrollTop;
7429 if (topNode) {
7430 // Make sure the topNode is always visible
7431 this.scrollTo(topNode);
7432 }
7433 // this.update(ChangeType.scroll);
7434 }
7435 }
7436 /**
7437 * Make sure that this node is horizontally scrolled into the viewport.
7438 * Called by {@link setColumn}.
7439 */
7440 scrollToHorz() {
7441 // const PADDING = 1;
7442 const fixedWidth = this.columns[0]._widthPx;
7443 const vpWidth = this.element.clientWidth;
7444 const scrollLeft = this.element.scrollLeft;
7445 const colElem = this.getActiveColElem();
7446 const colLeft = Number.parseInt(colElem === null || colElem === void 0 ? void 0 : colElem.style.left, 10);
7447 const colRight = colLeft + Number.parseInt(colElem === null || colElem === void 0 ? void 0 : colElem.style.width, 10);
7448 let newLeft = scrollLeft;
7449 if (colLeft - scrollLeft < fixedWidth) {
7450 // The current column is scrolled behind the left fixed column
7451 newLeft = colLeft - fixedWidth;
7452 }
7453 else if (colRight - scrollLeft > vpWidth) {
7454 // The current column is scrolled outside the right side
7455 newLeft = colRight - vpWidth;
7456 }
7457 newLeft = Math.max(0, newLeft);
7458 // util.assert(node._rowIdx != null);
7459 this.log(`scrollToHorz(${this.activeColIdx}): ${colLeft}..${colRight}, fixedOfs=${fixedWidth}, vpWidth=${vpWidth}, curLeft=${scrollLeft} -> ${newLeft}`);
7460 this.element.scrollLeft = newLeft;
7461 // this.update(ChangeType.scroll);
7462 }
7463 /**
7464 * Set column #colIdx to 'active'.
7465 *
7466 * This higlights the column header and -cells by adding the `wb-active`
7467 * class to all grid cells of the active column. <br>
7468 * Available in cell-nav mode only.
7469 *
7470 * If _options.edit_ is true, the embedded input element is focused, or if
7471 * colIdx is 0, the node title is put into edit mode.
7472 */
7473 setColumn(colIdx, options) {
7474 var _a, _b, _c;
7475 const edit = options === null || options === void 0 ? void 0 : options.edit;
7476 const scroll = (options === null || options === void 0 ? void 0 : options.scrollIntoView) !== false;
7477 assert(this.isCellNav(), "Expected cellNav mode");
7478 if (typeof colIdx === "string") {
7479 const cid = colIdx;
7480 colIdx = this.columns.findIndex((c) => c.id === colIdx);
7481 assert(colIdx >= 0, `Invalid colId: ${cid}`);
7482 }
7483 assert(0 <= colIdx && colIdx < this.columns.length, `Invalid colIdx: ${colIdx}`);
7484 this.activeColIdx = colIdx;
7485 // Update `wb-active` class for all headers
7486 if (this.hasHeader()) {
7487 for (const rowDiv of this.headerElement.children) {
7488 let i = 0;
7489 for (const colDiv of rowDiv.children) {
7490 colDiv.classList.toggle("wb-active", i++ === colIdx);
7491 }
7492 }
7493 }
7494 (_a = this.activeNode) === null || _a === void 0 ? void 0 : _a.update(ChangeType.status);
7495 // Update `wb-active` class for all cell spans
7496 for (const rowDiv of this.nodeListElement.children) {
7497 let i = 0;
7498 for (const colDiv of rowDiv.children) {
7499 colDiv.classList.toggle("wb-active", i++ === colIdx);
7500 }
7501 }
7502 // Horizontically scroll into view
7503 if (scroll || edit) {
7504 this.scrollToHorz();
7505 }
7506 if (edit && this.activeNode) {
7507 // this.activeNode.setFocus(); // Blur prev. input if any
7508 if (colIdx === 0) {
7509 this.activeNode.startEditTitle();
7510 }
7511 else {
7512 (_c = (_b = this.getActiveColElem()) === null || _b === void 0 ? void 0 : _b.querySelector("input,select")) === null || _c === void 0 ? void 0 : _c.focus();
7513 }
7514 }
7515 }
7516 /* Set or remove keyboard focus to the tree container. @internal */
7517 _setActiveNode(node) {
7518 this._activeNode = node;
7519 }
7520 /** Set or remove keyboard focus to the tree container. */
7521 setActiveNode(key, flag = true, options) {
7522 var _a;
7523 (_a = this.findKey(key)) === null || _a === void 0 ? void 0 : _a.setActive(flag, options);
7524 }
7525 /** Set or remove keyboard focus to the tree container. */
7526 setFocus(flag = true) {
7527 if (flag) {
7528 this.element.focus();
7529 }
7530 else {
7531 this.element.blur();
7532 }
7533 }
7534 /* Set or remove keyboard focus to the tree container. @internal */
7535 _setFocusNode(node) {
7536 this._focusNode = node;
7537 }
7538 /** Return the current selection/expansion/activation status. @experimental */
7539 getState(options) {
7540 var _a, _b;
7541 let expandedKeys = undefined;
7542 if (options.expandedKeys !== false) {
7543 expandedKeys = [];
7544 for (const node of this) {
7545 if (node.expanded) {
7546 expandedKeys.push(node.key);
7547 }
7548 }
7549 }
7550 const state = {
7551 activeKey: (_b = (_a = this.activeNode) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : null,
7552 activeColIdx: this.activeColIdx,
7553 selectedKeys: options.selectedKeys === false
7554 ? undefined
7555 : this.getSelectedNodes().flatMap((n) => n.key),
7556 expandedKeys: expandedKeys,
7557 };
7558 return state;
7559 }
7560 /** Apply selection/expansion/activation status. @experimental */
7561 setState(state, options) {
7562 this.runWithDeferredUpdate(() => {
7563 var _a, _b;
7564 if (state.selectedKeys) {
7565 this.selectAll(false);
7566 for (const key of state.selectedKeys) {
7567 (_a = this.findKey(key)) === null || _a === void 0 ? void 0 : _a.setSelected(true);
7568 }
7569 }
7570 if (state.expandedKeys) {
7571 for (const key of state.expandedKeys) {
7572 (_b = this.findKey(key)) === null || _b === void 0 ? void 0 : _b.setExpanded(true);
7573 }
7574 }
7575 if (state.activeKey) {
7576 this.setActiveNode(state.activeKey);
7577 }
7578 if (state.activeColIdx != null) {
7579 this.setColumn(state.activeColIdx);
7580 }
7581 });
7582 }
7583 update(change, node, options) {
7584 // this.log(`update(${change}) node=${node}`);
7585 if (!(node instanceof WunderbaumNode)) {
7586 options = node;
7587 node = undefined;
7588 }
7589 const immediate = !!getOption(options, "immediate");
7590 const RF = RenderFlag;
7591 const pending = this.pendingChangeTypes;
7592 if (this._disableUpdateCount) {
7593 // Assuming that we redraw all when enableUpdate() is re-enabled.
7594 // this.log(
7595 // `IGNORED update(${change}) node=${node} (disable level ${this._disableUpdateCount})`
7596 // );
7597 this._disableUpdateIgnoreCount++;
7598 return;
7599 }
7600 switch (change) {
7601 case ChangeType.any:
7602 case ChangeType.colStructure:
7603 pending.add(RF.header);
7604 pending.add(RF.clearMarkup);
7605 pending.add(RF.redraw);
7606 pending.add(RF.scroll);
7607 break;
7608 case ChangeType.resize:
7609 // case ChangeType.colWidth:
7610 pending.add(RF.header);
7611 pending.add(RF.redraw);
7612 break;
7613 case ChangeType.structure:
7614 pending.add(RF.redraw);
7615 break;
7616 case ChangeType.scroll:
7617 pending.add(RF.scroll);
7618 break;
7619 case ChangeType.row:
7620 case ChangeType.data:
7621 case ChangeType.status:
7622 assert(node, `Option '${change}' requires a node.`);
7623 // Single nodes are immediately updated if already inside the viewport
7624 // (otherwise we can ignore)
7625 if (node._rowElem) {
7626 node._render({ change: change });
7627 }
7628 break;
7629 default:
7630 error(`Invalid change type '${change}'.`);
7631 }
7632 if (change === ChangeType.colStructure) {
7633 const isGrid = this.isGrid();
7634 this.element.classList.toggle("wb-grid", isGrid);
7635 if (!isGrid && this.isCellNav()) {
7636 this.setCellNav(false);
7637 }
7638 }
7639 if (pending.size > 0) {
7640 if (immediate) {
7641 this._updateViewportImmediately();
7642 }
7643 else {
7644 this._updateViewportThrottled();
7645 }
7646 }
7647 }
7648 /** Disable mouse and keyboard interaction (return prev. state). */
7649 setEnabled(flag = true) {
7650 const prev = this.enabled;
7651 this.enabled = !!flag;
7652 this.element.classList.toggle("wb-disabled", !flag);
7653 return prev;
7654 }
7655 /** Return false if tree is disabled. */
7656 isEnabled() {
7657 return this.enabled;
7658 }
7659 /** Return true if tree has more than one column, i.e. has additional data columns. */
7660 isGrid() {
7661 return this.columns && this.columns.length > 1;
7662 }
7663 /** Return true if cell-navigation mode is active. */
7664 isCellNav() {
7665 return !!this._cellNavMode;
7666 }
7667 /** Return true if row-navigation mode is active. */
7668 isRowNav() {
7669 return !this._cellNavMode;
7670 }
7671 /** Set the tree's navigation mode. */
7672 setCellNav(flag = true) {
7673 var _a;
7674 const prev = this._cellNavMode;
7675 // if (flag === prev) {
7676 // return;
7677 // }
7678 this._cellNavMode = !!flag;
7679 if (flag && !prev) {
7680 // switch from row to cell mode
7681 this.setColumn(0);
7682 }
7683 this.element.classList.toggle("wb-cell-mode", flag);
7684 (_a = this.activeNode) === null || _a === void 0 ? void 0 : _a.update(ChangeType.status);
7685 }
7686 /** Set the tree's navigation mode option. */
7687 setNavigationOption(mode, reset = false) {
7688 if (!this.isGrid() && mode !== NavModeEnum.row) {
7689 this.logWarn("Plain trees only support row navigation mode.");
7690 return;
7691 }
7692 this.options.navigationModeOption = mode;
7693 switch (mode) {
7694 case NavModeEnum.cell:
7695 this.setCellNav(true);
7696 break;
7697 case NavModeEnum.row:
7698 this.setCellNav(false);
7699 break;
7700 case NavModeEnum.startCell:
7701 if (reset) {
7702 this.setCellNav(true);
7703 }
7704 break;
7705 case NavModeEnum.startRow:
7706 if (reset) {
7707 this.setCellNav(false);
7708 }
7709 break;
7710 default:
7711 error(`Invalid mode '${mode}'.`);
7712 }
7713 }
7714 /** Display tree status (ok, loading, error, noData) using styles and a dummy root node. */
7715 setStatus(status, options) {
7716 return this.root.setStatus(status, options);
7717 }
7718 /** Add or redefine node type definitions. */
7719 setTypes(types, replace = true) {
7720 assert(isPlainObject(types), `Expected plain objext: ${types}`);
7721 if (replace) {
7722 this.types = types;
7723 }
7724 else {
7725 extend(this.types, types);
7726 }
7727 // Convert `TYPE.classes` to a Set
7728 for (const t of Object.values(this.types)) {
7729 if (t.classes) {
7730 t.classes = toSet(t.classes);
7731 }
7732 }
7733 }
7734 /**
7735 * Sort nodes list by title or custom criteria.
7736 * @param {function} cmp custom compare function(a, b) that returns -1, 0, or 1
7737 * (defaults to sorting by title).
7738 * @param {boolean} deep pass true to sort all descendant nodes recursively
7739 */
7740 sortChildren(cmp = nodeTitleSorter, deep = false) {
7741 this.root.sortChildren(cmp, deep);
7742 }
7743 /**
7744 * Convenience method to implement column sorting.
7745 * @see {@link WunderbaumNode.sortByProperty}.
7746 * @since 0.11.0
7747 */
7748 sortByProperty(options) {
7749 this.root.sortByProperty(options);
7750 }
7751 /** Convert tree to an array of plain objects.
7752 *
7753 * @param callback is called for every node, in order to allow
7754 * modifications.
7755 * Return `false` to ignore this node or `"skip"` to include this node
7756 * without its children.
7757 * @see {@link WunderbaumNode.toDict}.
7758 */
7759 toDictArray(callback) {
7760 var _a;
7761 const res = this.root.toDict(true, callback);
7762 return (_a = res.children) !== null && _a !== void 0 ? _a : [];
7763 }
7764 /**
7765 * Update column headers and column width.
7766 * Return true if at least one column width changed.
7767 */
7768 // _updateColumnWidths(options?: UpdateColumnsOptions): boolean {
7769 _updateColumnWidths() {
7770 // options = Object.assign({ updateRows: true, renderMarkup: false }, options);
7771 const defaultMinWidth = 4;
7772 const vpWidth = this.element.clientWidth;
7773 // Shorten last column width to avoid h-scrollbar
7774 // (otherwise resizbing the demo would display a void scrollbar?)
7775 const FIX_ADJUST_LAST_COL = 1;
7776 const columns = this.columns;
7777 const col0 = columns[0];
7778 let totalWidth = 0;
7779 let totalWeight = 0;
7780 let fixedWidth = 0;
7781 let modified = false;
7782 // this.element.classList.toggle("wb-grid", isGrid);
7783 // if (!isGrid && this.isCellNav()) {
7784 // this.setCellNav(false);
7785 // }
7786 // if (options.calculateCols) {
7787 if (col0.id !== "*") {
7788 throw new Error(`First column must have id '*': got '${col0.id}'.`);
7789 }
7790 // Gather width definitions
7791 this._columnsById = {};
7792 for (const col of columns) {
7793 this._columnsById[col.id] = col;
7794 const cw = col.customWidthPx ? `${col.customWidthPx}px` : col.width;
7795 if (col.id === "*" && col !== col0) {
7796 throw new Error(`Column id '*' must be defined only once: '${col.title}'.`);
7797 }
7798 if (!cw || cw === "*") {
7799 col._weight = 1.0;
7800 totalWeight += 1.0;
7801 }
7802 else if (typeof cw === "number") {
7803 col._weight = cw;
7804 totalWeight += cw;
7805 }
7806 else if (typeof cw === "string" && cw.endsWith("px")) {
7807 col._weight = 0;
7808 const px = parseFloat(cw.slice(0, -2));
7809 if (col._widthPx != px) {
7810 modified = true;
7811 col._widthPx = px;
7812 }
7813 fixedWidth += px;
7814 }
7815 else {
7816 error(`Invalid column width: ${cw} (expected string ending with 'px' or number, e.g. "<num>px" or <int>).`);
7817 }
7818 }
7819 // Share remaining space between non-fixed columns
7820 const restPx = Math.max(0, vpWidth - fixedWidth);
7821 let ofsPx = 0;
7822 for (const col of columns) {
7823 let minWidth;
7824 if (col._weight) {
7825 const cmw = col.minWidth;
7826 if (typeof cmw === "number") {
7827 minWidth = cmw;
7828 }
7829 else if (typeof cmw === "string" && cmw.endsWith("px")) {
7830 minWidth = parseFloat(cmw.slice(0, -2));
7831 }
7832 else {
7833 minWidth = defaultMinWidth;
7834 }
7835 const px = Math.max(minWidth, (restPx * col._weight) / totalWeight);
7836 if (col._widthPx != px) {
7837 modified = true;
7838 col._widthPx = px;
7839 }
7840 }
7841 col._ofsPx = ofsPx;
7842 ofsPx += col._widthPx;
7843 }
7844 columns[columns.length - 1]._widthPx -= FIX_ADJUST_LAST_COL;
7845 totalWidth = ofsPx - FIX_ADJUST_LAST_COL;
7846 const tw = `${totalWidth}px`;
7847 this.headerElement.style.width = tw;
7848 this.listContainerElement.style.width = tw;
7849 // }
7850 // Every column has now a calculated `_ofsPx` and `_widthPx`
7851 // this.logInfo("UC", this.columns, vpWidth, this.element.clientWidth, this.element);
7852 // console.trace();
7853 // util.error("BREAK");
7854 // if (modified) {
7855 // this._renderHeaderMarkup();
7856 // if (options.renderMarkup) {
7857 // this.update(ChangeType.header, { removeMarkup: true });
7858 // } else if (options.updateRows) {
7859 // this._updateRows();
7860 // }
7861 // }
7862 return modified;
7863 }
7864 // protected _insertIcon(icon: string, elem: HTMLElement) {
7865 // const iconElem = document.createElement("i");
7866 // iconElem.className = icon;
7867 // elem.appendChild(iconElem);
7868 // }
7869 /** Create/update header markup from `this.columns` definition.
7870 * @internal
7871 */
7872 _renderHeaderMarkup() {
7873 assert(this.headerElement, "Expected a headerElement");
7874 const wantHeader = this.hasHeader();
7875 setElemDisplay(this.headerElement, wantHeader);
7876 if (!wantHeader) {
7877 return;
7878 }
7879 const iconMap = this.iconMap;
7880 const colCount = this.columns.length;
7881 const headerRow = this.headerElement.querySelector(".wb-row");
7882 assert(headerRow, "Expected a row in header element");
7883 headerRow.innerHTML = "<span class='wb-col'></span>".repeat(colCount);
7884 for (let i = 0; i < colCount; i++) {
7885 const col = this.columns[i];
7886 const colElem = headerRow.children[i];
7887 colElem.style.left = col._ofsPx + "px";
7888 colElem.style.width = col._widthPx + "px";
7889 // Add classes from `columns` definition to `<div.wb-col>` cells
7890 if (typeof col.headerClasses === "string") {
7891 col.headerClasses
7892 ? colElem.classList.add(...col.headerClasses.split(" "))
7893 : 0;
7894 }
7895 else {
7896 col.classes ? colElem.classList.add(...col.classes.split(" ")) : 0;
7897 }
7898 // Add tooltip to column title
7899 let tooltip = "";
7900 if (col.tooltip) {
7901 tooltip = escapeTooltip(col.tooltip);
7902 tooltip = ` title="${tooltip}"`;
7903 }
7904 // Add column header icons
7905 let addMarkup = "";
7906 // NOTE: we use CSS float: right to align icons, so they must be added in
7907 // reverse order
7908 if (toBool(col.menu, this.options.columnsMenu, false)) {
7909 const iconClass = "wb-col-icon-menu " + iconMap.colMenu;
7910 const icon = `<i data-command=menu class="wb-col-icon ${iconClass}"></i>`;
7911 addMarkup += icon;
7912 }
7913 if (toBool(col.sortable, this.options.columnsSortable, false)) {
7914 let iconClass = "wb-col-icon-sort " + iconMap.colSortable;
7915 if (col.sortOrder) {
7916 iconClass += `wb-col-sort-${col.sortOrder}`;
7917 iconClass +=
7918 col.sortOrder === "asc" ? iconMap.colSortAsc : iconMap.colSortDesc;
7919 }
7920 const icon = `<i data-command=sort class="wb-col-icon ${iconClass}"></i>`;
7921 addMarkup += icon;
7922 }
7923 if (toBool(col.filterable, this.options.columnsFilterable, false)) {
7924 colElem.classList.toggle("wb-col-filter", !!col.filterActive);
7925 let iconClass = "wb-col-icon-filter " + iconMap.colFilter;
7926 if (col.filterActive) {
7927 iconClass += iconMap.colFilterActive;
7928 }
7929 const icon = `<i data-command=filter class="wb-col-icon ${iconClass}"></i>`;
7930 addMarkup += icon;
7931 }
7932 // Add resizer to all but the last column
7933 if (i < colCount - 1) {
7934 if (toBool(col.resizable, this.options.columnsResizable, false)) {
7935 addMarkup +=
7936 '<span class="wb-col-resizer wb-col-resizer-active"></span>';
7937 }
7938 else {
7939 addMarkup += '<span class="wb-col-resizer"></span>';
7940 }
7941 }
7942 // Create column header
7943 const title = escapeHtml(col.title || col.id);
7944 colElem.innerHTML = `<span class="wb-col-title"${tooltip}>${title}</span>${addMarkup}`;
7945 // Highlight active column
7946 if (this.isCellNav()) {
7947 colElem.classList.toggle("wb-active", i === this.activeColIdx);
7948 }
7949 }
7950 }
7951 /**
7952 * Render pending changes that were scheduled using {@link WunderbaumNode.update} if any.
7953 *
7954 * This is hardly ever neccessary, since we normally either
7955 * - call `update(ChangeType.TYPE)` (async, throttled), or
7956 * - call `update(ChangeType.TYPE, {immediate: true})` (synchronous)
7957 *
7958 * `updatePendingModifications()` will only force immediate execution of
7959 * pending async changes if any.
7960 */
7961 updatePendingModifications() {
7962 if (this.pendingChangeTypes.size > 0) {
7963 this._updateViewportImmediately();
7964 }
7965 }
7966 /** @internal */
7967 _createNodeIcon(node, showLoading, showBadge) {
7968 const iconMap = this.iconMap;
7969 let iconElem;
7970 let icon = node.getOption("icon");
7971 if (node._errorInfo) {
7972 icon = iconMap.error;
7973 }
7974 else if (node._isLoading && showLoading) {
7975 // Status nodes, or nodes without expander (< minExpandLevel) should
7976 // display the 'loading' status with the i.wb-icon span
7977 icon = iconMap.loading;
7978 }
7979 if (icon === false) {
7980 return null; // explicitly disabled: don't try default icons
7981 }
7982 if (typeof icon === "string") ;
7983 else if (node.statusNodeType) {
7984 icon = iconMap[node.statusNodeType];
7985 }
7986 else if (node.expanded) {
7987 icon = iconMap.folderOpen;
7988 }
7989 else if (node.children) {
7990 icon = iconMap.folder;
7991 }
7992 else if (node.lazy) {
7993 icon = iconMap.folderLazy;
7994 }
7995 else {
7996 icon = iconMap.doc;
7997 }
7998 if (!icon) {
7999 iconElem = document.createElement("i");
8000 iconElem.className = "wb-icon";
8001 }
8002 else if (icon.indexOf("<") >= 0) {
8003 // HTML
8004 iconElem = elemFromHtml(icon);
8005 }
8006 else if (TEST_IMG.test(icon)) {
8007 // Image URL
8008 iconElem = elemFromHtml(`<i class="wb-icon" style="background-image: url('${icon}');">`);
8009 }
8010 else {
8011 // Class name
8012 iconElem = document.createElement("i");
8013 iconElem.className = "wb-icon " + icon;
8014 }
8015 // Event handler `tree.iconBadge` can return a badge text or HTMLSpanElement
8016 const cbRes = showBadge && node._callEvent("iconBadge", { iconSpan: iconElem });
8017 let badge = null;
8018 if (cbRes != null && cbRes !== false) {
8019 let classes = "";
8020 let tooltip = "";
8021 if (isPlainObject(cbRes)) {
8022 badge = "" + cbRes.badge;
8023 classes = cbRes.badgeClass ? " " + cbRes.badgeClass : "";
8024 tooltip = cbRes.badgeTooltip ? ` title="${cbRes.badgeTooltip}"` : "";
8025 }
8026 else if (typeof cbRes === "number") {
8027 badge = "" + cbRes;
8028 }
8029 else {
8030 badge = cbRes; // string or HTMLSpanElement
8031 }
8032 if (typeof badge === "string") {
8033 badge = elemFromHtml(`<span class="wb-badge${classes}"${tooltip}>${escapeHtml(badge)}</span>`);
8034 }
8035 if (badge) {
8036 iconElem.append(badge);
8037 }
8038 }
8039 return iconElem;
8040 }
8041 _updateTopBreadcrumb() {
8042 const breadcrumb = this.breadcrumb;
8043 const topmost = this.getTopmostVpNode(true);
8044 const parentList = topmost === null || topmost === void 0 ? void 0 : topmost.getParentList(false, false);
8045 if (parentList === null || parentList === void 0 ? void 0 : parentList.length) {
8046 breadcrumb.innerHTML = "";
8047 for (const n of topmost.getParentList(false, false)) {
8048 const icon = this._createNodeIcon(n, false, false);
8049 if (icon) {
8050 breadcrumb.append(icon, " ");
8051 }
8052 const part = document.createElement("a");
8053 part.textContent = n.title;
8054 part.href = "#";
8055 part.classList.add("wb-breadcrumb");
8056 part.dataset.key = n.key;
8057 breadcrumb.append(part, this.options.strings.breadcrumbDelimiter);
8058 }
8059 }
8060 else {
8061 breadcrumb.innerHTML = "&nbsp;";
8062 }
8063 }
8064 /**
8065 * This is the actual update method, which is wrapped inside a throttle method.
8066 * It calls `updateColumns()` and `_updateRows()`.
8067 *
8068 * This protected method should not be called directly but via
8069 * {@link WunderbaumNode.update}`, {@link Wunderbaum.update},
8070 * or {@link Wunderbaum.updatePendingModifications}.
8071 * @internal
8072 */
8073 _updateViewportImmediately() {
8074 if (this._disableUpdateCount) {
8075 this.log(`_updateViewportImmediately() IGNORED (disable level: ${this._disableUpdateCount}).`);
8076 this._disableUpdateIgnoreCount++;
8077 return;
8078 }
8079 if (this._updateViewportThrottled.pending()) {
8080 // this.logWarn(`_updateViewportImmediately() cancel pending timer.`);
8081 this._updateViewportThrottled.cancel();
8082 }
8083 // Shorten container height to avoid v-scrollbar
8084 const FIX_ADJUST_HEIGHT = 1;
8085 const RF = RenderFlag;
8086 const pending = new Set(this.pendingChangeTypes);
8087 this.pendingChangeTypes.clear();
8088 const scrollOnly = pending.has(RF.scroll) && pending.size === 1;
8089 if (scrollOnly) {
8090 this._updateRows({ newNodesOnly: true });
8091 // this.log("_updateViewportImmediately(): scroll only.");
8092 }
8093 else {
8094 this.log("_updateViewportImmediately():", pending);
8095 if (this.options.adjustHeight !== false) {
8096 let height = this.listContainerElement.clientHeight;
8097 const headerHeight = this.headerElement.clientHeight; // May be 0
8098 const wantHeight = this.element.clientHeight - headerHeight - FIX_ADJUST_HEIGHT;
8099 if (Math.abs(height - wantHeight) > 1.0) {
8100 // this.log("resize", height, wantHeight);
8101 this.listContainerElement.style.height = wantHeight + "px";
8102 height = wantHeight;
8103 }
8104 }
8105 // console.profile(`_updateViewportImmediately()`)
8106 if (pending.has(RF.clearMarkup)) {
8107 this.visit((n) => {
8108 n.removeMarkup();
8109 });
8110 }
8111 // let widthModified = false;
8112 if (pending.has(RF.header)) {
8113 // widthModified = this._updateColumnWidths();
8114 this._updateColumnWidths();
8115 this._renderHeaderMarkup();
8116 }
8117 this._updateRows();
8118 // console.profileEnd(`_updateViewportImmediately()`)
8119 }
8120 if (this.breadcrumb) {
8121 this._updateTopBreadcrumb();
8122 }
8123 this._callEvent("update");
8124 }
8125 // /**
8126 // * Assert that TR order matches the natural node order
8127 // * @internal
8128 // */
8129 // protected _validateRows(): boolean {
8130 // let trs = this.nodeListElement.childNodes;
8131 // let i = 0;
8132 // let prev = -1;
8133 // let ok = true;
8134 // trs.forEach((element) => {
8135 // const tr = element as HTMLTableRowElement;
8136 // const top = Number.parseInt(tr.style.top);
8137 // const n = (<any>tr)._wb_node;
8138 // // if (i < 4) {
8139 // // console.info(
8140 // // `TR#${i}, rowIdx=${n._rowIdx} , top=${top}px: '${n.title}'`
8141 // // );
8142 // // }
8143 // if (prev >= 0 && top !== prev + ROW_HEIGHT) {
8144 // n.logWarn(
8145 // `TR order mismatch at index ${i}: top=${top}px != ${
8146 // prev + ROW_HEIGHT
8147 // }`
8148 // );
8149 // // throw new Error("fault");
8150 // ok = false;
8151 // }
8152 // prev = top;
8153 // i++;
8154 // });
8155 // return ok;
8156 // }
8157 /*
8158 * - Traverse all *visible* nodes of the whole tree, i.e. skip collapsed nodes.
8159 * - Store count of rows to `tree.treeRowCount`.
8160 * - Renumber `node._rowIdx` for all visible nodes.
8161 * - Calculate the index range that must be rendered to fill the viewport
8162 * (including upper and lower prefetch)
8163 * -
8164 */
8165 _updateRows(options) {
8166 // const label = this.logTime("_updateRows");
8167 // this.log("_updateRows", opts)
8168 options = Object.assign({ newNodesOnly: false }, options);
8169 const newNodesOnly = !!options.newNodesOnly;
8170 const rowHeight = this.options.rowHeightPx;
8171 const vpHeight = this.element.clientHeight;
8172 const prefetch = RENDER_MAX_PREFETCH;
8173 // const grace_prefetch = RENDER_MAX_PREFETCH - RENDER_MIN_PREFETCH;
8174 const ofs = this.element.scrollTop;
8175 let startIdx = Math.max(0, ofs / rowHeight - prefetch);
8176 startIdx = Math.floor(startIdx);
8177 // Make sure start is always even, so the alternating row colors don't
8178 // change when scrolling:
8179 if (startIdx % 2) {
8180 startIdx--;
8181 }
8182 let endIdx = Math.max(0, (ofs + vpHeight) / rowHeight + prefetch);
8183 endIdx = Math.ceil(endIdx);
8184 // this.debug("render", opts);
8185 const obsoleteNodes = new Set();
8186 this.nodeListElement.childNodes.forEach((elem) => {
8187 if (elem._wb_node) {
8188 obsoleteNodes.add(elem._wb_node);
8189 }
8190 });
8191 let idx = 0;
8192 let top = 0;
8193 let modified = false;
8194 let prevElem = "first";
8195 this.visitRows(function (node) {
8196 // node.log("visit")
8197 const rowDiv = node._rowElem;
8198 // Renumber all expanded nodes
8199 if (node._rowIdx !== idx) {
8200 node._rowIdx = idx;
8201 modified = true;
8202 }
8203 if (idx < startIdx || idx > endIdx) {
8204 // row is outside viewport bounds
8205 if (rowDiv) {
8206 prevElem = rowDiv;
8207 }
8208 }
8209 else if (rowDiv && newNodesOnly) {
8210 obsoleteNodes.delete(node);
8211 // no need to update existing node markup
8212 rowDiv.style.top = idx * rowHeight + "px";
8213 prevElem = rowDiv;
8214 }
8215 else {
8216 obsoleteNodes.delete(node);
8217 // Create new markup
8218 if (rowDiv) {
8219 rowDiv.style.top = idx * rowHeight + "px";
8220 }
8221 node._render({ top: top, after: prevElem });
8222 // node.log("render", top, prevElem, "=>", node._rowElem);
8223 prevElem = node._rowElem;
8224 }
8225 idx++;
8226 top += rowHeight;
8227 });
8228 this.treeRowCount = idx;
8229 for (const n of obsoleteNodes) {
8230 n._callEvent("discard");
8231 n.removeMarkup();
8232 }
8233 // Resize tree container
8234 this.nodeListElement.style.height = `${top}px`;
8235 // this.log(
8236 // `_updateRows(scrollOfs:${ofs}, ${startIdx}..${endIdx})`,
8237 // this.nodeListElement.style.height
8238 // );
8239 // this.logTimeEnd(label);
8240 // this._validateRows();
8241 return modified;
8242 }
8243 /**
8244 * Call `callback(node)` for all nodes in hierarchical order (depth-first, pre-order).
8245 * @see {@link IterableIterator<WunderbaumNode>}, {@link WunderbaumNode.visit}.
8246 *
8247 * @param {function} callback the callback function.
8248 * Return false to stop iteration, return "skip" to skip this node and
8249 * children only.
8250 * @returns {boolean} false, if the iterator was stopped.
8251 */
8252 visit(callback) {
8253 return this.root.visit(callback, false);
8254 }
8255 /**
8256 * Call callback(node) for all nodes in vertical order, top down (or bottom up).
8257 *
8258 * Note that this considers expansion state, i.e. filtered nodes and children
8259 * of collapsed nodes are skipped, unless `includeHidden` is set.
8260 *
8261 * Stop iteration if callback() returns false.<br>
8262 * Return false if iteration was stopped.
8263 *
8264 * @returns {boolean} false if iteration was canceled
8265 */
8266 visitRows(callback, options) {
8267 if (!this.root.hasChildren()) {
8268 return false;
8269 }
8270 if (options && options.reverse) {
8271 delete options.reverse;
8272 return this._visitRowsUp(callback, options);
8273 }
8274 options = options || {};
8275 let i, nextIdx, parent, res, siblings, stopNode, siblingOfs = 0, skipFirstNode = options.includeSelf === false, node = options.start || this.root.children[0];
8276 const includeHidden = !!options.includeHidden;
8277 const checkFilter = !includeHidden && this.filterMode === "hide";
8278 parent = node.parent;
8279 while (parent) {
8280 // visit siblings
8281 siblings = parent.children;
8282 nextIdx = siblings.indexOf(node) + siblingOfs;
8283 assert(nextIdx >= 0, `Could not find ${node} in parent's children: ${parent}`);
8284 for (i = nextIdx; i < siblings.length; i++) {
8285 node = siblings[i];
8286 if (node === stopNode) {
8287 return false;
8288 }
8289 if (checkFilter &&
8290 !node.statusNodeType &&
8291 !node.match &&
8292 !node.subMatchCount) {
8293 continue;
8294 }
8295 if (!skipFirstNode && callback(node) === false) {
8296 return false;
8297 }
8298 skipFirstNode = false;
8299 // Dive into node's child nodes
8300 if (node.children &&
8301 node.children.length &&
8302 (includeHidden || node.expanded)) {
8303 res = node.visit((n) => {
8304 if (n === stopNode) {
8305 return false;
8306 }
8307 if (checkFilter && !n.match && !n.subMatchCount) {
8308 return "skip";
8309 }
8310 if (callback(n) === false) {
8311 return false;
8312 }
8313 if (!includeHidden && n.children && !n.expanded) {
8314 return "skip";
8315 }
8316 }, false);
8317 if (res === false) {
8318 return false;
8319 }
8320 }
8321 }
8322 // Visit parent nodes (bottom up)
8323 node = parent;
8324 parent = parent.parent;
8325 siblingOfs = 1; //
8326 if (!parent && options.wrap) {
8327 this.logDebug("visitRows(): wrap around");
8328 assert(options.start, "`wrap` option requires `start`");
8329 stopNode = options.start;
8330 options.wrap = false;
8331 parent = this.root;
8332 siblingOfs = 0;
8333 }
8334 }
8335 return true;
8336 }
8337 /**
8338 * Call fn(node) for all nodes in vertical order, bottom up.
8339 * @internal
8340 */
8341 _visitRowsUp(callback, options) {
8342 let children, idx, parent, node = options.start || this.root.children[0];
8343 const includeHidden = !!options.includeHidden;
8344 if (options.includeSelf !== false) {
8345 if (callback(node) === false) {
8346 return false;
8347 }
8348 }
8349 while (true) {
8350 parent = node.parent;
8351 children = parent.children;
8352 if (children[0] === node) {
8353 // If this is already the first sibling, goto parent
8354 node = parent;
8355 if (!node.parent) {
8356 break; // first node of the tree
8357 }
8358 children = parent.children;
8359 }
8360 else {
8361 // Otherwise, goto prev. sibling
8362 idx = children.indexOf(node);
8363 node = children[idx - 1];
8364 // If the prev. sibling has children, follow down to last descendant
8365 while ((includeHidden || node.expanded) &&
8366 node.children &&
8367 node.children.length) {
8368 children = node.children;
8369 parent = node;
8370 node = children[children.length - 1];
8371 }
8372 }
8373 // Skip invisible
8374 if (!includeHidden && !node.isVisible()) {
8375 continue;
8376 }
8377 if (callback(node) === false) {
8378 return false;
8379 }
8380 }
8381 return true;
8382 }
8383 /**
8384 * Reload the tree with a new source.
8385 *
8386 * Previous data is cleared. Note that also column- and type defintions may
8387 * be passed with the `source` object.
8388 */
8389 load(source) {
8390 this.clear();
8391 return this.root.load(source);
8392 }
8393 /**
8394 * Disable render requests during operations that would trigger many updates.
8395 *
8396 * ```js
8397 * try {
8398 * tree.enableUpdate(false);
8399 * // ... (long running operation that would trigger many updates)
8400 * foo();
8401 * // ... NOTE: make sure that async operations have finished, e.g.
8402 * await foo();
8403 * } finally {
8404 * tree.enableUpdate(true);
8405 * }
8406 * ```
8407 */
8408 enableUpdate(flag) {
8409 /*
8410 5 7 9 20 25 30
8411 1 >-------------------------------------<
8412 2 >--------------------<
8413 3 >--------------------------<
8414 */
8415 if (flag) {
8416 assert(this._disableUpdateCount > 0, "enableUpdate(true) was called too often");
8417 this._disableUpdateCount--;
8418 // this.logDebug(
8419 // `enableUpdate(${flag}): count -> ${this._disableUpdateCount}...`
8420 // );
8421 if (this._disableUpdateCount === 0) {
8422 this.logDebug(`enableUpdate(): active again. Re-painting to catch up with ${this._disableUpdateIgnoreCount} ignored update requests...`);
8423 this._disableUpdateIgnoreCount = 0;
8424 this.update(ChangeType.any, { immediate: true });
8425 }
8426 }
8427 else {
8428 this._disableUpdateCount++;
8429 // this.logDebug(
8430 // `enableUpdate(${flag}): count -> ${this._disableUpdateCount}...`
8431 // );
8432 // this._disableUpdate = Date.now();
8433 }
8434 // return !flag; // return previous value
8435 }
8436 /* ---------------------------------------------------------------------------
8437 * FILTER
8438 * -------------------------------------------------------------------------*/
8439 /**
8440 * Dim or hide unmatched nodes.
8441 * @param filter a string to match against node titles, or a callback function.
8442 * @param options filter options. Defaults to the `tree.options.filter` settings.
8443 * @returns the number of nodes that match the filter.
8444 * @example
8445 * ```ts
8446 * tree.filterNodes("foo", {mode: 'dim', fuzzy: true});
8447 * // or pass a callback
8448 * tree.filterNodes((node) => { return node.data.foo === true }, {mode: 'hide'});
8449 * ```
8450 */
8451 filterNodes(filter, options) {
8452 return this.extensions.filter.filterNodes(filter, options);
8453 }
8454 /**
8455 * Return the number of nodes that match the current filter.
8456 * @see {@link Wunderbaum.filterNodes}
8457 * @since 0.9.0
8458 */
8459 countMatches() {
8460 return this.extensions.filter.countMatches();
8461 }
8462 /**
8463 * Dim or hide whole branches.
8464 * @deprecated Use {@link filterNodes} instead and set `options.matchBranch: true`.
8465 */
8466 filterBranches(filter, options) {
8467 return this.extensions.filter.filterBranches(filter, options);
8468 }
8469 /**
8470 * Reset the filter.
8471 */
8472 clearFilter() {
8473 return this.extensions.filter.clearFilter();
8474 }
8475 /**
8476 * Return true if a filter is currently applied.
8477 */
8478 isFilterActive() {
8479 return !!this.filterMode;
8480 }
8481 /**
8482 * Re-apply current filter.
8483 */
8484 updateFilter() {
8485 return this.extensions.filter.updateFilter();
8486 }
8487 }
8488 Wunderbaum.sequence = 0;
8489 /** Wunderbaum release version number "MAJOR.MINOR.PATCH". */
8490 Wunderbaum.version = "v0.13.0"; // Set to semver by 'grunt release'
8491 /** Expose some useful methods of the util.ts module as `Wunderbaum.util`. */
8492 Wunderbaum.util = util;
8493
8494 exports.Wunderbaum = Wunderbaum;
8495
8496 }));