Skip to content

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

17.8 KB
Raw Blame
export { constrainToAspectRatio } from '#vue/shared/input/resize/rect'
export { tryStartResize } from '#vue/shared/input/resize/start'
import { isEqual } from 'es-toolkit'
import { toRaw } from 'vue'

import { resizedPathTextGlyphs, type Editor } from '@open-pencil/core'
import { computeAllLayouts } from '@open-pencil/core/layout'
import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/core/text'
import type { SceneNode, DerivedTextGlyph, TextPathData } from '@open-pencil/scene-graph'
import {
  cloneVectorNetwork,
  copyDerivedGlyphs,
  copyGeometryPaths,
  copyStrokes
} from '@open-pencil/scene-graph/copy'
import { findInstanceAncestor, recordInstanceOverride } from '@open-pencil/scene-graph/instances'
import {
  cloneInstanceOverrideState,
  type InstanceOverrideState
} from '@open-pencil/scene-graph/instances/overrides'
import { recapturedAspectRatio } from '@open-pencil/scene-graph/layout'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import {
  computeConstrainedResizeChanges,
  scaledGeometryChanges,
  type ResizeSnapshot
} from '@open-pencil/scene-graph/resize'
import { markSourceFieldsEdited } from '@open-pencil/scene-graph/source-metadata'

import { calculateResizeRect } from '#vue/shared/input/resize/rect'
import { draggedSizing, layerSizing } from '#vue/shared/input/resize/sizing'
import { applyResizeSnap, proportionalResizeRect } from '#vue/shared/input/resize/snap'
import { optionalEditorState } from '#vue/shared/input/snap'
import type { DragResize } from '#vue/shared/input/types'

/**
 * Resize path-text glyphs without baking anisotropic scale into fontSize.
 * commandsBlob stays in font units; paint multiplies by fontSize then scaleX/Y.
 * Accumulating scaleX/Y (not fontSize *= avg) keeps non-uniform stretch correct
 * under rotation — see drawDerivedText transform order.
 */
/**
 * Figma resize semantics for imported text-on-path: constant font size,
 * text laid out again along the scaled path (resizedPathTextGlyphs). Used
 * instead of geometric glyph/silhouette scaling whenever the node still has
 * its layout path. Baked node-level silhouettes cannot follow re-placed
 * glyphs, so strokeGeometry is cleared — the renderer rebuilds silhouettes
 * per glyph — and stroke weight stays constant like the font size.
 */
function reflowedPathTextChanges(
  node: SceneNode | undefined,
  orig: Pick<ResizeSnapshot, 'textPathData' | 'textPathBox' | 'derivedTextGlyphs' | 'strokes'>,
  sx: number,
  sy: number
): Partial<SceneNode> | null {
  if (!orig.textPathData || !orig.textPathBox || !orig.derivedTextGlyphs?.length) return null
  const box = {
    x: orig.textPathBox.x * sx,
    y: orig.textPathBox.y * sy,
    width: orig.textPathBox.width * sx,
    height: orig.textPathBox.height * sy
  }
  const glyphs =
    (node && resizedPathTextGlyphs(node, orig.derivedTextGlyphs, orig.textPathBox, box)) ??
    movedPathTextGlyphs(orig.derivedTextGlyphs, orig.textPathData, orig.textPathBox, box)
  if (!glyphs) return null
  return {
    derivedTextGlyphs: glyphs,
    textPathBox: box,
    strokeGeometry: [],
    strokes: copyStrokes(orig.strokes)
  }
}

/** Without the font, the old glyphs move along the path, keeping their spacing. */
function movedPathTextGlyphs(
  glyphs: DerivedTextGlyph[],
  data: TextPathData,
  origBox: Rect,
  box: Rect
): DerivedTextGlyph[] | null {
  const layout = calibratePathTextLayout(glyphs, data, origBox)
  return layout ? reflowPathTextGlyphs(glyphs, data, layout, box) : null
}

