import _ from "lodash"; export const s3ContentsToTree = ( s3Contents, props = {}, reducer: (...args: unknown[]) => Record = () => ({}) ) => { let __result = []; let level = { __result, __prefix: "" }; props = Object.assign( { key: "key", label: "label", children: "children", }, props ); s3Contents.forEach((s3Content) => { s3Content.Key.split("/").reduce((r, label, i, a) => { if (!r[label]) { const __prefix = `${r.__prefix ? r.__prefix + "/" : ""}${label}`; r[label] = { __result: [], __prefix }; r.__result.push({ [props.key]: __prefix, [props.label]: label, [props.children]: r[label].__result, // NOTE 这里要小心覆盖掉props.key props.label props.children ...reducer(r, label, i, a, s3Content), }); } return r[label]; }, level); }); return __result; }; export const trimTreeForSideBar = (tree) => {}; type TreeNodeLike = { label?: string; children?: TreeNodeLike[]; __path__?: string[]; } & { [K: string]: unknown }; export const getTreeFlatten = ( treeNode: T, order: "preorder" | "postorder" = "preorder", mode: "all" | "leaf" = "leaf", path: string[] = [] ): (T & TreeNodeLike)[] => { treeNode.__path__ = [...path, treeNode.label ?? ""]; if (treeNode.children?.length) { const result = _.flatMap(treeNode.children as T[], (node) => getTreeFlatten(node, order, mode, treeNode.__path__) ); if (mode === "all") { if (order === "preorder") { result.unshift(treeNode); } else if (order === "postorder") { result.push(treeNode); } } return result; } return [treeNode]; };