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

82.43% Statements 230/279
74% Branches 168/227
91.66% Functions 44/48
81.91% Lines 222/271

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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664        2x                                                             50x     4x     4x     3x     17x     1x   21x         12x       4x       16x 13x     3x 3x 2x       1x       13x         3x 3x 3x               67x 67x 18x     119x     49x               33x 33x       33x 33x 11x 11x       33x 33x 81x     33x             20x 20x   20x 49x       49x 37x 37x       20x                 17x 1x     16x   1x   1x   14x                 17x 4x     13x       13x                 16x       16x 16x   16x 16x 16x       16x 1x 1x                       15x       2x                       2x       2x       2x 2x 2x 2x   2x       2x       2x                   2x       2x 2x 2x       2x 2x   2x 2x       2x       2x         2x         2x 2x                               2x 2x                                 2x 2x 2x       2x 2x   2x   2x   2x 2x             2x 2x                         20x 1x     43x 19x 19x   20x 2x     17x 17x 20x 3x     14x 1x     13x 13x     20x       13x 13x 8x   20x 23x   20x           2x       20x 20x 20x   20x 20x 20x 1x       12x       20x 31x 12x 1x     11x 11x   11x 9x   9x 7x         2x     2x 2x     11x     19x 10x       10x 10x           9x 4x       4x 4x           5x     20x       12x 10x     2x 9x 5x 5x 5x 5x 2x 5x   5x   5x   2x       2x 2x 5x 5x       5x     2x             27x 27x 27x 16x       27x   13x 13x 1x     12x         27x 2x 2x     27x   6x 1x 1x     5x 5x 5x 5x 5x         27x   2x 2x 1x     1x 1x 1x       1x               1x         1x 1x   1x 1x             1x                 27x   1x 1x         1x 1x 1x         1x               1x         1x 1x 1x         27x 1x     27x                    
import { useCallback, useMemo, useState } from "react";
 
import type { CanvasComponent } from "@/types/canvas";
 
const HIERARCHY_DRAG_DATA_MIME = "application/x-swing-hierarchy-component";
 
type HierarchyType = "MenuBar" | "Menu" | "MenuItem" | "Panel" | "ToolBar" | "Other";
export type HierarchyDropPosition = "before" | "after" | "inside";
 
interface HierarchyDropInstruction {
  parentId: string | null;
  index: number;
}
 
export interface HierarchyDropTarget {
  componentId: string;
  position: HierarchyDropPosition;
}
 
export interface UseHierarchyDragDropOptions {
  components: CanvasComponent[];
  onMoveComponent: (componentId: string, parentId: string | null, index: number) => void;
}
 
export interface UseHierarchyDragDropResult {
  draggingComponentId: string | null;
  dropTarget: HierarchyDropTarget | null;
  isDraggableComponent: (componentId: string) => boolean;
  handleDragStart: (event: React.DragEvent<HTMLElement>, componentId: string) => void;
  handleDragOver: (event: React.DragEvent<HTMLElement>, targetComponentId: string) => void;
  handleDrop: (event: React.DragEvent<HTMLElement>, targetComponentId: string) => void;
  handleDragEnd: () => void;
}
 
function toHierarchyType(type: string): HierarchyType {
  switch (type) {
    case "MenuBar":
    case "JMenuBar":
      return "MenuBar";
    case "Menu":
    case "JMenu":
      return "Menu";
    case "MenuItem":
    case "JMenuItem":
      return "MenuItem";
    case "Panel":
    case "JPanel":
      return "Panel";
    case "ToolBar":
    case "JToolBar":
      return "ToolBar";
    default:
      return "Other";
  }
}
 
function isMovableType(type: HierarchyType): boolean {
  return type !== "MenuBar" && type !== "ToolBar";
}
 
function canBeRoot(type: HierarchyType): boolean {
  return type !== "Menu" && type !== "MenuItem";
}
 
function areEqualLists(first: readonly string[], second: readonly string[]): boolean {
  if (first.length !== second.length) {
    return false;
  }
 
  for (let index = 0; index < first.length; index += 1) {
    if (first[index] !== second[index]) {
      return false;
    }
  }
 
  return true;
}
 
function clampIndex(index: number, length: number): number {
  return Math.max(0, Math.min(index, length));
}
 
