Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 | 93x 93x 93x 93x 93x 93x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 9x 36x 3x 36x 2x 2x 34x 34x 36x 36x 1x 129x 84x 84x 84x 62x 62x 84x 84x 82x 41x 41x 3x 41x 1x 1x 1x 1x 2x 2x 6x 2x 2x 16x 2x 2x 2x 1x 1x 1x 4x 3x 22x 3x 22x 25x 25x 22x 22x 25x 4x 4x 2x 2x 2x 2x 2x 1x 1x 1x 1x 4x 4x 2x 2x 2x 1x 2x 2x 2x 1x 1x 1x 3x 3x 3x 11x 11x 11x 11x 11x 2x 9x 11x 14x 14x 14x 9x 9x 14x 2x 6x 6x 6x 6x 6x 5x 5x 6x 6x 5x 6x 6x 5x 5x 5x 5x 41x 41x 8x 8x 8x 8x 8x 1x 10x 10x 10x 10x 9x 9x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 7x 8x 10x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 2x 24x 5x 5x 2x 3x 46x 46x 24x 2x | import { Accessor, Datasource, DatasourceFactory, Event, IDictionary, IEvent, IEvents, Metadata } from '@zeedhi/core';
import merge from 'lodash.merge';
import set from 'lodash.set';
import { TreeDataStructure } from '../../utils/tree-data-structure';
import { ComponentRender } from '../zd-component/component-render';
import { IComponent, IComponentRender, IComponentRenderInstance } from '../zd-component/interfaces';
import { ICursorPosition, ITree, ITreeConditionComponent, ITreeNode, ITreeNodeModel, ITreeProps } from './interfaces';
export class Tree extends ComponentRender implements ITree {
/** Tree nodes */
public nodesValue: ITreeNodeModel<IDictionary>[] = [];
/** Tree Item icon name */
public itemIconName = '';
/** Tree Group icon name */
public groupIconName = '';
/** Tree opened group icon name */
public openedIconName = '';
/** Tree closed group icon name */
public closedIconName = '';
/** Allow selecting multiple nodes */
public allowMultiSelect = true;
/** Allow dragging nodes */
public allowDragDrop = true;
/** Render a component in front of the node title */
public afterTitleSlot?: ITreeConditionComponent;
/**
* Components that will be rendered on toolbar slot
*/
public toolbarSlot: IComponentRender[] = [];
/**
* Defines the component height. Possible values for this property can be
* <samp>'auto', '100%', '400px' or 400</samp>
*/
public height: string | number = 'auto';
/**
* Defines the component min height. Possible values for this property can be
* <samp>'auto', '100%', '400px' or 400</samp>
*/
public minHeight: string | number = 'auto';
/**
* Defines the component max height. Possible values for this property can be
* <samp>'auto', '100%', '400px' or 400</samp>
*/
public maxHeight: string | number = 'none';
/**
* Set component height to fill all space available
*/
public fillHeight = false;
/**
* Defines the component width. Possible values for this property can be
* <samp>'auto', '100%', '400px' or 400</samp>
*/
public width: string | number = '100%';
/**
* Defines the component min width. Possible values for this property can be
* <samp>'auto', '100%', '400px' or 400</samp>
*/
public minWidth: string | number = 'auto';
/**
* Defines the component max height. Possible values for this property can be
* <samp>'auto', '100%', '400px' or 400</samp>
*/
public maxWidth: string | number = 'none';
/**
* Components that will be rendered on title slot
*/
public titleSlot: ITreeConditionComponent[] = [];
/** Datasource object */
public datasource: Datasource;
/** Datasource parent field */
public parentField = '';
/** Datasource title field */
public titleField = '';
/** Datasource data field */
public dataField = '';
/** Datasource checked field */
public checkedField = 'checked';
/**
* Defines if the tree will be opened or not (true/false) or if it should open only until a specific level
*/
public openLevelOnLoad: number | boolean = false;
/**
* Allow row check
*/
public checkbox = false;
/**
* Function to check if node check should be disabled
*/
public disableCheckbox?: (args: { node: ITreeNode<IDictionary>; component: Tree }) => boolean;
/** SlVueTree component */
private tree!: any;
/** SlVueTree component */
private treeDataStructure?: TreeDataStructure;
/**
* Defines if should wait and not execute GET method when Datasource is created
*/
private lazyLoad = true;
/**
* Dictionary of nodePath ponting to Dictionary of path pointing to the condition (applied) return value
*/
private appliedConditions: IDictionary<IDictionary<any>> = {};
/* Conditions of tree */
private factoredConditions: IDictionary<IEvents<ITreeNode<IDictionary>>> = {};
/**
* Creates a new instance of LabelsTree
* @param props Image Link props
*/
constructor(props: ITreeProps) {
super(props);
this.itemIconName = this.getInitValue('itemIconName', props.itemIconName, this.itemIconName);
this.groupIconName = this.getInitValue('groupIconName', props.groupIconName, this.groupIconName);
this.openedIconName = this.getInitValue('openedIconName', props.openedIconName, this.openedIconName);
this.closedIconName = this.getInitValue('closedIconName', props.closedIconName, this.closedIconName);
this.allowMultiSelect = this.getInitValue('allowMultiSelect', props.allowMultiSelect, this.allowMultiSelect);
this.allowDragDrop = this.getInitValue('allowDragDrop', props.allowDragDrop, this.allowDragDrop);
this.parentField = this.getInitValue('parentField', props.parentField, this.parentField);
this.titleField = this.getInitValue('titleField', props.titleField, this.titleField);
this.dataField = this.getInitValue('dataField', props.dataField, this.dataField);
this.checkedField = this.getInitValue('checkedField', props.checkedField, this.checkedField);
this.openLevelOnLoad = this.getInitValue('openLevelOnLoad', props.openLevelOnLoad, this.openLevelOnLoad);
this.checkbox = this.getInitValue('checkbox', props.checkbox, this.checkbox);
this.height = this.getInitValue('height', props.height, this.height);
this.minHeight = this.getInitValue('minHeight', props.minHeight, this.minHeight);
this.maxHeight = this.getInitValue('maxHeight', props.maxHeight, this.maxHeight);
this.fillHeight = this.getInitValue('fillHeight', props.fillHeight, this.fillHeight);
this.width = this.getInitValue('width', props.width, this.width);
this.minWidth = this.getInitValue('minWidth', props.minWidth, this.minWidth);
this.maxWidth = this.getInitValue('maxWidth', props.maxWidth, this.maxWidth);
this.disableCheckbox = this.getInitValue('disableCheckbox', props.disableCheckbox, this.disableCheckbox);
this.afterTitleSlot = props.afterTitleSlot || this.afterTitleSlot;
this.toolbarSlot = props.toolbarSlot || this.toolbarSlot;
this.titleSlot = props.titleSlot || this.titleSlot;
if (props.afterTitleSlot) {
this.createConditions([props.afterTitleSlot]);
}
if (props.titleSlot) {
this.createConditions(props.titleSlot);
}
if (props.datasource && Object.keys(props.datasource).length) {
this.lazyLoad = props.datasource.lazyLoad !== false;
this.datasource = DatasourceFactory.factory({
...props.datasource,
searchIn: props.datasource.searchIn || [this.titleField, this.dataField].filter(Boolean),
lazyLoad: true,
loadAll: true,
});
} else {
this.datasource = DatasourceFactory.factory({ type: 'memory', data: [] });
console.warn('[Tree] Nenhum datasource foi passado para o componente. Datasource de memória vazio foi criado.');
}
this.nodes = props.nodes || this.nodes;
// Garante que os nós sejam criados a partir do datasource ao instanciar
if (this.datasource?.data?.length) {
this.createDataStructure();
}
}
/**
* Initialize all the properties of the declared nodes (reactivity)
*/
public initNodes(nodes: ITreeNodeModel<IDictionary>[], override?: IDictionary): ITreeNodeModel<IDictionary>[] {
return nodes.map((node) => {
let newNode = {
title: '',
isLeaf: false,
isExpanded: true,
isSelected: false,
isDraggable: true,
isSelectable: true,
data: {
[this.checkedField]: false,
},
children: [] as any[],
};
newNode = merge(newNode, node, override);
if (typeof node.isLeaf === 'undefined') {
const hasChildren = newNode.children.length > 0;
newNode.isLeaf = !hasChildren;
}
newNode.children = this.initNodes(node.children || [], override);
return newNode;
});
}
/** Nodes */
get nodes() {
return this.nodesValue;
}
set nodes(value: ITreeNodeModel<IDictionary>[]) {
let override = {};
if (!this.allowDragDrop) {
override = { isDraggable: false };
}
this.nodesValue = this.initNodes(value, override);
}
public async onCreated(): Promise<void> {
super.onCreated();
if (this.datasource) {
await this.datasource.initialize();
this.createDataStructure();
}
}
getCheckedNodes() {
const selectedNodes: ITreeNode<IDictionary>[] = [];
this.tree.traverse((node: ITreeNode<IDictionary>) => {
if (node.data?.[this.checkedField]) {
selectedNodes.push(node);
}
});
return selectedNodes;
}
/** Returns the selected nodes */
get selectedNodes(): ITreeNode<IDictionary>[] {
return this.tree?.getSelected() || [];
}
private createDataStructure() {
this.treeDataStructure = new TreeDataStructure(this);
this.treeDataStructure.initialize();
if (!this.lazyLoad) {
this.datasource!.get().then(() => {
this.createNodesFromDatasource(false);
});
} else {
this.createNodesFromDatasource();
}
}
/** create nodes from datasource object */
public createNodesFromDatasource(buildTree = true) {
if (this.datasource?.data.length && this.treeDataStructure) {
if (buildTree) this.treeDataStructure.buildTree();
const firstLevelNodes = this.treeDataStructure.treeData.filter((row) => row.tree__level === 1);
this.nodes = this.createChildrenNodes(firstLevelNodes);
}
}
private createNodeFromRow(row: IDictionary<any>) {
return {
title: row[this.titleField],
data: row[this.dataField],
isExpanded: row.tree__opened,
isLeaf: row.tree__children.length === 0,
children: this.createChildrenNodes(row.tree__children),
};
}
private createChildrenNodes(rows: IDictionary<any>[]) {
const newNodes: ITreeNodeModel<IDictionary>[] = [];
rows.forEach((row) => {
const newNode: ITreeNodeModel<IDictionary> = this.createNodeFromRow(row);
newNodes.push(newNode);
});
return newNodes;
}
/** Insert nodes by the current cursor position */
public insertNode(newNode: ITreeNodeModel<IDictionary>) {
const initNode = this.initNodes([newNode])[0];
if (this.selectedNodes.length) {
this.updateNodeData(this.selectedNodes[0], { isLeaf: false });
const cursorPosition: ICursorPosition<IDictionary> = {
node: this.selectedNodes[0],
placement: 'inside',
};
this.tree.insert(cursorPosition, initNode);
} else {
this.nodes.push(initNode);
}
}
/** Import multiples nodes by the current cursor position */
public importNodes(nodes: ITreeNodeModel<IDictionary>[]) {
if (this.selectedNodes.length) {
nodes.reverse().forEach((node) => {
this.insertNode(node);
});
} else {
nodes.forEach((node) => {
this.insertNode(node);
});
}
}
/** Remove selected node */
public removeSelected() {
const parentNodesPath: number[][] = [];
if (this.selectedNodes.length) {
const selectedPaths = this.selectedNodes.map((item) => {
const parent = this.getParentNode(item);
if (parent) {
parentNodesPath.push(parent.path);
}
return item.path;
});
this.tree.remove(selectedPaths);
parentNodesPath.forEach((path) => {
const parent = this.getNode(path);
if (parent?.children && parent.children.length === 0) {
this.tree.updateNode(path, { isLeaf: true });
}
});
}
}
/** Update selected node */
public updateNodeData(node: ITreeNode<IDictionary>, value: IDictionary) {
if (node.children && node.children.length === 0) {
this.tree.updateNode(node.path, { isLeaf: true });
}
this.tree.updateNode(node.path, value);
}
public setTree(tree: any) {
this.tree = tree;
}
/**
* Return plain conditions object
* @param conditions Conditions object
* @param parentPath Path to parent property
*/
protected getPlainConditions(conditions: IDictionary<any>, parentPath = '') {
let plainData: IDictionary<string> = {};
Object.keys(conditions).forEach((key) => {
const fullKey = parentPath ? [parentPath, key].join('.') : key;
if (typeof conditions[key] === 'object') {
plainData = { ...plainData, ...this.getPlainConditions(conditions[key], fullKey) };
} else {
plainData[fullKey] = conditions[key];
}
});
return plainData;
}
protected createConditions(children: ITreeConditionComponent[], parentPath = '') {
children.forEach((child) => {
const path = parentPath ? `${parentPath}.${child.name}` : child.name;
if (child.conditions) {
const plainConditions = this.getPlainConditions(child.conditions);
this.factoredConditions[path] = Event.factory(plainConditions);
}
if (child.children) {
this.createConditions(child.children, path);
}
});
}
protected applyCondition(node: ITreeNode<any>, factoredConditions: IEvents<ITreeNode<IDictionary>>) {
const appliedConditions: IDictionary = {};
Object.keys(factoredConditions).forEach((condition: string) => {
const conditionFunction = factoredConditions[condition] as IEvent<ITreeNode<IDictionary>>;
set(appliedConditions, condition, conditionFunction(node));
});
return appliedConditions;
}
protected applyChildCondition(node: ITreeNode<any>, factoredConditions = this.factoredConditions) {
const appliedConditions: IDictionary = {};
Object.keys(factoredConditions).forEach((comp: string) => {
const conditions = this.factoredConditions[comp];
appliedConditions[comp] = { ...this.applyCondition(node, conditions) };
});
return appliedConditions;
}
public reapplyConditions(node: ITreeNode<any>): IDictionary {
const nodePath = node.pathStr;
if (!nodePath) return {};
const appliedConditions = { ...this.appliedConditions };
appliedConditions[nodePath] = this.applyChildCondition(node);
this.appliedConditions = appliedConditions;
return this.appliedConditions[nodePath];
}
private filterObject<T>(obj: Record<string, T>, callback: (key: string, value: T) => boolean): Record<string, T> {
return Object.fromEntries(Object.entries(obj).filter(([key, value]) => callback(key, value as T)));
}
private deleteAccessorProps(newComponent: IComponent) {
const filteredProps = this.filterObject(newComponent, (_key, value) => !Accessor.isAccessorDefinition(value));
return filteredProps;
}
protected updateActionInstance(instanceName: string, newComponent: IComponent) {
const updatedComponent: any = this.deleteAccessorProps(newComponent);
updatedComponent.datasource = undefined;
updatedComponent.events = undefined;
const instance = Metadata.updateInstance<ComponentRender>(instanceName, updatedComponent);
return instance;
}
getSlotComponent(
slot: IComponentRender | IComponentRender[],
node: ITreeNode<IDictionary>,
parentPath = '',
): (IComponentRender | IComponentRenderInstance)[] {
const slotArr = Array.isArray(slot) ? slot : [slot];
const newComponents: (IComponentRender | IComponentRenderInstance)[] = [];
slotArr.forEach((component: IComponentRender | IComponentRenderInstance) => {
if (!component) return;
const nodePath = node.pathStr;
if (!nodePath) return;
const compName: any =
component.name.indexOf(`_${nodePath}`) > -1
? component.name.substring(0, component.name.indexOf(`_${nodePath}`))
: component.name;
const instanceName = `${compName}_${nodePath}`;
const path = parentPath ? `${parentPath}.${compName}` : compName;
const appliedConditions = this.appliedConditions[nodePath]?.[path];
const newComponent: IComponentRender = merge({}, component, appliedConditions);
const newChildren = newComponent.children ? this.getSlotComponent(newComponent.children, node, path) : [];
newComponent.name = instanceName;
newComponent.children = newChildren;
newComponent.allowDuplicate = true;
let instance: ComponentRender | null = null;
try {
instance = this.updateActionInstance(instanceName, newComponent);
} catch (_e) {
instance = null;
}
newComponents.push(instance || newComponent);
});
return newComponents;
}
/** Triggers when dragging nodes have been dropped */
public nodeDrop(
nodes: ITreeNode<IDictionary>[],
position: ICursorPosition<IDictionary>,
event?: Event,
element?: any,
) {
this.callEvent('onNodeDrop', {
event,
element,
component: this,
nodes,
position,
});
}
/** Triggers when a node has been selected/deselected */
public nodeSelect(nodes: ITreeNode<IDictionary>[], event?: Event, element?: any) {
setTimeout(() => {
this.callEvent('onNodeSelect', {
event,
element,
component: this,
nodes,
});
}, 10);
}
/** Handle click event on node */
public nodeClick(node: ITreeNode<IDictionary>, event?: Event, element?: any) {
this.callEvent('onNodeClick', {
event,
element,
component: this,
node,
});
}
/** Handle dblclick event on node */
public nodeDblClick(node: ITreeNode<IDictionary>, event?: Event, element?: any) {
this.callEvent('onNodeDblClick', {
event,
element,
component: this,
node,
});
}
/** Triggers when a node has been checked/unchecked */
public nodeCheck(node: ITreeNode<IDictionary>, event?: Event, element?: HTMLElement) {
this.callEvent('onNodeCheck', {
event,
element,
component: this,
node,
});
}
public clearSelection(nodes?: ITreeNodeModel<IDictionary<any>>[]) {
const nodesArray = nodes || this.nodes;
nodesArray.forEach((node) => {
node.isSelected = false;
if (node.children) {
this.clearSelection(node.children);
}
});
}
public getNode(path: number[]) {
return this.searchPath(this.nodes, path);
}
public getParentNode(node: ITreeNode<IDictionary>) {
const hasParent = Array.isArray(node.path) && node.path.length > 1;
if (hasParent) {
return this.tree.getNode(node.path!.slice(0, -1));
}
return undefined;
}
private searchPath(nodes: ITreeNodeModel<IDictionary>[], path: number[]): ITreeNodeModel<IDictionary> | undefined {
const currentNode = path[0] > -1 && path[0] < nodes.length ? nodes[path[0]] : undefined;
if (currentNode && path.length > 1) return this.searchPath(currentNode.children || [], path.slice(1));
return currentNode;
}
public callDisableCheckbox(node: ITreeNode<IDictionary>) {
return (
!!this.disableCheckbox &&
typeof this.disableCheckbox === 'function' &&
this.disableCheckbox({ node, component: this })
);
}
}
|