Debian Codegraph @

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

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