/**
 * The ratio a drag keeps, as Figma's handles keep it: a locked layer keeps its own unless Control
 * frees it, and Shift keeps the ratio the drag started from.
 */
function keptAspectRatio(d: DragResize, shiftKey: boolean, ctrlKey: boolean): number | null {
  if (d.lockedAspectRatio !== null && !ctrlKey) return d.lockedAspectRatio
  const { width, height } = d.origRect
  return shiftKey && width > 0 && height > 0 ? width / height : null
}

function resizeChanges(
  d: DragResize,
  type: SceneNode['type'],
  cx: number,
  cy: number,
  shiftKey: boolean,
  editor: Editor,
  ctrlKey: boolean
) {
  const { origRect } = d
  const aspect = keptAspectRatio(d, shiftKey, ctrlKey)
  // Control sets a lock aside even when Shift keeps the same ratio; the commit stores the size.
  d.freesLock = d.lockedAspectRatio !== null && ctrlKey
  const dx = cx - d.startX
  const dy = cy - d.startY
  const newRect =
    aspect !== null
      ? proportionalResizeRect(d, origRect, dx, dy, aspect, editor, ctrlKey)
      : applyResizeSnap(d, calculateResizeRect(d.handle, origRect, dx, dy, null), editor, ctrlKey)

  const changes: Partial<SceneNode> = {
    ...newRect,
    ...scaledGeometryChanges(
      {
        type,
        vectorNetwork: d.origVectorNetwork,
        fillGeometry: d.origFillGeometry,
        strokeGeometry: d.origStrokeGeometry,
        derivedTextGlyphs: d.origDerivedTextGlyphs,
        strokes: d.origStrokes,
        textPathData: d.origTextPathData,
        textPathBox: d.origTextPathBox
      },
      origRect.width,
      origRect.height,
      newRect.width,
      newRect.height
    )
  }
  return { changes, newRect }
}

/**
 * Re-apply the root resize to descendants through the constraint engine, then
 * layer path-text reflow on top: constrained children get their own before/after
 * box, and path text must re-place glyphs along its path rather than scale as a
 * blob (see reflowedPathTextChanges).
 */
function applyConstrainedChildren(
  d: DragResize,
  newRect: Pick<SceneNode, 'width' | 'height'>,
  editor: Editor
) {
  if (!d.origChildren || d.origRect.width <= 0 || d.origRect.height <= 0) return
  const changes = computeConstrainedResizeChanges(
    editor.graph,
    d.nodeId,
    d.origRect,
    newRect,
    d.origChildren
  )
  for (const [childId, childChanges] of changes) {
    const orig = d.origChildren.get(childId)
    if (orig && orig.width > 0 && orig.height > 0) {
      const width = childChanges.width ?? orig.width
      const height = childChanges.height ?? orig.height
      const reflow = reflowedPathTextChanges(
        editor.graph.getNode(childId),
        orig,
        width / orig.width,
        height / orig.height
      )
      if (reflow) Object.assign(childChanges, reflow)
    }
    editor.graph.updateNodePreview(childId, childChanges)
    editor.renderer?.invalidateVectorPath(childId)
  }
}

