mirror of
https://github.com/outline/outline.git
synced 2026-11-20 21:23:06 +03:00
43 lines
1.1 KiB
TypeScript
43 lines
1.1 KiB
TypeScript
import type { NavigationNode } from "../types";
|
|
import shallowEqual from "./shallowEqual";
|
|
import naturalSort from "./naturalSort";
|
|
|
|
type Sort = {
|
|
field: string;
|
|
direction: "asc" | "desc";
|
|
};
|
|
|
|
export const sortNavigationNodes = (
|
|
nodes: NavigationNode[],
|
|
sort: Sort,
|
|
sortChildren = true
|
|
): NavigationNode[] => {
|
|
// "index" field is manually sorted and is represented by the documentStructure
|
|
// already saved in the database, no further sort is needed
|
|
if (sort.field === "index") {
|
|
return nodes;
|
|
}
|
|
|
|
const orderedDocs = naturalSort(nodes, sort.field, {
|
|
direction: sort.direction,
|
|
});
|
|
|
|
if (!sortChildren) {
|
|
return orderedDocs;
|
|
}
|
|
|
|
return orderedDocs.map((node) => {
|
|
const sortedChildren = sortNavigationNodes(
|
|
node.children,
|
|
sort,
|
|
sortChildren
|
|
);
|
|
// Preserve the original node reference if children order didn't change.
|
|
// This allows React.memo to skip re-renders of unchanged tree nodes.
|
|
if (shallowEqual(sortedChildren, node.children)) {
|
|
return node;
|
|
}
|
|
return { ...node, children: sortedChildren };
|
|
});
|
|
};
|