@openremote/or-asset-tree 1.10.0-snapshot.20251016093424 → 1.10.0-snapshot.20251017113812

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/lib/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { LitElement, PropertyValues, TemplateResult } from "lit";
2
2
  import "@openremote/or-mwc-components/or-mwc-input";
3
3
  import { OrMwcInput } from "@openremote/or-mwc-components/or-mwc-input";
4
4
  import "@openremote/or-icon";
5
- import { Asset, AssetDescriptor, AssetEvent, AssetTreeNode, AssetTypeInfo, SharedEvent } from "@openremote/model";
5
+ import { Asset, AssetDescriptor, AssetEvent, AssetQueryOrderBy$Property, AssetTreeEvent, AssetTreeNode, SharedEvent } from "@openremote/model";
6
6
  import "@openremote/or-translate";
7
7
  import { style } from "./style";
8
8
  import { EventCallback, Util } from "@openremote/core";
@@ -111,7 +111,6 @@ declare global {
111
111
  [OrAssetTreeChangeParentEvent.NAME]: OrAssetTreeChangeParentEvent;
112
112
  }
113
113
  }
114
- export declare const getAssetTypes: () => Promise<string[] | undefined>;
115
114
  declare const OrAssetTree_base: (new (...args: any[]) => {
116
115
  _connectRequested: boolean;
117
116
  _subscriptionIds?: string[];
@@ -146,15 +145,13 @@ export declare class OrAssetTree extends OrAssetTree_base {
146
145
  /**
147
146
  * Allows arbitrary assets to be displayed using a tree
148
147
  */
149
- assets?: Asset[];
150
- assetInfos?: AssetTypeInfo[];
151
- _assetIdsOverride?: string[];
152
- rootAssets?: Asset[];
153
- rootAssetIds?: string[];
154
- dataProvider?: () => Promise<Asset[]>;
155
- readonly: boolean;
148
+ readonly assets?: Asset[];
149
+ readonly rootAssets?: Asset[];
150
+ readonly rootAssetIds?: string[];
151
+ readonly dataProvider?: () => Promise<Asset[]>;
152
+ readonly readonly: boolean;
156
153
  disabled: boolean;
157
- disableSubscribe: boolean;
154
+ readonly disableSubscribe: boolean;
158
155
  selectedIds?: string[];
159
156
  showDeselectBtn?: boolean;
160
157
  showSortBtn?: boolean;
@@ -163,6 +160,7 @@ export declare class OrAssetTree extends OrAssetTree_base {
163
160
  expandAllNodes?: boolean;
164
161
  expandedIds?: string[];
165
162
  checkboxes?: boolean;
163
+ readonly queryLimit = 100;
166
164
  protected config?: AssetTreeConfig;
167
165
  protected _nodes?: UiAssetTreeNode[];
168
166
  protected _loading: boolean;
@@ -171,7 +169,6 @@ export declare class OrAssetTree extends OrAssetTree_base {
171
169
  protected _expandedNodes: UiAssetTreeNode[];
172
170
  protected _initCallback?: EventCallback;
173
171
  protected _filter: OrAssetTreeFilter;
174
- protected _searchInputTimer?: number;
175
172
  protected _clearIconContainer: HTMLElement;
176
173
  protected _filterInput: OrMwcInput;
177
174
  protected _filterSettingOpen: boolean;
@@ -180,6 +177,8 @@ export declare class OrAssetTree extends OrAssetTree_base {
180
177
  protected _attributeValueFilter: OrMwcInput;
181
178
  protected _assetTypeFilter: string;
182
179
  protected _uniqueAssetTypes: string[];
180
+ protected _hasMoreParents: boolean;
181
+ protected _incompleteParentIds: string[];
183
182
  private _dragDropParentId;
184
183
  protected _expandTimer?: number;
185
184
  private _latestSelected;
@@ -208,7 +207,7 @@ export declare class OrAssetTree extends OrAssetTree_base {
208
207
  protected shouldUpdate(_changedProperties: PropertyValues): boolean;
209
208
  protected _updateSelectedNodes(): void;
210
209
  protected _updateSort(nodes: UiAssetTreeNode[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number): void;
211
- protected _toggleExpander(expander: HTMLElement, node: UiAssetTreeNode | null, silent?: boolean): void;
210
+ protected _toggleExpander(expander: HTMLElement, node: UiAssetTreeNode | null, silent?: boolean): Promise<void>;
212
211
  private _buildPaths;
213
212
  private _findNode;
214
213
  private _findNodeFromAssetId;
@@ -220,12 +219,17 @@ export declare class OrAssetTree extends OrAssetTree_base {
220
219
  protected _shouldEnableAttrType(value: string | undefined): void;
221
220
  protected applySettingFields(filter: OrAssetTreeFilter): OrAssetTreeFilter;
222
221
  protected _filterFromSettings(): void;
223
- protected _onFilterInputEvent(_e: KeyboardEvent): void;
224
- protected _onFilterInput(newValue: string | undefined, force: boolean): void;
222
+ protected _onFilterInput(newValue: string | undefined): void;
225
223
  protected _doFiltering(): Promise<void>;
226
- protected getMatcher(requireQuery: boolean): Promise<((asset: Asset) => boolean)>;
224
+ protected getMatcher(requireQuery: boolean): Promise<{
225
+ matcher: ((asset: Asset) => boolean);
226
+ assets?: Asset[];
227
+ }>;
227
228
  protected getSimpleNameMatcher(): Promise<((asset: Asset) => boolean)>;
228
- protected getMatcherFromQuery(): Promise<((asset: Asset) => boolean)>;
229
+ protected getMatcherFromQuery(): Promise<{
230
+ assets: Asset[];
231
+ matcher: ((asset: Asset) => boolean);
232
+ }>;
229
233
  protected isAnyFilter(): boolean;
230
234
  protected filterTreeNode(currentNode: UiAssetTreeNode, matcher: (asset: Asset) => boolean, parentMatching?: boolean): boolean;
231
235
  protected _onCopyClicked(): Promise<void>;
@@ -237,13 +241,31 @@ export declare class OrAssetTree extends OrAssetTree_base {
237
241
  protected _canAdd(): boolean;
238
242
  protected _getAllowedChildTypes(selectedNode: UiAssetTreeNode | undefined): AssetDescriptor[];
239
243
  protected _getSortFunction(): (a: UiAssetTreeNode, b: UiAssetTreeNode) => number;
240
- protected _loadAssets(): void;
244
+ protected _getOrderBy(sortBy?: string): AssetQueryOrderBy$Property;
245
+ /**
246
+ * Main function to load assets and populate the tree.
247
+ * Based on the HTML attributes of this component, it either fetches using a WebSocket connection or using a dataProvider.
248
+ * Once retrieved, these assets will be passed along to the {@link _buildTreeNodes} to construct the tree nodes.
249
+ * If the user has applied a filter, it will also be taken into count using {@link _doFiltering}.
250
+ *
251
+ * @param parentId - The parent ID an asset MUST be a child of during WebSocket retrieval. This is useful for pagination.
252
+ * @param offset - Offset number of the assets to request through WebSocket. This is useful for pagination.
253
+ * @param cache - An array of assets to populate the tree with alongside the retrieved nodes.
254
+ * @protected
255
+ */
256
+ protected _loadAssets(parentId?: string, offset?: number, cache?: Asset[]): Promise<AssetTreeEvent | undefined>;
241
257
  _addEventSubscriptions(): Promise<void>;
242
258
  onEventsConnect(): void;
243
259
  onEventsDisconnect(): void;
244
260
  getNodes(): UiAssetTreeNode[];
245
261
  _onEvent(event: SharedEvent): void;
246
- protected _buildTreeNodes(assets: Asset[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number): void;
262
+ /**
263
+ * Function that creates and constructs the tree node objects to display.
264
+ * @param assets - List of assets to display in the tree
265
+ * @param sortFunction - Optional sorting function for ordering the nodes
266
+ * @protected
267
+ */
268
+ protected _buildTreeNodes(assets: Asset[], sortFunction?: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number): void;
247
269
  protected _buildChildTreeNodes(treeNode: UiAssetTreeNode, assets: AssetWithReparentId[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number): void;
248
270
  _onDragStart(ev: any): void;
249
271
  _onDragEnd(ev: any): void;
@@ -252,6 +274,12 @@ export declare class OrAssetTree extends OrAssetTree_base {
252
274
  protected expandNode(assetId: string | null): void;
253
275
  _onDragEnter(ev: any): void;
254
276
  _onDragLeave(ev: any): void;
277
+ /**
278
+ * Generates the HTML TemplateResult for an individual node / tree item.
279
+ * @param treeNode Node to display
280
+ * @param level Level of depth in the tree from 0 to infinite. (0 = top level. If it has 2 parents, level = 2)
281
+ * @protected
282
+ */
255
283
  protected _treeNodeTemplate(treeNode: UiAssetTreeNode, level: number): TemplateResult | string | undefined;
256
284
  protected static _forEachNodeRecursive(nodes: UiAssetTreeNode[], fn: (node: UiAssetTreeNode) => void): void;
257
285
  }
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var OrAssetTree_1,FilterElementType,__decorate=this&&this.__decorate||function(e,t,s,i){var r,a=arguments.length,d=a<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)d=Reflect.decorate(e,t,s,i);else for(var n=e.length-1;n>=0;n--)(r=e[n])&&(d=(a<3?r(d):a>3?r(t,s,d):r(t,s))||d);return a>3&&d&&Object.defineProperty(t,s,d),d},__awaiter=this&&this.__awaiter||function(e,t,s,i){function r(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||(s=Promise))(function(s,a){function d(e){try{l(i.next(e))}catch(e){a(e)}}function n(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){e.done?s(e.value):r(e.value).then(d,n)}l((i=i.apply(e,t||[])).next())})};import{html,LitElement}from"lit";import{customElement,property,query,state}from"lit/decorators.js";import"@openremote/or-mwc-components/or-mwc-input";import{InputType}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-icon";import{AssetModelUtil}from"@openremote/model";import"@openremote/or-translate";import{style}from"./style";import manager,{subscribe,Util}from"@openremote/core";import Qs from"qs";import{getAssetDescriptorIconTemplate}from"@openremote/or-icon";import"@openremote/or-mwc-components/or-mwc-menu";import{getContentWithMenuTemplate}from"@openremote/or-mwc-components/or-mwc-menu";import"@openremote/or-mwc-components/or-mwc-list";import{i18next}from"@openremote/or-translate";import"@openremote/or-mwc-components/or-mwc-dialog";import{OrMwcDialog,showDialog,showErrorDialog,showOkCancelDialog}from"@openremote/or-mwc-components/or-mwc-dialog";import"./or-add-asset-dialog";import{showSnackbar}from"@openremote/or-mwc-components/or-mwc-snackbar";import{when}from"lit/directives/when.js";export class OrAssetTreeRequestSelectionEvent extends CustomEvent{constructor(e){super(OrAssetTreeRequestSelectionEvent.NAME,{bubbles:!0,composed:!0,detail:{allow:!0,detail:e}})}}OrAssetTreeRequestSelectionEvent.NAME="or-asset-tree-request-selection";export class OrAssetTreeSelectionEvent extends CustomEvent{constructor(e){super(OrAssetTreeSelectionEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeSelectionEvent.NAME="or-asset-tree-selection";export class OrAssetTreeChangeParentEvent extends CustomEvent{constructor(e,t){super(OrAssetTreeChangeParentEvent.NAME,{bubbles:!0,composed:!0,detail:{parentId:e,assetIds:t}})}}OrAssetTreeChangeParentEvent.NAME="or-asset-tree-change-parent";export class OrAssetTreeToggleExpandEvent extends CustomEvent{constructor(e){super(OrAssetTreeToggleExpandEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeToggleExpandEvent.NAME="or-asset-tree-expand",function(e){e[e.SEARCH_FILTER=0]="SEARCH_FILTER",e[e.ASSET_TYPE=1]="ASSET_TYPE",e[e.ATTRIBUTE_NAME=2]="ATTRIBUTE_NAME",e[e.ATTRIBUTE_VALUE=3]="ATTRIBUTE_VALUE"}(FilterElementType||(FilterElementType={}));export class OrAssetTreeRequestAddEvent extends CustomEvent{constructor(e){super(OrAssetTreeRequestAddEvent.NAME,{bubbles:!0,composed:!0,detail:{allow:!0,detail:e}})}}OrAssetTreeRequestAddEvent.NAME="or-asset-tree-request-add";export class OrAssetTreeAddEvent extends CustomEvent{constructor(e){super(OrAssetTreeAddEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeAddEvent.NAME="or-asset-tree-add";export class OrAssetTreeRequestDeleteEvent extends CustomEvent{constructor(e){super(OrAssetTreeRequestDeleteEvent.NAME,{bubbles:!0,composed:!0,detail:{allow:!0,detail:e}})}}OrAssetTreeRequestDeleteEvent.NAME="or-asset-tree-request-delete";export class OrAssetTreeAssetEvent extends CustomEvent{constructor(e){super(OrAssetTreeAssetEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeAssetEvent.NAME="or-asset-tree-asset-event";export class OrAssetTreeFilter{constructor(e){this.asset=e,this.assetType=[],this.attribute=[],this.attributeValue=[]}}export const getAssetTypes=()=>__awaiter(void 0,void 0,void 0,function*(){let e=yield manager.rest.api.AssetResource.queryAssets({select:{attributes:[]},recursive:!0});if(e&&e.data)return e.data.map(e=>e.type)});let OrAssetTree=OrAssetTree_1=class OrAssetTree extends subscribe(manager)(LitElement){constructor(){super(...arguments),this.readonly=!1,this.disabled=!1,this.disableSubscribe=!1,this.showDeselectBtn=!0,this.showSortBtn=!0,this.showFilter=!0,this.sortBy="name",this.expandAllNodes=!1,this.expandedIds=[],this.checkboxes=!1,this._loading=!1,this._connected=!1,this._selectedNodes=[],this._expandedNodes=[],this._filter=new OrAssetTreeFilter,this._searchInputTimer=void 0,this._filterSettingOpen=!1,this._assetTypes=[],this._uniqueAssetTypes=[],this._dragDropParentId=null,this._expandTimer=void 0,this._latestSelected=void 0,this.assetsChildren={}}static get styles(){return[style]}get selectedNodes(){return this._selectedNodes?[...this._selectedNodes]:[]}set selectedNodes(e){this.selectedIds=e.map(e=>e.asset.id)}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this.requestUpdate()}refresh(){this._nodes=void 0}isAncestorSelected(e){if(!this.selectedIds||!e.parent)return!1;for(;e.parent;)if(e=e.parent,this.selectedIds.includes(e.asset.id))return!0;return!1}applyFilter(e,t=!1){if(e&&"string"!=typeof e||(e=this.parseFromInputFilter(e)),Util.objectsEqual(this._filter,e))return void console.debug("Tried to apply filter to the asset tree, but it was the same.",e);console.debug("Applying filter to the asset tree:",e),this._filter=e,t&&this.updateComplete.finally(()=>this._filterInput.value=this.formatFilter(e))}mapDescriptors(e,t){let s=e.map(e=>({styleMap:{"--or-icon-fill":e.colour?"#"+e.colour:"unset"},icon:e.icon,text:Util.getAssetTypeLabel(e),value:e.name,data:e})).sort(Util.sortByString(e=>e.text));return t&&s.splice(0,0,t),s}getSelectHeader(){return html`<or-mwc-input style="width:100%;" ?disabled="${this._loading}" type="${InputType.TEXT}" .label="${i18next.t("filter.assetTypeLabel")}" iconTrailing="menu-down" iconColor="rgba(0, 0, 0, 0.87)" icon="selection-ellipse" value="${i18next.t("filter.assetTypeNone")}"></or-mwc-input>`}getSelectedHeader(e){return html`<or-mwc-input style="width:100%;" ?disabled="${this._loading}" type="${InputType.TEXT}" .label="${i18next.t("filter.assetTypeLabel")}" .iconColor="${e.colour}" iconTrailing="menu-down" icon="${e.icon}" value="${Util.getAssetTypeLabel(e)}"></or-mwc-input>`}assetTypeSelect(){if(!this._assetTypeFilter)return this.getSelectHeader();{let e=this._assetTypes.find(e=>e.name===this._assetTypeFilter);return e?this.getSelectedHeader(e):this.getSelectHeader()}}atLeastOneNodeToBeShown(){var e;let t=!1;return null==(e=this._nodes)||e.forEach(e=>{e.hidden||(t=!0)}),t}render(){let e=this._canAdd();return html`
1
+ var OrAssetTree_1,FilterElementType,__decorate=this&&this.__decorate||function(e,t,s,i){var r,l=arguments.length,a=l<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,s,i);else for(var n=e.length-1;n>=0;n--)(r=e[n])&&(a=(l<3?r(a):l>3?r(t,s,a):r(t,s))||a);return l>3&&a&&Object.defineProperty(t,s,a),a},__awaiter=this&&this.__awaiter||function(e,t,s,i){function r(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||(s=Promise))(function(s,l){function a(e){try{d(i.next(e))}catch(e){l(e)}}function n(e){try{d(i.throw(e))}catch(e){l(e)}}function d(e){e.done?s(e.value):r(e.value).then(a,n)}d((i=i.apply(e,t||[])).next())})};import{html,LitElement}from"lit";import{customElement,property,query,state}from"lit/decorators.js";import"@openremote/or-mwc-components/or-mwc-input";import{InputType}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-icon";import{AssetModelUtil}from"@openremote/model";import"@openremote/or-translate";import{style}from"./style";import manager,{subscribe,Util}from"@openremote/core";import Qs from"qs";import{getAssetDescriptorIconTemplate}from"@openremote/or-icon";import"@openremote/or-mwc-components/or-mwc-menu";import{getContentWithMenuTemplate}from"@openremote/or-mwc-components/or-mwc-menu";import"@openremote/or-mwc-components/or-mwc-list";import{i18next}from"@openremote/or-translate";import"@openremote/or-mwc-components/or-mwc-dialog";import{OrMwcDialog,showDialog,showErrorDialog,showOkCancelDialog}from"@openremote/or-mwc-components/or-mwc-dialog";import"./or-add-asset-dialog";import{showSnackbar}from"@openremote/or-mwc-components/or-mwc-snackbar";import{when}from"lit/directives/when.js";import{debounce}from"lodash";export class OrAssetTreeRequestSelectionEvent extends CustomEvent{constructor(e){super(OrAssetTreeRequestSelectionEvent.NAME,{bubbles:!0,composed:!0,detail:{allow:!0,detail:e}})}}OrAssetTreeRequestSelectionEvent.NAME="or-asset-tree-request-selection";export class OrAssetTreeSelectionEvent extends CustomEvent{constructor(e){super(OrAssetTreeSelectionEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeSelectionEvent.NAME="or-asset-tree-selection";export class OrAssetTreeChangeParentEvent extends CustomEvent{constructor(e,t){super(OrAssetTreeChangeParentEvent.NAME,{bubbles:!0,composed:!0,detail:{parentId:e,assetIds:t}})}}OrAssetTreeChangeParentEvent.NAME="or-asset-tree-change-parent";export class OrAssetTreeToggleExpandEvent extends CustomEvent{constructor(e){super(OrAssetTreeToggleExpandEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeToggleExpandEvent.NAME="or-asset-tree-expand",function(e){e[e.SEARCH_FILTER=0]="SEARCH_FILTER",e[e.ASSET_TYPE=1]="ASSET_TYPE",e[e.ATTRIBUTE_NAME=2]="ATTRIBUTE_NAME",e[e.ATTRIBUTE_VALUE=3]="ATTRIBUTE_VALUE"}(FilterElementType||(FilterElementType={}));export class OrAssetTreeRequestAddEvent extends CustomEvent{constructor(e){super(OrAssetTreeRequestAddEvent.NAME,{bubbles:!0,composed:!0,detail:{allow:!0,detail:e}})}}OrAssetTreeRequestAddEvent.NAME="or-asset-tree-request-add";export class OrAssetTreeAddEvent extends CustomEvent{constructor(e){super(OrAssetTreeAddEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeAddEvent.NAME="or-asset-tree-add";export class OrAssetTreeRequestDeleteEvent extends CustomEvent{constructor(e){super(OrAssetTreeRequestDeleteEvent.NAME,{bubbles:!0,composed:!0,detail:{allow:!0,detail:e}})}}OrAssetTreeRequestDeleteEvent.NAME="or-asset-tree-request-delete";export class OrAssetTreeAssetEvent extends CustomEvent{constructor(e){super(OrAssetTreeAssetEvent.NAME,{bubbles:!0,composed:!0,detail:e})}}OrAssetTreeAssetEvent.NAME="or-asset-tree-asset-event";export class OrAssetTreeFilter{constructor(e){this.asset=e,this.assetType=[],this.attribute=[],this.attributeValue=[]}}let OrAssetTree=OrAssetTree_1=class OrAssetTree extends subscribe(manager)(LitElement){constructor(){super(...arguments),this.readonly=!1,this.disabled=!1,this.disableSubscribe=!1,this.showDeselectBtn=!0,this.showSortBtn=!0,this.showFilter=!0,this.sortBy="name",this.expandAllNodes=!1,this.expandedIds=[],this.checkboxes=!1,this.queryLimit=100,this._loading=!1,this._connected=!1,this._selectedNodes=[],this._expandedNodes=[],this._filter=new OrAssetTreeFilter,this._filterSettingOpen=!1,this._assetTypes=[],this._uniqueAssetTypes=[],this._hasMoreParents=!1,this._incompleteParentIds=[],this._dragDropParentId=null,this._expandTimer=void 0,this._latestSelected=void 0,this.assetsChildren={}}static get styles(){return[style]}get selectedNodes(){return this._selectedNodes?[...this._selectedNodes]:[]}set selectedNodes(e){this.selectedIds=e.map(e=>e.asset.id)}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this.requestUpdate()}refresh(){this._nodes=void 0}isAncestorSelected(e){if(!this.selectedIds||!e.parent)return!1;for(;e.parent;)if(e=e.parent,this.selectedIds.includes(e.asset.id))return!0;return!1}applyFilter(e,t=!1){if(e&&"string"!=typeof e||(e=this.parseFromInputFilter(e)),Util.objectsEqual(this._filter,e))return void console.debug("Tried to apply filter to the asset tree, but it was the same.",e);console.debug("Applying filter to the asset tree:",e),this._filter=e,t&&this.updateComplete.finally(()=>this._filterInput.value=this.formatFilter(e))}mapDescriptors(e,t){let s=e.map(e=>({styleMap:{"--or-icon-fill":e.colour?"#"+e.colour:"unset"},icon:e.icon,text:Util.getAssetTypeLabel(e),value:e.name,data:e})).sort(Util.sortByString(e=>e.text));return t&&s.splice(0,0,t),s}getSelectHeader(){return html`<or-mwc-input style="width:100%;" ?disabled="${this._loading}" type="${InputType.TEXT}" .label="${i18next.t("filter.assetTypeLabel")}" iconTrailing="menu-down" iconColor="rgba(0, 0, 0, 0.87)" icon="selection-ellipse" value="${i18next.t("filter.assetTypeNone")}"></or-mwc-input>`}getSelectedHeader(e){return html`<or-mwc-input style="width:100%;" ?disabled="${this._loading}" type="${InputType.TEXT}" .label="${i18next.t("filter.assetTypeLabel")}" .iconColor="${e.colour}" iconTrailing="menu-down" icon="${e.icon}" value="${Util.getAssetTypeLabel(e)}"></or-mwc-input>`}assetTypeSelect(){if(!this._assetTypeFilter)return this.getSelectHeader();{let e=this._assetTypes.find(e=>e.name===this._assetTypeFilter);return e?this.getSelectedHeader(e):this.getSelectHeader()}}atLeastOneNodeToBeShown(){var e;let t=!1;return null==(e=this._nodes)||e.forEach(e=>{e.hidden||(t=!0)}),t}render(){let e=this._canAdd();return html`
2
2
  <div id="header">
3
3
  <div id="title-container">
4
4
  <or-translate id="title" value="asset_plural"></or-translate>
@@ -23,8 +23,7 @@ var OrAssetTree_1,FilterElementType,__decorate=this&&this.__decorate||function(e
23
23
  placeholder="${i18next.t("filter.filter")}..."
24
24
  compact="true"
25
25
  outlined="true"
26
- @input="${e=>{this._onFilterInputEvent(e)}}"
27
- @or-mwc-input-changed="${e=>{this._onFilterInput(e.detail.value||void 0,!0)}}">
26
+ @input="${debounce(()=>{this._onFilterInput(this._filterInput.nativeValue)},200)}">
28
27
  </or-mwc-input>
29
28
  <or-icon id="filterSettingsIcon" icon="${this._filterSettingOpen?"window-close":"tune"}" title="${i18next.t(this._filterSettingOpen?"filter.close":"filter.open")}" @click="${()=>{if(this._filterSettingOpen)this._filterSettingOpen=!1;else{if(this._filterSettingOpen=!0,0===this._assetTypes.length){let e=this._getAllowedChildTypes(this._selectedNodes[0]);this._assetTypes=e.filter(e=>"asset"===e.descriptorType)}this._filter.attribute.length>0&&(this._attributeNameFilter.value=this._filter.attribute[0]),this._filter.attributeValue.length>0&&this._filter.attribute.length>0&&(this._attributeValueFilter.disabled=!1,this._attributeValueFilter.value=this._filter.attributeValue[0]),this._filter.assetType.length>0?this._assetTypeFilter=this._filter.assetType[0]:this._assetTypeFilter=""}}}"></or-icon>
30
29
  </div>
@@ -50,42 +49,51 @@ var OrAssetTree_1,FilterElementType,__decorate=this&&this.__decorate||function(e
50
49
  </div>
51
50
  </div>
52
51
  `)}
53
-
54
- ${!this._nodes?html`
55
- <span id="loading"><or-translate value="loading"></or-translate></span>`:0===this._nodes.length||!this.atLeastOneNodeToBeShown()?html`<span id="noAssetsFound"><or-translate value="noAssetsFound"></or-translate></span>`:html`
56
- <div id="list-container">
57
- <ol id="list">
58
- ${this._nodes.map(e=>this._treeNodeTemplate(e,0)).filter(e=>!!e)}
59
- <li class="asset-list-element">
60
- <div class="end-element" node-asset-id="${""}" @dragleave=${e=>{this._onDragLeave(e)}} @dragenter="${e=>this._onDragEnter(e)}" @dragend="${e=>this._onDragEnd(e)}" @dragover="${e=>this._onDragOver(e)}"></div>
61
- </li>
62
- </ol>
63
- </div>
64
- `}
52
+
53
+ ${when(!this._nodes,()=>html`
54
+ <span id="loading"><or-translate value="loading"></or-translate></span>
55
+ `,()=>html`
56
+ ${when(0===this._nodes.length||!this.atLeastOneNodeToBeShown(),()=>html`<span id="noAssetsFound"><or-translate value="noAssetsFound"></or-translate></span>`,()=>{var e;return html`
57
+ <div id="list-container">
58
+ <ol id="list">
59
+ ${null==(e=this._nodes)?void 0:e.filter(e=>e&&!e.hidden).map(e=>this._treeNodeTemplate(e,0))}
60
+ ${when(this._hasMoreParents,()=>html`
61
+ <li class="asset-list-element">
62
+ <div class="end-element loadmore-element" node-asset-id="${""}" @dragleave=${e=>{this._onDragLeave(e)}}
63
+ @dragenter="${e=>this._onDragEnter(e)}" @dragend="${e=>this._onDragEnd(e)}"
64
+ @dragover="${e=>this._onDragOver(e)}">
65
+ <or-mwc-input type=${InputType.BUTTON} label="loadMore" outlined compact @or-mwc-input-changed=${()=>{var e,t,s;let i=[];OrAssetTree_1._forEachNodeRecursive(null!=(e=this._nodes)?e:[],e=>e.asset&&i.push(e.asset)),this._loadAssets(void 0,null!=(s=null==(t=this._nodes)?void 0:t.length)?s:0,i)}}></or-mwc-input>
66
+ </div>
67
+ </li>
68
+ `)}
69
+ </ol>
70
+ </div>
71
+ `})}
72
+ `)}
65
73
 
66
74
  <div id="footer">
67
75
 
68
76
  </div>
69
- `}_isReadonly(){return this.readonly||!manager.authenticated||!manager.hasRole("write:assets")}shouldUpdate(e){var t;let s=super.shouldUpdate(e);if((e.has("assets")||e.has("rootAssets")||e.has("rootAssetIds"))&&(this._nodes=void 0),!this._nodes)return this._loadAssets(),!0;if(e.has("selectedIds")){let s=e.get("selectedIds");!Util.objectsEqual(s,this.selectedIds)&&(this._updateSelectedNodes(),(null==s?void 0:s.length)===1&&this._filter.asset===s[0]&&(this.applyFilter(new OrAssetTreeFilter,!0),(null==(t=this.selectedIds)?void 0:t.length)||this._doFiltering()))}return e.has("sortBy")&&this._updateSort(this._nodes,this._getSortFunction()),e.has("disabledSubscribe")&&this.disableSubscribe&&this._removeEventSubscriptions(),s}_updateSelectedNodes(){let e=[],t=[];OrAssetTree_1._forEachNodeRecursive(this._nodes,s=>{if(this.selectedIds&&this.selectedIds.indexOf(s.asset.id)>=0){e.push(s.asset.id),t.push(s),s.selected=!0;let i=s.parent;for(;i;)i.expanded=!0,i=i.parent}else s.selected=!1;if(this.checkboxes){let t=s.parent;for(;t;){let s=[];OrAssetTree_1._forEachNodeRecursive(t.children,e=>{s.push(e)}),t.someChildrenSelected=!1,t.allChildrenSelected=!1,s.every(t=>e.includes(t.asset.id))?t.allChildrenSelected=!0:s.some(t=>e.includes(t.asset.id))&&(t.someChildrenSelected=!0),t=t.parent}}}),this.selectedIds=e;let s=this._selectedNodes;this._selectedNodes=t,this.dispatchEvent(new OrAssetTreeSelectionEvent({oldNodes:s,newNodes:t}))}_updateSort(e,t){e&&(e.sort(t),e.forEach(e=>this._updateSort(e.children,t)))}_toggleExpander(e,t,s=!1){t&&t.expandable&&(t.expanded=!t.expanded,t.expanded?this._expandedNodes.push(t):this._expandedNodes=this._expandedNodes.filter(e=>e!==t),e.parentElement.parentElement.parentElement.toggleAttribute("data-expanded"),s||this.dispatchEvent(new OrAssetTreeToggleExpandEvent({node:t})),this.requestUpdate())}_buildPaths(e){let t=[];return e.asset&&e.asset.id?(t.push(e.asset.id),e.children.length>0&&e.expanded&&e.children.forEach(e=>{t=t.concat(this._buildPaths(e))}),t):[]}_findNode(e,t){if(e.asset&&e.asset.id){if(e.asset.id===t)return e;if(e.children.length>0&&e.expanded){let s;return e.children.forEach(e=>{s||(s=this._findNode(e,t))}),s}return}}_findNodeFromAssetId(e){if(this._nodes){let t;return this._nodes.forEach(s=>{t||(t=this._findNode(s,e))}),t}}_onNodeClicked(e,t){var s,i,r,a;if(e&&e.defaultPrevented)return;e&&e.preventDefault();let d=e&&e.target.className.indexOf("expander")>=0,n=e&&(null==(i=null==(s=e.target)?void 0:s.icon)?void 0:i.includes("checkbox-multiple"));if(d)this._toggleExpander(e.target,t);else{let s=!0;if(t&&this.config&&(null==(r=this.config.select)?void 0:r.types)&&(s=this.config.select.types.indexOf(t.asset.type)>=0),!s&&!n)return;let i=[];if(t){let s=this.selectedNodes.indexOf(t),r=!0,d=!0,l=!this._isReadonly()&&(!this.config||!this.config.select||!this.config.select.multiSelect);if((this.checkboxes||l&&e&&(e.ctrlKey||e.shiftKey||e.metaKey))&&(d=!1,s>=0&&this.selectedIds&&this.selectedIds.length>1&&(r=!1)),n){i=[...this.selectedNodes];let e=[];OrAssetTree_1._forEachNodeRecursive(t.children,t=>{var s,i;let r=!0;t&&(null==(i=null==(s=this.config)?void 0:s.select)?void 0:i.types)&&(r=this.config.select.types.indexOf(t.asset.type)>=0),r&&e.push(t)}),i=t.allChildrenSelected?i.filter(t=>!e.map(e=>e.asset.id).includes(t.asset.id)):i.concat(e)}else if(d)this._latestSelected=Object.assign({},t),i=[t];else if(r){if(s<0){if(e&&e.shiftKey){let e=[];if(null==(a=this._nodes)||a.forEach(t=>{e=e.concat(this._buildPaths(t))}),this._latestSelected&&this._latestSelected.asset&&this._latestSelected.asset.id&&t.asset&&t.asset.id){let s=this._latestSelected.asset.id,r=t.asset.id,a=e.findIndex(e=>e.includes(s)),d=e.findIndex(e=>e.includes(r)),n=-1,l=-1;a>d?(n=d,l=a):(n=a,l=d);let o=e.slice(n,l+1),h=[];o.forEach(e=>{let t=this._findNodeFromAssetId(e);t&&h.push(t)}),i=(i=[...this.selectedNodes]).concat(h)}}else(i=[...this.selectedNodes]).push(t);this._latestSelected=Object.assign({},t)}}else s>=0&&(1===(i=[...this.selectedNodes]).length&&(this._latestSelected=void 0),i.splice(s,1))}Util.dispatchCancellableEvent(this,new OrAssetTreeRequestSelectionEvent({oldNodes:this.selectedNodes,newNodes:i})).then(e=>{e.allow&&(this.selectedNodes=e.detail.newNodes)})}}_onDeselectClicked(){this._onNodeClicked(null,null)}parseFromInputFilter(e){var t;void 0===e&&(e=null==(t=this._filterInput)?void 0:t.value);let s=new OrAssetTreeFilter;if(e){let t=e,i=e.match(/(attribute\:)(\"[^"]+\")\S*/g);i&&(i.length>0&&i.forEach((e,i)=>{t=t.replace(e,"");let r=e.toString().indexOf("attribute:"),a=e.toString().substring(r+10+1,e.toString().length-1);s.attribute.push(a),s.attributeValue.push("")}),this._attributeValueFilter.disabled=!1),(i=e.match(/(type\:)\S+/g))&&i.length>0&&i.forEach((e,i)=>{t=t.replace(e,"");let r=e.toString().indexOf("type:"),a=e.toString().substring(r+5);s.assetType.push(a)}),(i=e.match(/(\"[^\"]+\")\:(([^\"\s]+)|(\"[^\"]+\"))/g))&&i.length>0&&i.forEach((e,i)=>{t=t.replace(e,"");let r=e.toString().indexOf('":'),a=e.toString().substring(r+2),d=e.toString().substring(1,r);'"'===a[0]&&'"'===a[a.length-1]&&(a=a.substring(1,a.length-1)),s.attribute.push(d),s.attributeValue.push(a)}),s.asset=t&&t.length>0?t.trim():void 0}return s}formatFilter(e){let t=e.asset?e.asset:"",s=e.asset?" ":"",i=[];return e.assetType.length>0&&e.assetType.forEach(e=>{t+=s+"type:"+e,s=" "}),e.attribute.length>0&&e.attributeValue.length>0&&e.attributeValue.forEach((r,a)=>{i.push(e.attribute[a]),t+=s+'"'+e.attribute[a]+'":'+r,s=" "}),e.attribute.length>0&&0===e.attributeValue.length&&e.attribute.forEach(e=>{i.includes(e)||(t+=s+'attribute:"'+e+'"',s=" ")}),t}_shouldEnableAttrTypeEvent(e){let t;e.composedPath()&&(t=e.composedPath()[0].value||void 0),this._shouldEnableAttrType(t)}_shouldEnableAttrType(e){e?this._attributeValueFilter.disabled=!1:this._attributeValueFilter.disabled=!0}applySettingFields(e){if(this._assetTypeFilter?e.assetType=[this._assetTypeFilter]:e.assetType=[],this._attributeNameFilter.value?e.attribute=[this._attributeNameFilter.value]:e.attribute=[],this._attributeNameFilter.value&&this._attributeValueFilter.value){let t=this._attributeValueFilter.value;t.includes(" ")&&(t='"'+t+'"'),e.attributeValue=[t]}else e.attributeValue=[];return e}_filterFromSettings(){let e=this.parseFromInputFilter(),t=this.applySettingFields(e);this.applyFilter(t);let s=this.formatFilter(this._filter);this._filterInput.value=s,this._filterSettingOpen=!1,this._doFiltering()}_onFilterInputEvent(e){var t;this._onFilterInput(null==(t=this._filterInput)?void 0:t.nativeValue,!1)}_onFilterInput(e,t){this.applyFilter(e),this._searchInputTimer&&clearTimeout(this._searchInputTimer),t?this._doFiltering():this._searchInputTimer=window.setTimeout(()=>{this._doFiltering()},350)}_doFiltering(){return __awaiter(this,void 0,void 0,function*(){if(this._searchInputTimer&&(clearTimeout(this._searchInputTimer),this._searchInputTimer=void 0),this.isConnected&&this._nodes){if(!this._filter.asset&&!this._filter.attribute&&!this._filter.assetType&&!this._filter.attributeValue){OrAssetTree_1._forEachNodeRecursive(this._nodes,e=>{e.notMatchingFilter=!1,e.hidden=!1}),this.requestUpdate("_nodes");return}if(this.disabled=!0,this._filter.asset||this._filter.assetType||this._filter.attribute){let e=!1;this._filter.attribute&&(e=!0),this.getMatcher(e).then(e=>{this._nodes&&(this._nodes.forEach(t=>{this.filterTreeNode(t,e)}),this.disabled=!1)})}}})}getMatcher(e){return e?this.getMatcherFromQuery():this.getSimpleNameMatcher()}getSimpleNameMatcher(){return __awaiter(this,void 0,void 0,function*(){return e=>{let t=!0;return this._filter.asset&&(t=t&&e.name.toLowerCase().includes(this._filter.asset.toLowerCase())),this._filter.assetType.length>0&&(t=t&&e.type.toLowerCase()===this._filter.assetType[0].toLowerCase()),t}})}getMatcherFromQuery(){return __awaiter(this,void 0,void 0,function*(){let assetCond,attributeCond,assetTypeCond,foundAssets,foundAssetIds,assetQueries=[];this._filter.asset&&(assetCond=[{predicateType:"string",match:"CONTAINS",value:this._filter.asset,caseSensitive:!1}]),this._filter.assetType.length>0&&(assetTypeCond=this._filter.assetType),this._filter.attribute.length>0&&(attributeCond={operator:"AND",items:this._filter.attribute.map(e=>({name:{predicateType:"string",match:"EXACT",value:Util.sentenceCaseToCamelCase(e),caseSensitive:!1}}))}),assetQueries.push({select:{attributes:attributeCond?void 0:[]},names:assetCond,types:assetTypeCond,attributes:attributeCond}),this._filter.asset&&22===this._filter.asset.length&&assetQueries.push({select:{attributes:attributeCond?void 0:[]},types:assetTypeCond,attributes:attributeCond,ids:[this._filter.asset],limit:1});try{let promises=assetQueries.map(e=>manager.rest.api.AssetResource.queryAssets(e));foundAssetIds=(foundAssets=(yield Promise.all(promises)).flatMap(e=>e.data)).map(e=>e.id)}catch(e){console.error("Error querying Asset Tree assets with filter:",e),this._filter.assetType.forEach(e=>{-1===this._assetTypes.findIndex(t=>t.name===e)&&showSnackbar(void 0,"filter.assetTypeDoesNotExist","dismiss")}),foundAssetIds=[]}return asset=>{let attrValueCheck=!0;if(this._filter.attribute.length>0&&this._filter.attributeValue.length>0&&foundAssetIds.includes(asset.id)){let attributeVal=[];this._filter.attributeValue.forEach((e,t)=>{e.length>0&&attributeVal.push([this._filter.attribute[t],e])});let matchingAsset=foundAssets.find(e=>e.id===asset.id);if(matchingAsset&&matchingAsset.attributes)for(let attributeValIndex=0;attributeValIndex<attributeVal.length;attributeValIndex++){let currentAttributeVal=attributeVal[attributeValIndex],atLeastOneAttributeMatchValue=!1;Object.keys(matchingAsset.attributes).forEach(key=>{var _a,_b,_c;let attr=matchingAsset.attributes[key];if(attr.name.toLowerCase()===currentAttributeVal[0].toLowerCase())switch(attr.type){case"number":case"integer":case"long":case"bigInteger":case"bigNumber":case"positiveInteger":case"negativeInteger":case"positiveNumber":case"negativeNumber":{let normalizedValue=null==(_a=currentAttributeVal[1])?void 0:_a.replace(",",".");if(isNaN(Number(normalizedValue))){if(/\d/.test(normalizedValue)){normalizedValue.endsWith("%")&&(normalizedValue=null==normalizedValue?void 0:normalizedValue.replace("%","")),/^[0-9]/.test(normalizedValue)&&(normalizedValue="=="+normalizedValue);let func=attr.value+normalizedValue.replace(/[a-z]/gi,"");try{let resultNumberEval=eval(func);resultNumberEval&&(atLeastOneAttributeMatchValue=!0)}catch(_ignored){console.warn("Could not process filter on attribute number value;",func)}}}else(null!=(_b=attr.value)?_b:0)===Number(normalizedValue)&&(atLeastOneAttributeMatchValue=!0);break}case"boolean":{let value=currentAttributeVal[1];("false"===value||"true"===value)&&value===(null!=(_c=attr.value)&&_c).toString()&&(atLeastOneAttributeMatchValue=!0);break}case"text":if(attr.value){let unparsedValue=currentAttributeVal[1],multicharString="*",parsedValue=unparsedValue.replace(multicharString,".*");parsedValue=parsedValue.replace(/"/g,""),-1!=attr.value.toLowerCase().indexOf(parsedValue.toLowerCase())&&(atLeastOneAttributeMatchValue=!0)}}}),attrValueCheck=atLeastOneAttributeMatchValue}}return foundAssetIds.includes(asset.id)&&attrValueCheck}})}isAnyFilter(){return void 0!==this._filter.asset||this._filter.assetType.length>0||this._filter.attribute.length>0}filterTreeNode(e,t,s=!1){let i=t(e.asset);e.notMatchingFilter=!i;let r=e.children.map(e=>this.filterTreeNode(e,t,i)).some(e=>e);return i=i||r,e.expanded=r&&e.children.length>0&&this.isAnyFilter(),e.hidden=!i&&!s,i}_onCopyClicked(){return __awaiter(this,void 0,void 0,function*(){if(1===this._selectedNodes.length)try{let e=yield manager.rest.api.AssetResource.get(this._selectedNodes[0].asset.id);if(!e.data)throw Error("API returned an invalid response when retrieving the source asset");let t=JSON.parse(JSON.stringify(e.data));t.name+=" copy",delete t.id,delete t.path,delete t.createdOn,delete t.version,Util.dispatchCancellableEvent(this,new OrAssetTreeRequestAddEvent({sourceAsset:this._selectedNodes[0].asset,asset:t})).then(e=>{e.allow&&this.dispatchEvent(new OrAssetTreeAddEvent(e.detail))})}catch(e){console.error("Failed to copy asset",e),showErrorDialog("Failed to copy asset")}})}_onAddClicked(){let e,t=this._getAllowedChildTypes(this._selectedNodes[0]),s=t.filter(e=>"agent"===e.descriptorType),i=t.filter(e=>"asset"===e.descriptorType),r=this._selectedNodes&&1===this._selectedNodes.length?this._selectedNodes[0].asset:void 0,a=t=>{let s=!!t.detail.name&&t.detail.name.trim().length>0&&t.detail.name.trim().length<1024;e.shadowRoot.getElementById("add-btn").disabled=!t.detail.descriptor||!s};e=showDialog(new OrMwcDialog().setHeading(i18next.t("addAsset")).setContent(html`
70
- <or-add-asset-dialog id="add-panel" .config="${this.config}" .agentTypes="${s}" .assetTypes="${i}" .parent="${r}" @or-add-asset-changed="${a}"></or-add-asset-dialog>
71
- `).setActions([{actionName:"cancel",content:"cancel"},{actionName:"add",content:html`<or-mwc-input id="add-btn" class="button" .type="${InputType.BUTTON}" label="add" disabled></or-mwc-input>`,action:()=>{let t=e.shadowRoot.getElementById("add-panel"),s=t.selectedType,i=t.selectedAttributes,r=t.name.trim(),a=t.parent;if(!s)return;let d={name:r,type:s.name,realm:manager.displayRealm},n=AssetModelUtil.getAssetTypeInfo(s.name);if(!n)return;n.attributeDescriptors&&(d.attributes={},n.attributeDescriptors.filter(e=>!e.optional).forEach(e=>{d.attributes[e.name]={name:e.name,type:e.type,meta:e.meta?Object.assign({},e.meta):void 0}})),i&&(null==i||i.forEach(e=>{d.attributes[e.name]={name:e.name,type:e.type,meta:e.meta?Object.assign({},e.meta):void 0}})),this.selectedIds&&(d.parentId=a?a.id:void 0);let l={asset:d};Util.dispatchCancellableEvent(this,new OrAssetTreeRequestAddEvent(l)).then(e=>{e.allow&&this.dispatchEvent(new OrAssetTreeAddEvent(e.detail))})}}]).setStyles(html`
77
+ `}_isReadonly(){return this.readonly||!manager.authenticated||!manager.hasRole("write:assets")}shouldUpdate(e){var t;let s=super.shouldUpdate(e);if((e.has("assets")||e.has("rootAssets")||e.has("rootAssetIds")||e.has("queryLimit"))&&this.refresh(),!this._nodes)return this._loadAssets().catch(console.warn),!0;if(e.has("selectedIds")&&void 0!==this.selectedIds){let s=e.get("selectedIds");!Util.objectsEqual(s,this.selectedIds)&&(this._updateSelectedNodes(),(null==s?void 0:s.length)===1&&this._filter.asset===s[0]&&(this.applyFilter(new OrAssetTreeFilter,!0),(null==(t=this.selectedIds)?void 0:t.length)||this._doFiltering()))}return e.has("sortBy")&&this._updateSort(this._nodes,this._getSortFunction()),e.has("disabledSubscribe")&&this.disableSubscribe&&this._removeEventSubscriptions(),s}_updateSelectedNodes(){let e,t;if(OrAssetTree_1._forEachNodeRecursive(this._nodes,s=>{if(this.selectedIds&&this.selectedIds.indexOf(s.asset.id)>=0){null!=e||(e=[]),e.push(s.asset.id),null!=t||(t=[]),t.push(s),s.selected=!0;let i=s.parent;for(;i;)i.expanded=!0,i=i.parent}else s.selected=!1;if(this.checkboxes){let t=s.parent;for(;t;){let s=[];OrAssetTree_1._forEachNodeRecursive(t.children,e=>{s.push(e)}),t.someChildrenSelected=!1,t.allChildrenSelected=!1,s.every(t=>null==e?void 0:e.includes(t.asset.id))?t.allChildrenSelected=!0:s.some(t=>null==e?void 0:e.includes(t.asset.id))&&(t.someChildrenSelected=!0),t=t.parent}}}),(null==e?void 0:e.length)&&(this.selectedIds=e),void 0!==t||void 0!==this.selectedNodes){let e=this._selectedNodes;this._selectedNodes=null!=t?t:[],this.dispatchEvent(new OrAssetTreeSelectionEvent({oldNodes:e,newNodes:null!=t?t:[]}))}}_updateSort(e,t){e&&(e.sort(t),e.forEach(e=>this._updateSort(e.children,t)))}_toggleExpander(e,t){return __awaiter(this,arguments,void 0,function*(e,t,s=!1){var i,r,l,a;if(t&&t.expandable){if(t.expanded=!t.expanded,t.expanded)if(this._expandedNodes.push(t),null==(i=t.children)?void 0:i.length)console.debug(`Reusing cache for loading children of asset ${null==(r=t.asset)?void 0:r.id}...`);else{let e=[];OrAssetTree_1._forEachNodeRecursive(null!=(l=this._nodes)?l:[],t=>t.asset&&e.push(t.asset)),yield this._loadAssets(null==(a=t.asset)?void 0:a.id,0,e).catch(e=>console.warn(e))}else this._expandedNodes=this._expandedNodes.filter(e=>e!==t);e.parentElement.parentElement.parentElement.toggleAttribute("data-expanded",t.expanded),s||this.dispatchEvent(new OrAssetTreeToggleExpandEvent({node:t})),this.requestUpdate()}})}_buildPaths(e){let t=[];return e.asset&&e.asset.id?(t.push(e.asset.id),e.children.length>0&&e.expanded&&e.children.forEach(e=>{t=t.concat(this._buildPaths(e))}),t):[]}_findNode(e,t){if(e.asset&&e.asset.id){if(e.asset.id===t)return e;if(e.children.length>0&&e.expanded){let s;return e.children.forEach(e=>{s||(s=this._findNode(e,t))}),s}return}}_findNodeFromAssetId(e){if(this._nodes){let t;return this._nodes.forEach(s=>{t||(t=this._findNode(s,e))}),t}}_onNodeClicked(e,t){var s,i,r,l,a,n,d,o,h,c;if(e&&e.defaultPrevented)return;e&&e.preventDefault();let p=e&&e.target.className.indexOf("expander")>=0,u=e&&(null==(i=null==(s=e.target)?void 0:s.icon)?void 0:i.includes("checkbox-multiple")),_=e&&(null==(l=null==(r=e.target)?void 0:r.parentElement)?void 0:l.classList.contains("loadmore-element"));if(p)this._toggleExpander(e.target,t);else if(_){if(t){let e=[];OrAssetTree_1._forEachNodeRecursive(null!=(a=this._nodes)?a:[],t=>t.asset&&e.push(t.asset)),this._loadAssets(null==(n=t.asset)?void 0:n.id,null!=(o=null==(d=t.children)?void 0:d.length)?o:0,e)}}else{let s=!0;if(t&&this.config&&(null==(h=this.config.select)?void 0:h.types)&&(s=this.config.select.types.indexOf(t.asset.type)>=0),!s&&!u)return;let i=[];if(t){let s=this.selectedNodes.indexOf(t),r=!0,l=!0,a=!this._isReadonly()&&(!this.config||!this.config.select||!this.config.select.multiSelect);if((this.checkboxes||a&&e&&(e.ctrlKey||e.shiftKey||e.metaKey))&&(l=!1,s>=0&&this.selectedIds&&this.selectedIds.length>1&&(r=!1)),u){i=[...this.selectedNodes];let e=[];OrAssetTree_1._forEachNodeRecursive(t.children,t=>{var s,i;let r=!0;t&&(null==(i=null==(s=this.config)?void 0:s.select)?void 0:i.types)&&(r=this.config.select.types.indexOf(t.asset.type)>=0),r&&e.push(t)}),i=t.allChildrenSelected?i.filter(t=>!e.map(e=>e.asset.id).includes(t.asset.id)):i.concat(e)}else if(l)this._latestSelected=Object.assign({},t),i=[t];else if(r){if(s<0){if(e&&e.shiftKey){let e=[];if(null==(c=this._nodes)||c.forEach(t=>{e=e.concat(this._buildPaths(t))}),this._latestSelected&&this._latestSelected.asset&&this._latestSelected.asset.id&&t.asset&&t.asset.id){let s=this._latestSelected.asset.id,r=t.asset.id,l=e.findIndex(e=>e.includes(s)),a=e.findIndex(e=>e.includes(r)),n=-1,d=-1;l>a?(n=a,d=l):(n=l,d=a);let o=e.slice(n,d+1),h=[];o.forEach(e=>{let t=this._findNodeFromAssetId(e);t&&h.push(t)}),i=(i=[...this.selectedNodes]).concat(h)}}else(i=[...this.selectedNodes]).push(t);this._latestSelected=Object.assign({},t)}}else s>=0&&(1===(i=[...this.selectedNodes]).length&&(this._latestSelected=void 0),i.splice(s,1))}Util.dispatchCancellableEvent(this,new OrAssetTreeRequestSelectionEvent({oldNodes:this.selectedNodes,newNodes:i})).then(e=>{e.allow&&(this.selectedNodes=e.detail.newNodes)})}}_onDeselectClicked(){this._onNodeClicked(null,null)}parseFromInputFilter(e){var t;void 0===e&&(e=null==(t=this._filterInput)?void 0:t.value);let s=new OrAssetTreeFilter;if(e){let t=e,i=e.match(/(attribute\:)(\"[^"]+\")\S*/g);i&&(i.length>0&&i.forEach((e,i)=>{t=t.replace(e,"");let r=e.toString().indexOf("attribute:"),l=e.toString().substring(r+10+1,e.toString().length-1);s.attribute.push(l),s.attributeValue.push("")}),this._attributeValueFilter.disabled=!1),(i=e.match(/(type\:)\S+/g))&&i.length>0&&i.forEach((e,i)=>{t=t.replace(e,"");let r=e.toString().indexOf("type:"),l=e.toString().substring(r+5);s.assetType.push(l)}),(i=e.match(/(\"[^\"]+\")\:(([^\"\s]+)|(\"[^\"]+\"))/g))&&i.length>0&&i.forEach((e,i)=>{t=t.replace(e,"");let r=e.toString().indexOf('":'),l=e.toString().substring(r+2),a=e.toString().substring(1,r);'"'===l[0]&&'"'===l[l.length-1]&&(l=l.substring(1,l.length-1)),s.attribute.push(a),s.attributeValue.push(l)}),s.asset=t&&t.length>0?t.trim():void 0}return s}formatFilter(e){let t=e.asset?e.asset:"",s=e.asset?" ":"",i=[];return e.assetType.length>0&&e.assetType.forEach(e=>{t+=s+"type:"+e,s=" "}),e.attribute.length>0&&e.attributeValue.length>0&&e.attributeValue.forEach((r,l)=>{i.push(e.attribute[l]),t+=s+'"'+e.attribute[l]+'":'+r,s=" "}),e.attribute.length>0&&0===e.attributeValue.length&&e.attribute.forEach(e=>{i.includes(e)||(t+=s+'attribute:"'+e+'"',s=" ")}),t}_shouldEnableAttrTypeEvent(e){let t;e.composedPath()&&(t=e.composedPath()[0].value||void 0),this._shouldEnableAttrType(t)}_shouldEnableAttrType(e){e?this._attributeValueFilter.disabled=!1:this._attributeValueFilter.disabled=!0}applySettingFields(e){if(this._assetTypeFilter?e.assetType=[this._assetTypeFilter]:e.assetType=[],this._attributeNameFilter.value?e.attribute=[this._attributeNameFilter.value]:e.attribute=[],this._attributeNameFilter.value&&this._attributeValueFilter.value){let t=this._attributeValueFilter.value;t.includes(" ")&&(t='"'+t+'"'),e.attributeValue=[t]}else e.attributeValue=[];return e}_filterFromSettings(){let e=this.parseFromInputFilter(),t=this.applySettingFields(e);this.applyFilter(t);let s=this.formatFilter(this._filter);this._filterInput.value=s,this._filterSettingOpen=!1,this._doFiltering()}_onFilterInput(e){this.applyFilter(e),this._doFiltering()}_doFiltering(){return __awaiter(this,void 0,void 0,function*(){var e,t,s,i;if(this.isConnected&&this._nodes){if(!(null==(e=this._filter.asset)?void 0:e.length)&&!(null==(t=this._filter.attribute)?void 0:t.length)&&!(null==(s=this._filter.assetType)?void 0:s.length)&&!(null==(i=this._filter.attributeValue)?void 0:i.length)){console.debug("Clearing asset tree filter..."),OrAssetTree_1._forEachNodeRecursive(this._nodes,e=>{e.notMatchingFilter=!1,e.hidden=!1}),this.refresh();return}if(console.debug("Filtering asset tree using filter:",this._filter),this.disabled=!0,this._filter.asset||this._filter.assetType||this._filter.attribute){let e=!1;this._filter.attribute&&(e=!0),this.getMatcher(e).then(({matcher:e,assets:t})=>{var s,i;if(null!=t||(t=[]),this._nodes){let r=[];OrAssetTree_1._forEachNodeRecursive(null!=(s=this._nodes)?s:[],e=>e.asset&&r.push(e.asset));let l=new Map([...r,...t].map(e=>[e.id,e])).values();this._buildTreeNodes([...l]);let a=new Map;OrAssetTree_1._forEachNodeRecursive(null!=(i=this._nodes)?i:[],t=>{var s;let i=this.filterTreeNode(t,e);i&&!t.notMatchingFilter&&(null==(s=t.asset)?void 0:s.id)&&a.set(t.asset.id,i)}),1===a.size&&(console.debug("Only 1 asset is shown, automatically selecting it..."),this.selectedIds=Array.from(a.keys())),this.disabled=!1}})}}})}getMatcher(e){return __awaiter(this,void 0,void 0,function*(){return e?this.getMatcherFromQuery():{matcher:yield this.getSimpleNameMatcher()}})}getSimpleNameMatcher(){return __awaiter(this,void 0,void 0,function*(){return e=>{let t=!0;return this._filter.asset&&(t=t&&e.name.toLowerCase().includes(this._filter.asset.toLowerCase())),this._filter.assetType.length>0&&(t=t&&e.type.toLowerCase()===this._filter.assetType[0].toLowerCase()),t}})}getMatcherFromQuery(){return __awaiter(this,void 0,void 0,function*(){let assetCond,attributeCond,assetTypeCond,foundAssetIds,assetQueries=[];this._filter.asset&&(assetCond=[{predicateType:"string",match:"CONTAINS",value:this._filter.asset,caseSensitive:!1}]),this._filter.assetType.length>0&&(assetTypeCond=this._filter.assetType),this._filter.attribute.length>0&&(attributeCond={operator:"AND",items:this._filter.attribute.map(e=>({name:{predicateType:"string",match:"EXACT",value:Util.sentenceCaseToCamelCase(e),caseSensitive:!1}}))}),assetQueries.push({realm:{name:manager.displayRealm},select:{attributes:attributeCond?void 0:[]},orderBy:{property:this._getOrderBy(this.sortBy)},names:assetCond,types:assetTypeCond,attributes:attributeCond,limit:Math.max(this.queryLimit,1)}),this._filter.asset&&22===this._filter.asset.length&&assetQueries.push({realm:{name:manager.displayRealm},select:{attributes:attributeCond?void 0:[]},types:assetTypeCond,attributes:attributeCond,ids:[this._filter.asset],limit:1});let foundAssets=[];try{console.debug(`Querying assets using filter '${this._filterInput.nativeValue}'...`);let promises=assetQueries.map(e=>manager.rest.api.AssetResource.queryAssets(e));foundAssetIds=(foundAssets=(yield Promise.all(promises)).flatMap(e=>e.data)).map(e=>e.id),console.debug(`The filter query found ${foundAssets.length} assets!`)}catch(e){console.error("Error querying Asset Tree assets with filter:",e),this._filter.assetType.forEach(e=>{-1===this._assetTypes.findIndex(t=>t.name===e)&&showSnackbar(void 0,"filter.assetTypeDoesNotExist","dismiss")}),foundAssetIds=[]}let parentIds=new Set(foundAssets.filter(e=>e.path&&e.path.length>1).flatMap(e=>e.path.slice(0,-1))),unknownParentIds=Array.from(parentIds).filter(e=>{var t;return e&&!(null==(t=this.assets)?void 0:t.some(t=>t.id===e))});if(unknownParentIds.length>0)try{console.debug(`Querying parents of ${unknownParentIds.length} assets...`);let parentAssets=yield manager.rest.api.AssetResource.queryAssets({select:{attributes:attributeCond?void 0:[]},ids:unknownParentIds});console.debug(`The filter query found ${parentAssets.data.length} parents!`),foundAssetIds=foundAssets.map(e=>e.id),foundAssets=[...foundAssets,...parentAssets.data]}catch(e){console.error("Error querying Asset Tree parents of found assets:",e)}return{assets:foundAssets,matcher:asset=>{let attrValueCheck=!0;if(this._filter.attribute.length>0&&this._filter.attributeValue.length>0&&foundAssetIds.includes(asset.id)){let attributeVal=[];this._filter.attributeValue.forEach((e,t)=>{e.length>0&&attributeVal.push([this._filter.attribute[t],e])});let matchingAsset=foundAssets.find(e=>e.id===asset.id);if(matchingAsset&&matchingAsset.attributes)for(let attributeValIndex=0;attributeValIndex<attributeVal.length;attributeValIndex++){let currentAttributeVal=attributeVal[attributeValIndex],atLeastOneAttributeMatchValue=!1;Object.keys(matchingAsset.attributes).forEach(key=>{var _a,_b,_c;let attr=matchingAsset.attributes[key];if(attr.name.toLowerCase()===currentAttributeVal[0].toLowerCase())switch(attr.type){case"number":case"integer":case"long":case"bigInteger":case"bigNumber":case"positiveInteger":case"negativeInteger":case"positiveNumber":case"negativeNumber":{let normalizedValue=null==(_a=currentAttributeVal[1])?void 0:_a.replace(",",".");if(isNaN(Number(normalizedValue))){if(/\d/.test(normalizedValue)){normalizedValue.endsWith("%")&&(normalizedValue=null==normalizedValue?void 0:normalizedValue.replace("%","")),/^[0-9]/.test(normalizedValue)&&(normalizedValue="=="+normalizedValue);let func=attr.value+normalizedValue.replace(/[a-z]/gi,"");try{let resultNumberEval=eval(func);resultNumberEval&&(atLeastOneAttributeMatchValue=!0)}catch(_ignored){console.warn("Could not process filter on attribute number value;",func)}}}else(null!=(_b=attr.value)?_b:0)===Number(normalizedValue)&&(atLeastOneAttributeMatchValue=!0);break}case"boolean":{let value=currentAttributeVal[1];("false"===value||"true"===value)&&value===(null!=(_c=attr.value)&&_c).toString()&&(atLeastOneAttributeMatchValue=!0);break}case"text":if(attr.value){let unparsedValue=currentAttributeVal[1],multicharString="*",parsedValue=unparsedValue.replace(multicharString,".*");parsedValue=parsedValue.replace(/"/g,""),-1!=attr.value.toLowerCase().indexOf(parsedValue.toLowerCase())&&(atLeastOneAttributeMatchValue=!0)}}}),attrValueCheck=atLeastOneAttributeMatchValue}}return foundAssetIds.includes(asset.id)&&attrValueCheck}}})}isAnyFilter(){return void 0!==this._filter.asset||this._filter.assetType.length>0||this._filter.attribute.length>0}filterTreeNode(e,t,s=!1){let i=t(e.asset);e.notMatchingFilter=!i;let r=e.children.map(e=>this.filterTreeNode(e,t,i)).some(e=>e);return i=i||r,e.expanded=r&&e.children.length>0&&this.isAnyFilter(),e.hidden=!i&&!s,i}_onCopyClicked(){return __awaiter(this,void 0,void 0,function*(){if(1===this._selectedNodes.length)try{let e=yield manager.rest.api.AssetResource.get(this._selectedNodes[0].asset.id);if(!e.data)throw Error("API returned an invalid response when retrieving the source asset");let t=JSON.parse(JSON.stringify(e.data));t.name+=" copy",delete t.id,delete t.path,delete t.createdOn,delete t.version,Util.dispatchCancellableEvent(this,new OrAssetTreeRequestAddEvent({sourceAsset:this._selectedNodes[0].asset,asset:t})).then(e=>{e.allow&&this.dispatchEvent(new OrAssetTreeAddEvent(e.detail))})}catch(e){console.error("Failed to copy asset",e),showErrorDialog("Failed to copy asset")}})}_onAddClicked(){let e,t=this._getAllowedChildTypes(this._selectedNodes[0]),s=t.filter(e=>"agent"===e.descriptorType),i=t.filter(e=>"asset"===e.descriptorType),r=this._selectedNodes&&1===this._selectedNodes.length?this._selectedNodes[0].asset:void 0,l=t=>{let s=!!t.detail.name&&t.detail.name.trim().length>0&&t.detail.name.trim().length<1024;e.shadowRoot.getElementById("add-btn").disabled=!t.detail.descriptor||!s};e=showDialog(new OrMwcDialog().setHeading(i18next.t("addAsset")).setContent(html`
78
+ <or-add-asset-dialog id="add-panel" .config="${this.config}" .agentTypes="${s}" .assetTypes="${i}" .parent="${r}" @or-add-asset-changed="${l}"></or-add-asset-dialog>
79
+ `).setActions([{actionName:"cancel",content:"cancel"},{actionName:"add",content:html`<or-mwc-input id="add-btn" class="button" .type="${InputType.BUTTON}" label="add" disabled></or-mwc-input>`,action:()=>{let t=e.shadowRoot.getElementById("add-panel"),s=t.selectedType,i=t.selectedAttributes,r=t.name.trim(),l=t.parent;if(!s)return;let a={name:r,type:s.name,realm:manager.displayRealm},n=AssetModelUtil.getAssetTypeInfo(s.name);if(!n)return;n.attributeDescriptors&&(a.attributes={},n.attributeDescriptors.filter(e=>!e.optional).forEach(e=>{a.attributes[e.name]={name:e.name,type:e.type,meta:e.meta?Object.assign({},e.meta):void 0}})),i&&(null==i||i.forEach(e=>{a.attributes[e.name]={name:e.name,type:e.type,meta:e.meta?Object.assign({},e.meta):void 0}})),this.selectedIds&&(a.parentId=l?l.id:void 0);let d={asset:a};Util.dispatchCancellableEvent(this,new OrAssetTreeRequestAddEvent(d)).then(e=>{e.allow&&this.dispatchEvent(new OrAssetTreeAddEvent(e.detail))})}}]).setStyles(html`
72
80
  <style>
73
81
  .mdc-dialog__content {
74
82
  padding: 0 !important;
75
83
  }
76
84
  </style>
77
- `).setDismissAction(null))}_gatewayDescendantIsSelected(){return this._selectedNodes.some(e=>{var t;let s=null==e?void 0:e.parent;for(;s;){if((null==(t=s.asset)?void 0:t.type)==="GatewayAsset")return!0;s=s.parent}return!1})}_onDeleteClicked(){this._selectedNodes.length>0&&Util.dispatchCancellableEvent(this,new OrAssetTreeRequestDeleteEvent(this._selectedNodes)).then(e=>{e.allow&&this._doDelete()})}_onSortClicked(e){this.sortBy=e}_doDelete(){if(!this._selectedNodes||0===this._selectedNodes.length)return;let e=new Set,t=this._selectedNodes.filter(t=>{var s;return(null==(s=t.asset)?void 0:s.type)!=="GatewayAsset"||(e.add(t.asset),!1)});OrAssetTree_1._forEachNodeRecursive(t,t=>{var s;let i=t.parent,r=!0;for(;i&&r;)"GatewayAsset"===(null==(s=null==i?void 0:i.asset)?void 0:s.type)&&(r=!1),i=i.parent;r&&e.add(t.asset)});let s=Array.from(e).map(e=>e.id),i=Array.from(e).map(e=>e.name),r=()=>{this.disabled=!0,manager.rest.api.AssetResource.delete({assetId:s},{paramsSerializer:e=>Qs.stringify(e,{arrayFormat:"repeat"})}).then(e=>{this.refresh(),this.disabled=!1,204!==e.status&&showErrorDialog(i18next.t("deleteAssetsFailed"))}).catch(e=>{this.refresh(),this.disabled=!1,showErrorDialog(i18next.t("deleteAssetsFailed"))})};showOkCancelDialog(i18next.t("deleteAssets"),i18next.t("deleteAssetsConfirm",{assetNames:i.join(",\n- ")}),i18next.t("delete")).then(e=>{e&&r()})}_canAdd(){var e;if(this._selectedNodes&&this._selectedNodes.length>1)return!1;let t=this._selectedNodes?this._selectedNodes[0]:void 0;return!((null==(e=null==t?void 0:t.asset)?void 0:e.type)==="GatewayAsset"||this._gatewayDescendantIsSelected())&&this._getAllowedChildTypes(t).length>0}_getAllowedChildTypes(e){let t,s;if(this.config&&this.config.add){if(this.config.add.typesProvider){let t=this.config.add.typesProvider(e);if(t)return t}if(this.config.add.typesParent){let i;!e&&this.config.add.typesParent.none?i=this.config.add.typesParent.none:e&&this.config.add.typesParent.assetTypes&&(i=this.config.add.typesParent.assetTypes[e.asset.type]),i||(i=this.config.add.typesParent.default),i&&(t=i.include,s=i.exclude||[])}}return AssetModelUtil.getAssetDescriptors().filter(e=>(!t||t.some(t=>Util.stringMatch(t,e.name)))&&(!s||!s.some(t=>Util.stringMatch(t,e.name))))}_getSortFunction(){return"createdOn"===this.sortBy?Util.sortByNumber(e=>e.asset[this.sortBy]):Util.sortByString(e=>e.asset[this.sortBy])}_loadAssets(){let e=this._getSortFunction();if(this.assets)this._loading=!1,this._buildTreeNodes(this.assets,e);else{if(!this._connected||this._loading)return;if(this._loading=!0,this.dataProvider)this.dataProvider().then(t=>{var s;this._loading=!1,this._buildTreeNodes(t,e),(null==(s=this._filterInput)?void 0:s.value)&&this._doFiltering()});else{let t={realm:{name:manager.displayRealm},select:{attributes:[]}};this.assetIds?(t.ids=this.assetIds,t.recursive=!0):this.rootAssets?(t.ids=this.rootAssets.map(e=>e.id),t.recursive=!0):this.rootAssetIds&&(t.ids=this.rootAssetIds,t.recursive=!0),this._sendEventWithReply({eventType:"read-assets",assetQuery:t}).then(t=>{var s;this._loading=!1,this._buildTreeNodes(t.assets,e),(null==(s=this._filterInput)?void 0:s.value)&&this._doFiltering()})}}}_addEventSubscriptions(){return __awaiter(this,void 0,void 0,function*(){this.disableSubscribe||(this._subscriptionIds=[(yield manager.getEventProvider().subscribeAssetEvents(void 0,!1,e=>this._onEvent(e)))])})}onEventsConnect(){this._connected=!0,this._loadAssets()}onEventsDisconnect(){this._connected=!1,this._nodes=void 0}getNodes(){return this._nodes||[]}_onEvent(e){var t;if("assets"===e.eventType){let t=e;this._buildTreeNodes(t.assets,this._getSortFunction());return}if("asset"===e.eventType){let s=e;if("READ"===s.cause||"UPDATE"===s.cause&&!(s.updatedProperties.includes("name")||s.updatedProperties.includes("parentId")))return;let i=[];"DELETE"!==s.cause&&i.push(s.asset),this._nodes&&OrAssetTree_1._forEachNodeRecursive(this._nodes,e=>{e.asset.id!==s.asset.id&&i.push(e.asset)}),this._buildTreeNodes(i,this._getSortFunction()),(null==(t=this._filterInput)?void 0:t.value)&&this._doFiltering(),this.dispatchEvent(new OrAssetTreeAssetEvent(s))}}_buildTreeNodes(e,t){if(e&&0!==e.length){let s,i;manager.isRestrictedUser()&&e.forEach(t=>{if(t.parentId&&t.path&&void 0===e.find(e=>e.id===t.parentId)){let s=null;for(let i=0;i<t.path.length;i++){let r=t.path[i];t.id!==r&&void 0!==e.find(e=>e.id===r)&&(s=r)}t.reparentId=s}}),this.rootAssetIds?s=this.rootAssetIds:this.rootAssets&&(s=this.rootAssets.map(e=>e.id)),i=s?e.filter(e=>s.indexOf(e.id)>=0||null===e.reparentId).map(e=>({asset:e})):e.filter(e=>!e.parentId||null===e.reparentId).map(e=>({asset:e})),this.assetsChildren={},e.forEach(e=>{e.parentId&&(this.assetsChildren[e.parentId]||(this.assetsChildren[e.parentId]=[]),this.assetsChildren[e.parentId].push({asset:e})),e.reparentId&&(this.assetsChildren[e.reparentId]||(this.assetsChildren[e.reparentId]=[]),this.assetsChildren[e.reparentId].push({asset:e}))}),i.sort(t),i.forEach(s=>this._buildChildTreeNodes(s,e,t)),this._nodes=i;let r=[];this._expandedNodes.forEach(e=>{OrAssetTree_1._forEachNodeRecursive(this._nodes,t=>{if(t.asset&&e&&e.asset&&t.asset.id===e.asset.id){t.expanded=!0,r.push(t);let e=t.parent;for(;e;)e.expanded=!0,e=e.parent,0>r.indexOf(e)&&r.push(e)}})}),this._expandedNodes=r}else this._nodes=[];this.selectedIds&&this.selectedIds.length>0&&this._updateSelectedNodes(),this.expandAllNodes&&OrAssetTree_1._forEachNodeRecursive(this._nodes,e=>{e.children&&e.children.length>0&&(e.expanded=!0)})}_buildChildTreeNodes(e,t,s){let i=this.assetsChildren[e.asset.id];e.children=i?i.sort(s):[],e.children.length>0&&(e.expandable=!0),e.children.forEach(i=>{i.parent=e,this._buildChildTreeNodes(i,t,s)})}_onDragStart(e){this._dragDropParentId=null;let t=e.currentTarget.getAttribute("node-asset-id");this.selectedIds||(this.selectedIds=[]),t&&this.selectedIds&&!this.selectedIds.includes(t)&&(e.ctrlKey||e.shiftKey||(this.selectedIds=[]),this.selectedIds.push(t))}_onDragEnd(e){let t=e.x,s=e.y;if(null!==this.shadowRoot){let e=this.shadowRoot.getElementById("list");if(e){let i=e.getBoundingClientRect().top,r=e.getBoundingClientRect().bottom,a=e.getBoundingClientRect().left,d=e.getBoundingClientRect().right;if(t<a||t>d||s>r||s<i)return}}this.selectedIds&&this.dispatchEvent(new OrAssetTreeChangeParentEvent(!this._dragDropParentId?void 0:this._dragDropParentId,this.selectedIds))}isExpandable(e){return!!(this._nodes&&this.shadowRoot&&this.shadowRoot.querySelector('[node-asset-id="'+e+'"] > .node-name > [data-expandable]'))||!1}_onDragOver(e){let t=e.currentTarget;t.classList.add("over");let s=t.getAttribute("node-asset-id");s&&this.isExpandable(s)&&!this._expandTimer&&(this._expandTimer=window.setTimeout(()=>{this.expandNode(s)},1e3))}expandNode(e){var t;if(this.shadowRoot&&e&&e===this._dragDropParentId){let s=this._findNodeFromAssetId(e),i=null==(t=this.shadowRoot)?void 0:t.querySelector('[node-asset-id="'+e+'"]');i&&s&&!s.expanded&&this._toggleExpander(i.firstElementChild.firstElementChild,s,!0)}}_onDragEnter(e){let t=e.currentTarget;t.classList.add("over");let s=t.getAttribute("node-asset-id");this._dragDropParentId=s}_onDragLeave(e){e.currentTarget.classList.remove("over"),clearTimeout(this._expandTimer),this._expandTimer=void 0}_treeNodeTemplate(e,t){let s,i=AssetModelUtil.getAssetDescriptor(e.asset.type);if(s=e.allChildrenSelected?"checkbox-multiple-marked":e.someChildrenSelected?"checkbox-multiple-marked-outline":"checkbox-multiple-blank-outline",e.hidden)return html``;let r=!1;return e.asset&&e.notMatchingFilter&&(r=!0),e.expanded&&0===e.children.length&&(e.expanded=!1),this.expandedIds&&-1!==this.expandedIds.findIndex(t=>t===e.asset.id)&&(e.expanded=!0),html`
85
+ `).setDismissAction(null))}_gatewayDescendantIsSelected(){return this._selectedNodes.some(e=>{var t;let s=null==e?void 0:e.parent;for(;s;){if((null==(t=s.asset)?void 0:t.type)==="GatewayAsset")return!0;s=s.parent}return!1})}_onDeleteClicked(){this._selectedNodes.length>0&&Util.dispatchCancellableEvent(this,new OrAssetTreeRequestDeleteEvent(this._selectedNodes)).then(e=>{e.allow&&this._doDelete()})}_onSortClicked(e){this.sortBy=e}_doDelete(){if(!this._selectedNodes||0===this._selectedNodes.length)return;let e=new Set,t=this._selectedNodes.filter(t=>{var s;return(null==(s=t.asset)?void 0:s.type)!=="GatewayAsset"||(e.add(t.asset),!1)});OrAssetTree_1._forEachNodeRecursive(t,t=>{var s;let i=t.parent,r=!0;for(;i&&r;)"GatewayAsset"===(null==(s=null==i?void 0:i.asset)?void 0:s.type)&&(r=!1),i=i.parent;r&&e.add(t.asset)});let s=Array.from(e).map(e=>e.id),i=Array.from(e).map(e=>e.name),r=()=>{this.disabled=!0,manager.rest.api.AssetResource.delete({assetId:s},{paramsSerializer:e=>Qs.stringify(e,{arrayFormat:"repeat"})}).then(e=>{this._onDeselectClicked(),204!==e.status&&showErrorDialog(i18next.t("deleteAssetsFailed"))}).catch(e=>{showErrorDialog(i18next.t("deleteAssetsFailed"))}).finally(()=>{this.disabled=!1})};showOkCancelDialog(i18next.t("deleteAssets"),i18next.t("deleteAssetsConfirm",{assetNames:i.join(",\n- ")}),i18next.t("delete")).then(e=>{e&&r()})}_canAdd(){var e;if(this._selectedNodes&&this._selectedNodes.length>1)return!1;let t=this._selectedNodes?this._selectedNodes[0]:void 0;return!((null==(e=null==t?void 0:t.asset)?void 0:e.type)==="GatewayAsset"||this._gatewayDescendantIsSelected())&&this._getAllowedChildTypes(t).length>0}_getAllowedChildTypes(e){let t,s;if(this.config&&this.config.add){if(this.config.add.typesProvider){let t=this.config.add.typesProvider(e);if(t)return t}if(this.config.add.typesParent){let i;!e&&this.config.add.typesParent.none?i=this.config.add.typesParent.none:e&&this.config.add.typesParent.assetTypes&&(i=this.config.add.typesParent.assetTypes[e.asset.type]),i||(i=this.config.add.typesParent.default),i&&(t=i.include,s=i.exclude||[])}}return AssetModelUtil.getAssetDescriptors().filter(e=>(!t||t.some(t=>Util.stringMatch(t,e.name)))&&(!s||!s.some(t=>Util.stringMatch(t,e.name))))}_getSortFunction(){return"createdOn"===this.sortBy?Util.sortByNumber(e=>e.asset[this.sortBy]):Util.sortByString(e=>e.asset[this.sortBy])}_getOrderBy(e){switch(e){case"createdOn":return"CREATED_ON";case"type":return"ASSET_TYPE";default:return"NAME"}}_loadAssets(e){return __awaiter(this,arguments,void 0,function*(e,t=0,s){if(console.debug(`Loading assets with ${e?`parent ${e}`:"no parents"}...`),this.assets){console.debug("Assets already pre-loaded using HTML attributes; reusing them to construct the tree UI..."),this._loading=!1,this._buildTreeNodes(this.assets);return}if(!this._connected)throw Error("Not connected to the server; cannot load assets.");if(this._loading)throw Error("Already loading assets for asset tree; ignoring request.");if(this._loading=!0,this.dataProvider)this.dataProvider().then(e=>{var t;this._loading=!1,this._buildTreeNodes(e),(null==(t=this._filterInput)?void 0:t.value)&&this._doFiltering()});else{let i={realm:{name:manager.displayRealm},parents:e?[{id:e}]:[],select:{attributes:[]},orderBy:{property:this._getOrderBy(this.sortBy)},offset:t,limit:Math.max(this.queryLimit,1)};this.assetIds?(i.ids=this.assetIds,i.recursive=!0):this.rootAssets?(i.ids=this.rootAssets.map(e=>e.id),i.recursive=!0):this.rootAssetIds&&(i.ids=this.rootAssetIds,i.recursive=!0);let r=this._sendEventWithReply({eventType:"read-asset-tree",assetQuery:i});return r.then(t=>{var i,r,l,a,n,d;let o=null!=(r=null==(i=t.assetTree)?void 0:i.assets)?r:[],h=null!=(a=null==(l=t.assetTree)?void 0:l.hasMore)&&a;if(e?e&&this._incompleteParentIds.includes(e)&&!h?this._incompleteParentIds=this._incompleteParentIds.filter(t=>t!==e):e&&h&&(this._incompleteParentIds=[...this._incompleteParentIds,e]):this._hasMoreParents=h,console.debug(`Received read-assets-tree event with ${o.length} assets.`),console.debug(`Combining these assets with the cache of ${null!=(n=null==s?void 0:s.length)?n:0} assets...`),this._loading=!1,s){let e=[...s,...o.filter(e=>!s.find(t=>t.id===e.id))];this._buildTreeNodes(e)}else this._buildTreeNodes(o);(null==(d=this._filterInput)?void 0:d.value)&&this._doFiltering()}),r}})}_addEventSubscriptions(){return __awaiter(this,void 0,void 0,function*(){this.disableSubscribe||(this._subscriptionIds=[(yield manager.getEventProvider().subscribeAssetEvents(void 0,!1,e=>this._onEvent(e)))])})}onEventsConnect(){this._connected=!0,this._loadAssets().catch(console.warn)}onEventsDisconnect(){this._connected=!1,this._nodes=void 0}getNodes(){return this._nodes||[]}_onEvent(e){var t;if("assets"===e.eventType){let t=e;this._buildTreeNodes(t.assets);return}if("asset"===e.eventType){let s=e;if("READ"===s.cause||"UPDATE"===s.cause&&!(s.updatedProperties.includes("name")||s.updatedProperties.includes("parentId")))return;let i=[];"DELETE"!==s.cause&&i.push(s.asset),this._nodes&&OrAssetTree_1._forEachNodeRecursive(this._nodes,e=>{e.asset.id!==s.asset.id&&i.push(e.asset)}),this._buildTreeNodes(i),(null==(t=this._filterInput)?void 0:t.value)&&this._doFiltering(),this.dispatchEvent(new OrAssetTreeAssetEvent(s))}}_buildTreeNodes(e,t=this._getSortFunction()){var s;if(console.debug(`Building asset tree nodes for ${e.length} assets...`),e&&0!==e.length){let s,i;manager.isRestrictedUser()&&e.forEach(t=>{if(t.parentId&&t.path&&void 0===e.find(e=>e.id===t.parentId)){let s=null;for(let i=0;i<t.path.length;i++){let r=t.path[i];t.id!==r&&void 0!==e.find(e=>e.id===r)&&(s=r)}t.reparentId=s}}),this.rootAssetIds?s=this.rootAssetIds:this.rootAssets&&(s=this.rootAssets.map(e=>e.id)),i=s?e.filter(e=>s.indexOf(e.id)>=0||null===e.reparentId).map(e=>({asset:e})):e.filter(e=>!e.parentId||null===e.reparentId).map(e=>({asset:e})),this.assetsChildren={},e.forEach(e=>{e.parentId&&(this.assetsChildren[e.parentId]||(this.assetsChildren[e.parentId]=[]),this.assetsChildren[e.parentId].push({asset:e})),e.reparentId&&(this.assetsChildren[e.reparentId]||(this.assetsChildren[e.reparentId]=[]),this.assetsChildren[e.reparentId].push({asset:e}))}),i.sort(t),i.forEach(s=>this._buildChildTreeNodes(s,e,t)),this._nodes=i;let r=[];this._expandedNodes.forEach(e=>{OrAssetTree_1._forEachNodeRecursive(this._nodes,t=>{var s,i;if((null==(s=t.asset)?void 0:s.id)&&(null==(i=null==e?void 0:e.asset)?void 0:i.id)&&t.asset.id===e.asset.id&&this.isExpandable(e.asset.id)){t.expanded=!0,r.push(t);let e=t.parent;for(;e;)e.expanded=!0,e=e.parent,0>r.indexOf(e)&&r.push(e)}})}),this._expandedNodes=r}else this._nodes=[];console.debug(`Asset tree nodes built. Now selecting ${null==(s=this.selectedIds)?void 0:s.length} nodes...`),this.selectedIds&&this.selectedIds.length>0&&this._updateSelectedNodes(),this.expandAllNodes&&OrAssetTree_1._forEachNodeRecursive(this._nodes,e=>{e.children&&e.children.length>0&&(e.expanded=!0)})}_buildChildTreeNodes(e,t,s){var i,r;let l=this.assetsChildren[e.asset.id];e.children=l?l.sort(s):[],e.expandable=(null==(i=e.asset)?void 0:i.hasChildren)||(null==(r=e.children)?void 0:r.length),e.children.forEach(i=>{i.parent=e,this._buildChildTreeNodes(i,t,s)})}_onDragStart(e){this._dragDropParentId=null;let t=e.currentTarget.getAttribute("node-asset-id");this.selectedIds||(this.selectedIds=[]),t&&this.selectedIds&&!this.selectedIds.includes(t)&&(e.ctrlKey||e.shiftKey||(this.selectedIds=[]),this.selectedIds.push(t))}_onDragEnd(e){let t=e.x,s=e.y;if(null!==this.shadowRoot){let e=this.shadowRoot.getElementById("list");if(e){let i=e.getBoundingClientRect().top,r=e.getBoundingClientRect().bottom,l=e.getBoundingClientRect().left,a=e.getBoundingClientRect().right;if(t<l||t>a||s>r||s<i)return}}this.selectedIds&&this.dispatchEvent(new OrAssetTreeChangeParentEvent(!this._dragDropParentId?void 0:this._dragDropParentId,this.selectedIds))}isExpandable(e){return!!(this._nodes&&this.shadowRoot&&this.shadowRoot.querySelector('[node-asset-id="'+e+'"] > .node-name > [data-expandable]'))||!1}_onDragOver(e){let t=e.currentTarget;t.classList.add("over");let s=t.getAttribute("node-asset-id");s&&this.isExpandable(s)&&!this._expandTimer&&(this._expandTimer=window.setTimeout(()=>{this.expandNode(s)},1e3))}expandNode(e){var t;if(this.shadowRoot&&e&&e===this._dragDropParentId){let s=this._findNodeFromAssetId(e),i=null==(t=this.shadowRoot)?void 0:t.querySelector('[node-asset-id="'+e+'"]');i&&s&&!s.expanded&&this._toggleExpander(i.firstElementChild.firstElementChild,s,!0)}}_onDragEnter(e){let t=e.currentTarget;t.classList.add("over");let s=t.getAttribute("node-asset-id");this._dragDropParentId=s}_onDragLeave(e){e.currentTarget.classList.remove("over"),clearTimeout(this._expandTimer),this._expandTimer=void 0}_treeNodeTemplate(e,t){var s;let i,r=AssetModelUtil.getAssetDescriptor(e.asset.type);if(i=e.allChildrenSelected?"checkbox-multiple-marked":e.someChildrenSelected?"checkbox-multiple-marked-outline":"checkbox-multiple-blank-outline",e.hidden)return html``;let l=!1;return e.asset&&e.notMatchingFilter&&(l=!0),e.expanded&&0===e.children.length&&(console.debug("Tree node has no children, collapsing it..."),e.expanded=!1),this.expandedIds&&-1!==this.expandedIds.findIndex(t=>t===e.asset.id)&&(e.expanded=!0),html`
78
86
  <li class="asset-list-element" ?data-selected="${e.selected}" ?data-expanded="${e.expanded}" @click="${t=>this._onNodeClicked(t,e)}">
79
87
  <div class="in-between-element" node-asset-id="${e.parent?e.parent.asset?e.parent.asset.id:"":void 0}" @dragleave=${e=>{this._onDragLeave(e)}} @dragenter="${e=>this._onDragEnter(e)}" @dragend="${e=>this._onDragEnd(e)}" @dragover="${e=>this._onDragOver(e)}"></div>
80
88
  <div class="node-container draggable" node-asset-id="${e.asset?e.asset.id:""}" draggable="${!this._isReadonly()}" @dragleave=${e=>{this._onDragLeave(e)}} @dragenter="${e=>this._onDragEnter(e)}" @dragstart="${e=>this._onDragStart(e)}" @dragend="${e=>this._onDragEnd(e)}" @dragover="${e=>this._onDragOver(e)}" style="padding-left: ${22*t}px">
81
89
  <div class="node-name">
82
90
  <div class="expander" ?data-expandable="${e.expandable}"></div>
83
- ${getAssetDescriptorIconTemplate(i,void 0,void 0,r?"d3d3d3":void 0)}
84
- <span style="color: ${r?"#d3d3d3;":""}">${e.asset.name}</span>
91
+ ${getAssetDescriptorIconTemplate(r,void 0,void 0,l?"d3d3d3":void 0)}
92
+ <span style="color: ${l?"#d3d3d3;":""}">${e.asset.name}</span>
85
93
  ${this.checkboxes?html`
86
94
  <span class="mdc-list-item__graphic">
87
95
  ${e.expandable?html`<div class="mdc-checkbox">
88
- <or-icon class="mdc-checkbox--parent" icon="${s}"></or-icon>
96
+ <or-icon class="mdc-checkbox--parent" icon="${i}"></or-icon>
89
97
  </div>`:""}
90
98
  <div class="mdc-checkbox">
91
99
  ${e.selected?html`<or-icon icon="checkbox-marked"></or-icon>`:html`<or-icon icon="checkbox-blank-outline"></or-icon>`}
@@ -95,6 +103,11 @@ var OrAssetTree_1,FilterElementType,__decorate=this&&this.__decorate||function(e
95
103
  </div>
96
104
  <ol>
97
105
  ${!e.children||e.expandable&&!e.expanded?"":e.children.map(e=>this._treeNodeTemplate(e,t+1)).filter(e=>!!e)}
106
+ ${when((null==(s=e.asset)?void 0:s.id)&&this._incompleteParentIds.includes(e.asset.id),()=>html`
107
+ <li class="asset-list-element loadmore-element">
108
+ <or-mwc-input type=${InputType.BUTTON} outlined label="loadMore" style="padding-left: ${(t+1)*22}px;"></or-mwc-input>
109
+ </li>
110
+ `)}
98
111
  </ol>
99
112
  </li>
100
- `}static _forEachNodeRecursive(e,t){e&&e.forEach(e=>{t(e),this._forEachNodeRecursive(e.children,t)})}};__decorate([property({type:Array,reflect:!1})],OrAssetTree.prototype,"assets",void 0),__decorate([property({type:Object})],OrAssetTree.prototype,"assetInfos",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"_assetIdsOverride",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"rootAssets",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"rootAssetIds",void 0),__decorate([property({type:Object})],OrAssetTree.prototype,"dataProvider",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"readonly",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"disabled",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"disableSubscribe",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"selectedIds",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"showDeselectBtn",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"showSortBtn",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"showFilter",void 0),__decorate([property({type:String})],OrAssetTree.prototype,"sortBy",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"expandAllNodes",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"expandedIds",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"checkboxes",void 0),__decorate([property({attribute:!1})],OrAssetTree.prototype,"_nodes",void 0),__decorate([state()],OrAssetTree.prototype,"_filter",void 0),__decorate([query("#clearIconContainer")],OrAssetTree.prototype,"_clearIconContainer",void 0),__decorate([query("#filterInput")],OrAssetTree.prototype,"_filterInput",void 0),__decorate([state()],OrAssetTree.prototype,"_filterSettingOpen",void 0),__decorate([state()],OrAssetTree.prototype,"_assetTypes",void 0),__decorate([query("#attributeNameFilter")],OrAssetTree.prototype,"_attributeNameFilter",void 0),__decorate([query("#attributeValueFilter")],OrAssetTree.prototype,"_attributeValueFilter",void 0),__decorate([state()],OrAssetTree.prototype,"_assetTypeFilter",void 0),OrAssetTree=OrAssetTree_1=__decorate([customElement("or-asset-tree")],OrAssetTree);export{style,OrAssetTree};
113
+ `}static _forEachNodeRecursive(e,t){e&&e.forEach(e=>{t(e),this._forEachNodeRecursive(e.children,t)})}};__decorate([property({type:Array,reflect:!1})],OrAssetTree.prototype,"assets",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"rootAssets",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"rootAssetIds",void 0),__decorate([property({type:Object})],OrAssetTree.prototype,"dataProvider",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"readonly",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"disabled",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"disableSubscribe",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"selectedIds",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"showDeselectBtn",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"showSortBtn",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"showFilter",void 0),__decorate([property({type:String})],OrAssetTree.prototype,"sortBy",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"expandAllNodes",void 0),__decorate([property({type:Array})],OrAssetTree.prototype,"expandedIds",void 0),__decorate([property({type:Boolean})],OrAssetTree.prototype,"checkboxes",void 0),__decorate([property({type:Number})],OrAssetTree.prototype,"queryLimit",void 0),__decorate([state()],OrAssetTree.prototype,"_nodes",void 0),__decorate([state()],OrAssetTree.prototype,"_filter",void 0),__decorate([query("#clearIconContainer")],OrAssetTree.prototype,"_clearIconContainer",void 0),__decorate([query("#filterInput")],OrAssetTree.prototype,"_filterInput",void 0),__decorate([state()],OrAssetTree.prototype,"_filterSettingOpen",void 0),__decorate([state()],OrAssetTree.prototype,"_assetTypes",void 0),__decorate([query("#attributeNameFilter")],OrAssetTree.prototype,"_attributeNameFilter",void 0),__decorate([query("#attributeValueFilter")],OrAssetTree.prototype,"_attributeValueFilter",void 0),__decorate([state()],OrAssetTree.prototype,"_assetTypeFilter",void 0),__decorate([state()],OrAssetTree.prototype,"_hasMoreParents",void 0),__decorate([state()],OrAssetTree.prototype,"_incompleteParentIds",void 0),OrAssetTree=OrAssetTree_1=__decorate([customElement("or-asset-tree")],OrAssetTree);export{style,OrAssetTree};