/** Control both frees a locked ratio and turns snapping off, as in Figma. */
export function applyResize(
  dragState: DragResize,
  cx: number,
  cy: number,
  shiftKey: boolean,
  editor: Editor,
  ctrlKey = false
) {
  // Drag state lives in Vue-reactive input state; nested arrays read through
  // it are reactive proxies. Writing those into the graph poisons it for
  // structuredClone consumers (export subgraph clone, undo snapshots) with
  // DataCloneError. Unwrap once — also keeps the drag hot path off proxies.
  const d = toRaw(dragState)
  const node = editor.graph.getNode(d.nodeId)
  if (!node) return
  const { changes, newRect } = resizeChanges(d, node.type, cx, cy, shiftKey, editor, ctrlKey)
  d.appliedRect = { ...newRect }
  d.origSizing ??= layerSizing(node)
  d.appliedSizing = draggedSizing(editor.graph, node, d.origSizing, d.origRect, newRect)
  Object.assign(changes, d.appliedSizing)
  markResized(d, newRect, editor)
  if (d.origRect.width > 0 && d.origRect.height > 0) {
    const reflow = reflowedPathTextChanges(
      node,
      {
        textPathData: d.origTextPathData,
        textPathBox: d.origTextPathBox,
        derivedTextGlyphs: d.origDerivedTextGlyphs,
        strokes: d.origStrokes
      },
      newRect.width / d.origRect.width,
      newRect.height / d.origRect.height
    )
    if (reflow) Object.assign(changes, reflow)
  }
  editor.graph.updateNodePreview(d.nodeId, changes)
  if (changes.fillGeometry || changes.strokeGeometry || changes.vectorNetwork) {
    editor.renderer?.invalidateVectorPath(d.nodeId)
  }

  // Two passes around the layout run: the first sizes children so Yoga can
  // resolve HUG/FILL, the second re-applies against the settled boxes.
  applyConstrainedChildren(d, newRect, editor)
  editor.graph.runPreviewUpdates(() => computeAllLayouts(editor.graph, d.nodeId))
  applyConstrainedChildren(d, newRect, editor)
  editor.graph.runPreviewUpdates(() => computeAllLayouts(editor.graph, d.nodeId))
  editor.requestRepaint()
}

/**
 * Deep-copy geometry read back from a previewed node — preview values can
 * be reactivity-wrapped, and storing proxies breaks structuredClone snapshots
 * (delete/undo would throw DataCloneError).
 */
function snapshotResizeFinal(node: SceneNode, hadStrokeGeometry: boolean): Partial<SceneNode> {
  const final: Partial<SceneNode> = {
    x: node.x,
    y: node.y,
    width: node.width,
    height: node.height
  }
  if (node.vectorNetwork) final.vectorNetwork = cloneVectorNetwork(node.vectorNetwork)
  if (node.fillGeometry.length > 0) final.fillGeometry = copyGeometryPaths(node.fillGeometry)
  // Path-text reflow and a resize that redraws a stroke at its weight legitimately EMPTY
  // strokeGeometry — commit it so the pre-resize outlines don't resurrect. A node that had none
  // keeps the length guard: a spurious strokeGeometry key would clear its raw Figma payload.
  if (node.strokeGeometry.length > 0 || node.textPathBox || hadStrokeGeometry) {
    final.strokeGeometry = copyGeometryPaths(node.strokeGeometry)
  }
  if (node.derivedTextGlyphs?.length) {
    final.derivedTextGlyphs = copyDerivedGlyphs(node.derivedTextGlyphs)
  }
  if (node.textPathBox) final.textPathBox = { ...node.textPathBox }
  if (node.textPathData) final.textPathData = structuredClone(node.textPathData)
  if (node.strokes.length > 0) final.strokes = copyStrokes(node.strokes)
  return final
}

/**
 * Resize commits run inside preserveSourceMetadataDuring so the raw Figma
 * payload (vectorData, textPathStart, effects, ...) survives — but the
 * geometry-derived raw fields are now stale and export PREFERS them over
 * node values (rawSize would resurrect the pre-resize dimensions in the
 * exported file). Invalidate exactly those.
 */
function clearResizedRawGeometry(editor: Editor, nodeId: string): void {
  const node = editor.graph.getNode(nodeId)
  if (!node) return
  node.source.fig.rawSize = null
  node.source.fig.rawTransform = null
  const raw = node.source.fig.rawNodeFields
  delete raw.fillGeometry
  delete raw.strokeGeometry
  delete raw.strokeWeight
  // vectorData is dual-use: for VECTOR nodes it gates nodeForGeometryExport —
  // leaving it makes export pair stale raw vectorData with styleID-less
  // explicit paths (multi-color icons turn gray). For TEXT it is the
  // TEXT_PATH layout path and must survive or reflow dies.
  if (node.type !== 'TEXT') delete raw.vectorData
}

const RECT_FIELDS = ['x', 'y', 'width', 'height'] as const

