Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions libs/shared/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,51 @@ export function makeHierarchy(
};
}

export function cleanItemModel(model: Partial<TreeItemModel>): TreeItemModel {
if (!model.id) throw new Error("Missing id on tree model");

const children = model.children ?? [];

return {
...model, // In case
id: model.id,
children,
hasChildren: children.length > 0,
data: model.data,
isExpanded: model.isExpanded ?? false,
};
}
export function cleanTreeModel(model: Partial<TreeModel>): TreeModel {
const items: TreeModel["items"] = {};
if (model.items) {
for (const itemId in model.items) {
const item = model.items[itemId];
if (!item) {
continue;
}

const cleanedItem = cleanItemModel(item);
const children = [];
for (const child of cleanedItem.children) {
if (child && model.items[child]) {
children.push(child);
}
}

items[itemId] = {
...cleanedItem,
children
};
}
}

return {
...model, // In case
rootId: model.rootId ?? ROOT_ID,
items: items
};
}

const TreeActions = {
addItem,
mutateItem,
Expand All @@ -152,6 +197,8 @@ const TreeActions = {
deleteItem,
flattenTree,
makeHierarchy,
cleanTreeModel,
cleanItemModel
};

export default TreeActions;
2 changes: 1 addition & 1 deletion pages/api/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default api()
.use(useAuth)
.use(useStore)
.get(async (req, res) => {
const tree = await req.state.treeStore.get();
const tree = TreeActions.cleanTreeModel(await req.state.treeStore.get());
const style = req.query['style'];
switch (style) {
case 'hierarchy':
Expand Down