function getDraggingId(dataTransfer: DataTransfer): string | null {
  const dragId =
    dataTransfer.getData(HIERARCHY_DRAG_DATA_MIME) || dataTransfer.getData("text/plain");
  const trimmedDragId = dragId.trim();
  return trimmedDragId.length > 0 ? trimmedDragId : null;
}
 
function resolveParentId(
  componentId: string,
  components: CanvasComponent[],
  componentsById: Map<string, CanvasComponent>,
): string | null {
  const component = componentsById.get(componentId);
  if (component?.parentId && componentsById.has(component.parentId)) {
    return component.parentId;
  }
 
  const explicitParent = components.find((candidate) =>
    (candidate.children ?? []).includes(componentId),
  );
  return explicitParent?.id ?? null;
}
 
function getOrderedChildIds(
  parentId: string,
  components: CanvasComponent[],
  componentsById: Map<string, CanvasComponent>,
): string[] {
  const parent = componentsById.get(parentId);
  Iif (!parent) {
    return [];
  }
 
  const explicitChildren: string[] = [];
  for (const childId of parent.children ?? []) {
    Eif (componentsById.has(childId) && !explicitChildren.includes(childId)) {
      explicitChildren.push(childId);
    }
  }
 
  const explicitChildIds = new Set(explicitChildren);
  const implicitChildren = components
    .filter((candidate) => candidate.parentId === parentId && !explicitChildIds.has(candidate.id))
    .map((candidate) => candidate.id);
 
  return [...explicitChildren, ...implicitChildren];
}
 
function getOrderedRootIds(
  components: CanvasComponent[],
  componentsById: Map<string, CanvasComponent>,
): string[] {
  const rootIds: string[] = [];
  const seen = new Set<string>();
 
  for (const component of components) {
    Iif (seen.has(component.id)) {
      continue;
    }
 
    if (resolveParentId(component.id, components, componentsById) === null) {
      rootIds.push(component.id);
      seen.add(component.id);
    }
  }
 
  return rootIds;
}
 
function resolveDropPosition(event: React.DragEvent<HTMLElement>): "before" | "after" {
  const targetBounds = event.currentTarget.getBoundingClientRect();
  return event.clientY >= targetBounds.top + targetBounds.height / 2 ? "after" : "before";
}
 
function canAcceptChildType(parentType: HierarchyType, childType: HierarchyType): boolean {
  if (childType === "MenuBar" || childType === "ToolBar") {
    return false;
  }
 
  switch (parentType) {
    case "MenuBar":
      return childType === "Menu";
    case "Menu":
      return childType === "Menu" || childType === "MenuItem";
    case "Panel":
      return childType !== "Menu" && childType !== "MenuItem";
    case "ToolBar":
      return childType !== "Panel" && childType !== "Menu" && childType !== "MenuItem";
    default:
      return false;
  }
}
 
function canMoveToParent(childType: HierarchyType, parentType: HierarchyType | null): boolean {
  if (parentType === null) {
    return canBeRoot(childType);
  }
 
  return canAcceptChildType(parentType, childType);
}
 
function isAssignedToParent(component: CanvasComponent, parentId: string | null): boolean {
  return parentId === null ? component.parentId == null : component.parentId === parentId;
}
 
function wouldCreateCycle(
  draggedComponentId: string,
  targetParentId: string,
  components: CanvasComponent[],
  componentsById: Map<string, CanvasComponent>,
): boolean {
  Iif (draggedComponentId === targetParentId) {
    return true;
  }
 
  const visited = new Set<string>([draggedComponentId]);
  const queue = [draggedComponentId];
 
  while (queue.length > 0) {
    const currentId = queue.shift();
    Iif (!currentId) {
      continue;
    }
 
    for (const childId of getOrderedChildIds(currentId, components, componentsById)) {
      Eif (childId === targetParentId) {
        return true;
      }
 
      if (visited.has(childId)) {
        continue;
      }
 
      visited.add(childId);
      queue.push(childId);
    }
  }
 
  return false;
}
 
function shouldForceInsideDrop(draggedType: HierarchyType, targetType: HierarchyType): boolean {
  return (
    (draggedType === "MenuItem" && targetType === "Menu") ||
    (draggedType === "Menu" && targetType === "MenuBar")
  );
}
 