function sameRect(a: Rect, b: Rect): boolean {
  return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height
}

/**
 * Resizing keeps the raw payload a file gave the layer but not its size, so once the drag
 * changes the rect, layout lays out a resized frame from a .fig again, during the drag too,
 * instead of keeping the sizes it saved.
 */
function markResized(d: DragResize, rect: Rect, editor: Editor) {
  const node = editor.graph.getNode(d.nodeId)
  if (!node || d.origEditedFields || sameRect(rect, d.origRect)) return
  d.origEditedFields = [...node.source.editedFields]
  markSourceFieldsEdited(node, ['width', 'height'])
}

/** A drag that ends where it began, or is cancelled, leaves the layer's edits as they were. */
function restoreEditedFields(d: DragResize, editor: Editor) {
  const node = editor.graph.getNode(d.nodeId)
  if (node && d.origEditedFields) node.source.editedFields = d.origEditedFields
  d.origEditedFields = undefined
}

function restoreResizePreview(d: DragResize, editor: Editor) {
  editor.graph.updateNodePreview(d.nodeId, d.origRect)
  for (const [childId, orig] of d.origChildren ?? []) {
    editor.graph.updateNodePreview(childId, {
      x: orig.x,
      y: orig.y,
      width: orig.width,
      height: orig.height,
      vectorNetwork: orig.vectorNetwork,
      fillGeometry: orig.fillGeometry,
      strokeGeometry: orig.strokeGeometry,
      derivedTextGlyphs: orig.derivedTextGlyphs,
      strokes: orig.strokes,
      textPathData: orig.textPathData,
      textPathBox: orig.textPathBox
    })
  }
}

/** Puts a resize the pointer abandoned back where it started. */
export function cancelResizePreview(dragState: DragResize, editor: Editor) {
  const d = toRaw(dragState)
  optionalEditorState(editor)?.snapGuides.splice(0)
  restoreResizePreview(d, editor)
  // The preview scaled the layer's own geometry too, which a commit would have replaced.
  editor.graph.updateNodePreview(d.nodeId, {
    vectorNetwork: d.origVectorNetwork,
    fillGeometry: d.origFillGeometry,
    strokeGeometry: d.origStrokeGeometry,
    derivedTextGlyphs: d.origDerivedTextGlyphs,
    strokes: d.origStrokes,
    textPathData: d.origTextPathData,
    textPathBox: d.origTextPathBox
  })
  if (d.origSizing) editor.graph.updateNodePreview(d.nodeId, d.origSizing)
  editor.renderer?.invalidateVectorPath(d.nodeId)
  restoreEditedFields(d, editor)
  editor.graph.runPreviewUpdates(() => computeAllLayouts(editor.graph, d.nodeId))
  editor.requestRender()
}

export function commitResizePreview(dragState: DragResize, editor: Editor) {
  // See applyResize — reactive drag state must not leak into graph writes.
  const d = toRaw(dragState)
  const node = editor.graph.getNode(d.nodeId)
  // A section resized over layers takes in the ones it now covers, a lock that Control set aside
  // takes the new size, and an axis that stopped hugging or filling stays fixed, in one undo step.
  const adoptsLayers = node?.type === 'SECTION'
  const recaptured = node && d.freesLock ? recapturedAspectRatio(node, node.width, node.height) : {}
  const fixesSizing =
    d.origSizing !== undefined &&
    d.appliedSizing !== undefined &&
    !isEqual(d.origSizing, d.appliedSizing)
  if (!adoptsLayers && !recaptured.targetAspectRatio && !fixesSizing) {
    commitResizeGeometry(d, editor)
    return
  }
  editor.undo.runBatch('Resize', () => {
    // Recorded from the sizing the layer started with, so undo puts it back.
    if (fixesSizing && d.origSizing && d.appliedSizing) {
      editor.graph.updateNodePreview(d.nodeId, d.origSizing)
      editor.updateNodeWithUndo(d.nodeId, d.appliedSizing, 'Resize')
    }
    commitResizeGeometry(d, editor)
    if (recaptured.targetAspectRatio) editor.updateNodeWithUndo(d.nodeId, recaptured, 'Resize')
    if (adoptsLayers) editor.adoptCoveredLayers(d.nodeId)
  })
}

