Skip to content

AI-native design editor. Open-source Figma alternative.

5.5 KB
Raw Blame
import {
  attachInstruction,
  extractInstruction,
  type ItemMode
} from '@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item'
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'
import {
  draggable,
  dropTargetForElements,
  monitorForElements
} from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
import { onScopeDispose, ref, watchEffect, type Ref } from 'vue'

import { resolveEditorProfile, type Editor } from '@open-pencil/core'

import type { LayerDragInstruction } from '#vue/primitives/LayerTree/context'
import { dropIndex, listsChildrenInFlow } from '#vue/primitives/LayerTree/model'

interface DragItem {
  id: string
  level: number
  hasChildren: boolean
  parentId: string | null
}

type TreeInstruction = LayerDragInstruction

export function useLayerDrag(
  editor: Editor,
  indentPerLevel = 16,
  onMakeChildDrop?: (targetId: string) => void
) {
  const draggingId = ref<string | null>(null)
  const instruction = ref<TreeInstruction | null>(null)
  const instructionTargetId = ref<string | null>(null)

  function setupItem(el: Ref<HTMLElement | null>, item: () => DragItem) {
    watchEffect((onCleanup) => {
      const element = el.value
      if (!element) return

      const data = item()

      const isContainer = editor.graph.isContainer(data.id)
      const mode: ItemMode = data.hasChildren ? 'expanded' : 'standard'
      const parentId = editor.graph.getNode(data.id)?.parentId ?? editor.state.currentPageId
      // Inside an instance only slots take layers; the rest of it comes from its component.
      const acceptsChildren = isContainer && editor.acceptsChildren(data.id)
      const acceptsSiblings = editor.acceptsChildren(parentId)
      const block: Array<'make-child' | 'reorder-above' | 'reorder-below' | 'reparent'> = [
        'reparent',
        ...(acceptsChildren ? [] : (['make-child'] as const)),
        ...(acceptsSiblings ? [] : (['reorder-above', 'reorder-below'] as const))
      ]

      const cleanup = combine(
        draggable({
          element,
          // A read-only document's layers keep their order.
          canDrag: () => acceptsSiblings && resolveEditorProfile(editor.state).edits,
          getInitialData: () => ({ id: data.id }),
          onDragStart: () => {
            draggingId.value = data.id
          },
          onDrop: () => {
            draggingId.value = null
          }
        }),
        dropTargetForElements({
          element,
          getData: ({ input, element: el }) =>
            attachInstruction(
              { id: data.id },
              {
                input,
                element: el,
                indentPerLevel,
                currentLevel: data.level,
                mode,
                block
              }
            ),
          canDrop: ({ source }) => source.data.id !== data.id,
          onDrag: ({ self }) => {
            const inst = extractInstruction(self.data)
            if (!inst || inst.type === 'instruction-blocked') {
              instruction.value = null
              instructionTargetId.value = null
              return
            }
            instruction.value = inst as TreeInstruction
            instructionTargetId.value = data.id
          },
          onDragLeave: () => {
            instruction.value = null
            instructionTargetId.value = null
          },
          onDrop: () => {
            instruction.value = null
            instructionTargetId.value = null
          },
          getIsSticky: () => true
        })
      )

      onCleanup(cleanup)
    })
  }

  const cleanupMonitor = monitorForElements({
    onDrop: ({ source, location }) => {
      const target = location.current.dropTargets.at(0)
      if (!target) return

      const sourceId = source.data.id as string
      const targetId = target.data.id as string
      const rawInstruction = extractInstruction(target.data)
      if (!rawInstruction || rawInstruction.type === 'instruction-blocked') return
      const inst = rawInstruction as TreeInstruction
      if (!sourceId || !targetId) return

      if (editor.graph.isDescendant(targetId, sourceId)) return

      const targetNode = editor.graph.getNode(targetId)
      if (!targetNode) return
      const targetParentId = targetNode.parentId ?? editor.state.currentPageId
      const targetParent = editor.graph.getNode(targetParentId)
      if (!targetParent) return
      const targetIndex = targetParent.childIds.indexOf(targetId)
      const at = (index: number) => dropIndex(targetParent.childIds, sourceId, index)

      // Rows list layers front-most first, so a row above the target is in front of it; in an
      // auto layout they follow the flow, so a row above comes before it.
      const inFlow = listsChildrenInFlow(targetParent)
      if (inst.type === 'reorder-above') {
        editor.reorderChildWithUndo(sourceId, targetParentId, at(targetIndex + (inFlow ? 0 : 1)))
      } else if (inst.type === 'reorder-below') {
        editor.reorderChildWithUndo(sourceId, targetParentId, at(targetIndex + (inFlow ? 1 : 0)))
      } else {
        const container = editor.graph.getNode(targetId)
        if (!container || !editor.graph.isContainer(targetId)) return
        // Into a container on top of its other layers (the top of its rows), or last in its flow.
        editor.reorderChildWithUndo(sourceId, targetId, container.childIds.length)
        onMakeChildDrop?.(targetId)
      }

      draggingId.value = null
      instruction.value = null
      instructionTargetId.value = null
    }
  })
  onScopeDispose(cleanupMonitor)

  return {
    draggingId,
    instruction,
    instructionTargetId,
    setupItem
  }
}