function getDropPositionCandidates(
  event: React.DragEvent<HTMLElement>,
  draggedType: HierarchyType,
  targetType: HierarchyType,
  allowInside: boolean,
): HierarchyDropPosition[] {
  Iif (shouldForceInsideDrop(draggedType, targetType)) {
    return ["inside"];
  }
 
  Iif (!allowInside) {
    return [resolveDropPosition(event)];
  }
 
  const targetBounds = event.currentTarget.getBoundingClientRect();
  const offsetY = event.clientY - targetBounds.top;
  const topThreshold = targetBounds.height * 0.25;
  const bottomThreshold = targetBounds.height * 0.75;
 
  Iif (offsetY <= topThreshold) {
    return ["before", "inside", "after"];
  }
 
  Iif (offsetY >= bottomThreshold) {
    return ["after", "inside", "before"];
  }
 
  return ["inside", "before", "after"];
}
 
function resolveDropInstruction(
  draggedComponentId: string,
  targetComponentId: string,
  dropPosition: HierarchyDropPosition,
  components: CanvasComponent[],
  componentsById: Map<string, CanvasComponent>,
): HierarchyDropInstruction | null {
  Iif (draggedComponentId === targetComponentId) {
    return null;
  }
 
  const draggedComponent = componentsById.get(draggedComponentId);
  const targetComponent = componentsById.get(targetComponentId);
  Iif (!draggedComponent || !targetComponent) {
    return null;
  }
 
  const draggedType = toHierarchyType(draggedComponent.type);
  const targetType = toHierarchyType(targetComponent.type);
 
  Eif (dropPosition === "inside") {
    Iif (!canAcceptChildType(targetType, draggedType)) {
      return null;
    }
 
    Iif (wouldCreateCycle(draggedComponentId, targetComponent.id, components, componentsById)) {
      return null;
    }
 
    const targetChildren = getOrderedChildIds(
      targetComponent.id,
      components,
      componentsById,
    ).filter((childId) => childId !== draggedComponentId);
    return { parentId: targetComponent.id, index: targetChildren.length };
  }
 
  const targetParentId = resolveParentId(targetComponent.id, components, componentsById);
  const targetParent = targetParentId ? componentsById.get(targetParentId) : null;
  const targetParentType = targetParent ? toHierarchyType(targetParent.type) : null;
  Iif (!canMoveToParent(draggedType, targetParentType)) {
    return null;
  }
 
  if (
    targetParentId &&
    wouldCreateCycle(draggedComponentId, targetParentId, components, componentsById)
  ) {
    return null;
  }
 
  const siblings = (
    targetParentId
      ? getOrderedChildIds(targetParentId, components, componentsById)
      : getOrderedRootIds(components, componentsById)
  ).filter((childId) => childId !== draggedComponentId);
  const targetIndex = siblings.indexOf(targetComponent.id);
  Iif (targetIndex < 0) {
    return null;
  }
 
  return {
    parentId: targetParentId,
    index: dropPosition === "after" ? targetIndex + 1 : targetIndex,
  };
}
 
function resolveDropForEvent(
  event: React.DragEvent<HTMLElement>,
  draggedComponentId: string,
  targetComponentId: string,
  components: CanvasComponent[],
  componentsById: Map<string, CanvasComponent>,
): { instruction: HierarchyDropInstruction; position: HierarchyDropPosition } | null {
  const draggedComponent = componentsById.get(draggedComponentId);
  const targetComponent = componentsById.get(targetComponentId);
  Iif (!draggedComponent || !targetComponent) {
    return null;
  }
 
  const draggedType = toHierarchyType(draggedComponent.type);
  const targetType = toHierarchyType(targetComponent.type);
  const allowInside =
    canAcceptChildType(targetType, draggedType) &&
    !wouldCreateCycle(draggedComponentId, targetComponentId, components, componentsById);
  const candidatePositions = getDropPositionCandidates(event, draggedType, targetType, allowInside);
 
  for (const candidatePosition of candidatePositions) {
    const instruction = resolveDropInstruction(
      draggedComponentId,
      targetComponentId,
      candidatePosition,
      components,
      componentsById,
    );
    Eif (instruction) {
      return { instruction, position: candidatePosition };
    }
  }
 
  return null;
}
 