/**
 * Runs a resize that moves layers by their constraints while recording only the box fields the
 * resize changed on the resized layer as an instance override: in Figma a layer inside an instance that its constraints
 * place keeps following the component, so a later component edit still reaches it.
 */
function keepingOnlyOwnOverrides(
  editor: Editor,
  nodeId: string,
  ownFields: readonly string[],
  placedIds: readonly string[],
  commit: () => void
) {
  const owners = new Map<string, InstanceOverrideState>()
  for (const id of [nodeId, ...placedIds]) {
    const owner = findInstanceAncestor(editor.graph, id)
    if (owner && !owners.has(owner.id))
      owners.set(owner.id, cloneInstanceOverrideState(owner.instanceOverrides))
  }
  commit()
  for (const [id, state] of owners) editor.graph.updateNode(id, { instanceOverrides: state })
  if (owners.size > 0) recordInstanceOverride(editor.graph, nodeId, ownFields)
}

function commitResizeGeometry(d: DragResize, editor: Editor) {
  optionalEditorState(editor)?.snapGuides.splice(0)
  const node = editor.graph.getNode(d.nodeId)
  if (!node) return
  if (!d.appliedRect || sameRect(d.appliedRect, d.origRect)) restoreEditedFields(d, editor)
  const finalChanges = snapshotResizeFinal(node, d.origStrokeGeometry.length > 0)

  if (d.origChildren) {
    const finalChildren = new Map<string, Partial<SceneNode>>()
    for (const [childId, original] of d.origChildren) {
      const child = editor.graph.getNode(childId)
      if (!child) continue
      finalChildren.set(childId, snapshotResizeFinal(child, original.strokeGeometry.length > 0))
    }
    restoreResizePreview(d, editor)
    // Resize is geometric — the raw Figma import payload (vectorData,
    // textPathStart, effects, ...) must survive or path-text reflow works
    // exactly once and export fidelity degrades.
    keepingOnlyOwnOverrides(
      editor,
      d.nodeId,
      RECT_FIELDS.filter((key) => finalChanges[key] !== d.origRect[key]),
      [...finalChildren.keys()],
      () => {
        editor.graph.preserveSourceMetadataDuring(() => {
          editor.updateNode(d.nodeId, finalChanges)
          for (const [childId, final] of finalChildren) {
            editor.updateNode(childId, final)
          }
        })
      }
    )
    clearResizedRawGeometry(editor, d.nodeId)
    for (const [childId] of finalChildren) clearResizedRawGeometry(editor, childId)
    editor.commitGroupResize(d.nodeId, d.origRect, d.origChildren)
    editor.requestRepaint()
  } else {
    editor.graph.updateNodePreview(d.nodeId, d.origRect)
    // See the group branch — raw import payload survives geometric commits.
    editor.graph.preserveSourceMetadataDuring(() => {
      editor.updateNode(d.nodeId, finalChanges)
    })
    clearResizedRawGeometry(editor, d.nodeId)
    const original: Parameters<typeof editor.commitResize>[1] = { ...d.origRect }
    if (d.origVectorNetwork || node.vectorNetwork) original.vectorNetwork = d.origVectorNetwork
    if (d.origFillGeometry.length > 0) original.fillGeometry = d.origFillGeometry
    if (d.origStrokeGeometry.length > 0) original.strokeGeometry = d.origStrokeGeometry
    if (d.origDerivedTextGlyphs?.length) original.derivedTextGlyphs = d.origDerivedTextGlyphs
    if (d.origStrokes.length > 0) original.strokes = d.origStrokes
    if (d.origTextPathData) original.textPathData = d.origTextPathData
    if (d.origTextPathBox) original.textPathBox = d.origTextPathBox
    editor.commitResize(d.nodeId, original)
  }
}