primereact
Version:
[](https://opensource.org/licenses/MIT) [](https://badge.fury.io/js/primereact) [ • 24.4 kB
JavaScript
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Tree = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ClassNames = require("../utils/ClassNames");
var _ObjectUtils = _interopRequireDefault(require("../utils/ObjectUtils"));
var _UITreeNode = require("./UITreeNode");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var Tree = /*#__PURE__*/function (_Component) {
_inherits(Tree, _Component);
var _super = _createSuper(Tree);
function Tree(props) {
var _this;
_classCallCheck(this, Tree);
_this = _super.call(this, props);
_this.state = {
filter: ''
};
if (!_this.props.onToggle) {
_this.state['expandedKeys'] = _this.props.expandedKeys;
}
_this.isNodeLeaf = _this.isNodeLeaf.bind(_assertThisInitialized(_this));
_this.onToggle = _this.onToggle.bind(_assertThisInitialized(_this));
_this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this));
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onDropPoint = _this.onDropPoint.bind(_assertThisInitialized(_this));
_this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this));
_this.onFilterInputKeyDown = _this.onFilterInputKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Tree, [{
key: "getExpandedKeys",
value: function getExpandedKeys() {
return this.props.onToggle ? this.props.expandedKeys : this.state.expandedKeys;
}
}, {
key: "getRootNode",
value: function getRootNode() {
return this.props.filter && this.filteredNodes ? this.filteredNodes : this.props.value;
}
}, {
key: "onToggle",
value: function onToggle(event) {
if (this.props.onToggle) {
this.props.onToggle(event);
} else {
this.setState({
expandedKeys: event.value
});
}
}
}, {
key: "onDragStart",
value: function onDragStart(event) {
this.dragState = {
path: event.path,
index: event.index
};
}
}, {
key: "onDragEnd",
value: function onDragEnd() {
this.dragState = null;
}
}, {
key: "onDrop",
value: function onDrop(event) {
if (this.validateDropNode(this.dragState.path, event.path)) {
var value = JSON.parse(JSON.stringify(this.props.value));
var dragPaths = this.dragState.path.split('-');
dragPaths.pop();
var dragNodeParent = this.findNode(value, dragPaths);
var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index];
var dropNode = this.findNode(value, event.path.split('-'));
if (dropNode.children) dropNode.children.push(dragNode);else dropNode.children = [dragNode];
if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1);
if (this.props.onDragDrop) {
this.props.onDragDrop({
originalEvent: event.originalEvent,
value: value,
dragNode: dragNode,
dropNode: dropNode,
dropIndex: event.index
});
}
}
}
}, {
key: "onDropPoint",
value: function onDropPoint(event) {
if (this.validateDropPoint(event)) {
var value = JSON.parse(JSON.stringify(this.props.value));
var dragPaths = this.dragState.path.split('-');
dragPaths.pop();
var dropPaths = event.path.split('-');
dropPaths.pop();
var dragNodeParent = this.findNode(value, dragPaths);
var dropNodeParent = this.findNode(value, dropPaths);
var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index];
var siblings = this.areSiblings(this.dragState.path, event.path);
if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1);
if (event.position < 0) {
var dropIndex = siblings ? this.dragState.index > event.index ? event.index : event.index - 1 : event.index;
if (dropNodeParent) dropNodeParent.children.splice(dropIndex, 0, dragNode);else value.splice(dropIndex, 0, dragNode);
} else {
if (dropNodeParent) dropNodeParent.children.push(dragNode);else value.push(dragNode);
}
if (this.props.onDragDrop) {
this.props.onDragDrop({
originalEvent: event.originalEvent,
value: value,
dragNode: dragNode,
dropNode: dropNodeParent,
dropIndex: event.index
});
}
}
}
}, {
key: "validateDrop",
value: function validateDrop(dragPath, dropPath) {
if (!dragPath) {
return false;
} else {
//same node
if (dragPath === dropPath) {
return false;
} //parent dropped on an descendant
if (dropPath.indexOf(dragPath) === 0) {
return false;
}
return true;
}
}
}, {
key: "validateDropNode",
value: function validateDropNode(dragPath, dropPath) {
var validateDrop = this.validateDrop(dragPath, dropPath);
if (validateDrop) {
//child dropped on parent
if (dragPath.indexOf('-') > 0 && dragPath.substring(0, dragPath.lastIndexOf('-')) === dropPath) {
return false;
}
return true;
} else {
return false;
}
}
}, {
key: "validateDropPoint",
value: function validateDropPoint(event) {
var validateDrop = this.validateDrop(this.dragState.path, event.path);
if (validateDrop) {
//child dropped to next sibling's drop point
if (event.position === -1 && this.areSiblings(this.dragState.path, event.path) && this.dragState.index + 1 === event.index) {
return false;
}
return true;
} else {
return false;
}
}
}, {
key: "areSiblings",
value: function areSiblings(path1, path2) {
if (path1.length === 1 && path2.length === 1) return true;else return path1.substring(0, path1.lastIndexOf('-')) === path2.substring(0, path2.lastIndexOf('-'));
}
}, {
key: "findNode",
value: function findNode(value, path) {
if (path.length === 0) {
return null;
} else {
var index = parseInt(path[0], 10);
var nextSearchRoot = value.children ? value.children[index] : value[index];
if (path.length === 1) {
return nextSearchRoot;
} else {
path.shift();
return this.findNode(nextSearchRoot, path);
}
}
}
}, {
key: "isNodeLeaf",
value: function isNodeLeaf(node) {
return node.leaf === false ? false : !(node.children && node.children.length);
}
}, {
key: "onFilterInputKeyDown",
value: function onFilterInputKeyDown(event) {
//enter
if (event.which === 13) {
event.preventDefault();
}
}
}, {
key: "onFilterInputChange",
value: function onFilterInputChange(event) {
this.filterChanged = true;
this.setState({
filter: event.target.value
});
}
}, {
key: "filter",
value: function filter() {
if (!this.filterChanged) {
return;
}
if (this.state.filter === '') {
this.filteredNodes = this.props.value;
} else {
this.filteredNodes = [];
var searchFields = this.props.filterBy.split(',');
var filterText = this.state.filter.toLocaleLowerCase(this.props.filterLocale);
var isStrictMode = this.props.filterMode === 'strict';
var _iterator = _createForOfIteratorHelper(this.props.value),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var node = _step.value;
var copyNode = _objectSpread({}, node);
var paramsWithoutNode = {
searchFields: searchFields,
filterText: filterText,
isStrictMode: isStrictMode
};
if (isStrictMode && (this.findFilteredNodes(copyNode, paramsWithoutNode) || this.isFilterMatched(copyNode, paramsWithoutNode)) || !isStrictMode && (this.isFilterMatched(copyNode, paramsWithoutNode) || this.findFilteredNodes(copyNode, paramsWithoutNode))) {
this.filteredNodes.push(copyNode);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
this.filterChanged = false;
}
}, {
key: "findFilteredNodes",
value: function findFilteredNodes(node, paramsWithoutNode) {
if (node) {
var matched = false;
if (node.children) {
var childNodes = _toConsumableArray(node.children);
node.children = [];
var _iterator2 = _createForOfIteratorHelper(childNodes),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var childNode = _step2.value;
var copyChildNode = _objectSpread({}, childNode);
if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) {
matched = true;
node.children.push(copyChildNode);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
if (matched) {
return true;
}
}
}
}, {
key: "isFilterMatched",
value: function isFilterMatched(node, _ref) {
var searchFields = _ref.searchFields,
filterText = _ref.filterText,
isStrictMode = _ref.isStrictMode;
var matched = false;
var _iterator3 = _createForOfIteratorHelper(searchFields),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var field = _step3.value;
var fieldValue = String(_ObjectUtils.default.resolveFieldData(node, field)).toLocaleLowerCase(this.props.filterLocale);
if (fieldValue.indexOf(filterText) > -1) {
matched = true;
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
if (!matched || isStrictMode && !this.isNodeLeaf(node)) {
matched = this.findFilteredNodes(node, {
searchFields: searchFields,
filterText: filterText,
isStrictMode: isStrictMode
}) || matched;
}
return matched;
}
}, {
key: "renderRootChild",
value: function renderRootChild(node, index, last) {
return /*#__PURE__*/_react.default.createElement(_UITreeNode.UITreeNode, {
key: node.key || node.label,
node: node,
index: index,
last: last,
path: String(index),
disabled: this.props.disabled,
selectionMode: this.props.selectionMode,
selectionKeys: this.props.selectionKeys,
onSelectionChange: this.props.onSelectionChange,
metaKeySelection: this.props.metaKeySelection,
contextMenuSelectionKey: this.props.contextMenuSelectionKey,
onContextMenuSelectionChange: this.props.onContextMenuSelectionChange,
onContextMenu: this.props.onContextMenu,
propagateSelectionDown: this.props.propagateSelectionDown,
propagateSelectionUp: this.props.propagateSelectionUp,
onExpand: this.props.onExpand,
onCollapse: this.props.onCollapse,
onSelect: this.props.onSelect,
onUnselect: this.props.onUnselect,
expandedKeys: this.getExpandedKeys(),
onToggle: this.onToggle,
nodeTemplate: this.props.nodeTemplate,
isNodeLeaf: this.isNodeLeaf,
dragdropScope: this.props.dragdropScope,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd,
onDrop: this.onDrop,
onDropPoint: this.onDropPoint
});
}
}, {
key: "renderRootChildren",
value: function renderRootChildren() {
var _this2 = this;
if (this.props.filter) {
this.filterChanged = true;
this.filter();
}
var value = this.getRootNode();
return value.map(function (node, index) {
return _this2.renderRootChild(node, index, index === value.length - 1);
});
}
}, {
key: "renderModel",
value: function renderModel() {
if (this.props.value) {
var rootNodes = this.renderRootChildren();
var contentClass = (0, _ClassNames.classNames)('p-tree-container', this.props.contentClassName);
return /*#__PURE__*/_react.default.createElement("ul", {
className: contentClass,
role: "tree",
"aria-label": this.props.ariaLabel,
"aria-labelledby": this.props.ariaLabelledBy,
style: this.props.contentStyle
}, rootNodes);
}
return null;
}
}, {
key: "renderLoader",
value: function renderLoader() {
if (this.props.loading) {
var icon = (0, _ClassNames.classNames)('p-tree-loading-icon pi-spin', this.props.loadingIcon);
return /*#__PURE__*/_react.default.createElement("div", {
className: "p-tree-loading-overlay p-component-overlay"
}, /*#__PURE__*/_react.default.createElement("i", {
className: icon
}));
}
return null;
}
}, {
key: "renderFilter",
value: function renderFilter() {
if (this.props.filter) {
return /*#__PURE__*/_react.default.createElement("div", {
className: "p-tree-filter-container"
}, /*#__PURE__*/_react.default.createElement("input", {
type: "text",
autoComplete: "off",
className: "p-tree-filter p-inputtext p-component",
placeholder: this.props.filterPlaceholder,
onKeyDown: this.onFilterInputKeyDown,
onChange: this.onFilterInputChange,
disabled: this.props.disabled
}), /*#__PURE__*/_react.default.createElement("span", {
className: "p-tree-filter-icon pi pi-search"
}));
}
return null;
}
}, {
key: "render",
value: function render() {
var className = (0, _ClassNames.classNames)('p-tree p-component', this.props.className, {
'p-tree-selectable': this.props.selectionMode,
'p-tree-loading': this.props.loading,
'p-disabled': this.props.disabled
});
var loader = this.renderLoader();
var content = this.renderModel();
var filter = this.renderFilter();
return /*#__PURE__*/_react.default.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, loader, filter, content);
}
}]);
return Tree;
}(_react.Component);
exports.Tree = Tree;
_defineProperty(Tree, "defaultProps", {
id: null,
value: null,
disabled: false,
selectionMode: null,
selectionKeys: null,
onSelectionChange: null,
contextMenuSelectionKey: null,
onContextMenuSelectionChange: null,
expandedKeys: null,
style: null,
className: null,
contentStyle: null,
contentClassName: null,
metaKeySelection: true,
propagateSelectionUp: true,
propagateSelectionDown: true,
loading: false,
loadingIcon: 'pi pi-spinner',
dragdropScope: null,
filter: false,
filterBy: 'label',
filterMode: 'lenient',
filterPlaceholder: null,
filterLocale: undefined,
nodeTemplate: null,
onSelect: null,
onUnselect: null,
onExpand: null,
onCollapse: null,
onToggle: null,
onDragDrop: null,
onContextMenu: null
});
_defineProperty(Tree, "propTypes", {
id: _propTypes.default.string,
value: _propTypes.default.any,
disabled: _propTypes.default.bool,
selectionMode: _propTypes.default.string,
selectionKeys: _propTypes.default.any,
onSelectionChange: _propTypes.default.func,
contextMenuSelectionKey: _propTypes.default.any,
onContextMenuSelectionChange: _propTypes.default.func,
expandedKeys: _propTypes.default.object,
style: _propTypes.default.object,
className: _propTypes.default.string,
contentStyle: _propTypes.default.object,
contentClassName: _propTypes.default.string,
metaKeySelection: _propTypes.default.bool,
propagateSelectionUp: _propTypes.default.bool,
propagateSelectionDown: _propTypes.default.bool,
loading: _propTypes.default.bool,
loadingIcon: _propTypes.default.string,
dragdropScope: _propTypes.default.string,
filter: _propTypes.default.bool,
filterBy: _propTypes.default.any,
filterMode: _propTypes.default.string,
filterPlaceholder: _propTypes.default.string,
filterLocale: _propTypes.default.string,
nodeTemplate: _propTypes.default.func,
onSelect: _propTypes.default.func,
onUnselect: _propTypes.default.func,
onExpand: _propTypes.default.func,
onCollapse: _propTypes.default.func,
onToggle: _propTypes.default.func,
onDragDrop: _propTypes.default.func,
onContextMenu: _propTypes.default.func
});