From 7d6e9f97434d32c8cb66bf95f9563f57c7f725be Mon Sep 17 00:00:00 2001 From: cha0s Date: Sat, 9 Apr 2022 19:41:53 -0500 Subject: [PATCH] feat: tree sorting --- packages/react/src/components/tree/index.jsx | 10 ++++ packages/react/src/components/tree/node.jsx | 48 +++++++++++--------- 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/packages/react/src/components/tree/index.jsx b/packages/react/src/components/tree/index.jsx index dbaae6b..b17d0d3 100644 --- a/packages/react/src/components/tree/index.jsx +++ b/packages/react/src/components/tree/index.jsx @@ -31,4 +31,14 @@ Tree.propTypes = { Tree.displayName = 'Tree'; +Tree.fileSort = (l, r) => { + if (l.nodes && !r.nodes) { + return -1; + } + if (!l.nodes && r.nodes) { + return 1; + } + return l.value < r.value ? -1 : 1; +}; + export default Tree; diff --git a/packages/react/src/components/tree/node.jsx b/packages/react/src/components/tree/node.jsx index a7dfd93..e31d126 100644 --- a/packages/react/src/components/tree/node.jsx +++ b/packages/react/src/components/tree/node.jsx @@ -14,31 +14,33 @@ const Node = (props) => { isCollapsed, nodes, renderLabel, + sort, styles, value, } = props; const children = nodes - ? nodes.map( - ({ - label, - nodes, - styles, - value, - }) => ( - - ), - ) + ? (sort ? nodes.sort(sort) : nodes) + .map( + ({ + label, + nodes, + styles, + value, + }) => ( + + ), + ) : null; let item = renderLabel({...props, builtinStyles}); for (let i = 0; i < indent; ++i) { @@ -98,6 +100,7 @@ Node.defaultProps = { {label} ), + sort: null, styles: {}, }; @@ -109,6 +112,7 @@ const propTypesTree = { // Enough to fool lint. nodes: PropTypes.arrayOf(PropTypes.shape({})), renderLabel: PropTypes.func, + sort: PropTypes.func, styles: PropTypes.shape({ active: PropTypes.string, collapsed: PropTypes.string, @@ -120,7 +124,7 @@ const propTypesTree = { value: PropTypes.string.isRequired, }; -propTypesTree.nodes = PropTypes.arrayOf(propTypesTree); +propTypesTree.nodes = PropTypes.arrayOf(PropTypes.shape(propTypesTree)); Node.propTypes = propTypesTree;