All files / webview-app/src/hooks useCanvasState.ts

100% Statements 106/106
93.24% Branches 69/74
100% Functions 40/40
100% Lines 93/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                          36x 36x   36x 1x     36x 1x 1x       36x 2x 2x 5x   3x   3x 1x 1x     3x 1x   1x       3x     2x     36x 4x 1x     3x 8x 9x   3x 1x     2x 3x 3x 3x   3x   3x 1x     1x 4x 1x           3x 1x   1x       2x 1x           1x         36x 3x 3x 8x   3x 1x     2x 3x 3x   3x 1x     1x 3x 1x   1x       2x 1x 1x 1x     1x         36x   5x   2x 1x     4x 1x 3x 3x   2x 2x 4x     2x         36x 3x 1x 3x       36x   5x 1x 1x     7x 3x           36x 28x   6x   1x       36x 51x       36x                              
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
 
import type { CanvasComponent } from "@/types/canvas";
 
export interface UseCanvasStateResult {
  components: CanvasComponent[];
  selectedComponentId: string | null;
  selectedComponent: CanvasComponent | null;
  setComponents: Dispatch<SetStateAction<CanvasComponent[]>>;
  addComponent: (component: CanvasComponent) => void;
  updateComponent: (id: string, updates: Partial<CanvasComponent>) => void;
  removeComponent: (id: string) => void;
  addChild: (parentId: string, childId: string) => void;
  removeChild: (parentId: string, childId: string) => void;
  getChildren: (componentId: string) => CanvasComponent[];
  getRootComponents: () => CanvasComponent[];
  selectComponent: (id: string | null) => void;
}
 
export function useCanvasState(initialComponents: CanvasComponent[] = []): UseCanvasStateResult {
  const [components, setComponents] = useState<CanvasComponent[]>(initialComponents);
  const [selectedComponentId, setSelectedComponentId] = useState<string | null>(null);
 
  const addComponent = useCallback((component: CanvasComponent) => {
    setComponents((previous) => [...previous, component]);
  }, []);
 
  const updateComponent = useCallback((id: string, updates: Partial<CanvasComponent>) => {
    setComponents((previous) =>
      previous.map((component) => (component.id === id ? { ...component, ...updates } : component)),
    );
  }, []);
 
  const removeComponent = useCallback((id: string) => {
    setComponents((previous) =>
      previous
        .filter((component) => component.id !== id)
        .map((component) => {
          let nextComponent = component;
 
          if (nextComponent.parentId === id) {
            nextComponent = { ...nextComponent };
            delete nextComponent.parentId;
          }
 
          if (nextComponent.children?.includes(id)) {
            nextComponent = {
              ...nextComponent,
              children: nextComponent.children.filter((childId) => childId !== id),
            };
          }
 
          return nextComponent;
        }),
    );
    setSelectedComponentId((previous) => (previous === id ? null : previous));
  }, []);
 
  const addChild = useCallback((parentId: string, childId: string) => {
    if (parentId === childId) {
      return;
    }
 
    setComponents((previous) => {
      const parent = previous.find((component) => component.id === parentId);
      const child = previous.find((component) => component.id === childId);
 
      if (!parent || !child) {
        return previous;
      }
 
      const parentChildren = parent.children ?? [];
      const shouldAddChildToParent = !parentChildren.includes(childId);
      const shouldUpdateChildParent = child.parentId !== parentId;
      const previousParentId = child.parentId;
      const shouldDetachFromPreviousParent =
        previousParentId !== undefined && previousParentId !== parentId;
 
      if (!shouldAddChildToParent && !shouldUpdateChildParent && !shouldDetachFromPreviousParent) {
        return previous;
      }
 
      return previous.map((component) => {
        if (component.id === parentId && shouldAddChildToParent) {
          return {
            ...component,
            children: [...parentChildren, childId],
          };
        }
 
        if (shouldDetachFromPreviousParent && component.id === previousParentId) {
          return {
            ...component,
            children: (component.children ?? []).filter((id) => id !== childId),
          };
        }
 
        if (component.id === childId && shouldUpdateChildParent) {
          return {
            ...component,
            parentId,
          };
        }
 
        return component;
      });
    });
  }, []);
 
  const removeChild = useCallback((parentId: string, childId: string) => {
    setComponents((previous) => {
      const parent = previous.find((component) => component.id === parentId);
      const child = previous.find((component) => component.id === childId);
 
      if (!parent || !child) {
        return previous;
      }
 
      const parentChildren = parent.children ?? [];
      const shouldRemoveChildFromParent = parentChildren.includes(childId);
      const shouldClearChildParent = child.parentId === parentId;
 
      if (!shouldRemoveChildFromParent && !shouldClearChildParent) {
        return previous;
      }
 
      return previous.map((component) => {
        if (component.id === parentId && shouldRemoveChildFromParent) {
          return {
            ...component,
            children: parentChildren.filter((id) => id !== childId),
          };
        }
 
        if (component.id === childId && shouldClearChildParent) {
          const childWithoutParent = { ...component };
          delete childWithoutParent.parentId;
          return childWithoutParent;
        }
 
        return component;
      });
    });
  }, []);
 
  const getChildren = useCallback(
    (componentId: string) => {
      const parent = components.find((component) => component.id === componentId);
 
      if (!parent) {
        return [];
      }
 
      const componentsById = new Map(components.map((component) => [component.id, component]));
      const orderedChildren = (parent.children ?? [])
        .map((childId) => componentsById.get(childId))
        .filter((child): child is CanvasComponent => child !== undefined);
 
      const knownChildIds = new Set(orderedChildren.map((child) => child.id));
      const parentBasedChildren = components.filter(
        (component) => component.parentId === componentId && !knownChildIds.has(component.id),
      );
 
      return [...orderedChildren, ...parentBasedChildren];
    },
    [components],
  );
 
  const getRootComponents = useCallback(() => {
    const componentIds = new Set(components.map((component) => component.id));
    return components.filter(
      (component) => !component.parentId || !componentIds.has(component.parentId),
    );
  }, [components]);
 
  const selectComponent = useCallback(
    (id: string | null) => {
      if (id === null) {
        setSelectedComponentId(null);
        return;
      }
 
      if (components.some((component) => component.id === id)) {
        setSelectedComponentId(id);
      }
    },
    [components],
  );
 
  useEffect(() => {
    if (
      selectedComponentId &&
      !components.some((component) => component.id === selectedComponentId)
    ) {
      setSelectedComponentId(null);
    }
  }, [components, selectedComponentId]);
 
  const selectedComponent = useMemo(
    () => components.find((component) => component.id === selectedComponentId) ?? null,
    [components, selectedComponentId],
  );
 
  return {
    components,
    selectedComponentId,
    selectedComponent,
    setComponents,
    addComponent,
    updateComponent,
    removeComponent,
    addChild,
    removeChild,
    getChildren,
    getRootComponents,
    selectComponent,
  };
}