export function moveComponentInHierarchy(
  components: CanvasComponent[],
  componentId: string,
  nextParentId: string | null,
  nextIndex: number,
): CanvasComponent[] {
  if (nextParentId && componentId === nextParentId) {
    return components;
  }
 
  const componentsById = new Map(components.map((component) => [component.id, component]));
  const component = componentsById.get(componentId);
  const nextParent = nextParentId ? componentsById.get(nextParentId) : null;
 
  if (!component || (nextParentId && !nextParent)) {
    return components;
  }
 
  const componentType = toHierarchyType(component.type);
  const nextParentType = nextParent ? toHierarchyType(nextParent.type) : null;
  if (!canMoveToParent(componentType, nextParentType)) {
    return components;
  }
 
  if (nextParentId && wouldCreateCycle(componentId, nextParentId, components, componentsById)) {
    return components;
  }
 
  const currentParentId = resolveParentId(componentId, components, componentsById);
  const currentChildren = currentParentId
    ? getOrderedChildIds(currentParentId, components, componentsById)
    : [];
  Iif (currentParentId && !currentChildren.includes(componentId)) {
    return components;
  }
 
  const sameParent = currentParentId === nextParentId;
  const sourceChildrenWithoutComponent = currentParentId
    ? currentChildren.filter((childId) => childId !== componentId)
    : [];
  const rootChildren = getOrderedRootIds(components, componentsById).filter(
    (childId) => childId !== componentId,
  );
  const targetChildrenBeforeInsert = sameParent
    ? currentParentId
      ? sourceChildrenWithoutComponent
      : rootChildren
    : nextParentId
      ? getOrderedChildIds(nextParentId, components, componentsById).filter(
          (childId) => childId !== componentId,
        )
      : rootChildren;
 
  const insertionIndex = clampIndex(nextIndex, targetChildrenBeforeInsert.length);
  const reorderedTargetChildren = [...targetChildrenBeforeInsert];
  reorderedTargetChildren.splice(insertionIndex, 0, componentId);
 
  const currentOrder = currentParentId ? currentChildren : getOrderedRootIds(components, componentsById);
  const noReorderChange = sameParent && areEqualLists(currentOrder, reorderedTargetChildren);
  if (noReorderChange && isAssignedToParent(component, nextParentId)) {
    return components;
  }
 
  let didChange =
    currentParentId === null &&
    nextParentId === null &&
    !areEqualLists(currentOrder, reorderedTargetChildren);
 
  const updatedComponents = components.map((candidate) => {
    if (candidate.id === componentId) {
      if (isAssignedToParent(candidate, nextParentId)) {
        return candidate;
      }
 
      didChange = true;
      const nextCandidate = { ...candidate };
 
      if (nextParentId) {
        nextCandidate.parentId = nextParentId;
 
        if (nextParent?.type === "Panel") {
          nextCandidate.parentOffset = {
            x: Math.round(nextCandidate.x - nextParent.x),
            y: Math.round(nextCandidate.y - nextParent.y),
          };
        } else {
          delete nextCandidate.parentOffset;
        }
      } else {
        delete nextCandidate.parentId;
        delete nextCandidate.parentOffset;
      }
 
      return nextCandidate;
    }
 
    if (nextParentId && candidate.id === nextParentId) {
      Iif (areEqualLists(candidate.children ?? [], reorderedTargetChildren)) {
        return candidate;
      }
 
      didChange = true;
      return {
        ...candidate,
        children: reorderedTargetChildren,
      };
    }
 
    if (!sameParent && candidate.id === currentParentId) {
      Iif (areEqualLists(candidate.children ?? [], sourceChildrenWithoutComponent)) {
        return candidate;
      }
 
      didChange = true;
      return {
        ...candidate,
        children: sourceChildrenWithoutComponent,
      };
    }
 
    return candidate;
  });
 
  Iif (!didChange) {
    return components;
  }
 
  if (nextParentId) {
    return updatedComponents;
  }
 
  const reorderedRootComponents = reorderedTargetChildren
    .map((id) => updatedComponents.find((candidate) => candidate.id === id))
    .filter((candidate): candidate is CanvasComponent => candidate !== undefined);
  const reorderedRootIds = new Set(reorderedRootComponents.map((candidate) => candidate.id));
  const nonRootComponents = updatedComponents.filter((candidate) => !reorderedRootIds.has(candidate.id));
  const updatedComponentsById = new Map(updatedComponents.map((candidate) => [candidate.id, candidate]));
  const rootInsertionIndexes = updatedComponents
    .map((candidate, index) => ({ candidate, index }))
    .filter(
      ({ candidate }) => resolveParentId(candidate.id, updatedComponents, updatedComponentsById) === null,
    )
    .map(({ index }) => index);
 
  Iif (rootInsertionIndexes.length === 0) {
    return updatedComponents;
  }
 
  const nextComponents = [...nonRootComponents];
  for (const [rootOrderIndex, insertionIndex] of rootInsertionIndexes.entries()) {
    const rootComponent = reorderedRootComponents[rootOrderIndex];
    Iif (!rootComponent) {
      continue;
    }
 
    nextComponents.splice(insertionIndex, 0, rootComponent);
  }
 
  return nextComponents;
}
 
