ItemsTree.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import React, { FC } from 'react';
  2. import { IPage } from '../../../interfaces/page';
  3. import { ItemNode } from './ItemNode';
  4. import Item from './Item';
  5. import { useSWRxPageAncestorsChildren } from '../../../stores/page-listing';
  6. import { useTargetAndAncestors } from '../../../stores/context';
  7. import { HasObjectId } from '../../../interfaces/has-object-id';
  8. /*
  9. * Utility to generate initial node
  10. */
  11. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPage>[]): ItemNode => {
  12. const nodes = targetAndAncestors.map((page): ItemNode => {
  13. return new ItemNode(page, []);
  14. });
  15. // update children for each node
  16. const rootNode = nodes.reduce((child, parent) => {
  17. parent.children = [child];
  18. return parent;
  19. });
  20. return rootNode;
  21. };
  22. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPage & HasObjectId>[]>, rootNode: ItemNode): ItemNode => {
  23. const paths = Object.keys(ancestorsChildren);
  24. let currentNode = rootNode;
  25. paths.reverse().forEach((path) => {
  26. const childPages = ancestorsChildren[path];
  27. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  28. const nextNode = currentNode.children.filter((node) => {
  29. return paths.includes(node.page.path as string);
  30. })[0];
  31. currentNode = nextNode;
  32. });
  33. return rootNode;
  34. };
  35. /*
  36. * ItemsTree
  37. */
  38. const ItemsTree: FC = () => {
  39. // TODO: get from static SWR
  40. const path = '/Sandbox/Mathematics';
  41. const { data, error } = useTargetAndAncestors();
  42. const { data: ancestorsChildrenData, error: error2 } = useSWRxPageAncestorsChildren(path);
  43. if (error != null || error2 != null) {
  44. return null;
  45. }
  46. if (data == null) {
  47. return null;
  48. }
  49. const { targetAndAncestors, rootPage } = data;
  50. let initialNode: ItemNode;
  51. /*
  52. * Before swr response comes back
  53. */
  54. if (ancestorsChildrenData == null) {
  55. initialNode = generateInitialNodeBeforeResponse(targetAndAncestors);
  56. }
  57. /*
  58. * When swr request finishes
  59. */
  60. else {
  61. const { ancestorsChildren } = ancestorsChildrenData;
  62. const rootNode = new ItemNode(rootPage);
  63. initialNode = generateInitialNodeAfterResponse(ancestorsChildren, rootNode);
  64. }
  65. const isOpen = true;
  66. return (
  67. <>
  68. <Item key={(initialNode as ItemNode).page.path} itemNode={(initialNode as ItemNode)} isOpen={isOpen} />
  69. </>
  70. );
  71. };
  72. export default ItemsTree;