salix/front/core/components/treeview/index.js

146 lines
3.2 KiB
JavaScript

import ngModule from '../../module';
import Component from '../../lib/component';
import './style.scss';
import './childs';
import './content';
/**
* Treeview
*/
export default class Treeview extends Component {
constructor($element, $scope, $transclude) {
super($element, $scope);
this.$transclude = $transclude;
this.readOnly = true;
}
get data() {
return this._data;
}
set data(value) {
this._data = value;
const sons = value.length;
const rootElement = [{
childs: value,
active: true,
sons: sons
}];
this.setParent(rootElement[0], value);
this.items = rootElement;
}
fetch() {
return this.fetchFunc().then(res =>
this.data = res
);
}
setParent(parent, childs) {
childs.forEach(child => {
child.parent = parent;
if (child.childs)
this.setParent(parent, child.childs);
});
}
onToggle(item) {
if (item.active)
this.fold(item);
else
this.unfold(item);
}
fold(item) {
item.childs = undefined;
item.active = false;
}
unfold(item) {
return this.fetchFunc({$item: item}).then(newData => {
this.setParent(item, newData);
const childs = item.childs;
if (childs) {
childs.forEach(child => {
let index = newData.findIndex(newChild => {
return newChild.id == child.id;
});
newData[index] = child;
});
}
if (this.sortFunc) {
item.childs = newData.sort((a, b) =>
this.sortFunc({$a: a, $b: b})
);
}
}).then(() => item.active = true);
}
onRemove(item) {
if (this.removeFunc)
this.removeFunc({$item: item});
}
remove(item) {
const parent = item.parent;
let childs = parent.childs;
if (!childs) childs = [];
let index = childs.indexOf(item);
childs.splice(index, 1);
if (parent) parent.sons--;
}
onCreate(parent) {
if (this.createFunc)
this.createFunc({$parent: parent});
}
create(item) {
const parent = item.parent;
let childs = parent.childs;
if (!childs) childs = [];
childs.push(item);
if (this.sortFunc) {
childs = childs.sort((a, b) =>
this.sortFunc({$a: a, $b: b})
);
}
if (parent) parent.sons++;
}
onDrop(item, dragged, dropped) {
this.emit('drop', {item, dragged, dropped});
}
}
Treeview.$inject = ['$element', '$scope', '$transclude'];
ngModule.component('vnTreeview', {
template: require('./index.html'),
controller: Treeview,
bindings: {
rootLabel: '@',
data: '<?',
draggable: '<?',
droppable: '<?',
fetchFunc: '&',
removeFunc: '&?',
createFunc: '&?',
sortFunc: '&?',
readOnly: '<?'
},
transclude: true
});