wunderbaum 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/wunderbaum.css +1 -1
- package/dist/wunderbaum.d.ts +233 -85
- package/dist/wunderbaum.esm.js +512 -346
- package/dist/wunderbaum.esm.min.js +20 -20
- package/dist/wunderbaum.esm.min.js.map +1 -1
- package/dist/wunderbaum.umd.js +512 -346
- package/dist/wunderbaum.umd.min.js +26 -26
- package/dist/wunderbaum.umd.min.js.map +1 -1
- package/package.json +2 -2
- package/src/common.ts +31 -0
- package/src/util.ts +1 -0
- package/src/wb_ext_edit.ts +10 -1
- package/src/wb_ext_keynav.ts +8 -4
- package/src/wb_node.ts +124 -54
- package/src/wunderbaum.scss +8 -4
- package/src/wunderbaum.ts +433 -318
|
@@ -1,70 +1,70 @@
|
|
|
1
1
|
/*!
|
|
2
2
|
* Wunderbaum - util
|
|
3
3
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
4
|
-
* v0.0.
|
|
4
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
5
5
|
*/
|
|
6
6
|
const MOUSE_BUTTONS={0:"",1:"left",2:"middle",3:"right",4:"back",5:"forward"},MAX_INT=9007199254740991,userInfo=_getUserInfo(),isMac=userInfo.isMac,REX_HTML=/[&<>"'/]/g,REX_TOOLTIP=/[<>"'/]/g,ENTITY_MAP={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};class Deferred$1{constructor(){this.thens=[],this.catches=[],this.status=""}resolve(e){if(this.status)throw new Error("already settled");this.status="resolved",this.resolvedValue=e,this.thens.forEach((t=>t(e))),this.thens=[]}reject(e){if(this.status)throw new Error("already settled");this.status="rejected",this.rejectedError=e,this.catches.forEach((t=>t(e))),this.catches=[]}then(e){"resolved"===status?e(this.resolvedValue):this.thens.unshift(e)}catch(e){"rejected"===this.status?e(this.rejectedError):this.catches.unshift(e)}promise(){return{then:this.then,catch:this.catch}}}function assert(e,t){if(!e)throw t=t||"Assertion failed.",new Error(t)}function _getUserInfo(){const e=navigator;return{isMac:/Mac/.test(e.platform)}}function documentReady(e){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}function documentReadyPromise(){return new Promise((e=>{documentReady(e)}))}function each(e,t){if(null==e)return e;let i=e.length,s=0;if("number"==typeof i)for(;s<i&&!1!==t.call(e[s],s,e[s]);s++);else for(let i in e)if(!1===t.call(e[s],i,e[i]))break;return e}function error(e){throw new Error(e)}function escapeHtml(e){return(""+e).replace(REX_HTML,(function(e){return ENTITY_MAP[e]}))}function escapeRegex(e){return(""+e).replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function escapeTooltip(e){return(""+e).replace(REX_TOOLTIP,(function(e){return ENTITY_MAP[e]}))}function extractHtmlText(e){return e.indexOf(">")>=0&&error("Not implemented"),e}function getValueFromElem(e,t=!1){const i=e.tagName;let s=null;if("SPAN"===i&&e.classList.contains("wb-col")){const i=e,n=i.querySelector("input,select");if(n)return getValueFromElem(n,t);i.innerText=""+s}else if("INPUT"===i){const i=e;switch(i.type){case"button":case"reset":case"submit":case"image":break;case"checkbox":s=i.indeterminate?null:i.checked;break;case"date":case"datetime":case"datetime-local":case"month":case"time":case"week":s=t?i.valueAsDate:i.value;break;case"number":case"range":s=i.valueAsNumber;break;case"radio":const e=i.name,n=i.parentElement.querySelector(`input[name="${e}"]:checked`);s=n?n.value:void 0;break;default:s=i.value}}else if("SELECT"===i){s=e.value}return s}function setValueToElem(e,t){const i=e.tagName;if("SPAN"===i&&e.classList.contains("wb-col")){const i=e,s=i.querySelector("input,select");if(s)return setValueToElem(s,t);i.innerText=""+t}else if("INPUT"===i){const i=e;switch(i.type){case"checkbox":i.indeterminate=null==t,i.checked=!!t;break;case"date":case"month":case"time":case"week":case"datetime":case"datetime-local":i.valueAsDate=t;break;case"number":case"range":i.valueAsNumber=t;break;case"radio":error("Not implemented");break;case"button":case"reset":case"submit":case"image":break;default:i.innerText=t}}else if("SELECT"===i){e.value=t}}function elemFromHtml(e){const t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstElementChild}const _IGNORE_KEYS=new Set(["Alt","Control","Meta","Shift"]);function elemFromSelector(e){return e?"string"==typeof e?document.querySelector(e):e:null}function eventTargetFromSelector(e){return e?"string"==typeof e?document.querySelector(e):e:null}function eventToString(e){let t=e.key,i=e.type,s=[];return e.altKey&&s.push("Alt"),e.ctrlKey&&s.push("Control"),e.metaKey&&s.push("Meta"),e.shiftKey&&s.push("Shift"),"click"===i||"dblclick"===i?s.push(MOUSE_BUTTONS[e.button]+i):"wheel"===i?s.push(i):_IGNORE_KEYS.has(t)||s.push(t),s.join("+")}function extend(...e){for(let t=1;t<e.length;t++){let i=e[t];if(null!=i)for(let t in i)Object.prototype.hasOwnProperty.call(i,t)&&(e[0][t]=i[t])}return e[0]}function isArray(e){return Array.isArray(e)}function isEmptyObject(e){return 0===Object.keys(e).length&&e.constructor===Object}function isFunction(e){return"function"==typeof e}function isPlainObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function noop(...e){}function onEvent(e,t,i,s){let n,r;e=eventTargetFromSelector(e),s?(n=i,r=s):(n="",r=i),t.split(" ").forEach((t=>{e.addEventListener(t,(function(e){if(!n)return r(e);if(e.target){let t=e.target;if(t.matches(n))return r(e);if(t=t.closest(n),t)return r(e)}}))}))}function overrideMethod(e,t,i,s){let n,r,o=s||e,l=e[t],a=(...e)=>l.apply(o,e),d=e=>l.apply(o,e);e[t]=(...e)=>{try{return n=o._super,r=o._superApply,o._super=a,o._superApply=d,i.apply(o,e)}finally{o._super=n,o._superApply=r}}}function setTimeoutPromise(e,t){return new Promise(((i,s)=>{setTimeout((()=>{try{i(e.apply(self))}catch(e){s(e)}}),t)}))}async function sleep(e){return new Promise((t=>setTimeout(t,e)))}function toggleCheckbox(e,t,i){const s=elemFromSelector(e);if(assert("checkbox"===s.type),null!=i||(i=s.classList.contains("wb-tristate")||s.indeterminate),void 0===t){switch(s.indeterminate?null:s.checked){case!0:t=!1;break;case!1:t=!i||null;break;case null:t=!0}}s.indeterminate=null==t,s.checked=!!t}function getOption(e,t,i){let s;e&&t.indexOf(".")>=0&&([s,t]=t.split("."),e=e[s]);let n=e?e[t]:null;return null!=n?n:i}function toSet(e){if(e instanceof Set)return e;if("string"==typeof e){let t=new Set;for(const i of e.split(" "))t.add(i.trim());return t}if(Array.isArray(e))return new Set(e);throw new Error("Cannot convert to Set<string>: "+e)}function type(e){return Object.prototype.toString.call(e).replace(/^\[object (.+)\]$/,"$1").toLowerCase()}var util=Object.freeze({__proto__:null,MOUSE_BUTTONS:MOUSE_BUTTONS,MAX_INT:MAX_INT,isMac:isMac,Deferred:Deferred$1,assert:assert,documentReady:documentReady,documentReadyPromise:documentReadyPromise,each:each,error:error,escapeHtml:escapeHtml,escapeRegex:escapeRegex,escapeTooltip:escapeTooltip,extractHtmlText:extractHtmlText,getValueFromElem:getValueFromElem,setValueToElem:setValueToElem,elemFromHtml:elemFromHtml,elemFromSelector:elemFromSelector,eventTargetFromSelector:eventTargetFromSelector,eventToString:eventToString,extend:extend,isArray:isArray,isEmptyObject:isEmptyObject,isFunction:isFunction,isPlainObject:isPlainObject,noop:noop,onEvent:onEvent,overrideMethod:overrideMethod,setTimeoutPromise:setTimeoutPromise,sleep:sleep,toggleCheckbox:toggleCheckbox,getOption:getOption,toSet:toSet,type:type});
|
|
7
7
|
/*!
|
|
8
8
|
* Wunderbaum - common
|
|
9
9
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
10
|
-
* v0.0.
|
|
11
|
-
*/const DEFAULT_DEBUGLEVEL=4,ROW_HEIGHT=22,ICON_WIDTH=20,ROW_EXTRA_PAD=7,RENDER_MAX_PREFETCH=5,TEST_IMG=new RegExp(/\.|\//);var ChangeType,NodeStatusType,TargetType;!function(e){e.any="any",e.row="row",e.structure="structure",e.status="status",e.vscroll="vscroll",e.header="header"}(ChangeType||(ChangeType={})),function(e){e.ok="ok",e.loading="loading",e.error="error",e.noData="noData"}(NodeStatusType||(NodeStatusType={})),function(e){e.unknown="",e.checkbox="checkbox",e.column="column",e.expander="expander",e.icon="icon",e.prefix="prefix",e.title="title"}(TargetType||(TargetType={}));let iconMap={error:"bi bi-exclamation-triangle",loading:"bi bi-arrow-repeat wb-spin",noData:"bi bi-question-circle",expanderExpanded:"bi bi-chevron-down",expanderCollapsed:"bi bi-chevron-right",expanderLazy:"bi bi-chevron-right wb-helper-lazy-expander",checkChecked:"bi bi-check-square",checkUnchecked:"bi bi-square",checkUnknown:"bi dash-square-dotted",radioChecked:"bi bi-circle-fill",radioUnchecked:"bi bi-circle",radioUnknown:"bi bi-circle-dotted",folder:"bi bi-folder2",folderOpen:"bi bi-folder2-open",doc:"bi bi-file-earmark"};var NavigationModeOption,NavigationMode;!function(e){e.startRow="startRow",e.cell="cell",e.startCell="startCell",e.row="row"}(NavigationModeOption||(NavigationModeOption={})),function(e){e.row="row",e.cellNav="cellNav",e.cellEdit="cellEdit"}(NavigationMode||(NavigationMode={}));const KEY_TO_ACTION_DICT={" ":"toggleSelect","+":"expand",Add:"expand",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",Backspace:"parent","/":"collapseAll",Divide:"collapseAll",End:"lastCol",Home:"firstCol","Control+End":"last","Control+Home":"first","*":"expandAll",Multiply:"expandAll",PageDown:"pageDown",PageUp:"pageUp","-":"collapse",Subtract:"collapse"};function makeNodeTitleMatcher(e){return e=escapeRegex(e.toLowerCase()),function(t){return t.title.toLowerCase().indexOf(e)>=0}}function makeNodeTitleStartMatcher(e){e=escapeRegex(e);const t=new RegExp("^"+e,"i");return function(e){return t.test(e.title)}}
|
|
10
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
11
|
+
*/const DEFAULT_DEBUGLEVEL=4,ROW_HEIGHT=22,ICON_WIDTH=20,ROW_EXTRA_PAD=7,RENDER_MAX_PREFETCH=5,TEST_IMG=new RegExp(/\.|\//);var ChangeType,NodeStatusType,TargetType;!function(e){e.any="any",e.row="row",e.structure="structure",e.status="status",e.vscroll="vscroll",e.header="header"}(ChangeType||(ChangeType={})),function(e){e.ok="ok",e.loading="loading",e.error="error",e.noData="noData"}(NodeStatusType||(NodeStatusType={})),function(e){e.unknown="",e.checkbox="checkbox",e.column="column",e.expander="expander",e.icon="icon",e.prefix="prefix",e.title="title"}(TargetType||(TargetType={}));let iconMap={error:"bi bi-exclamation-triangle",loading:"bi bi-arrow-repeat wb-spin",noData:"bi bi-question-circle",expanderExpanded:"bi bi-chevron-down",expanderCollapsed:"bi bi-chevron-right",expanderLazy:"bi bi-chevron-right wb-helper-lazy-expander",checkChecked:"bi bi-check-square",checkUnchecked:"bi bi-square",checkUnknown:"bi dash-square-dotted",radioChecked:"bi bi-circle-fill",radioUnchecked:"bi bi-circle",radioUnknown:"bi bi-circle-dotted",folder:"bi bi-folder2",folderOpen:"bi bi-folder2-open",doc:"bi bi-file-earmark"};var NavigationModeOption,NavigationMode;!function(e){e.startRow="startRow",e.cell="cell",e.startCell="startCell",e.row="row"}(NavigationModeOption||(NavigationModeOption={})),function(e){e.row="row",e.cellNav="cellNav",e.cellEdit="cellEdit"}(NavigationMode||(NavigationMode={}));const KEY_TO_ACTION_DICT={" ":"toggleSelect","+":"expand",Add:"expand",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",Backspace:"parent","/":"collapseAll",Divide:"collapseAll",End:"lastCol",Home:"firstCol","Control+End":"last","Control+Home":"first","Meta+ArrowDown":"last","Meta+ArrowUp":"first","*":"expandAll",Multiply:"expandAll",PageDown:"pageDown",PageUp:"pageUp","-":"collapse",Subtract:"collapse"};function makeNodeTitleMatcher(e){return e=escapeRegex(e.toLowerCase()),function(t){return t.title.toLowerCase().indexOf(e)>=0}}function makeNodeTitleStartMatcher(e){e=escapeRegex(e);const t=new RegExp("^"+e,"i");return function(e){return t.test(e.title)}}
|
|
12
12
|
/*!
|
|
13
13
|
* Wunderbaum - wb_extension_base
|
|
14
14
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
15
|
-
* v0.0.
|
|
15
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
16
16
|
*/class WunderbaumExtension{constructor(e,t,i){this.enabled=!0,this.tree=e,this.id=t,this.treeOpts=e.options;const s=e.options;void 0===this.treeOpts[t]?s[t]=this.extensionOpts=extend({},i):(this.extensionOpts=extend({},i,s[t]),s[t]=this.extensionOpts),this.enabled=this.getPluginOption("enabled",!0)}init(){this.tree.element.classList.add("wb-ext-"+this.id)}getPluginOption(e,t){var i;return null!==(i=this.extensionOpts[e])&&void 0!==i?i:t}setPluginOption(e,t){this.extensionOpts[e]=t}setEnabled(e=!0){return this.setPluginOption("enabled",!!e)}onKeyEvent(e){}onRender(e){}}
|
|
17
17
|
/*!
|
|
18
18
|
* debounce & throttle, taken from https://github.com/lodash/lodash v4.17.21
|
|
19
19
|
* MIT License: https://raw.githubusercontent.com/lodash/lodash/4.17.21-npm/LICENSE
|
|
20
20
|
* Modified for TypeScript type annotations.
|
|
21
|
-
*/const freeGlobal="object"==typeof global&&null!==global&&global.Object===Object&&global,freeGlobalThis="object"==typeof globalThis&&null!==globalThis&&globalThis.Object==Object&&globalThis,freeSelf="object"==typeof self&&null!==self&&self.Object===Object&&self,root=freeGlobalThis||freeGlobal||freeSelf||Function("return this")();function isObject(e){const t=typeof e;return null!=e&&("object"===t||"function"===t)}function debounce(e,t=0,i={}){let s,n,r,o,l,a,d=0,c=!1,h=!1,u=!0;const p=!t&&0!==t&&"function"==typeof root.requestAnimationFrame;if("function"!=typeof e)throw new TypeError("Expected a function");function g(t){const i=s,r=n;return s=n=void 0,d=t,o=e.apply(r,i),o}function f(e,t){return p?(root.cancelAnimationFrame(l),root.requestAnimationFrame(e)):setTimeout(e,t)}function
|
|
21
|
+
*/const freeGlobal="object"==typeof global&&null!==global&&global.Object===Object&&global,freeGlobalThis="object"==typeof globalThis&&null!==globalThis&&globalThis.Object==Object&&globalThis,freeSelf="object"==typeof self&&null!==self&&self.Object===Object&&self,root=freeGlobalThis||freeGlobal||freeSelf||Function("return this")();function isObject(e){const t=typeof e;return null!=e&&("object"===t||"function"===t)}function debounce(e,t=0,i={}){let s,n,r,o,l,a,d=0,c=!1,h=!1,u=!0;const p=!t&&0!==t&&"function"==typeof root.requestAnimationFrame;if("function"!=typeof e)throw new TypeError("Expected a function");function g(t){const i=s,r=n;return s=n=void 0,d=t,o=e.apply(r,i),o}function f(e,t){return p?(root.cancelAnimationFrame(l),root.requestAnimationFrame(e)):setTimeout(e,t)}function m(e){const i=e-a;return void 0===a||i>=t||i<0||h&&e-d>=r}function v(){const e=Date.now();if(m(e))return y(e);l=f(v,function(e){const i=e-d,s=t-(e-a);return h?Math.min(s,r-i):s}(e))}function y(e){return l=void 0,u&&s?g(e):(s=n=void 0,o)}function b(...e){const i=Date.now(),r=m(i);if(s=e,n=this,a=i,r){if(void 0===l)return function(e){return d=e,l=f(v,t),c?g(e):o}(a);if(h)return l=f(v,t),g(a)}return void 0===l&&(l=f(v,t)),o}return t=+t||0,isObject(i)&&(c=!!i.leading,h="maxWait"in i,r=h?Math.max(+i.maxWait||0,t):r,u="trailing"in i?!!i.trailing:u),b.cancel=function(){void 0!==l&&function(e){if(p)return root.cancelAnimationFrame(e);clearTimeout(e)}(l),d=0,s=a=n=l=void 0},b.flush=function(){return void 0===l?o:y(Date.now())},b.pending=function(){return void 0!==l},b}function throttle(e,t=0,i={}){let s=!0,n=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return isObject(i)&&(s="leading"in i?!!i.leading:s,n="trailing"in i?!!i.trailing:n),debounce(e,t,{leading:s,trailing:n,maxWait:t})}
|
|
22
22
|
/*!
|
|
23
23
|
* Wunderbaum - ext-filter
|
|
24
24
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
25
|
-
* v0.0.
|
|
25
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
26
26
|
*/const START_MARKER="",END_MARKER="",RE_START_MARKER=new RegExp(escapeRegex(""),"g"),RE_END_MARTKER=new RegExp(escapeRegex(""),"g");class FilterExtension extends WunderbaumExtension{constructor(e){super(e,"filter",{autoApply:!0,autoExpand:!1,counter:!0,fuzzy:!1,hideExpandedCounter:!0,hideExpanders:!1,highlight:!0,leavesOnly:!1,mode:"hide",noData:!0}),this.lastFilterArgs=null}init(){super.init();let e=this.getPluginOption("attachInput");e&&(this.queryInput=elemFromSelector(e),onEvent(this.queryInput,"input",debounce((e=>{this.filterNodes(this.queryInput.value.trim(),{})}),700)))}_applyFilterNoUpdate(e,t,i){return this.tree.runWithoutUpdate((()=>this._applyFilterImpl(e,t,i)))}_applyFilterImpl(e,t,i){let s,n,r=Date.now(),o=0,l=this.tree,a=l.options,d=a.autoCollapse,c=extend({},a.filter,i),h="hide"===c.mode,u=!!c.leavesOnly&&!t;if("string"==typeof e){if(""===e)return l.logInfo("Passing an empty string as a filter is handled as clearFilter()."),void this.clearFilter();s=c.fuzzy?e.split("").map(escapeRegex).reduce((function(e,t){return e+"([^"+t+"]*)"+t}),""):escapeRegex(e);let t=new RegExp(s,"i"),i=new RegExp(escapeRegex(e),"gi");e=e=>{if(!e.title)return!1;let s=e.title,r=s.match(t);return r&&c.highlight&&(n=c.fuzzy?_markFuzzyMatchedChars(s,r,!0):s.replace(i,(function(e){return""+e+""})),e.titleWithHighlight=escapeHtml(n).replace(RE_START_MARKER,"<mark>").replace(RE_END_MARTKER,"</mark>")),!!r}}return l.filterMode=c.mode,this.lastFilterArgs=arguments,l.element.classList.toggle("wb-ext-filter-hide",!!h),l.element.classList.toggle("wb-ext-filter-dim",!h),l.element.classList.toggle("wb-ext-filter-hide-expanders",!!c.hideExpanders),l.root.subMatchCount=0,l.visit((e=>{delete e.match,delete e.titleWithHighlight,e.subMatchCount=0})),l.setStatus(NodeStatusType.ok),a.autoCollapse=!1,l.visit((i=>{if(u&&null!=i.children)return;let s=e(i);if("skip"===s)return i.visit((function(e){e.match=!1}),!0),"skip";let n=!1;(t||"branch"===s)&&i.parent.match&&(s=!0,n=!0),s&&(o++,i.match=!0,i.visitParents((e=>{e!==i&&(e.subMatchCount+=1),!c.autoExpand||n||e.expanded||(e.setExpanded(!0,{noAnimation:!0,noEvents:!0,scrollIntoView:!1}),e._filterAutoExpanded=!0)}),!0))})),a.autoCollapse=d,0===o&&c.noData&&h&&l.root.setStatus(NodeStatusType.noData),l.logInfo(`Filter '${s}' found ${o} nodes in ${Date.now()-r} ms.`),o}filterNodes(e,t){return this._applyFilterNoUpdate(e,!1,t)}filterBranches(e,t){return this._applyFilterNoUpdate(e,!0,t)}updateFilter(){let e=this.tree;e.filterMode&&this.lastFilterArgs&&e.options.filter.autoApply?this._applyFilterNoUpdate.apply(this,this.lastFilterArgs):e.logWarn("updateFilter(): no filter active.")}clearFilter(){let e=this.tree;e.enableUpdate(!1),e.setStatus(NodeStatusType.ok),delete e.root.match,delete e.root.subMatchCount,e.visit((e=>{if(e.match&&e._rowElem){let t=e._rowElem.querySelector("span.wb-title");t.textContent=e.title,e._callEvent("enhanceTitle",{titleElem:t})}delete e.match,delete e.subMatchCount,delete e.titleWithHighlight,e.subMatchBadge&&(e.subMatchBadge.remove(),delete e.subMatchBadge),e._filterAutoExpanded&&e.expanded&&e.setExpanded(!1,{noAnimation:!0,noEvents:!0,scrollIntoView:!1}),delete e._filterAutoExpanded})),e.filterMode=null,this.lastFilterArgs=null,e.element.classList.remove("wb-ext-filter-dim","wb-ext-filter-hide"),e.enableUpdate(!0)}}function _markFuzzyMatchedChars(e,t,i=!0){let s=[];for(let e=1;e<t.length;e++){let i=t[e].length+(1===e?0:1)+(s[s.length-1]||0);s.push(i)}let n=e.split("");return i?s.forEach((function(e){n[e]=""+n[e]+""})):s.forEach((function(e){n[e]="<mark>"+n[e]+"</mark>"})),n.join("")}
|
|
27
27
|
/*!
|
|
28
28
|
* Wunderbaum - ext-keynav
|
|
29
29
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
30
|
-
* v0.0.
|
|
31
|
-
*/class KeynavExtension extends WunderbaumExtension{constructor(e){super(e,"keynav",{})}onKeyEvent(e){let t,i=e.event,s=eventToString(i),n=e.node,r=this.tree,o=e.options,l=!0,a=!i.ctrlKey||o.autoActivate;const d=o.navigationMode;if(r.logDebug(`onKeyEvent: ${s}`),!1===r._callEvent("keydown",e))return!1;if(!1===r._callMethod("edit._preprocessKeyEvent",e))return!1;if(!n){const e=r.getActiveNode(),i=r.getFirstChild();if(!e&&i&&"ArrowDown"===s)return i.logInfo("Keydown: activate first node."),void i.setActive();t=e||i,t&&(t.setFocus(),n=r.getFocusNode(),n.logInfo("Keydown: force focus on active node."))}if(r.navMode===NavigationMode.row){if(o.quicksearch&&1===s.length&&/^\w$/.test(s)){const e=Date.now();e-r.lastQuicksearchTime>500&&(r.lastQuicksearchTerm=""),r.lastQuicksearchTime=e,r.lastQuicksearchTerm+=s;let t=r.findNextNode(r.lastQuicksearchTerm,r.getActiveNode());return t&&t.setActive(!0,{event:i}),void i.preventDefault()}switch(s){case"ArrowLeft":n.expanded&&(s="Subtract");break;case"ArrowRight":if(n.expanded||!n.children&&!n.lazy){if(d===NavigationModeOption.startRow)return void r.
|
|
30
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
31
|
+
*/class KeynavExtension extends WunderbaumExtension{constructor(e){super(e,"keynav",{})}onKeyEvent(e){let t,i=e.event,s=eventToString(i),n=e.node,r=this.tree,o=e.options,l=!0,a=!i.ctrlKey||o.autoActivate;const d=o.navigationMode;if(r.logDebug(`onKeyEvent: ${s}`),!1===r._callEvent("keydown",e))return!1;if(!1===r._callMethod("edit._preprocessKeyEvent",e))return!1;if(!n){const e=r.getActiveNode(),i=r.getFirstChild();if(!e&&i&&"ArrowDown"===s)return i.logInfo("Keydown: activate first node."),void i.setActive();t=e||i,t&&(t.setFocus(),n=r.getFocusNode(),n.logInfo("Keydown: force focus on active node."))}if(r.navMode===NavigationMode.row){if(o.quicksearch&&1===s.length&&/^\w$/.test(s)){const e=Date.now();e-r.lastQuicksearchTime>500&&(r.lastQuicksearchTerm=""),r.lastQuicksearchTime=e,r.lastQuicksearchTerm+=s;let t=r.findNextNode(r.lastQuicksearchTerm,r.getActiveNode());return t&&t.setActive(!0,{event:i}),void i.preventDefault()}switch(s){case"ArrowLeft":n.expanded&&(s="Subtract");break;case"ArrowRight":if(n.expanded||!n.children&&!n.lazy){if(d===NavigationModeOption.startRow)return void r.setNavigationMode(NavigationMode.cellNav)}else s="Add"}switch(s){case"+":case"Add":n.setExpanded(!0);break;case"-":case"Subtract":n.setExpanded(!1);break;case" ":n.getOption("checkbox")?n.setSelected(!n.isSelected()):n.setActive(!0,{event:i});break;case"Enter":n.setActive(!0,{event:i});break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"Backspace":case"End":case"Home":case"Control+End":case"Control+Home":case"Meta+ArrowDown":case"Meta+ArrowUp":case"PageDown":case"PageUp":n.navigate(s,{activate:a,event:i});break;default:l=!1}}else switch(s){case" ":if(0===r.activeColIdx&&n.getOption("checkbox"))n.setSelected(!n.isSelected()),l=!0;else{const e=r.getActiveColElem(),t=null==e?void 0:e.querySelector("input[type=checkbox]");null==t||t.click()}break;case"Enter":0===r.activeColIdx&&n.isExpandable()&&(n.setExpanded(!n.isExpanded()),l=!0);break;case"Escape":r.navMode===NavigationMode.cellEdit?(r.setNavigationMode(NavigationMode.cellNav),l=!0):r.navMode===NavigationMode.cellNav&&(r.setNavigationMode(NavigationMode.row),l=!0);break;case"ArrowLeft":r.activeColIdx>0?(r.setColumn(r.activeColIdx-1),l=!0):d!==NavigationModeOption.cell&&(r.setNavigationMode(NavigationMode.row),l=!0);break;case"ArrowRight":r.activeColIdx<r.columns.length-1&&(r.setColumn(r.activeColIdx+1),l=!0);break;case"ArrowDown":case"ArrowUp":case"Backspace":case"End":case"Home":case"Control+End":case"Control+Home":case"Meta+ArrowDown":case"Meta+ArrowUp":case"PageDown":case"PageUp":n.navigate(s,{activate:a,event:i});break;default:l=!1}l&&i.preventDefault()}}
|
|
32
32
|
/*!
|
|
33
33
|
* Wunderbaum - ext-logger
|
|
34
34
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
35
|
-
* v0.0.
|
|
35
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
36
36
|
*/class LoggerExtension extends WunderbaumExtension{constructor(e){super(e,"logger",{}),this.ignoreEvents=new Set(["enhanceTitle","render","discard"]),this.prefix=e+".ext-logger"}init(){const e=this.tree;if(e.getOption("debugLevel")>=4){const t=this.ignoreEvents,i=this.prefix;overrideMethod(e,"callEvent",(function(s,n){if(t.has(s))return e._superApply(arguments);let r=Date.now();const o=e._superApply(arguments);return console.debug(`${i}: callEvent('${s}') took ${Date.now()-r} ms.`,arguments[1]),o}))}}onKeyEvent(e){console.debug(`${this.prefix}: onKeyEvent()`,e)}}
|
|
37
37
|
/*!
|
|
38
38
|
* Wunderbaum - ext-dnd
|
|
39
39
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
40
|
-
* v0.0.
|
|
40
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
41
41
|
*/const nodeMimeType="application/x-wunderbaum-node";class DndExtension extends WunderbaumExtension{constructor(e){super(e,"dnd",{autoExpandMS:1500,multiSource:!1,effectAllowed:"all",dropEffectDefault:"move",preventForeignNodes:!1,preventLazyParents:!0,preventNonNodes:!1,preventRecursion:!0,preventSameParent:!1,preventVoidMoves:!0,scroll:!0,scrollSensitivity:20,scrollSpeed:5,sourceCopyHook:null,dragStart:null,dragDrag:null,dragEnd:null,dragEnter:null,dragOver:null,dragExpand:null,dragDrop:null,dragLeave:null}),this.srcNode=null,this.lastTargetNode=null,this.lastEnterStamp=0,this.lastAllowedDropRegions=null,this.lastDropEffect=null,this.lastDropRegion=!1}init(){super.init();const e=this.tree,t=e.options.dnd;t.dragStart&&onEvent(e.element,"dragstart drag dragend",this.onDragEvent.bind(this)),t.dragEnter&&onEvent(e.element,"dragenter dragover dragleave drop",this.onDropEvent.bind(this))}_leaveNode(){const e=this.lastTargetNode;this.lastEnterStamp=0,e&&(e.removeClass("wb-drop-target wb-drop-over wb-drop-after wb-drop-before"),this.lastTargetNode=null)}unifyDragover(e){if(!1===e)return!1;if(e instanceof Set)return e.size>0&&e;if(!0===e)return new Set(["over","before","after"]);if("string"==typeof e||isArray(e))return(e=toSet(e)).size>0&&e;throw new Error("Unsupported drop region definition: "+e)}_calcDropRegion(e,t){const i=e.offsetY;return!!t&&(3===t.size?i<5.5?"before":i>16.5?"after":"over":1===t.size&&t.has("over")?"over":i>11?"after":"before")}autoScroll(e){let t=this.tree,i=t.options.dnd,s=t.scrollContainer,n=i.scrollSensitivity,r=i.scrollSpeed,o=0;const l=s.offsetTop;if(l+s.offsetHeight-e.pageY<n){s.scrollHeight-s.clientHeight-l>0&&(s.scrollTop=o=l+r)}else l>0&&e.pageY-l<n&&(s.scrollTop=o=l-r);return o}onDragEvent(e){const t=this.treeOpts.dnd,i=Wunderbaum.getNode(e);if(i){if("drag"!==e.type&&this.tree.logDebug("onDragEvent."+e.type+", srcNode: "+i,e),"dragstart"===e.type){e.dataTransfer.effectAllowed=t.effectAllowed;if(!i._callEvent("dnd.dragStart",{event:e}))return e.preventDefault(),!1;let s=i.toDict(!0,(e=>{e._org_key=e.key,delete e.key}));s.treeId=i.tree.id;const n=JSON.stringify(s);e.dataTransfer.setData(nodeMimeType,n),e.dataTransfer.setData("text/plain",i.title),this.srcNode=i,setTimeout((()=>{i.addClass("wb-drag-source")}),0)}else"drag"===e.type||"dragend"===e.type&&(i.removeClass("wb-drag-source"),this.srcNode=null,this.lastTargetNode&&this._leaveNode());return!0}}onDropEvent(e){const t=Wunderbaum.getNode(e),i=this.treeOpts.dnd,s=e.dataTransfer;if(t){if("dragover"!==e.type&&this.tree.logDebug("onDropEvent."+e.type+" targetNode: "+t+", ea: "+(null==s?void 0:s.effectAllowed)+", de: "+(null==s?void 0:s.dropEffect),", cy: "+e.offsetY,", r: "+this._calcDropRegion(e,this.lastAllowedDropRegions),e),"dragenter"===e.type){if(this.lastAllowedDropRegions=null,this.lastTargetNode&&this.lastTargetNode!==t&&this._leaveNode(),this.lastTargetNode=t,this.lastEnterStamp=Date.now(),i.preventVoidMoves&&t===this.srcNode||t.isStatusNode())return s.dropEffect="none",!0;let n=t._callEvent("dnd.dragEnter",{event:e});return n=this.unifyDragover(n),n?(this.lastAllowedDropRegions=n,this.lastDropEffect=s.dropEffect,t.addClass("wb-drop-target"),e.preventDefault(),!1):(s.dropEffect="none",!0)}if("dragover"===e.type){this.autoScroll(e);const s=this._calcDropRegion(e,this.lastAllowedDropRegions);if(this.lastDropRegion=s,i.autoExpandMS>0&&t.isExpandable(!0)&&!t._isLoading&&Date.now()-this.lastEnterStamp>i.autoExpandMS&&!1!==t._callEvent("dnd.dragExpand",{event:e})&&t.setExpanded(),!s)return;return t.toggleClass("wb-drop-over","over"===s),t.toggleClass("wb-drop-before","before"===s),t.toggleClass("wb-drop-after","after"===s),e.preventDefault(),!1}"dragleave"===e.type||"drop"===e.type&&(e.stopPropagation(),this._leaveNode(),t._callEvent("dnd.drop",{event:e,region:this.lastDropRegion,sourceNode:this.srcNode}))}else this._leaveNode()}}
|
|
42
42
|
/*!
|
|
43
43
|
* Wunderbaum - drag_observer
|
|
44
44
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
45
|
-
* v0.0.
|
|
45
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
46
46
|
*/class DragObserver{constructor(e){this.start={x:0,y:0,altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1},this.dragElem=null,this.dragging=!1,this.events=["mousedown","mouseup","mousemove","keydown"],assert(e.root),this.opts=extend({thresh:5},e),this.root=e.root,this._handler=this.handleEvent.bind(this),this.events.forEach((e=>{this.root.addEventListener(e,this._handler)}))}disconnect(){this.events.forEach((e=>{this.root.removeEventListener(e,this._handler)}))}getDragElem(){return this.dragElem}isDragging(){return this.dragging}stopDrag(e){this.dragging&&this.opts.dragstop&&e&&(e.type="dragstop",this.opts.dragstop(e)),this.dragElem=null,this.dragging=!1}handleEvent(e){const t=e.type,i=this.opts,s={type:e.type,event:e,dragElem:this.dragElem,dx:e.pageX-this.start.x,dy:e.pageY-this.start.y,apply:void 0};switch(t){case"keydown":this.stopDrag(s);break;case"mousedown":if(this.dragElem){this.stopDrag(s);break}if(i.selector){let t=e.target;if(t.matches(i.selector))this.dragElem=t;else{if(t=t.closest(i.selector),!t)break;this.dragElem=t}}this.start.x=e.pageX,this.start.y=e.pageY,this.start.altKey=e.altKey,this.start.ctrlKey=e.ctrlKey,this.start.metaKey=e.metaKey,this.start.shiftKey=e.shiftKey;break;case"mousemove":if(!this.dragElem)break;if(!this.dragging){if(i.thresh){if(s.dx*s.dx+s.dy*s.dy<i.thresh*i.thresh)break}if(s.type="dragstart",!1===i.dragstart(s)){this.stopDrag(s);break}this.dragging=!0}this.dragging&&this.opts.drag&&(s.type="drag",this.opts.drag(s));break;case"mouseup":if(!this.dragging){this.stopDrag(s);break}0===e.button?s.apply=!0:s.apply=!1,this.stopDrag(s)}}}
|
|
47
47
|
/*!
|
|
48
48
|
* Wunderbaum - ext-grid
|
|
49
49
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
50
|
-
* v0.0.
|
|
50
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
51
51
|
*/class GridExtension extends WunderbaumExtension{constructor(e){super(e,"grid",{}),this.observer=new DragObserver({root:window.document,selector:"span.wb-col-resizer",thresh:4,dragstart:e=>this.tree.element.contains(e.dragElem),drag:e=>this.handleDrag(e),dragstop:e=>this.handleDrag(e)})}init(){super.init()}handleDrag(e){const t=Wunderbaum.getEventInfo(e.event);this.tree.log(`${e.type}(${e.dx})`,e,t)}}
|
|
52
52
|
/*!
|
|
53
53
|
* Wunderbaum - deferred
|
|
54
54
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
55
|
-
* v0.0.
|
|
55
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
56
56
|
*/class Deferred{constructor(){this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){this._resolve(e)}reject(e){this._reject(e)}promise(){return this._promise}then(e){return this._promise.then(e)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}}
|
|
57
57
|
/*!
|
|
58
58
|
* Wunderbaum - wunderbaum_node
|
|
59
59
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
60
|
-
* v0.0.
|
|
61
|
-
*/const NODE_PROPS=new Set(["classes","expanded","icon","key","lazy","refKey","selected","title","tooltip","type"]),NODE_ATTRS=new Set(["checkbox","expanded","extraClasses","folder","icon","iconTooltip","key","lazy","partsel","radiogroup","refKey","selected","statusNodeType","title","tooltip","type","unselectable","unselectableIgnore","unselectableStatus"]);class WunderbaumNode{constructor(e,t,i){var s,n;if(this.refKey=void 0,this.children=null,this.lazy=!1,this.expanded=!1,this.selected=!1,this.extraClasses=new Set,this.data={},this._isLoading=!1,this._requestId=0,this._errorInfo=null,this._partsel=!1,this._partload=!1,this.subMatchCount=0,this._rowIdx=0,this._rowElem=void 0,assert(!t||t.tree===e),assert(!i.children),this.tree=e,this.parent=t,this.key=""+(null!==(s=i.key)&&void 0!==s?s:++WunderbaumNode.sequence),this.title=""+(null!==(n=i.title)&&void 0!==n?n:"<"+this.key+">"),null!=i.refKey&&(this.refKey=""+i.refKey),null!=i.statusNodeType&&(this.statusNodeType=""+i.statusNodeType),null!=i.type&&(this.type=""+i.type),null!=i.checkbox&&(this.checkbox=!!i.checkbox),null!=i.colspan&&(this.colspan=!!i.colspan),this.expanded=!0===i.expanded,null!=i.icon&&(this.icon=i.icon),this.lazy=!0===i.lazy,this.selected=!0===i.selected,i.classes)for(const e of i.classes.split(" "))this.extraClasses.add(e.trim());for(const[e,t]of Object.entries(i))NODE_PROPS.has(e)||(this.data[e]=t);t&&!this.statusNodeType&&e._registerNode(this)}toString(){return"WunderbaumNode@"+this.key+"<'"+this.title+"'>"}_callEvent(e,t){return this.tree._callEvent(e,extend({node:this,typeInfo:this.type?this.tree.types[this.type]:{}},t))}addChildren(e,t){let i=t?t.before:null,s=[];try{this.tree.enableUpdate(!1),isPlainObject(e)&&(e=[e]);for(let t of e){let e=t.children;delete t.children;let i=new WunderbaumNode(this.tree,this,t);s.push(i),e&&i.addChildren(e,{redraw:!1})}if(this.children)if(null==i||0===this.children.length)this.children=this.children.concat(s);else{i=this.findDirectChild(i);let e=this.children.indexOf(i);assert(e>=0,"insertBefore must be an existing child"),this.children.splice(e,0,...s)}else this.children=s;return this.tree.setModified(ChangeType.structure),s[0]}finally{this.tree.enableUpdate(!0)}}addNode(e,t="child"){switch("over"===t&&(t="child"),t){case"after":return this.parent.addChildren(e,{before:this.getNextSibling()});case"before":return this.parent.addChildren(e,{before:this});case"firstChild":return this.addChildren(e,{before:0});case"child":return this.addChildren(e)}assert(!1,"Invalid mode: "+t)}applyCommand(e,t){return this.tree.applyCommand(e,this,t)}addClass(e){toSet(e).forEach((e=>{var t;this.extraClasses.add(e),null===(t=this._rowElem)||void 0===t||t.classList.add(e)}))}removeClass(e){toSet(e).forEach((e=>{var t;this.extraClasses.delete(e),null===(t=this._rowElem)||void 0===t||t.classList.remove(e)}))}toggleClass(e,t){toSet(e).forEach((e=>{var i;t?this.extraClasses.add(e):this.extraClasses.delete(e),null===(i=this._rowElem)||void 0===i||i.classList.toggle(e,t)}))}async expandAll(e=!0){this.visit((t=>{t.setExpanded(e)}))}findAll(e){const t=isFunction(e)?e:makeNodeTitleMatcher(e),i=[];return this.visit((e=>{t(e)&&i.push(e)})),i}findDirectChild(e){let t=this.children;if(!t)return null;if("string"==typeof e){for(let i=0,s=t.length;i<s;i++)if(t[i].key===e)return t[i]}else{if("number"==typeof e)return t[e];if(e.parent===this)return e}return null}findFirst(e){const t=isFunction(e)?e:makeNodeTitleMatcher(e);let i=null;return this.visit((e=>{if(t(e))return i=e,!1})),i}findRelatedNode(e,t=!1){return this.tree.findRelatedNode(this,e,t)}getColElem(e){var t;"string"==typeof e&&(e=this.tree.columns.findIndex((t=>t.id===e)));const i=null===(t=this._rowElem)||void 0===t?void 0:t.querySelectorAll("span.wb-col");return i?i[e]:null}getFirstChild(){return this.children?this.children[0]:null}getLastChild(){return this.children?this.children[this.children.length-1]:null}getLevel(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}getNextSibling(){let e=this.parent.children,t=e.indexOf(this);return e[t+1]||null}getParent(){return this.parent}getParentList(e=!1,t=!1){let i=[],s=t?this:this.parent;for(;s;)(e||s.parent)&&i.unshift(s),s=s.parent;return i}getPath(e=!0,t="title",i="/"){let s,n=[],r="function"==typeof t;return this.visitParents((e=>{e.parent&&(s=r?t(e):e[t],n.unshift(s))}),e),n.join(i)}getPrevSibling(){let e=this.parent.children,t=e.indexOf(this);return e[t-1]||null}hasChildren(){if(this.lazy){if(null==this.children)return;if(0===this.children.length)return!1;if(1===this.children.length&&this.children[0].isStatusNode())return;return!0}return!(!this.children||!this.children.length)}isActive(){return this.tree.activeNode===this}isChildOf(e){return this.parent&&this.parent===e}isDescendantOf(e){if(!e||e.tree!==this.tree)return!1;for(var t=this.parent;t;){if(t===e)return!0;t===t.parent&&error("Recursive parent link: "+t),t=t.parent}return!1}isExpandable(e=!1){return!(!this.children||this.expanded&&e)}isEditing(){return this.tree._callMethod("edit.isEditingTitle",this)}isExpanded(){return!!this.expanded}isFirstSibling(){var e=this.parent;return!e||e.children[0]===this}isLastSibling(){var e=this.parent;return!e||e.children[e.children.length-1]===this}isLazy(){return!!this.lazy}isLoaded(){return!this.lazy||void 0!==this.hasChildren()}isLoading(){return this._isLoading}isPagingNode(){return"paging"===this.statusNodeType}isPartload(){return!!this._partload}isPartsel(){return!this.selected&&!!this._partsel}isRendered(){return!!this._rowElem}isRootNode(){return this.tree.root===this}isSelected(){return!!this.selected}isStatusNode(){return!!this.statusNodeType}isTopLevel(){return this.tree.root===this.parent}isUnloaded(){return void 0===this.hasChildren()}isVisible(){let e,t,i,s="hide"===this.tree.filterMode,n=this.getParentList(!1,!1);if(s&&!this.match&&!this.subMatchCount)return!1;for(e=0,t=n.length;e<t;e++)if(i=n[e],!i.expanded)return!1;return!0}_loadSourceObject(e){const t=this.tree;this._callEvent("receive",{response:e}),isArray(e)&&(e={children:e}),assert(isPlainObject(e)),assert(e.children,"If `source` is an object, it must have a `children` property"),e.types&&extend(t.types,e.types),this.addChildren(e.children),this._callEvent("load")}async load(e){const t=this.tree,i=Date.now(),s=this.parent,n="string"==typeof e?e:e.url;this._requestId&&this.logWarn(`Recursive load request #${i} while #${this._requestId} is pending.`),this._requestId=i;const r=t.logTime(this+".load()");try{if(n){this.setStatus(NodeStatusType.loading);const e=await fetch(n,{method:"GET"});e.ok||error(`GET ${n} returned ${e.status}, ${e}`);const r=await e.json();if(this._requestId&&this._requestId>i)return void this.logWarn(`Ignored load response #${i} because #${this._requestId} is pending.`);if(this.logDebug(`Received response for load request #${i}`),null===this.parent&&null!==s)return void this.logWarn("Lazy parent node was removed while loading: discarding response.");this.setStatus(NodeStatusType.ok),r.columns&&(t.logInfo("Re-define columns",r.columns),assert(!this.parent),t.columns=r.columns,delete r.columns,t.renderHeader()),this._loadSourceObject(r)}else this._loadSourceObject(e)}catch(t){throw this.logError("Error during load()",e,t),this._callEvent("error",{error:t}),this.setStatus(NodeStatusType.error,""+t),t}finally{this._requestId=0,t.logTimeEnd(r)}}async loadLazy(e=!1){const t=this.expanded;if(assert(this.lazy,"load() requires a lazy node"),e||this.isUnloaded()){this.isLoaded()&&this.resetLazy(),this.setStatus(NodeStatusType.loading);try{const e=await this._callEvent("lazyLoad");if(!1===e)return void this.setStatus(NodeStatusType.ok);assert(isArray(e)||e&&e.url,"The lazyLoad event must return a node list, `{url: ...}` or false."),await this.load(e),t?(this.expanded=!0,this.tree.setModified(ChangeType.structure)):this.render()}catch(e){this.setStatus(NodeStatusType.error,""+e)}}}log(...e){this.logDebug.apply(this,e)}logDebug(...e){this.tree.options.debugLevel>=4&&(Array.prototype.unshift.call(e,this.toString()),console.log.apply(console,e))}logError(...e){this.tree.options.debugLevel>=1&&(Array.prototype.unshift.call(e,this.toString()),console.error.apply(console,e))}logInfo(...e){this.tree.options.debugLevel>=3&&(Array.prototype.unshift.call(e,this.toString()),console.info.apply(console,e))}logWarn(...e){this.tree.options.debugLevel>=2&&(Array.prototype.unshift.call(e,this.toString()),console.warn.apply(console,e))}async makeVisible(e){let t,i=new Deferred,s=[],n=this.getParentList(!1,!1),r=n.length,o=!(e&&!0===e.noAnimation),l=!(e&&!1===e.scrollIntoView);for(t=r-1;t>=0;t--)s.push(n[t].setExpanded(!0,e));return Promise.all(s).then((()=>{l?this.scrollIntoView(o).then((()=>{i.resolve()})):i.resolve()})),i.promise()}moveTo(e,t="appendChild",i){"prependChild"===t&&(e.children&&e.children.length?(t="before",e=e.children[0]):t="appendChild");let s,n=this.tree,r=this.parent,o="appendChild"===t?e:e.parent;if(this!==e){if(this.parent?o.isDescendantOf(this)&&error("Cannot move a node to its own descendant"):error("Cannot move system root"),o!==r&&r.triggerModifyChild("remove",this),1===this.parent.children.length){if(this.parent===o)return;this.parent.children=this.parent.lazy?[]:null,this.parent.expanded=!1}else s=this.parent.children.indexOf(this),assert(s>=0,"invalid source parent"),this.parent.children.splice(s,1);if(this.parent=o,o.hasChildren())switch(t){case"appendChild":o.children.push(this);break;case"before":s=o.children.indexOf(e),assert(s>=0,"invalid target parent"),o.children.splice(s,0,this);break;case"after":s=o.children.indexOf(e),assert(s>=0,"invalid target parent"),o.children.splice(s+1,0,this);break;default:error("Invalid mode "+t)}else o.children=[this];i&&e.visit(i,!0),o===r?o.triggerModifyChild("move",this):o.triggerModifyChild("add",this),n!==e.tree&&(this.logWarn("Cross-tree moveTo is experimental!"),this.visit((function(t){t.tree=e.tree}),!0)),n.setModified(ChangeType.structure)}}async navigate(e,t){e=KEY_TO_ACTION_DICT[e]||e;let i=this.findRelatedNode(e);if(i){try{i.makeVisible({scrollIntoView:!1})}catch(e){}return i.setFocus(),!1===(null==t?void 0:t.activate)?Promise.resolve(this):i.setActive(!0,{event:null==t?void 0:t.event})}return this.logWarn("Could not find related node '"+e+"'."),Promise.resolve(this)}remove(){const e=this.tree,t=this.parent.children.indexOf(this);this.parent.children.splice(t,1),this.visit((t=>{t.removeMarkup(),e._unregisterNode(t)}),!0)}removeChildren(){const e=this.tree;this.children&&(e.activeNode&&e.activeNode.isDescendantOf(this)&&e.activeNode.setActive(!1),e.focusNode&&e.focusNode.isDescendantOf(this)&&(e.focusNode=null),this.triggerModifyChild("remove",null),this.visit((t=>{e._unregisterNode(t)})),this.lazy?this.children=[]:this.children=null,this.isRootNode()||(this.expanded=!1),this.tree.setModified(ChangeType.structure))}removeMarkup(){this._rowElem&&(delete this._rowElem._wb_node,this._rowElem.remove(),this._rowElem=void 0)}_getRenderInfo(){let e={},t=0,i=this._rowElem?this._rowElem.querySelectorAll("span.wb-col"):null;for(let s of this.tree.columns)e[s.id]={id:s.id,idx:t,elem:i?i[t]:null,info:s},t++;return e}_createIcon(e,t){let i,s=this.getOption("icon");return this._errorInfo?s=iconMap.error:this._isLoading&&(s=iconMap.loading),!1===s?null:("string"==typeof s||(s=this.statusNodeType?iconMap[this.statusNodeType]:this.expanded?iconMap.folderOpen:this.children?iconMap.folder:iconMap.doc),s.indexOf("<")>=0?i=elemFromHtml(s):TEST_IMG.test(s)?i=elemFromHtml(`<img src="${s}" class="wb-icon">`):(i=document.createElement("i"),i.className="wb-icon "+s),t?e.replaceChild(i,t):e.appendChild(i),i)}render(e){const t=this.tree,i=t.options,s=!1!==this.getOption("checkbox"),n=t.columns,r=this.type?t.types[this.type]:null,o=this.getLevel();let l,a,d,c,h=this._rowElem,u=null,p=null;const g=t.navMode===NavigationMode.row?null:t.activeColIdx,f=!h;assert(!this.isRootNode());let v=["wb-row"];if(this.expanded&&v.push("wb-expanded"),this.lazy&&v.push("wb-lazy"),this.selected&&v.push("wb-selected"),this===t.activeNode&&v.push("wb-active"),this===t.focusNode&&v.push("wb-focus"),this._errorInfo&&v.push("wb-error"),this._isLoading&&v.push("wb-loading"),this.statusNodeType&&v.push("wb-status-"+this.statusNodeType),this.match&&v.push("wb-match"),this.subMatchCount&&v.push("wb-submatch"),i.skeleton&&v.push("wb-skeleton"),h)a=h.querySelector("span.wb-node"),d=a.querySelector("span.wb-title"),p=a.querySelector("i.wb-expander"),u=a.querySelector("i.wb-checkbox"),c=a.querySelector("i.wb-icon");else{h=document.createElement("div"),h._wb_node=this,a=document.createElement("span"),a.classList.add("wb-node","wb-col"),h.appendChild(a);let e=0;s&&(u=document.createElement("i"),a.appendChild(u),e+=20);for(let t=o-1;t>0;t--)l=document.createElement("i"),l.classList.add("wb-indent"),a.appendChild(l),e+=20;if(i.minExpandLevel&&o>i.minExpandLevel&&(p=document.createElement("i"),a.appendChild(p),e+=20),c=this._createIcon(a),c&&(e+=20),d=document.createElement("span"),d.classList.add("wb-title"),a.appendChild(d),this._callEvent("enhanceTitle",{titleSpan:d}),a._ofsTitlePx=e,t.options.dnd.dragStart&&(a.draggable=!0),!this.colspan&&n.length>1){let e=0;for(let t of n){let i;e++,"*"===t.id?i=a:(i=document.createElement("span"),i.classList.add("wb-col"),h.appendChild(i)),e===g&&i.classList.add("wb-active"),t.classes&&i.classList.add(...t.classes.split(" ")),i.style.left=t._ofsPx+"px",i.style.width=t._widthPx+"px",f&&t.html&&"string"==typeof t.html&&(i.innerHTML=t.html)}}}if(h.className=v.join(" "),h.classList.add(...this.extraClasses),r&&r.classes&&h.classList.add(...r.classes),h.style.top=22*this._rowIdx+"px",p&&(this.isExpandable(!1)?this.expanded?p.className="wb-expander "+iconMap.expanderExpanded:p.className="wb-expander "+iconMap.expanderCollapsed:this._isLoading?p.className="wb-expander "+iconMap.loading:this.lazy&&null==this.children?p.className="wb-expander "+iconMap.expanderLazy:p.classList.add("wb-indent")),u&&(this.selected?u.className="wb-checkbox "+iconMap.checkChecked:u.className="wb-checkbox "+iconMap.checkUnchecked),this.titleWithHighlight?d.innerHTML=this.titleWithHighlight:d.textContent=this.title,!i.skeleton)if(this.colspan){let e=t.element.clientWidth;d.style.width=e-a._ofsTitlePx-7+"px"}else d.style.width=n[0]._widthPx-a._ofsTitlePx-7+"px";this._rowElem=h,this.statusNodeType?this._callEvent("renderStatusNode",{isNew:f,nodeElem:a}):this.parent&&this._callEvent("render",{isNew:f,nodeElem:a,typeInfo:r,colInfosById:this._getRenderInfo()}),t.nodeListElement.appendChild(h)}resetLazy(){this.removeChildren(),this.expanded=!1,this.lazy=!0,this.children=null,this.tree.setModified(ChangeType.structure)}toDict(e=!1,t){const i={};if(NODE_ATTRS.forEach((e=>{const t=this[e];t instanceof Set?t.size&&(i[e]=Array.prototype.join.call(t.keys()," ")):(t||!1===t||0===t)&&(i[e]=t)})),isEmptyObject(this.data)||(i.data=extend({},this.data),isEmptyObject(i.data)&&delete i.data),t){const s=t(i,this);if(!1===s)return!1;"skip"===s&&(e=!1)}if(e&&isArray(this.children)){i.children=[];for(let e=0,s=this.children.length;e<s;e++){const s=this.children[e];if(!s.isStatusNode()){const e=s.toDict(!0,t);!1!==e&&i.children.push(e)}}}return i}getOption(e,t){let i=this.tree,s=i.options;e.indexOf(".")>=0&&([s,e]=e.split("."));let n=s[e];if("function"==typeof n){let e=n.call(i,{type:"resolve",tree:i,node:this});if(void 0!==e)return e}if(void 0!==this[e])return this[e];let r=this.type?i.types[this.type]:void 0,o=r?r[e]:void 0;return void 0!==o?o:null!=n?n:t}async scrollIntoView(e){return this.tree.scrollTo(this)}async setActive(e=!0,t){const i=this.tree,s=i.activeNode,n=null==t?void 0:t.retrigger;if(!(null==t?void 0:t.noEvent)){let r=null==t?void 0:t.event;if(e){if(s!==this||n){if(!1===(null==s?void 0:s._callEvent("deactivate",{nextNode:this,orgEvent:r})))return;if(!1===this._callEvent("activate",{prevNode:s,orgEvent:r}))return i.activeNode=null,void(null==s||s.setModified())}}else(s===this||n)&&this._callEvent("deactivate",{nextNode:null,orgEvent:r})}s!==this&&(i.activeNode=this,null==s||s.setModified(),this.setModified()),t&&null!=t.colIdx&&t.colIdx!==i.activeColIdx&&i.navMode!==NavigationMode.row&&i.setColumn(t.colIdx),this.scrollIntoView()}setModified(e=ChangeType.status){assert(e===ChangeType.status),this.tree.setModified(ChangeType.row,this)}async setExpanded(e=!0,t){!e&&this.isExpanded()&&this.getLevel()<this.getOption("minExpandLevel")&&!getOption(t,"force")?this.logDebug("Ignored collapse request."):(e&&this.lazy&&null==this.children&&await this.loadLazy(),this.expanded=e,this.tree.setModified(ChangeType.structure))}setIcon(){throw new Error("Not yet implemented")}setFocus(e=!0,t){const i=this.tree.focusNode;this.tree.focusNode=this,null==i||i.setModified(),this.setModified()}setSelected(e=!0,t){!!e!==this.selected&&this._callEvent("select",{flag:e}),this.selected=!!e,this.setModified()}setStatus(e,t,i){let s=this.tree,n=null;const r=e=>{let t=this.children,i=t?t[0]:null;return assert(e.statusNodeType),assert(!i||!i.isStatusNode()),n=this.addNode(e,"firstChild"),n.match=!0,s.setModified(ChangeType.structure),n};switch((()=>{let e=this.children;e&&e.length&&e[0].isStatusNode()&&e[0].remove()})(),e){case"ok":this._isLoading=!1,this._errorInfo=null;break;case"loading":this.parent||r({statusNodeType:e,title:s.options.strings.loading+(t?" ("+t+")":""),checkbox:!1,colspan:!0,tooltip:i}),this._isLoading=!0,this._errorInfo=null;break;case"error":r({statusNodeType:e,title:s.options.strings.loadError+(t?" ("+t+")":""),checkbox:!1,colspan:!0,tooltip:i}),this._isLoading=!1,this._errorInfo={message:t,details:i};break;case"noData":r({statusNodeType:e,title:t||s.options.strings.noData,checkbox:!1,colspan:!0,tooltip:i}),this._isLoading=!1,this._errorInfo=null;break;default:error("invalid node status "+e)}return s.setModified(ChangeType.structure),n}setTitle(e){this.title=e,this.setModified()}triggerModifyChild(e,t,i){this.tree.options.modifyChild&&(t&&t.parent!==this&&error("child "+t+" is not a child of "+this),this._callEvent("modifyChild",extend({operation:e,child:t},i)))}triggerModify(e,t){this.parent.triggerModifyChild(e,this,t)}visit(e,t=!1){let i,s,n=!0,r=this.children;if(!0===t&&(n=e(this),!1===n||"skip"===n))return n;if(r)for(i=0,s=r.length;i<s&&(n=r[i].visit(e,!0),!1!==n);i++);return n}visitParents(e,t=!1){if(t&&!1===e(this))return!1;let i=this.parent;for(;i;){if(!1===e(i))return!1;i=i.parent}return!0}visitSiblings(e,t=!1){let i,s,n,r=this.parent.children;for(i=0,s=r.length;i<s;i++)if(n=r[i],(t||n!==this)&&!1===e(n))return!1;return!0}isMatched(){return!(this.tree.filterMode&&!this.match)}}WunderbaumNode.sequence=0;
|
|
60
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
61
|
+
*/const NODE_PROPS=new Set(["classes","expanded","icon","key","lazy","refKey","selected","title","tooltip","type"]),NODE_ATTRS=new Set(["checkbox","expanded","extraClasses","folder","icon","iconTooltip","key","lazy","partsel","radiogroup","refKey","selected","statusNodeType","title","tooltip","type","unselectable","unselectableIgnore","unselectableStatus"]);class WunderbaumNode{constructor(e,t,i){var s,n;if(this.refKey=void 0,this.children=null,this.lazy=!1,this.expanded=!1,this.selected=!1,this.extraClasses=new Set,this.data={},this._isLoading=!1,this._requestId=0,this._errorInfo=null,this._partsel=!1,this._partload=!1,this.subMatchCount=0,this._rowIdx=0,this._rowElem=void 0,assert(!t||t.tree===e),assert(!i.children),this.tree=e,this.parent=t,this.key=""+(null!==(s=i.key)&&void 0!==s?s:++WunderbaumNode.sequence),this.title=""+(null!==(n=i.title)&&void 0!==n?n:"<"+this.key+">"),null!=i.refKey&&(this.refKey=""+i.refKey),null!=i.statusNodeType&&(this.statusNodeType=""+i.statusNodeType),null!=i.type&&(this.type=""+i.type),null!=i.checkbox&&(this.checkbox=!!i.checkbox),null!=i.colspan&&(this.colspan=!!i.colspan),this.expanded=!0===i.expanded,null!=i.icon&&(this.icon=i.icon),this.lazy=!0===i.lazy,this.selected=!0===i.selected,i.classes)for(const e of i.classes.split(" "))this.extraClasses.add(e.trim());for(const[e,t]of Object.entries(i))NODE_PROPS.has(e)||(this.data[e]=t);t&&!this.statusNodeType&&e._registerNode(this)}toString(){return"WunderbaumNode@"+this.key+"<'"+this.title+"'>"}_callEvent(e,t){return this.tree._callEvent(e,extend({node:this,typeInfo:this.type?this.tree.types[this.type]:{}},t))}addChildren(e,t){let i=t?t.before:null,s=[];try{this.tree.enableUpdate(!1),isPlainObject(e)&&(e=[e]);for(let t of e){let e=t.children;delete t.children;let i=new WunderbaumNode(this.tree,this,t);s.push(i),e&&i.addChildren(e,{redraw:!1})}if(this.children)if(null==i||0===this.children.length)this.children=this.children.concat(s);else{i=this.findDirectChild(i);let e=this.children.indexOf(i);assert(e>=0,"insertBefore must be an existing child"),this.children.splice(e,0,...s)}else this.children=s;return this.tree.setModified(ChangeType.structure),s[0]}finally{this.tree.enableUpdate(!0)}}addNode(e,t="child"){switch("over"===t&&(t="child"),t){case"after":return this.parent.addChildren(e,{before:this.getNextSibling()});case"before":return this.parent.addChildren(e,{before:this});case"firstChild":return this.addChildren(e,{before:0});case"child":return this.addChildren(e)}assert(!1,"Invalid mode: "+t)}applyCommand(e,t){return this.tree.applyCommand(e,this,t)}addClass(e){toSet(e).forEach((e=>{var t;this.extraClasses.add(e),null===(t=this._rowElem)||void 0===t||t.classList.add(e)}))}removeClass(e){toSet(e).forEach((e=>{var t;this.extraClasses.delete(e),null===(t=this._rowElem)||void 0===t||t.classList.remove(e)}))}toggleClass(e,t){toSet(e).forEach((e=>{var i;t?this.extraClasses.add(e):this.extraClasses.delete(e),null===(i=this._rowElem)||void 0===i||i.classList.toggle(e,t)}))}async expandAll(e=!0){this.visit((t=>{t.setExpanded(e)}))}findAll(e){const t=isFunction(e)?e:makeNodeTitleMatcher(e),i=[];return this.visit((e=>{t(e)&&i.push(e)})),i}findDirectChild(e){let t=this.children;if(!t)return null;if("string"==typeof e){for(let i=0,s=t.length;i<s;i++)if(t[i].key===e)return t[i]}else{if("number"==typeof e)return t[e];if(e.parent===this)return e}return null}findFirst(e){const t=isFunction(e)?e:makeNodeTitleMatcher(e);let i=null;return this.visit((e=>{if(t(e))return i=e,!1})),i}findRelatedNode(e,t=!1){return this.tree.findRelatedNode(this,e,t)}getColElem(e){var t;"string"==typeof e&&(e=this.tree.columns.findIndex((t=>t.id===e)));const i=null===(t=this._rowElem)||void 0===t?void 0:t.querySelectorAll("span.wb-col");return i?i[e]:null}getFirstChild(){return this.children?this.children[0]:null}getLastChild(){return this.children?this.children[this.children.length-1]:null}getLevel(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}getNextSibling(){let e=this.parent.children,t=e.indexOf(this);return e[t+1]||null}getParent(){return this.parent}getParentList(e=!1,t=!1){let i=[],s=t?this:this.parent;for(;s;)(e||s.parent)&&i.unshift(s),s=s.parent;return i}getPath(e=!0,t="title",i="/"){let s,n=[],r="function"==typeof t;return this.visitParents((e=>{e.parent&&(s=r?t(e):e[t],n.unshift(s))}),e),n.join(i)}getPrevSibling(){let e=this.parent.children,t=e.indexOf(this);return e[t-1]||null}hasChildren(){if(this.lazy){if(null==this.children)return;if(0===this.children.length)return!1;if(1===this.children.length&&this.children[0].isStatusNode())return;return!0}return!(!this.children||!this.children.length)}isActive(){return this.tree.activeNode===this}isChildOf(e){return this.parent&&this.parent===e}isDescendantOf(e){if(!e||e.tree!==this.tree)return!1;for(var t=this.parent;t;){if(t===e)return!0;t===t.parent&&error("Recursive parent link: "+t),t=t.parent}return!1}isExpandable(e=!1){return!(!this.children||this.expanded&&e)}isEditing(){return this.tree._callMethod("edit.isEditingTitle",this)}isExpanded(){return!!this.expanded}isFirstSibling(){var e=this.parent;return!e||e.children[0]===this}isLastSibling(){var e=this.parent;return!e||e.children[e.children.length-1]===this}isLazy(){return!!this.lazy}isLoaded(){return!this.lazy||void 0!==this.hasChildren()}isLoading(){return this._isLoading}isPagingNode(){return"paging"===this.statusNodeType}isPartload(){return!!this._partload}isPartsel(){return!this.selected&&!!this._partsel}isRendered(){return!!this._rowElem}isRootNode(){return this.tree.root===this}isSelected(){return!!this.selected}isStatusNode(){return!!this.statusNodeType}isTopLevel(){return this.tree.root===this.parent}isUnloaded(){return void 0===this.hasChildren()}isVisible(){let e,t,i,s="hide"===this.tree.filterMode,n=this.getParentList(!1,!1);if(s&&!this.match&&!this.subMatchCount)return!1;for(e=0,t=n.length;e<t;e++)if(i=n[e],!i.expanded)return!1;return!0}_loadSourceObject(e){const t=this.tree;this._callEvent("receive",{response:e}),isArray(e)&&(e={children:e}),assert(isPlainObject(e)),assert(e.children,"If `source` is an object, it must have a `children` property"),e.types&&extend(t.types,e.types),this.addChildren(e.children),this._callEvent("load")}async load(e){const t=this.tree,i=Date.now(),s=this.parent,n="string"==typeof e?e:e.url;this._requestId&&this.logWarn(`Recursive load request #${i} while #${this._requestId} is pending.`),this._requestId=i;const r=t.logTime(this+".load()");try{if(n){this.setStatus(NodeStatusType.loading);const e=await fetch(n,{method:"GET"});e.ok||error(`GET ${n} returned ${e.status}, ${e}`);const r=await e.json();if(this._requestId&&this._requestId>i)return void this.logWarn(`Ignored load response #${i} because #${this._requestId} is pending.`);if(this.logDebug(`Received response for load request #${i}`),null===this.parent&&null!==s)return void this.logWarn("Lazy parent node was removed while loading: discarding response.");this.setStatus(NodeStatusType.ok),r.columns&&(t.logInfo("Re-define columns",r.columns),assert(!this.parent),t.columns=r.columns,delete r.columns,t.updateColumns({calculateCols:!1})),this._loadSourceObject(r)}else this._loadSourceObject(e)}catch(t){throw this.logError("Error during load()",e,t),this._callEvent("error",{error:t}),this.setStatus(NodeStatusType.error,""+t),t}finally{this._requestId=0,t.logTimeEnd(r)}}async loadLazy(e=!1){const t=this.expanded;if(assert(this.lazy,"load() requires a lazy node"),e||this.isUnloaded()){this.isLoaded()&&this.resetLazy(),this.setStatus(NodeStatusType.loading);try{const e=await this._callEvent("lazyLoad");if(!1===e)return void this.setStatus(NodeStatusType.ok);assert(isArray(e)||e&&e.url,"The lazyLoad event must return a node list, `{url: ...}`, or false."),await this.load(e),t?(this.expanded=!0,this.tree.setModified(ChangeType.structure)):this.setModified()}catch(e){this.logError("Error during loadLazy()",e),this._callEvent("error",{error:e}),this.setStatus(NodeStatusType.error,""+e)}}}log(...e){this.logDebug.apply(this,e)}logDebug(...e){this.tree.options.debugLevel>=4&&(Array.prototype.unshift.call(e,this.toString()),console.log.apply(console,e))}logError(...e){this.tree.options.debugLevel>=1&&(Array.prototype.unshift.call(e,this.toString()),console.error.apply(console,e))}logInfo(...e){this.tree.options.debugLevel>=3&&(Array.prototype.unshift.call(e,this.toString()),console.info.apply(console,e))}logWarn(...e){this.tree.options.debugLevel>=2&&(Array.prototype.unshift.call(e,this.toString()),console.warn.apply(console,e))}async makeVisible(e){let t,i=new Deferred,s=[],n=this.getParentList(!1,!1),r=n.length,o=!(e&&!0===e.noAnimation),l=!(e&&!1===e.scrollIntoView);for(t=r-1;t>=0;t--)s.push(n[t].setExpanded(!0,e));return Promise.all(s).then((()=>{l?this.scrollIntoView(o).then((()=>{i.resolve()})):i.resolve()})),i.promise()}moveTo(e,t="appendChild",i){"prependChild"===t&&(e.children&&e.children.length?(t="before",e=e.children[0]):t="appendChild");let s,n=this.tree,r=this.parent,o="appendChild"===t?e:e.parent;if(this!==e){if(this.parent?o.isDescendantOf(this)&&error("Cannot move a node to its own descendant"):error("Cannot move system root"),o!==r&&r.triggerModifyChild("remove",this),1===this.parent.children.length){if(this.parent===o)return;this.parent.children=this.parent.lazy?[]:null,this.parent.expanded=!1}else s=this.parent.children.indexOf(this),assert(s>=0,"invalid source parent"),this.parent.children.splice(s,1);if(this.parent=o,o.hasChildren())switch(t){case"appendChild":o.children.push(this);break;case"before":s=o.children.indexOf(e),assert(s>=0,"invalid target parent"),o.children.splice(s,0,this);break;case"after":s=o.children.indexOf(e),assert(s>=0,"invalid target parent"),o.children.splice(s+1,0,this);break;default:error("Invalid mode "+t)}else o.children=[this];i&&e.visit(i,!0),o===r?o.triggerModifyChild("move",this):o.triggerModifyChild("add",this),n!==e.tree&&(this.logWarn("Cross-tree moveTo is experimental!"),this.visit((function(t){t.tree=e.tree}),!0)),n.setModified(ChangeType.structure)}}async navigate(e,t){e=KEY_TO_ACTION_DICT[e]||e;const i=this.findRelatedNode(e);if(!i)return this.logWarn(`Could not find related node '${e}'.`),Promise.resolve(this);try{i.makeVisible({scrollIntoView:!1})}catch(e){}return i.setFocus(),!1===(null==t?void 0:t.activate)?Promise.resolve(this):i.setActive(!0,{event:null==t?void 0:t.event})}remove(){const e=this.tree,t=this.parent.children.indexOf(this);this.triggerModify("remove"),this.parent.children.splice(t,1),this.visit((t=>{t.removeMarkup(),e._unregisterNode(t)}),!0),e.setModified(ChangeType.structure)}removeChildren(){const e=this.tree;this.children&&(e.activeNode&&e.activeNode.isDescendantOf(this)&&e.activeNode.setActive(!1),e.focusNode&&e.focusNode.isDescendantOf(this)&&(e.focusNode=null),this.triggerModifyChild("remove",null),this.visit((t=>{e._unregisterNode(t)})),this.lazy?this.children=[]:this.children=null,this.isRootNode()||(this.expanded=!1),this.tree.setModified(ChangeType.structure))}removeMarkup(){this._rowElem&&(delete this._rowElem._wb_node,this._rowElem.remove(),this._rowElem=void 0)}_getRenderInfo(){let e={},t=0,i=this._rowElem?this._rowElem.querySelectorAll("span.wb-col"):null;for(let s of this.tree.columns)e[s.id]={id:s.id,idx:t,elem:i?i[t]:null,info:s},t++;return e}_createIcon(e,t){let i,s=this.getOption("icon");return this._errorInfo?s=iconMap.error:this._isLoading&&(s=iconMap.loading),!1===s?null:("string"==typeof s||(s=this.statusNodeType?iconMap[this.statusNodeType]:this.expanded?iconMap.folderOpen:this.children?iconMap.folder:iconMap.doc),s.indexOf("<")>=0?i=elemFromHtml(s):TEST_IMG.test(s)?i=elemFromHtml(`<img src="${s}" class="wb-icon">`):(i=document.createElement("i"),i.className="wb-icon "+s),t?e.replaceChild(i,t):e.appendChild(i),i)}render(e){const t=this.tree,i=t.options,s=!1!==this.getOption("checkbox"),n=t.columns,r=this.type?t.types[this.type]:null,o=this.getLevel();let l,a,d,c,h=this._rowElem,u=null,p=null;const g=t.navMode===NavigationMode.row?null:t.activeColIdx,f=!h;assert(!f||e&&e.after,"opts.after expected, unless updating"),assert(!this.isRootNode());let m=["wb-row"];if(this.expanded&&m.push("wb-expanded"),this.lazy&&m.push("wb-lazy"),this.selected&&m.push("wb-selected"),this===t.activeNode&&m.push("wb-active"),this===t.focusNode&&m.push("wb-focus"),this._errorInfo&&m.push("wb-error"),this._isLoading&&m.push("wb-loading"),this.statusNodeType&&m.push("wb-status-"+this.statusNodeType),this.match&&m.push("wb-match"),this.subMatchCount&&m.push("wb-submatch"),i.skeleton&&m.push("wb-skeleton"),h)a=h.querySelector("span.wb-node"),d=a.querySelector("span.wb-title"),p=a.querySelector("i.wb-expander"),u=a.querySelector("i.wb-checkbox"),c=a.querySelector("i.wb-icon");else{h=document.createElement("div"),h._wb_node=this,a=document.createElement("span"),a.classList.add("wb-node","wb-col"),h.appendChild(a);let e=0;s&&(u=document.createElement("i"),a.appendChild(u),e+=20);for(let t=o-1;t>0;t--)l=document.createElement("i"),l.classList.add("wb-indent"),a.appendChild(l),e+=20;if((!i.minExpandLevel||o>i.minExpandLevel)&&(p=document.createElement("i"),a.appendChild(p),e+=20),c=this._createIcon(a),c&&(e+=20),d=document.createElement("span"),d.classList.add("wb-title"),a.appendChild(d),this._callEvent("enhanceTitle",{titleSpan:d}),a._ofsTitlePx=e,t.options.dnd.dragStart&&(a.draggable=!0),!this.colspan&&n.length>1){let e=0;for(let t of n){let i;e++,"*"===t.id?i=a:(i=document.createElement("span"),i.classList.add("wb-col"),h.appendChild(i)),e===g&&i.classList.add("wb-active"),t.classes&&i.classList.add(...t.classes.split(" ")),i.style.left=t._ofsPx+"px",i.style.width=t._widthPx+"px",f&&t.html&&"string"==typeof t.html&&(i.innerHTML=t.html)}}}if(h.className=m.join(" "),h.classList.add(...this.extraClasses),r&&r.classes&&h.classList.add(...r.classes),h.style.top=22*this._rowIdx+"px",p&&(this.isExpandable(!1)?this.expanded?p.className="wb-expander "+iconMap.expanderExpanded:p.className="wb-expander "+iconMap.expanderCollapsed:this._isLoading?p.className="wb-expander "+iconMap.loading:this.lazy&&null==this.children?p.className="wb-expander "+iconMap.expanderLazy:p.classList.add("wb-indent")),u&&(this.selected?u.className="wb-checkbox "+iconMap.checkChecked:u.className="wb-checkbox "+iconMap.checkUnchecked),this.titleWithHighlight?d.innerHTML=this.titleWithHighlight:d.textContent=this.title,!i.skeleton)if(this.colspan){let e=t.element.clientWidth;d.style.width=e-a._ofsTitlePx-7+"px"}else d.style.width=n[0]._widthPx-a._ofsTitlePx-7+"px";if(this._rowElem=h,this.statusNodeType?this._callEvent("renderStatusNode",{isNew:f,nodeElem:a}):this.parent&&this._callEvent("render",{isNew:f,nodeElem:a,typeInfo:r,colInfosById:this._getRenderInfo()}),f){switch(e?e.after:"last"){case"first":t.nodeListElement.prepend(h);break;case"last":t.nodeListElement.appendChild(h);break;default:e.after.after(h)}}}resetLazy(){this.removeChildren(),this.expanded=!1,this.lazy=!0,this.children=null,this.tree.setModified(ChangeType.structure)}toDict(e=!1,t){const i={};if(NODE_ATTRS.forEach((e=>{const t=this[e];t instanceof Set?t.size&&(i[e]=Array.prototype.join.call(t.keys()," ")):(t||!1===t||0===t)&&(i[e]=t)})),isEmptyObject(this.data)||(i.data=extend({},this.data),isEmptyObject(i.data)&&delete i.data),t){const s=t(i,this);if(!1===s)return!1;"skip"===s&&(e=!1)}if(e&&isArray(this.children)){i.children=[];for(let e=0,s=this.children.length;e<s;e++){const s=this.children[e];if(!s.isStatusNode()){const e=s.toDict(!0,t);!1!==e&&i.children.push(e)}}}return i}getOption(e,t){let i=this.tree,s=i.options;e.indexOf(".")>=0&&([s,e]=e.split("."));let n=s[e];if("function"==typeof n){let e=n.call(i,{type:"resolve",tree:i,node:this});if(void 0!==e)return e}if(void 0!==this[e])return this[e];let r=this.type?i.types[this.type]:void 0,o=r?r[e]:void 0;return void 0!==o?o:null!=n?n:t}async scrollIntoView(e){return this.tree.scrollTo(this)}async setActive(e=!0,t){const i=this.tree,s=i.activeNode,n=null==t?void 0:t.retrigger;if(!(null==t?void 0:t.noEvents)){let r=null==t?void 0:t.event;if(e){if(s!==this||n){if(!1===(null==s?void 0:s._callEvent("deactivate",{nextNode:this,orgEvent:r})))return;if(!1===this._callEvent("activate",{prevNode:s,orgEvent:r}))return i.activeNode=null,void(null==s||s.setModified())}}else(s===this||n)&&this._callEvent("deactivate",{nextNode:null,orgEvent:r})}return s!==this&&(i.activeNode=this,null==s||s.setModified(),this.setModified()),t&&null!=t.colIdx&&t.colIdx!==i.activeColIdx&&i.navMode!==NavigationMode.row&&i.setColumn(t.colIdx),this.scrollIntoView()}async setExpanded(e=!0,t){!e&&this.isExpanded()&&this.getLevel()<this.getOption("minExpandLevel")&&!getOption(t,"force")?this.logDebug("Ignored collapse request below expandLevel."):(e&&this.lazy&&null==this.children&&await this.loadLazy(),this.expanded=e,this.tree.setModified(ChangeType.structure))}setFocus(e=!0,t){const i=this.tree.focusNode;this.tree.focusNode=this,null==i||i.setModified(),this.setModified()}setIcon(){throw new Error("Not yet implemented")}setKey(e,t){throw new Error("Not yet implemented")}setModified(e=ChangeType.status){assert(e===ChangeType.status),this.tree.setModified(ChangeType.row,this)}setSelected(e=!0,t){!!e!==this.selected&&this._callEvent("select",{flag:e}),this.selected=!!e,this.setModified()}setStatus(e,t,i){const s=this.tree;let n=null;const r=e=>{let t=this.children,i=t?t[0]:null;return assert(e.statusNodeType),assert(!i||!i.isStatusNode()),n=this.addNode(e,"firstChild"),n.match=!0,s.setModified(ChangeType.structure),n};switch((()=>{let e=this.children;e&&e.length&&e[0].isStatusNode()&&e[0].remove()})(),e){case"ok":this._isLoading=!1,this._errorInfo=null;break;case"loading":this.parent||r({statusNodeType:e,title:s.options.strings.loading+(t?" ("+t+")":""),checkbox:!1,colspan:!0,tooltip:i}),this._isLoading=!0,this._errorInfo=null;break;case"error":r({statusNodeType:e,title:s.options.strings.loadError+(t?" ("+t+")":""),checkbox:!1,colspan:!0,tooltip:i}),this._isLoading=!1,this._errorInfo={message:t,details:i};break;case"noData":r({statusNodeType:e,title:t||s.options.strings.noData,checkbox:!1,colspan:!0,tooltip:i}),this._isLoading=!1,this._errorInfo=null;break;default:error("invalid node status "+e)}return s.setModified(ChangeType.structure),n}setTitle(e){this.title=e,this.setModified()}triggerModifyChild(e,t,i){this.tree.options.modifyChild&&(t&&t.parent!==this&&error("child "+t+" is not a child of "+this),this._callEvent("modifyChild",extend({operation:e,child:t},i)))}triggerModify(e,t){this.parent&&this.parent.triggerModifyChild(e,this,t)}visit(e,t=!1){let i,s,n=!0,r=this.children;if(!0===t&&(n=e(this),!1===n||"skip"===n))return n;if(r)for(i=0,s=r.length;i<s&&(n=r[i].visit(e,!0),!1!==n);i++);return n}visitParents(e,t=!1){if(t&&!1===e(this))return!1;let i=this.parent;for(;i;){if(!1===e(i))return!1;i=i.parent}return!0}visitSiblings(e,t=!1){let i,s,n,r=this.parent.children;for(i=0,s=r.length;i<s;i++)if(n=r[i],(t||n!==this)&&!1===e(n))return!1;return!0}isMatched(){return!(this.tree.filterMode&&!this.match)}}WunderbaumNode.sequence=0;
|
|
62
62
|
/*!
|
|
63
63
|
* Wunderbaum - ext-edit
|
|
64
64
|
* Copyright (c) 2021-2022, Martin Wendt. Released under the MIT license.
|
|
65
|
-
* v0.0.
|
|
65
|
+
* v0.0.3, Mon, 18 Apr 2022 11:52:44 GMT (https://github.com/mar10/wunderbaum)
|
|
66
66
|
*/
|
|
67
|
-
class EditExtension extends WunderbaumExtension{constructor(e){super(e,"edit",{debounce:100,minlength:1,maxlength:null,trigger:[],trim:!0,select:!0,slowClickDelay:1e3,validity:!0,beforeEdit:null,edit:null,apply:null}),this.curEditNode=null,this.relatedNode=null,this.debouncedOnChange=debounce(this._onChange.bind(this),this.getPluginOption("debounce"))}_applyChange(e,t,i,s){let n;t.log(`_applyChange(${e})`,s),i.classList.add("wb-dirty"),i.classList.remove("wb-error");try{n=t._callEvent(e,s)}catch(s){t.logError(`Error in ${e} event handler`,s),i.classList.add("wb-error"),i.classList.remove("wb-dirty")}return n instanceof Promise||(n=Promise.resolve(n)),n.catch((s=>{t.logError(`Error in ${e} event promise`,s),i.classList.add("wb-error")})).finally((()=>{i.classList.remove("wb-dirty")})),n}_onChange(e){const t=Wunderbaum.getEventInfo(e),i=t.node,s=t.colElem;i&&0!==t.colIdx?this._applyChange("change",i,s,{info:t,event:e,inputElem:e.target,inputValue:Wunderbaum.util.getValueFromElem(e.target)}):this.tree.log("Ignored change event for removed element or node title")}init(){super.init(),onEvent(this.tree.element,"change",".contenteditable,input,textarea,select",(e=>{this.debouncedOnChange(e)}))}_preprocessKeyEvent(e){const t=e.event,i=eventToString(t),s=this.tree,n=this.getPluginOption("trigger"),r=t.target&&t.target.closest("input,[contenteditable]");if(s.logDebug(`_preprocessKeyEvent: ${i}`),r){switch(i){case"Enter":return this._stopEditTitle(!0,{event:t}),!1;case"Escape":return this._stopEditTitle(!1,{event:t}),!1}return!1}if(s.navMode===NavigationMode.row||0===s.activeColIdx){switch(i){case"Enter":if(n.indexOf("macEnter")>=0&&isMac)return this.startEditTitle(),!1;break;case"F2":if(n.indexOf("F2")>=0)return this.startEditTitle(),!1}return!0}return!0}isEditingTitle(e){return e?this.curEditNode===e:!!this.curEditNode}startEditTitle(e){e=null!=e?e:this.tree.getActiveNode();const t=this.getPluginOption("validity"),i=this.getPluginOption("select");if(!e)return;this.tree.logDebug(`startEditTitle(node=${e})`);let s=e._callEvent("edit.beforeEdit");if(!1===s)return void e.logInfo("beforeEdit canceled operation.");if(!s){s=`<input type=text class="wb-input-edit" value="${escapeHtml(e.title)}" required autocorrect=off>`}const n=e.getColElem(0).querySelector(".wb-title");n.innerHTML=s;const r=n.firstElementChild;t&&r.addEventListener("keydown",(e=>{r.reportValidity()})),r.focus(),i&&r.select(),this.curEditNode=e,e._callEvent("edit.edit",{inputElem:r})}stopEditTitle(e){return this._stopEditTitle(e,{})}_stopEditTitle(e,t){const i=document.activeElement;let s=i?getValueFromElem(i):null;const n=this.curEditNode,r=!!t.forceClose,o=this.getPluginOption("validity");if(s&&this.getPluginOption("trim")&&(s=s.trim()),n)if(n.logDebug(`stopEditTitle(${e})`,t,i,s),e&&null!==s&&s!==n.title){const e=n.getColElem(0);this._applyChange("edit.apply",n,
|
|
67
|
+
class EditExtension extends WunderbaumExtension{constructor(e){super(e,"edit",{debounce:100,minlength:1,maxlength:null,trigger:[],trim:!0,select:!0,slowClickDelay:1e3,validity:!0,beforeEdit:null,edit:null,apply:null}),this.curEditNode=null,this.relatedNode=null,this.debouncedOnChange=debounce(this._onChange.bind(this),this.getPluginOption("debounce"))}_applyChange(e,t,i,s){let n;t.log(`_applyChange(${e})`,s),i.classList.add("wb-dirty"),i.classList.remove("wb-error");try{n=t._callEvent(e,s)}catch(s){t.logError(`Error in ${e} event handler`,s),i.classList.add("wb-error"),i.classList.remove("wb-dirty")}return n instanceof Promise||(n=Promise.resolve(n)),n.catch((s=>{t.logError(`Error in ${e} event promise`,s),i.classList.add("wb-error")})).finally((()=>{i.classList.remove("wb-dirty")})),n}_onChange(e){const t=Wunderbaum.getEventInfo(e),i=t.node,s=t.colElem;i&&0!==t.colIdx?this._applyChange("change",i,s,{info:t,event:e,inputElem:e.target,inputValue:Wunderbaum.util.getValueFromElem(e.target)}):this.tree.log("Ignored change event for removed element or node title")}init(){super.init(),onEvent(this.tree.element,"change",".contenteditable,input,textarea,select",(e=>{this.debouncedOnChange(e)}))}_preprocessKeyEvent(e){const t=e.event,i=eventToString(t),s=this.tree,n=this.getPluginOption("trigger"),r=t.target&&t.target.closest("input,[contenteditable]");if(s.logDebug(`_preprocessKeyEvent: ${i}`),r){switch(i){case"Enter":return this._stopEditTitle(!0,{event:t}),!1;case"Escape":return this._stopEditTitle(!1,{event:t}),!1}return!1}if(s.navMode===NavigationMode.row||0===s.activeColIdx){switch(i){case"Enter":if(n.indexOf("macEnter")>=0&&isMac)return this.startEditTitle(),!1;break;case"F2":if(n.indexOf("F2")>=0)return this.startEditTitle(),!1}return!0}return!0}isEditingTitle(e){return e?this.curEditNode===e:!!this.curEditNode}startEditTitle(e){e=null!=e?e:this.tree.getActiveNode();const t=this.getPluginOption("validity"),i=this.getPluginOption("select");if(!e)return;this.tree.logDebug(`startEditTitle(node=${e})`);let s=e._callEvent("edit.beforeEdit");if(!1===s)return void e.logInfo("beforeEdit canceled operation.");if(!s){s=`<input type=text class="wb-input-edit" value="${escapeHtml(e.title)}" required autocorrect=off>`}const n=e.getColElem(0).querySelector(".wb-title");n.innerHTML=s;const r=n.firstElementChild;t&&r.addEventListener("keydown",(e=>{r.setCustomValidity(""),r.reportValidity()})),r.focus(),i&&r.select(),this.curEditNode=e,e._callEvent("edit.edit",{inputElem:r})}stopEditTitle(e){return this._stopEditTitle(e,{})}_stopEditTitle(e,t){const i=document.activeElement;let s=i?getValueFromElem(i):null;const n=this.curEditNode,r=!!t.forceClose,o=this.getPluginOption("validity");if(s&&this.getPluginOption("trim")&&(s=s.trim()),n)if(n.logDebug(`stopEditTitle(${e})`,t,i,s),e&&null!==s&&s!==n.title){const e=i.validationMessage;if(e)throw new Error(`Input validation failed for "${s}": ${e}.`);const t=n.getColElem(0);this._applyChange("edit.apply",n,t,{oldValue:n.title,newValue:s,inputElem:i}).then((e=>{const t=i.validationMessage;if(o&&t&&!1!==e)throw new Error(`Edit apply validation failed for "${s}": ${t}.`);(r||!1!==e)&&(null==n||n.setTitle(s),this.curEditNode.render(),this.curEditNode=null,this.relatedNode=null,this.tree.setFocus())})).catch((e=>{}))}else this.curEditNode.render(),this.curEditNode=null,this.relatedNode=null,this.tree.setFocus();else this.tree.logDebug("stopEditTitle: not in edit mode.")}createNode(e="after",t,i){const s=this.tree;if(assert(t=null!=t?t:s.getActiveNode(),"No node was passed, or no node is currently active."),e=e||"prependChild",null==i?i={title:""}:"string"==typeof i?i={title:i}:assert(isPlainObject(i)),("prependChild"===e||"appendChild"===e)&&(null==t?void 0:t.isExpandable(!0)))return void t.setExpanded().then((()=>{this.createNode(e,t,i)}));const n=t.addNode(i,e);n.addClass("wb-edit-new"),this.relatedNode=t,n.match=!0,n.makeVisible({noAnimation:!0}).then((()=>{this.startEditTitle(n)}))}}
|
|
68
68
|
/*!
|
|
69
69
|
* wunderbaum.ts
|
|
70
70
|
*
|
|
@@ -73,7 +73,7 @@ class EditExtension extends WunderbaumExtension{constructor(e){super(e,"edit",{d
|
|
|
73
73
|
* Copyright (c) 2021-2022, Martin Wendt (https://wwWendt.de).
|
|
74
74
|
* Released under the MIT license.
|
|
75
75
|
*
|
|
76
|
-
* @version v0.0.
|
|
77
|
-
* @date
|
|
78
|
-
*/class Wunderbaum{constructor(e){this.extensionList=[],this.extensions={},this.keyMap=new Map,this.refKeyMap=new Map,this.viewNodes=new Set,this.activeNode=null,this.focusNode=null,this._disableUpdate=0,this._disableUpdateCount=0,this.types={},this.columns=[],this._columnsById={},this.changedSince=0,this.changes=new Set,this.changedNodes=new Set,this.changeRedrawPending=!1,this.filterMode=null,this.activeColIdx=0,this.navMode=NavigationMode.row,this.lastQuicksearchTime=0,this.lastQuicksearchTerm="",this.lastClickTime=0,this._util=util,this.log=this.logDebug;let t=this.options=extend({id:null,source:null,element:null,debugLevel:4,header:null,headerHeightPx:22,rowHeightPx:22,columns:null,types:null,showSpinner:!1,checkbox:!0,minExpandLevel:0,updateThrottleWait:200,skeleton:!1,navigationMode:NavigationModeOption.startRow,quicksearch:!0,change:noop,enhanceTitle:noop,error:noop,receive:noop,strings:{loadError:"Error",loading:"Loading...",noData:"No data"}},e);const i=new Deferred;this.ready=i.promise();let s=!1;if(this.ready.then((()=>{s=!0;try{this._callEvent("init")}catch(e){console.error("Exception inside `init(e)` event:",e)}})).catch((e=>{if(s)throw e;this._callEvent("init",{error:e})})),this.id=t.id||"wb_"+ ++Wunderbaum.sequence,this.root=new WunderbaumNode(this,null,{key:"__root__"}),this._registerExtension(new KeynavExtension(this)),this._registerExtension(new EditExtension(this)),this._registerExtension(new FilterExtension(this)),this._registerExtension(new DndExtension(this)),this._registerExtension(new GridExtension(this)),this._registerExtension(new LoggerExtension(this)),this.columns=t.columns,delete t.columns,!this.columns){let e="string"==typeof t.header?t.header:this.id;this.columns=[{id:"*",title:e,width:"*"}]}this.types=t.types||{},delete t.types;for(let e of Object.values(this.types))e.classes&&(e.classes=toSet(e.classes));1===this.columns.length&&(t.navigationMode=NavigationModeOption.row),t.navigationMode!==NavigationModeOption.cell&&t.navigationMode!==NavigationModeOption.startCell||(this.navMode=NavigationMode.cellNav),this._updateViewportThrottled=throttle((()=>{this._updateViewport()}),t.updateThrottleWait,{leading:!0,trailing:!0}),this.element=elemFromSelector(t.element),assert(!!this.element,`Invalid 'element' option: ${t.element}`),this.element.classList.add("wunderbaum"),this.element.getAttribute("tabindex")||(this.element.tabIndex=0),this.element._wb_tree=this,this.headerElement=this.element.querySelector("div.wb-header");const n=null==t.header?this.columns.length>1:!!t.header;if(this.headerElement){assert(!this.columns,"`opts.columns` must not be set if markup already contains a header"),this.columns=[];const e=this.headerElement.querySelector("div.wb-row");for(const t of e.querySelectorAll("div"))this.columns.push({id:t.dataset.id||null,text:""+t.textContent})}else if(n){const e="<span class='wb-col'></span>".repeat(this.columns.length);this.element.innerHTML=`\n <div class='wb-header'>\n <div class='wb-row'>\n ${e}\n </div>\n </div>`}else this.element.innerHTML="";this.element.innerHTML+='\n <div class="wb-scroll-container">\n <div class="wb-node-list"></div>\n </div>',this.scrollContainer=this.element.querySelector("div.wb-scroll-container"),this.nodeListElement=this.scrollContainer.querySelector("div.wb-node-list"),this.headerElement=this.element.querySelector("div.wb-header"),this.columns.length>1&&this.element.classList.add("wb-grid"),this._initExtensions(),t.source?(t.showSpinner&&(this.nodeListElement.innerHTML="<progress class='spinner'>loading...</progress>"),this.load(t.source).then((()=>{i.resolve()})).catch((e=>{i.reject(e)})).finally((()=>{var e;null===(e=this.element.querySelector("progress.spinner"))||void 0===e||e.remove(),this.element.classList.remove("wb-initializing")}))):i.resolve(),setTimeout((()=>{this.updateViewport()}),50),this.scrollContainer.addEventListener("scroll",(e=>{this.setModified(ChangeType.vscroll)})),this.resizeObserver=new ResizeObserver((e=>{this.setModified(ChangeType.vscroll),console.log("ResizeObserver: Size changed",e)})),this.resizeObserver.observe(this.element),onEvent(this.nodeListElement,"click","div.wb-row",(e=>{const t=Wunderbaum.getEventInfo(e),i=t.node;if(!1===this._callEvent("click",{event:e,node:i,info:t}))return this.lastClickTime=Date.now(),!1;if(i){const s=this.getOption("edit.trigger"),n=this.getOption("edit.slowClickDelay");s.indexOf("clickActive")>=0&&"title"===t.region&&i.isActive()&&(!n||Date.now()-this.lastClickTime<n)&&this._callMethod("edit.startEditTitle",i),t.colIdx>=0?i.setActive(!0,{colIdx:t.colIdx,event:e}):i.setActive(!0,{event:e}),t.region===TargetType.expander?i.setExpanded(!i.isExpanded()):t.region===TargetType.checkbox&&i.setSelected(!i.isSelected())}this.lastClickTime=Date.now()})),onEvent(this.element,"keydown",(e=>{const t=Wunderbaum.getEventInfo(e),i=eventToString(e);this._callHook("onKeyEvent",{event:e,node:t.node,info:t,eventName:i})})),onEvent(this.element,"focusin focusout",(e=>{const t="focusin"===e.type;this._callEvent("focus",{flag:t,event:e}),t||this._callMethod("edit._stopEditTitle",!0,{event:e,forceClose:!0})}))}static getTree(e){if(e instanceof Wunderbaum)return e;if(e instanceof WunderbaumNode)return e.tree;if(void 0===e&&(e=0),"number"==typeof e)e=document.querySelectorAll(".wunderbaum")[e];else if("string"==typeof e){for(let t of document.querySelectorAll(".wunderbaum")){const i=t._wb_tree;if(i&&i.id===e)return i}if(!(e=document.querySelector(e)))return null}else e.target&&(e=e.target);return assert(e instanceof Element),e.matches(".wunderbaum")||(e=e.closest(".wunderbaum")),e&&e._wb_tree?e._wb_tree:null}static getNode(e){if(!e)return null;if(e instanceof WunderbaumNode)return e;for(void 0!==e.target&&(e=e.target);e;){if(e._wb_node)return e._wb_node;e=e.parentElement}return null}_registerExtension(e){this.extensionList.push(e),this.extensions[e.id]=e}_initExtensions(){for(let e of this.extensionList)e.init()}_registerNode(e){let t=e.key;assert(null!=t&&!this.keyMap.has(t)),this.keyMap.set(t,e);let i=e.refKey;if(i){let t=this.refKeyMap.get(i);t?t.add(e):this.refKeyMap.set(i,new Set)}}_unregisterNode(e){const t=e.refKey;if(t){const i=this.refKeyMap.get(t);i&&i.delete(e)&&!i.size&&this.refKeyMap.delete(t)}e.tree=null,e.parent=null,this.viewNodes.delete(e),e.removeMarkup()}_callHook(e,t={}){let i,s=extend({},{tree:this,options:this.options,result:void 0},t);for(let t of this.extensionList){if(i=t[e].call(t,s),!1===i)break;void 0!==s.result&&(i=s.result)}return i}_callMethod(e,...t){const[i,s]=e.split("."),n=s?this.extensions[i]:this,r=n[s];if(r)return r.apply(n,t);this.logError(`Calling undefined method '${e}()'.`)}_callEvent(e,t){const[i,s]=e.split("."),n=this.options,r=s?n[i][s]:n[i];if(r)return r.call(this,extend({name:e,tree:this,util:this._util},t))}_firstNodeInView(e=!0){let t,i;return t=e?Math.ceil(this.scrollContainer.scrollTop/22):Math.floor(this.scrollContainer.scrollTop/22),this.visitRows((e=>{if(e._rowIdx===t)return i=e,!1})),i}_lastNodeInView(e=!0){let t,i;return t=e?Math.floor((this.scrollContainer.scrollTop+this.scrollContainer.clientHeight)/22)-1:Math.ceil((this.scrollContainer.scrollTop+this.scrollContainer.clientHeight)/22)-1,this.visitRows((e=>{if(e._rowIdx===t)return i=e,!1})),i}_getPrevNodeInView(e,t=1){return this.visitRows((i=>{if(e=i,t--<=0)return!1}),{reverse:!0,start:e||this.getActiveNode()}),e}_getNextNodeInView(e,t=1){return this.visitRows((i=>{if(e=i,t--<=0)return!1}),{reverse:!1,start:e||this.getActiveNode()}),e}addChildren(e,t){return this.root.addChildren(e,t)}applyCommand(e,t,i){let s,n;switch(t instanceof WunderbaumNode?s=t:(s=this.getActiveNode(),assert(void 0===i),i=t),e){case"moveUp":n=s.getPrevSibling(),n&&(s.moveTo(n,"before"),s.setActive());break;case"moveDown":n=s.getNextSibling(),n&&(s.moveTo(n,"after"),s.setActive());break;case"indent":n=s.getPrevSibling(),n&&(s.moveTo(n,"appendChild"),n.setExpanded(),s.setActive());break;case"outdent":s.isTopLevel()||(s.moveTo(s.getParent(),"after"),s.setActive());break;case"remove":n=s.getPrevSibling()||s.getParent(),s.remove(),n&&n.setActive();break;case"addChild":this._callMethod("edit.createNode","prependChild");break;case"addSibling":this._callMethod("edit.createNode","after");break;case"rename":this._callMethod("edit.startEditTitle");break;case"down":case"first":case"last":case"left":case"pageDown":case"pageUp":case"parent":case"right":case"up":return s.navigate(e);default:error(`Unhandled command: '${e}'`)}}clear(){this.root.removeChildren(),this.root.children=null,this.keyMap.clear(),this.refKeyMap.clear(),this.viewNodes.clear(),this.activeNode=null,this.focusNode=null,this.changedSince=0,this.changes.clear(),this.changedNodes.clear(),this.setModified(ChangeType.structure)}destroy(){this.logInfo("destroy()..."),this.clear(),this.resizeObserver.disconnect(),this.element.innerHTML="",this.element.outerHTML=this.element.outerHTML}getOption(e,t){let i,s=this.options;e.indexOf(".")>=0&&([i,e]=e.split("."),s=s[i]);let n=s[e];return"function"==typeof n&&(n=n({type:"resolve",tree:this})),null!=n?n:t}setOption(e,t){if(-1===e.indexOf("."))return void(this.options[e]=t);const i=e.split(".");this.extensions[i[0]].setPluginOption(i[1],t)}hasFocus(){return this.element.contains(document.activeElement)}runWithoutUpdate(e,t=null){try{return this.enableUpdate(!1),e()}finally{this.enableUpdate(!0)}}async expandAll(e=!0){const t=this.logTime("expandAll("+e+")");try{this.enableUpdate(!1),await this.root.expandAll(e)}finally{this.enableUpdate(!0),this.logTimeEnd(t)}}count(e=!1){return e?this.viewNodes.size:this.keyMap.size}_check(){let e=0;this.visit((t=>{e++})),this.keyMap.size!==e&&this.logWarn(`_check failed: ${this.keyMap.size} !== ${e}`)}findAll(e){return this.root.findAll(e)}findFirst(e){return this.root.findFirst(e)}findNextNode(e,t){let i=null,s=this.getFirstChild(),n="string"==typeof e?makeNodeTitleStartMatcher(e):e;function r(e){if(n(e)&&(i=e),i||e===t)return!1}return t=t||s,this.visitRows(r,{start:t,includeSelf:!1}),i||t===s||this.visitRows(r,{start:s,includeSelf:!0}),i}findRelatedNode(e,t,i=!1){let s=null,n=Math.floor(this.scrollContainer.clientHeight/22);switch(t){case"parent":case"left":e.parent&&e.parent.parent&&(s=e.parent);break;case"first":this.visit((function(e){if(e.isVisible())return s=e,!1}));break;case"last":this.visit((function(e){e.isVisible()&&(s=e)}));break;case"right":e.children&&e.children.length&&(s=e.children[0]);break;case"up":s=this._getPrevNodeInView(e);break;case"down":s=this._getNextNodeInView(e);break;case"pageDown":let i=this._lastNodeInView();s=this.focusNode!==i?i:this._getNextNodeInView(e,n);break;case"pageUp":if(this.focusNode&&0===this.focusNode._rowIdx)s=this.focusNode;else{let t=this._firstNodeInView();s=this.focusNode!==t?t:this._getPrevNodeInView(e,n)}break;default:this.logWarn("Unknown relation '"+t+"'.")}return s}getActiveColElem(){return this.activeNode&&this.activeColIdx>=0?this.activeNode.getColElem(this.activeColIdx):null}getActiveNode(){return this.activeNode}getFirstChild(){return this.root.getFirstChild()}getFocusNode(){return this.focusNode}static getEventInfo(e){let t=e.target,i=t.classList,s=t.closest("span.wb-col"),n=Wunderbaum.getNode(t),r=n?n.tree:Wunderbaum.getTree(e),o={tree:r,node:n,region:TargetType.unknown,colDef:void 0,colIdx:-1,colId:void 0,colElem:s};if(i.contains("wb-title"))o.region=TargetType.title;else if(i.contains("wb-expander"))o.region=!1===n.hasChildren()?TargetType.prefix:TargetType.expander;else if(i.contains("wb-checkbox"))o.region=TargetType.checkbox;else if(i.contains("wb-icon"))o.region=TargetType.icon;else if(i.contains("wb-node"))o.region=TargetType.title;else{if(!s)return"mousemove"!==e.type&&console.warn("getEventInfo(): not found",e,o),o;{o.region=TargetType.column;const e=Array.prototype.indexOf.call(s.parentNode.children,s);o.colIdx=e}}return-1===o.colIdx&&(o.colIdx=0),o.colDef=null==r?void 0:r.columns[o.colIdx],null!=o.colDef&&(o.colId=o.colDef.id),o}toString(){return"Wunderbaum<'"+this.id+"'>"}isEditing(){return this._callMethod("edit.isEditingTitle")}isLoading(){var e=!1;return this.root.visit((t=>{if(t._isLoading||t._requestId)return e=!0,!1}),!0),e}logDebug(...e){this.options.debugLevel>=4&&(Array.prototype.unshift.call(e,this.toString()),console.log.apply(console,e))}logError(...e){this.options.debugLevel>=1&&(Array.prototype.unshift.call(e,this.toString()),console.error.apply(console,e))}logInfo(...e){this.options.debugLevel>=3&&(Array.prototype.unshift.call(e,this.toString()),console.info.apply(console,e))}logTime(e){return this.options.debugLevel>=4&&console.time(this+": "+e),e}logTimeEnd(e){this.options.debugLevel>=4&&console.timeEnd(this+": "+e)}logWarn(...e){this.options.debugLevel>=2&&(Array.prototype.unshift.call(e,this.toString()),console.warn.apply(console,e))}render(e){const t=this.logTime("render");let i=0,s=0;let n=!1,r=null==e?void 0:e.startIdx,o=null==e?void 0:e.endIdx;const l=this.viewNodes,a=!!getOption(e,"newNodesOnly");this.viewNodes=new Set;let d=this.viewNodes;assert(null!=r&&null!=o),r%2&&r--,this.visitRows((function(e){const t=e._rowIdx;d.add(e),l.delete(e),t!==i&&(e._rowIdx=i,n=!0),i<r||i>o?(e._callEvent("discard"),e.removeMarkup()):e._rowElem&&a||e.render({top:s}),i++,s+=22}));for(const e of l)e._callEvent("discard"),e.removeMarkup();return this.nodeListElement.style.height=s+"px",this.logTimeEnd(t),n}renderHeader(){if(!this.headerElement)return;const e=this.headerElement.querySelector(".wb-row");assert(e),e.innerHTML="<span class='wb-col'></span>".repeat(this.columns.length);for(let t=0;t<this.columns.length;t++){const i=this.columns[t],s=e.children[t];s.style.left=i._ofsPx+"px",s.style.width=i._widthPx+"px";const n=escapeHtml(i.title||i.id);s.innerHTML=`<span class="wb-col-title">${n}</span> <span class="wb-col-resizer"></span>`}}scrollTo(e){const t=e.node||this.getActiveNode();assert(null!=t._rowIdx);const i=this.scrollContainer.scrollTop,s=this.scrollContainer.clientHeight,n=22*t._rowIdx;let r;n>i?n+22<i+s||(r=n-s+22-1):n<i&&(r=n+1),null!=r&&(this.log("scrollTo("+n+"): "+i+" => "+r,s),this.scrollContainer.scrollTop=r,this.setModified(ChangeType.vscroll))}setCellMode(e){if(e===this.navMode)return;const t=this.navMode,i=e!==NavigationMode.row;this.navMode=e,i&&t===NavigationMode.row&&this.setColumn(0),this.element.classList.toggle("wb-cell-mode",i),this.element.classList.toggle("wb-cell-edit-mode",e===NavigationMode.cellEdit),this.setModified(ChangeType.row,this.activeNode)}setColumn(e){if(assert(this.navMode!==NavigationMode.row),assert(0<=e&&e<this.columns.length),this.activeColIdx=e,this.setModified(ChangeType.row,this.activeNode),this.headerElement)for(let t of this.headerElement.children){let i=0;for(let s of t.children)s.classList.toggle("wb-active",i++===e)}for(let t of this.nodeListElement.children){let i=0;for(let s of t.children)s.classList.toggle("wb-active",i++===e)}}setFocus(e=!0){e?this.element.focus():this.element.blur()}setModified(e,t,i){if(t instanceof WunderbaumNode||(i=t),this._disableUpdate)return;const s=!!getOption(i,"immediate");switch(e){case ChangeType.any:case ChangeType.structure:case ChangeType.header:this.changeRedrawPending=!0,this.updateViewport(s);break;case ChangeType.vscroll:this.updateViewport(s);break;case ChangeType.row:case ChangeType.status:t._rowElem&&t.render();break;default:error(`Invalid change type ${e}`)}}setStatus(e,t,i){return this.root.setStatus(e,t,i)}updateColumns(e){let t=!1,i=this.element.clientWidth,s=0,n=0;this._columnsById={};for(let e of this.columns){this._columnsById[e.id]=e;let i=e.width;if(i&&"*"!==i)if("number"==typeof i)e._weight=i,s+=i;else if("string"==typeof i&&i.endsWith("px")){e._weight=0;let s=parseFloat(i.slice(0,-2));e._widthPx!=s&&(t=!0,e._widthPx=s),n+=s}else error("Invalid column width: "+i);else e._weight=1,s+=1}let r=Math.max(0,i-n),o=0;for(let e of this.columns){if(e._weight){let i=Math.max(4,r*e._weight/s);e._widthPx!=i&&(t=!0,e._widthPx=i)}e._ofsPx=o,o+=e._widthPx}t&&(this.renderHeader(),!1!==e.render&&this.render())}updateViewport(e=!1){this._updateViewportThrottled(),e&&this._updateViewportThrottled.flush()}_updateViewport(){if(this._disableUpdate)return;const e=!this.changeRedrawPending;this.changeRedrawPending=!1;let t=this.scrollContainer.clientHeight;const i=this.options.headerHeightPx,s=this.element.clientHeight-i,n=this.scrollContainer.scrollTop;Math.abs(t-s)>1&&(this.scrollContainer.style.height=s+"px",t=s),this.updateColumns({render:!1}),this.render({startIdx:Math.max(0,n/22-5),endIdx:Math.max(0,(n+t)/22+5),newNodesOnly:e}),this._callEvent("update")}visit(e){return this.root.visit(e,!1)}visitRows(e,t){if(!this.root.hasChildren())return!1;if(t&&t.reverse)return delete t.reverse,this._visitRowsUp(e,t);let i,s,n,r,o,l,a=0,d=!1===(t=t||{}).includeSelf,c=!!t.includeHidden,h=!c&&"hide"===this.filterMode,u=t.start||this.root.children[0];for(n=u.parent;n;){for(o=n.children,s=o.indexOf(u)+a,assert(s>=0,"Could not find "+u+" in parent's children: "+n),i=s;i<o.length;i++){if(u=o[i],u===l)return!1;if(!h||u.statusNodeType||u.match||u.subMatchCount){if(!d&&!1===e(u))return!1;if(d=!1,u.children&&u.children.length&&(c||u.expanded)&&(r=u.visit((function(t){return t!==l&&(!h||t.match||t.subMatchCount?!1!==e(t)&&(c||!t.children||t.expanded?void 0:"skip"):"skip")}),!1),!1===r))return!1}}u=n,n=n.parent,a=1,!n&&t.wrap&&(this.logDebug("visitRows(): wrap around"),assert(t.start,"`wrap` option requires `start`"),l=t.start,t.wrap=!1,n=this.root,a=0)}return!0}_visitRowsUp(e,t){let i,s,n,r=!!t.includeHidden,o=t.start||this.root.children[0];if(!1!==t.includeSelf&&!1===e(o))return!1;for(;;){if(n=o.parent,i=n.children,i[0]===o){if(o=n,!o.parent)break;i=n.children}else for(s=i.indexOf(o),o=i[s-1];(r||o.expanded)&&o.children&&o.children.length;)i=o.children,n=o,o=i[i.length-1];if((r||o.isVisible())&&!1===e(o))return!1}return!0}load(e,t={}){this.clear();return(t.columns||e.columns)&&(this.columns=t.columns,this.renderHeader()),this.root.load(e)}enableUpdate(e){e?(assert(this._disableUpdateCount>0),this._disableUpdateCount--,0===this._disableUpdateCount&&this.updateViewport()):this._disableUpdateCount++}clearFilter(){return this.extensions.filter.clearFilter()}isFilterActive(){return!!this.filterMode}updateFilter(){return this.extensions.filter.updateFilter()}}Wunderbaum.version="v0.0.2",Wunderbaum.sequence=0,Wunderbaum.util=util;export{Wunderbaum};
|
|
76
|
+
* @version v0.0.3
|
|
77
|
+
* @date Mon, 18 Apr 2022 11:52:44 GMT
|
|
78
|
+
*/class Wunderbaum{constructor(e){this.extensionList=[],this.extensions={},this.keyMap=new Map,this.refKeyMap=new Map,this.treeRowCount=0,this._disableUpdateCount=0,this.activeNode=null,this.focusNode=null,this.types={},this.columns=[],this._columnsById={},this.changeRedrawRequestPending=!1,this._util=util,this.filterMode=null,this.activeColIdx=0,this.navMode=NavigationMode.row,this.lastQuicksearchTime=0,this.lastQuicksearchTerm="",this.lastClickTime=0,this.log=this.logDebug;let t=this.options=extend({id:null,source:null,element:null,debugLevel:4,header:null,headerHeightPx:22,rowHeightPx:22,columns:null,types:null,showSpinner:!1,checkbox:!0,minExpandLevel:0,updateThrottleWait:200,skeleton:!1,navigationMode:NavigationModeOption.startRow,quicksearch:!0,change:noop,enhanceTitle:noop,error:noop,receive:noop,strings:{loadError:"Error",loading:"Loading...",noData:"No data"}},e);const i=new Deferred;this.ready=i.promise();let s=!1;if(this.ready.then((()=>{s=!0;try{this._callEvent("init")}catch(e){console.error("Exception inside `init(e)` event:",e)}})).catch((e=>{if(s)throw e;this._callEvent("init",{error:e})})),this.id=t.id||"wb_"+ ++Wunderbaum.sequence,this.root=new WunderbaumNode(this,null,{key:"__root__"}),this._registerExtension(new KeynavExtension(this)),this._registerExtension(new EditExtension(this)),this._registerExtension(new FilterExtension(this)),this._registerExtension(new DndExtension(this)),this._registerExtension(new GridExtension(this)),this._registerExtension(new LoggerExtension(this)),this.columns=t.columns,delete t.columns,!this.columns){let e="string"==typeof t.header?t.header:this.id;this.columns=[{id:"*",title:e,width:"*"}]}this.types=t.types||{},delete t.types;for(let e of Object.values(this.types))e.classes&&(e.classes=toSet(e.classes));1===this.columns.length&&(t.navigationMode=NavigationModeOption.row),t.navigationMode!==NavigationModeOption.cell&&t.navigationMode!==NavigationModeOption.startCell||(this.navMode=NavigationMode.cellNav),this._updateViewportThrottled=throttle((()=>{this._updateViewport()}),t.updateThrottleWait,{leading:!0,trailing:!0}),this.element=elemFromSelector(t.element),assert(!!this.element,`Invalid 'element' option: ${t.element}`),this.element.classList.add("wunderbaum"),this.element.getAttribute("tabindex")||(this.element.tabIndex=0),this.element._wb_tree=this,this.headerElement=this.element.querySelector("div.wb-header");const n=null==t.header?this.columns.length>1:!!t.header;if(this.headerElement){assert(!this.columns,"`opts.columns` must not be set if markup already contains a header"),this.columns=[];const e=this.headerElement.querySelector("div.wb-row");for(const t of e.querySelectorAll("div"))this.columns.push({id:t.dataset.id||null,text:""+t.textContent})}else if(n){const e="<span class='wb-col'></span>".repeat(this.columns.length);this.element.innerHTML=`\n <div class='wb-header'>\n <div class='wb-row'>\n ${e}\n </div>\n </div>`}else this.element.innerHTML="";this.element.innerHTML+='\n <div class="wb-scroll-container">\n <div class="wb-node-list"></div>\n </div>',this.scrollContainer=this.element.querySelector("div.wb-scroll-container"),this.nodeListElement=this.scrollContainer.querySelector("div.wb-node-list"),this.headerElement=this.element.querySelector("div.wb-header"),this.columns.length>1&&this.element.classList.add("wb-grid"),this._initExtensions(),t.source?(t.showSpinner&&(this.nodeListElement.innerHTML="<progress class='spinner'>loading...</progress>"),this.load(t.source).then((()=>{i.resolve()})).catch((e=>{i.reject(e)})).finally((()=>{var e;null===(e=this.element.querySelector("progress.spinner"))||void 0===e||e.remove(),this.element.classList.remove("wb-initializing")}))):i.resolve(),setTimeout((()=>{this.updateViewport()}),50),this.scrollContainer.addEventListener("scroll",(e=>{this.setModified(ChangeType.vscroll)})),this.resizeObserver=new ResizeObserver((e=>{this.setModified(ChangeType.vscroll),console.log("ResizeObserver: Size changed",e)})),this.resizeObserver.observe(this.element),onEvent(this.nodeListElement,"click","div.wb-row",(e=>{const t=Wunderbaum.getEventInfo(e),i=t.node;if(!1===this._callEvent("click",{event:e,node:i,info:t}))return this.lastClickTime=Date.now(),!1;if(i){const s=this.getOption("edit.trigger"),n=this.getOption("edit.slowClickDelay");s.indexOf("clickActive")>=0&&"title"===t.region&&i.isActive()&&(!n||Date.now()-this.lastClickTime<n)&&this._callMethod("edit.startEditTitle",i),t.colIdx>=0?i.setActive(!0,{colIdx:t.colIdx,event:e}):i.setActive(!0,{event:e}),t.region===TargetType.expander?i.setExpanded(!i.isExpanded()):t.region===TargetType.checkbox&&i.setSelected(!i.isSelected())}this.lastClickTime=Date.now()})),onEvent(this.element,"keydown",(e=>{const t=Wunderbaum.getEventInfo(e),i=eventToString(e);this._callHook("onKeyEvent",{event:e,node:t.node,info:t,eventName:i})})),onEvent(this.element,"focusin focusout",(e=>{const t="focusin"===e.type;this._callEvent("focus",{flag:t,event:e}),t||this._callMethod("edit._stopEditTitle",!0,{event:e,forceClose:!0})}))}static getTree(e){if(e instanceof Wunderbaum)return e;if(e instanceof WunderbaumNode)return e.tree;if(void 0===e&&(e=0),"number"==typeof e)e=document.querySelectorAll(".wunderbaum")[e];else if("string"==typeof e){for(let t of document.querySelectorAll(".wunderbaum")){const i=t._wb_tree;if(i&&i.id===e)return i}if(!(e=document.querySelector(e)))return null}else e.target&&(e=e.target);return assert(e instanceof Element),e.matches(".wunderbaum")||(e=e.closest(".wunderbaum")),e&&e._wb_tree?e._wb_tree:null}static getNode(e){if(!e)return null;if(e instanceof WunderbaumNode)return e;for(void 0!==e.target&&(e=e.target);e;){if(e._wb_node)return e._wb_node;e=e.parentElement}return null}_registerExtension(e){this.extensionList.push(e),this.extensions[e.id]=e}_initExtensions(){for(let e of this.extensionList)e.init()}_registerNode(e){let t=e.key;assert(null!=t&&!this.keyMap.has(t)),this.keyMap.set(t,e);let i=e.refKey;if(i){let t=this.refKeyMap.get(i);t?t.add(e):this.refKeyMap.set(i,new Set)}}_unregisterNode(e){const t=e.refKey;if(t){const i=this.refKeyMap.get(t);i&&i.delete(e)&&!i.size&&this.refKeyMap.delete(t)}e.tree=null,e.parent=null,e.removeMarkup()}_callHook(e,t={}){let i,s=extend({},{tree:this,options:this.options,result:void 0},t);for(let t of this.extensionList){if(i=t[e].call(t,s),!1===i)break;void 0!==s.result&&(i=s.result)}return i}_callMethod(e,...t){const[i,s]=e.split("."),n=s?this.extensions[i]:this,r=n[s];if(r)return r.apply(n,t);this.logError(`Calling undefined method '${e}()'.`)}_callEvent(e,t){const[i,s]=e.split("."),n=this.options,r=s?n[i][s]:n[i];if(r)return r.call(this,extend({name:e,tree:this,util:this._util},t))}_getNodeByRowIdx(e){let t=null;return this.visitRows((i=>{if(i._rowIdx===e)return t=i,!1})),t}_firstNodeInView(e=!0){let t;return t=e?Math.ceil((this.scrollContainer.scrollTop-1)/22):Math.floor(this.scrollContainer.scrollTop/22),this._getNodeByRowIdx(t)}_lastNodeInView(e=!0){let t;return t=e?Math.floor((this.scrollContainer.scrollTop+this.scrollContainer.clientHeight)/22)-1:Math.ceil((this.scrollContainer.scrollTop+this.scrollContainer.clientHeight)/22)-1,t=Math.min(t,this.count(!0)-1),this._getNodeByRowIdx(t)}_getPrevNodeInView(e,t=1){return this.visitRows((i=>{if(e=i,t--<=0)return!1}),{reverse:!0,start:e||this.getActiveNode()}),e}_getNextNodeInView(e,t=1){return this.visitRows((i=>{if(e=i,t--<=0)return!1}),{reverse:!1,start:e||this.getActiveNode()}),e}addChildren(e,t){return this.root.addChildren(e,t)}applyCommand(e,t,i){let s,n;switch(t instanceof WunderbaumNode?s=t:(s=this.getActiveNode(),assert(void 0===i),i=t),e){case"moveUp":n=s.getPrevSibling(),n&&(s.moveTo(n,"before"),s.setActive());break;case"moveDown":n=s.getNextSibling(),n&&(s.moveTo(n,"after"),s.setActive());break;case"indent":n=s.getPrevSibling(),n&&(s.moveTo(n,"appendChild"),n.setExpanded(),s.setActive());break;case"outdent":s.isTopLevel()||(s.moveTo(s.getParent(),"after"),s.setActive());break;case"remove":n=s.getPrevSibling()||s.getParent(),s.remove(),n&&n.setActive();break;case"addChild":this._callMethod("edit.createNode","prependChild");break;case"addSibling":this._callMethod("edit.createNode","after");break;case"rename":this._callMethod("edit.startEditTitle");break;case"down":case"first":case"last":case"left":case"pageDown":case"pageUp":case"parent":case"right":case"up":return s.navigate(e);default:error(`Unhandled command: '${e}'`)}}clear(){this.root.removeChildren(),this.root.children=null,this.keyMap.clear(),this.refKeyMap.clear(),this.treeRowCount=0,this.activeNode=null,this.focusNode=null,this.setModified(ChangeType.structure)}destroy(){this.logInfo("destroy()..."),this.clear(),this.resizeObserver.disconnect(),this.element.innerHTML="",this.element.outerHTML=this.element.outerHTML}getOption(e,t){let i,s=this.options;e.indexOf(".")>=0&&([i,e]=e.split("."),s=s[i]);let n=s[e];return"function"==typeof n&&(n=n({type:"resolve",tree:this})),null!=n?n:t}setOption(e,t){if(-1===e.indexOf("."))return void(this.options[e]=t);const i=e.split(".");this.extensions[i[0]].setPluginOption(i[1],t)}hasFocus(){return this.element.contains(document.activeElement)}runWithoutUpdate(e,t=null){try{this.enableUpdate(!1);const t=e();return assert(!(t instanceof Promise)),t}finally{this.enableUpdate(!0)}}async expandAll(e=!0){const t=this.logTime("expandAll("+e+")");try{this.enableUpdate(!1),await this.root.expandAll(e)}finally{this.enableUpdate(!0),this.logTimeEnd(t)}}count(e=!1){return e?this.treeRowCount:this.keyMap.size}_check(){let e=0;this.visit((t=>{e++})),this.keyMap.size!==e&&this.logWarn(`_check failed: ${this.keyMap.size} !== ${e}`)}findAll(e){return this.root.findAll(e)}findFirst(e){return this.root.findFirst(e)}findNextNode(e,t){let i=null,s=this.getFirstChild(),n="string"==typeof e?makeNodeTitleStartMatcher(e):e;function r(e){if(n(e)&&(i=e),i||e===t)return!1}return t=t||s,this.visitRows(r,{start:t,includeSelf:!1}),i||t===s||this.visitRows(r,{start:s,includeSelf:!0}),i}findRelatedNode(e,t,i=!1){let s=null;const n=Math.floor(this.scrollContainer.clientHeight/22);switch(t){case"parent":case"left":e.parent&&e.parent.parent&&(s=e.parent);break;case"first":this.visit((function(e){if(e.isVisible())return s=e,!1}));break;case"last":this.visit((function(e){e.isVisible()&&(s=e)}));break;case"right":e.children&&e.children.length&&(s=e.children[0]);break;case"up":s=this._getPrevNodeInView(e);break;case"down":s=this._getNextNodeInView(e);break;case"pageDown":const i=this._lastNodeInView();s=e._rowIdx<i._rowIdx?i:this._getNextNodeInView(e,n);break;case"pageUp":if(0===e._rowIdx)s=e;else{const t=this._firstNodeInView();s=e._rowIdx>t._rowIdx?t:this._getPrevNodeInView(e,n)}break;default:this.logWarn("Unknown relation '"+t+"'.")}return s}getActiveColElem(){return this.activeNode&&this.activeColIdx>=0?this.activeNode.getColElem(this.activeColIdx):null}getActiveNode(){return this.activeNode}getFirstChild(){return this.root.getFirstChild()}getFocusNode(){return this.focusNode}static getEventInfo(e){let t=e.target,i=t.classList,s=t.closest("span.wb-col"),n=Wunderbaum.getNode(t),r=n?n.tree:Wunderbaum.getTree(e),o={tree:r,node:n,region:TargetType.unknown,colDef:void 0,colIdx:-1,colId:void 0,colElem:s};if(i.contains("wb-title"))o.region=TargetType.title;else if(i.contains("wb-expander"))o.region=!1===n.hasChildren()?TargetType.prefix:TargetType.expander;else if(i.contains("wb-checkbox"))o.region=TargetType.checkbox;else if(i.contains("wb-icon"))o.region=TargetType.icon;else if(i.contains("wb-node"))o.region=TargetType.title;else{if(!s)return"mousemove"===e.type||e instanceof KeyboardEvent||console.warn("getEventInfo(): not found",e,o),o;{o.region=TargetType.column;const e=Array.prototype.indexOf.call(s.parentNode.children,s);o.colIdx=e}}return-1===o.colIdx&&(o.colIdx=0),o.colDef=null==r?void 0:r.columns[o.colIdx],null!=o.colDef&&(o.colId=o.colDef.id),o}toString(){return"Wunderbaum<'"+this.id+"'>"}isEditing(){return this._callMethod("edit.isEditingTitle")}isLoading(){var e=!1;return this.root.visit((t=>{if(t._isLoading||t._requestId)return e=!0,!1}),!0),e}logDebug(...e){this.options.debugLevel>=4&&(Array.prototype.unshift.call(e,this.toString()),console.log.apply(console,e))}logError(...e){this.options.debugLevel>=1&&(Array.prototype.unshift.call(e,this.toString()),console.error.apply(console,e))}logInfo(...e){this.options.debugLevel>=3&&(Array.prototype.unshift.call(e,this.toString()),console.info.apply(console,e))}logTime(e){return this.options.debugLevel>=4&&console.time(this+": "+e),e}logTimeEnd(e){this.options.debugLevel>=4&&console.timeEnd(this+": "+e)}logWarn(...e){this.options.debugLevel>=2&&(Array.prototype.unshift.call(e,this.toString()),console.warn.apply(console,e))}scrollTo(e){const t=e.node||this.getActiveNode();assert(null!=t._rowIdx);const i=this.scrollContainer.scrollTop,s=this.scrollContainer.clientHeight,n=22*t._rowIdx;let r;n>i?n+22<i+s||(r=n-s+22-1):n<i&&(r=n+1),null!=r&&(this.log("scrollTo("+n+"): "+i+" => "+r,s),this.scrollContainer.scrollTop=r,this.setModified(ChangeType.vscroll))}setColumn(e){if(assert(this.navMode!==NavigationMode.row),assert(0<=e&&e<this.columns.length),this.activeColIdx=e,this.setModified(ChangeType.row,this.activeNode),this.headerElement)for(let t of this.headerElement.children){let i=0;for(let s of t.children)s.classList.toggle("wb-active",i++===e)}for(let t of this.nodeListElement.children){let i=0;for(let s of t.children)s.classList.toggle("wb-active",i++===e)}}setFocus(e=!0){e?this.element.focus():this.element.blur()}setModified(e,t,i){if(this._disableUpdateCount)return;t instanceof WunderbaumNode||(i=t);const s=!!getOption(i,"immediate");switch(e){case ChangeType.any:case ChangeType.structure:case ChangeType.header:this.changeRedrawRequestPending=!0,this.updateViewport(s);break;case ChangeType.vscroll:this.updateViewport(s);break;case ChangeType.row:case ChangeType.status:t._rowElem&&t.render();break;default:error(`Invalid change type ${e}`)}}setNavigationMode(e){if(e===this.navMode)return;const t=this.navMode,i=e!==NavigationMode.row;this.navMode=e,i&&t===NavigationMode.row&&this.setColumn(0),this.element.classList.toggle("wb-cell-mode",i),this.element.classList.toggle("wb-cell-edit-mode",e===NavigationMode.cellEdit),this.setModified(ChangeType.row,this.activeNode)}setStatus(e,t,i){return this.root.setStatus(e,t,i)}updateColumns(e){e=Object.assign({calculateCols:!0,updateRows:!0},e);const t=this.element.clientWidth;let i=0,s=0,n=!1;if(e.calculateCols){this._columnsById={};for(let e of this.columns){this._columnsById[e.id]=e;let t=e.width;if(t&&"*"!==t)if("number"==typeof t)e._weight=t,i+=t;else if("string"==typeof t&&t.endsWith("px")){e._weight=0;let i=parseFloat(t.slice(0,-2));e._widthPx!=i&&(n=!0,e._widthPx=i),s+=i}else error("Invalid column width: "+t);else e._weight=1,i+=1}const e=Math.max(0,t-s);let r=0;for(let t of this.columns){if(t._weight){const s=Math.max(4,e*t._weight/i);t._widthPx!=s&&(n=!0,t._widthPx=s)}t._ofsPx=r,r+=t._widthPx}}n&&(this._renderHeaderMarkup(),e.updateRows&&this._updateRows())}_renderHeaderMarkup(){if(!this.headerElement)return;const e=this.headerElement.querySelector(".wb-row");assert(e),e.innerHTML="<span class='wb-col'></span>".repeat(this.columns.length);for(let t=0;t<this.columns.length;t++){const i=this.columns[t],s=e.children[t];s.style.left=i._ofsPx+"px",s.style.width=i._widthPx+"px";const n=escapeHtml(i.title||i.id);s.innerHTML=`<span class="wb-col-title">${n}</span> <span class="wb-col-resizer"></span>`}}updateViewport(e=!1){this._updateViewportThrottled(),e&&this._updateViewportThrottled.flush()}_updateViewport(){if(this._disableUpdateCount)return void this.log(`IGNORED _updateViewport() disable level: ${this._disableUpdateCount}`);const e=!this.changeRedrawRequestPending;this.changeRedrawRequestPending=!1;let t=this.scrollContainer.clientHeight;const i=this.options.headerHeightPx,s=this.element.clientHeight-i;Math.abs(t-s)>1&&(this.scrollContainer.style.height=s+"px",t=s),this.updateColumns({updateRows:!1}),this._updateRows({newNodesOnly:e}),this._callEvent("update")}_validateRows(){let e=this.nodeListElement.childNodes,t=0,i=-1,s=!0;return e.forEach((e=>{const n=e,r=Number.parseInt(n.style.top),o=n._wb_node;r<=i&&(console.warn(`TR order mismatch at index ${t}: top=${r}px, node=${o}`),s=!1),i=r,t++})),s}_updateRows(e){const t=this.logTime("_updateRows"),i=!!(e=Object.assign({newNodesOnly:!1},e)).newNodesOnly,s=this.scrollContainer.clientHeight,n=this.scrollContainer.scrollTop;let r=Math.max(0,n/22-5);r=Math.floor(r),r%2&&r--;let o=Math.max(0,(n+s)/22+5);o=Math.ceil(o);const l=new Set;this.nodeListElement.childNodes.forEach((e=>{const t=e;l.add(t._wb_node)}));let a=0,d=0,c=!1,h="first";this.visitRows((function(e){const t=e._rowElem;e._rowIdx!==a&&(e._rowIdx=a,c=!0),a<r||a>o?t&&(h=t):t&&i?(l.delete(e),t.style.top=22*a+"px",h=t):(l.delete(e),e.render({top:d,after:h}),h=e._rowElem),a++,d+=22})),this.treeRowCount=a;for(const e of l)e._callEvent("discard"),e.removeMarkup();return this.nodeListElement.style.height=`${d}px`,this.logTimeEnd(t),this._validateRows(),c}visit(e){return this.root.visit(e,!1)}visitRows(e,t){if(!this.root.hasChildren())return!1;if(t&&t.reverse)return delete t.reverse,this._visitRowsUp(e,t);let i,s,n,r,o,l,a=0,d=!1===(t=t||{}).includeSelf,c=!!t.includeHidden,h=!c&&"hide"===this.filterMode,u=t.start||this.root.children[0];for(n=u.parent;n;){for(o=n.children,s=o.indexOf(u)+a,assert(s>=0,"Could not find "+u+" in parent's children: "+n),i=s;i<o.length;i++){if(u=o[i],u===l)return!1;if(!h||u.statusNodeType||u.match||u.subMatchCount){if(!d&&!1===e(u))return!1;if(d=!1,u.children&&u.children.length&&(c||u.expanded)&&(r=u.visit((function(t){return t!==l&&(!h||t.match||t.subMatchCount?!1!==e(t)&&(c||!t.children||t.expanded?void 0:"skip"):"skip")}),!1),!1===r))return!1}}u=n,n=n.parent,a=1,!n&&t.wrap&&(this.logDebug("visitRows(): wrap around"),assert(t.start,"`wrap` option requires `start`"),l=t.start,t.wrap=!1,n=this.root,a=0)}return!0}_visitRowsUp(e,t){let i,s,n,r=!!t.includeHidden,o=t.start||this.root.children[0];if(!1!==t.includeSelf&&!1===e(o))return!1;for(;;){if(n=o.parent,i=n.children,i[0]===o){if(o=n,!o.parent)break;i=n.children}else for(s=i.indexOf(o),o=i[s-1];(r||o.expanded)&&o.children&&o.children.length;)i=o.children,n=o,o=i[i.length-1];if((r||o.isVisible())&&!1===e(o))return!1}return!0}load(e,t={}){this.clear();return(t.columns||e.columns)&&(this.columns=t.columns,this.updateColumns({calculateCols:!1})),this.root.load(e)}enableUpdate(e){e?(assert(this._disableUpdateCount>0,"enableUpdate(true) was called too often"),this._disableUpdateCount--,0===this._disableUpdateCount&&this.updateViewport()):this._disableUpdateCount++}clearFilter(){return this.extensions.filter.clearFilter()}isFilterActive(){return!!this.filterMode}updateFilter(){return this.extensions.filter.updateFilter()}}Wunderbaum.sequence=0,Wunderbaum.version="v0.0.3",Wunderbaum.util=util;export{Wunderbaum};
|
|
79
79
|
//# sourceMappingURL=wunderbaum.esm.min.js.map
|