"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var FrameShapeUtil_exports = {};
__export(FrameShapeUtil_exports, {
  FrameShapeUtil: () => FrameShapeUtil,
  defaultEmptyAs: () => defaultEmptyAs
});
module.exports = __toCommonJS(FrameShapeUtil_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_editor = require("@cmpd/editor");
var import_classnames = __toESM(require("classnames"));
var import_ShapeFill = require("../shared/ShapeFill");
var import_createTextSvgElementFromSpans = require("../shared/createTextSvgElementFromSpans");
var import_FrameHeading = require("./components/FrameHeading");
function defaultEmptyAs(str, dflt) {
  if (str.match(/^\s*$/)) {
    return dflt;
  }
  return str;
}
class FrameShapeUtil extends import_editor.BaseBoxShapeUtil {
  static type = "frame";
  static props = import_editor.frameShapeProps;
  static migrations = import_editor.frameShapeMigrations;
  canBind = () => true;
  canEdit = () => true;
  getDefaultProps() {
    return { w: 160 * 2, h: 90 * 2, name: "" };
  }
  getGeometry(shape) {
    return new import_editor.Rectangle2d({
      width: shape.props.w,
      height: shape.props.h,
      isFilled: false
    });
  }
  component(shape) {
    const bounds = this.editor.getShapeGeometry(shape).bounds;
    const theme = (0, import_ShapeFill.useDefaultColorTheme)();
    const isCreating = (0, import_editor.useValue)(
      "is creating this shape",
      () => {
        const resizingState = this.editor.getStateDescendant("select.resizing");
        if (!resizingState)
          return false;
        if (!resizingState.getIsActive())
          return false;
        const info = resizingState?.info;
        if (!info)
          return false;
        return info.isCreating && this.editor.getOnlySelectedShape()?.id === shape.id;
      },
      [shape.id]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_editor.SVGContainer, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        "rect",
        {
          className: (0, import_classnames.default)("tl-frame__body", { "tl-frame__creating": isCreating }),
          width: bounds.width,
          height: bounds.height,
          fill: theme.solid,
          stroke: theme.text
        }
      ) }),
      isCreating ? null : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_FrameHeading.FrameHeading,
        {
          id: shape.id,
          name: shape.props.name,
          width: bounds.width,
          height: bounds.height
        }
      )
    ] });
  }
  toSvg(shape) {
    const theme = (0, import_editor.getDefaultColorTheme)({ isDarkMode: this.editor.user.getIsDarkMode() });
    const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
    const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("width", shape.props.w.toString());
    rect.setAttribute("height", shape.props.h.toString());
    rect.setAttribute("fill", theme.solid);
    rect.setAttribute("stroke", theme.black.solid);
    rect.setAttribute("stroke-width", "1");
    rect.setAttribute("rx", "1");
    rect.setAttribute("ry", "1");
    g.appendChild(rect);
    const pageRotation = (0, import_editor.canonicalizeRotation)(
      this.editor.getShapePageTransform(shape.id).rotation()
    );
    const offsetRotation = pageRotation + Math.PI / 4;
    const scaledRotation = (offsetRotation * (2 / Math.PI) + 4) % 4;
    const labelSide = ["top", "left", "bottom", "right"][Math.floor(scaledRotation)];
    let labelTranslate;
    switch (labelSide) {
      case "top":
        labelTranslate = ``;
        break;
      case "right":
        labelTranslate = `translate(${(0, import_editor.toDomPrecision)(shape.props.w)}px, 0px) rotate(90deg)`;
        break;
      case "bottom":
        labelTranslate = `translate(${(0, import_editor.toDomPrecision)(shape.props.w)}px, ${(0, import_editor.toDomPrecision)(
          shape.props.h
        )}px) rotate(180deg)`;
        break;
      case "left":
        labelTranslate = `translate(0px, ${(0, import_editor.toDomPrecision)(shape.props.h)}px) rotate(270deg)`;
        break;
      default:
        labelTranslate = ``;
    }
    const opts = {
      fontSize: 12,
      fontFamily: "Inter, sans-serif",
      textAlign: "start",
      width: shape.props.w,
      height: 32,
      padding: 0,
      lineHeight: 1,
      fontStyle: "normal",
      fontWeight: "normal",
      overflow: "truncate-ellipsis",
      verticalTextAlign: "middle"
    };
    const spans = this.editor.textMeasure.measureTextSpans(
      defaultEmptyAs(shape.props.name, "Frame") + String.fromCharCode(8203),
      opts
    );
    const firstSpan = spans[0];
    const lastSpan = (0, import_editor.last)(spans);
    const labelTextWidth = lastSpan.box.w + lastSpan.box.x - firstSpan.box.x;
    const text = (0, import_createTextSvgElementFromSpans.createTextSvgElementFromSpans)(this.editor, spans, {
      offsetY: -opts.height - 2,
      ...opts
    });
    text.style.setProperty("transform", labelTranslate);
    const textBg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    textBg.setAttribute("x", "-8px");
    textBg.setAttribute("y", -opts.height - 4 + "px");
    textBg.setAttribute("width", labelTextWidth + 16 + "px");
    textBg.setAttribute("height", `${opts.height}px`);
    textBg.setAttribute("rx", "4px");
    textBg.setAttribute("ry", "4px");
    textBg.setAttribute("fill", theme.background);
    g.appendChild(textBg);
    g.appendChild(text);
    return g;
  }
  indicator(shape) {
    const bounds = this.editor.getShapeGeometry(shape).bounds;
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "rect",
      {
        width: (0, import_editor.toDomPrecision)(bounds.width),
        height: (0, import_editor.toDomPrecision)(bounds.height),
        className: `tl-frame-indicator`
      }
    );
  }
  canReceiveNewChildrenOfType = (shape, _type) => {
    return !shape.isLocked;
  };
  providesBackgroundForChildren() {
    return true;
  }
  canDropShapes = (shape, _shapes) => {
    return !shape.isLocked;
  };
  onDragShapesOver = (frame, shapes) => {
    if (!shapes.every((child) => child.parentId === frame.id)) {
      this.editor.reparentShapes(
        shapes.map((shape) => shape.id),
        frame.id
      );
      return { shouldHint: true };
    }
    return { shouldHint: false };
  };
  onDragShapesOut = (_shape, shapes) => {
    const parent = this.editor.getShape(_shape.parentId);
    const isInGroup = parent && this.editor.isShapeOfType(parent, "group");
    if (isInGroup) {
      this.editor.reparentShapes(shapes, parent.id);
    } else {
      this.editor.reparentShapes(shapes, this.editor.getCurrentPageId());
    }
  };
  onResizeEnd = (shape) => {
    const bounds = this.editor.getShapePageBounds(shape);
    const children = this.editor.getSortedChildIdsForParent(shape.id);
    const shapesToReparent = [];
    for (const childId of children) {
      const childBounds = this.editor.getShapePageBounds(childId);
      if (!bounds.includes(childBounds)) {
        shapesToReparent.push(childId);
      }
    }
    if (shapesToReparent.length > 0) {
      this.editor.reparentShapes(shapesToReparent, this.editor.getCurrentPageId());
    }
  };
  onResize = (shape, info) => {
    return (0, import_editor.resizeBox)(shape, info);
  };
}
//# sourceMappingURL=FrameShapeUtil.js.map