export function useHierarchyDragDrop({
  components,
  onMoveComponent,
}: UseHierarchyDragDropOptions): UseHierarchyDragDropResult {
  const [draggingComponentId, setDraggingComponentId] = useState<string | null>(null);
  const [dropTarget, setDropTarget] = useState<HierarchyDropTarget | null>(null);
  const componentsById = useMemo(
    () => new Map(components.map((component) => [component.id, component])),
    [components],
  );
 
  const isDraggableComponent = useCallback(
    (componentId: string): boolean => {
      const component = componentsById.get(componentId);
      if (!component) {
        return false;
      }
 
      return isMovableType(toHierarchyType(component.type));
    },
    [componentsById],
  );
 
  const resetDragState = useCallback(() => {
    setDraggingComponentId(null);
    setDropTarget(null);
  }, []);
 
  const handleDragStart = useCallback(
    (event: React.DragEvent<HTMLElement>, componentId: string) => {
      if (!isDraggableComponent(componentId)) {
        event.preventDefault();
        return;
      }
 
      event.dataTransfer.effectAllowed = "move";
      event.dataTransfer.setData(HIERARCHY_DRAG_DATA_MIME, componentId);
      event.dataTransfer.setData("text/plain", componentId);
      setDraggingComponentId(componentId);
      setDropTarget(null);
    },
    [isDraggableComponent],
  );
 
  const handleDragOver = useCallback(
    (event: React.DragEvent<HTMLElement>, targetComponentId: string) => {
      const draggedId = getDraggingId(event.dataTransfer) ?? draggingComponentId;
      if (!draggedId) {
        return;
      }
 
      const draggedComponent = componentsById.get(draggedId);
      const targetComponent = componentsById.get(targetComponentId);
      Iif (!draggedComponent || !targetComponent) {
        return;
      }
 
      const resolvedDrop = resolveDropForEvent(
        event,
        draggedId,
        targetComponentId,
        components,
        componentsById,
      );
 
      Iif (!resolvedDrop) {
        setDropTarget(null);
        return;
      }
 
      event.preventDefault();
      event.dataTransfer.dropEffect = "move";
 
      setDropTarget((previous) => {
        Iif (
          previous?.componentId === targetComponentId &&
          previous.position === resolvedDrop.position
        ) {
          return previous;
        }
 
        return {
          componentId: targetComponentId,
          position: resolvedDrop.position,
        };
      });
    },
    [components, componentsById, draggingComponentId],
  );
 
  const handleDrop = useCallback(
    (event: React.DragEvent<HTMLElement>, targetComponentId: string) => {
      const draggedId = getDraggingId(event.dataTransfer) ?? draggingComponentId;
      Iif (!draggedId) {
        resetDragState();
        return;
      }
 
      const draggedComponent = componentsById.get(draggedId);
      const targetComponent = componentsById.get(targetComponentId);
      Iif (!draggedComponent || !targetComponent) {
        resetDragState();
        return;
      }
 
      const resolvedDrop = resolveDropForEvent(
        event,
        draggedId,
        targetComponentId,
        components,
        componentsById,
      );
 
      Iif (!resolvedDrop) {
        resetDragState();
        return;
      }
 
      event.preventDefault();
      onMoveComponent(draggedId, resolvedDrop.instruction.parentId, resolvedDrop.instruction.index);
      resetDragState();
    },
    [components, componentsById, draggingComponentId, onMoveComponent, resetDragState],
  );
 
  const handleDragEnd = useCallback(() => {
    resetDragState();
  }, [resetDragState]);
 
  return {
    draggingComponentId,
    dropTarget,
    isDraggableComponent,
    handleDragStart,
    handleDragOver,
    handleDrop,
    handleDragEnd,
  };
}