import {
  Box2d,
  Vec2d,
  compact
} from "@cmpd/editor";
function removeFrame(editor, ids) {
  const frames = compact(
    ids.map((id) => editor.getShape(id)).filter((f) => f && editor.isShapeOfType(f, "frame"))
  );
  if (!frames.length)
    return;
  const allChildren = [];
  editor.batch(() => {
    frames.map((frame) => {
      const children = editor.getSortedChildIdsForParent(frame.id);
      if (children.length) {
        editor.reparentShapes(children, frame.parentId, frame.index);
        allChildren.push(...children);
      }
    });
    editor.setSelectedShapes(allChildren);
    editor.deleteShapes(ids);
  });
}
const DEFAULT_FRAME_PADDING = 50;
function fitFrameToContent(editor, id, opts = {}) {
  const frame = editor.getShape(id);
  if (!frame)
    return;
  const childIds = editor.getSortedChildIdsForParent(frame.id);
  const children = compact(childIds.map((id2) => editor.getShape(id2)));
  if (!children.length)
    return;
  const bounds = Box2d.FromPoints(
    children.flatMap((shape) => {
      const geometry = editor.getShapeGeometry(shape.id);
      return editor.getShapeLocalTransform(shape).applyToPoints(geometry.vertices);
    })
  );
  const { padding = DEFAULT_FRAME_PADDING } = opts;
  const w = bounds.w + 2 * padding;
  const h = bounds.h + 2 * padding;
  const dx = padding - bounds.minX;
  const dy = padding - bounds.minY;
  if (dx === 0 && dy === 0 && frame.props.w === w && frame.props.h === h)
    return;
  const diff = new Vec2d(dx, dy).rot(frame.rotation);
  editor.batch(() => {
    const changes = childIds.map((child) => {
      const shape = editor.getShape(child);
      return {
        id: shape.id,
        type: shape.type,
        x: shape.x + dx,
        y: shape.y + dy
      };
    });
    changes.push({
      id: frame.id,
      type: frame.type,
      x: frame.x - diff.x,
      y: frame.y - diff.y,
      props: {
        w,
        h
      }
    });
    editor.updateShapes(changes);
  });
}
export {
  DEFAULT_FRAME_PADDING,
  fitFrameToContent,
  removeFrame
};
//# sourceMappingURL=frames.mjs.map
