ItemsTree.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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, useCurrentPagePath } 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. const { data: currentPath } = useCurrentPagePath();
  40. const { data, error } = useTargetAndAncestors();
  41. const { data: ancestorsChildrenData, error: error2 } = useSWRxPageAncestorsChildren(currentPath || null);
  42. if (error != null || error2 != null) {
  43. return null;
  44. }
  45. if (data == null) {
  46. return null;
  47. }
  48. const { targetAndAncestors, rootPage } = data;
  49. let initialNode: ItemNode;
  50. /*
  51. * Before swr response comes back
  52. */
  53. if (ancestorsChildrenData == null) {
  54. initialNode = generateInitialNodeBeforeResponse(targetAndAncestors);
  55. }
  56. /*
  57. * When swr request finishes
  58. */
  59. else {
  60. const { ancestorsChildren } = ancestorsChildrenData;
  61. const rootNode = new ItemNode(rootPage);
  62. initialNode = generateInitialNodeAfterResponse(ancestorsChildren, rootNode);
  63. }
  64. const isOpen = true;
  65. return (
  66. <div className="grw-pagetree p-3">
  67. <Item key={(initialNode as ItemNode).page.path} itemNode={(initialNode as ItemNode)} isOpen={isOpen} />
  68. </div>
  69. );
  70. };
  71. export default ItemsTree;