var B = Object.defineProperty;
var q = (n, l, e) => l in n ? B(n, l, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[l] = e;
var p = (n, l, e) => q(n, typeof l != "symbol" ? l + "" : l, e);
import { m as I, T as R, l as y, r as j, e as U, s as Y, Q as D, f as M, p as z } from "./index-B_vi5hpq.js";
import { randomId as C, blotName as d, TableColFormat as G, TableCellFormat as E, TableCellInnerFormat as x, tableUpSize as _ } from "./index-CE4rH_Gv.js";
import { c as $ } from "./TableUpLogical-Cn6AxmlC.js";
import { isVideoUrl as K, normalizeVideoUrl as Q } from "./Video-1qPHq5DJ.js";
const T = D.import("delta"), X = D.import("modules/clipboard"), J = /<table[\s>]/i, H = /* @__PURE__ */ new Set(["", "transparent", "rgba(0,0,0,0)", "rgba(0, 0, 0, 0)"]), N = "data-aeditor-empty-row";
function k(n) {
  if (typeof n == "number" && Number.isFinite(n)) {
    const l = Math.floor(n);
    return l > 0 ? l : 1;
  }
  if (typeof n == "string") {
    const l = Number.parseInt(n.trim(), 10);
    if (Number.isFinite(l) && l > 0) return l;
  }
  return 1;
}
function L(n) {
  return K(n) ? new T().insert({
    video: Q(n)
  }).insert(`
`) : null;
}
const v = globalThis;
function Z() {
  if (v.__AEDITOR_TABLE_CLIPBOARD_STYLES_PATCHED__) return;
  const n = /* @__PURE__ */ new Set([...E.allowStyle, ...M]);
  E.allowStyle = n, x.allowStyle = /* @__PURE__ */ new Set([...x.allowStyle, ...M]), v.__AEDITOR_TABLE_CLIPBOARD_STYLES_PATCHED__ = !0;
}
function F(n) {
  let l = Number.parseFloat(n.getAttribute("width") || "");
  if (Number.isNaN(l)) {
    const e = n.style.width;
    l = e ? Number.parseFloat(e) : n.offsetWidth;
  }
  return l || _.colDefaultWidth;
}
function V(n, l) {
  const e = Number.parseFloat(l.getComputedStyle(n).width);
  return Number.isFinite(e) && e > 0 ? e : F(n);
}
function W(n, l, e = F) {
  const t = new Array(l).fill(_.colDefaultWidth), o = Array.from(n.querySelectorAll("tr")), r = [];
  for (const i of o) {
    const c = Array.from(i.querySelectorAll("td, th"));
    let s = A(0, O(r));
    for (const a of c) {
      const h = Math.max(a.colSpan || 1, 1);
      if (s = A(s, r), s >= l) break;
      P(r, s, h, a.rowSpan || 1);
      const b = e(a) / h;
      for (let u = 0; u < h && s + u < l; u += 1)
        t[s + u] = b || t[s + u];
      s += h;
    }
  }
  return t;
}
function w(n) {
  const l = Math.round(n * 100) / 100;
  return Number.isFinite(l) && l > 0 ? l : _.colDefaultWidth;
}
function tt(n, l) {
  const e = n == null ? void 0 : n.width;
  let t;
  if (typeof e == "number") t = e;
  else if (typeof e == "string") t = Number.parseFloat(e);
  else return w(l);
  return Number.isFinite(t) && t > 0 ? w(t) : w(l);
}
function et(n, l) {
  return typeof (n == null ? void 0 : n.full) == "boolean" ? n.full : Object.hasOwn(l.dataset, "full") || l.querySelector("col[data-full], colgroup[data-full]") !== null;
}
function ot(n) {
  if (!n) return;
  const l = z(n)["background-color"];
  if (!(!l || H.has(l)))
    return l;
}
function rt(n, l, e) {
  let t = n;
  for (; t; ) {
    const o = t === n ? e.getComputedStyle(t).getPropertyValue("background-color").trim() : e.getComputedStyle(t).backgroundColor.trim();
    if (o && !H.has(o)) return o;
    if (t === l) break;
    t = t.parentElement;
  }
}
function O(n) {
  for (let l = 0; l < n.length; l += 1)
    n[l] > 0 && (n[l] -= 1);
  return n;
}
function A(n, l) {
  let e = n;
  for (; l[e] > 0; ) e += 1;
  return e;
}
function P(n, l, e, t) {
  if (!(t <= 1))
    for (let o = 0; o < e; o += 1)
      n[l + o] = Math.max(n[l + o] || 0, t);
}
class dt extends X {
  constructor(e, t) {
    Z();
    super(e, t);
    p(this, "matchCaptionHandler", (e, t) => this.matchCaption(e, t));
    p(this, "matchColHandler", (e, t) => this.matchCol(e, t));
    p(this, "matchColgroupHandler", (e, t) => this.matchColgroup(e, t));
    p(this, "matchTableHandler", (e, t) => this.matchTable(e, t));
    p(this, "matchTbodyHandler", (e, t) => this.matchTbody(e, t));
    p(this, "matchTdAttributorHandler", (e, t) => this.matchTdAttributor(e, t));
    p(this, "matchTdHandler", (e, t) => this.matchTd(e, t));
    p(this, "matchTheadHandler", (e, t) => this.matchThead(e, t));
    p(this, "matchTrHandler", (e, t) => this.matchTr(e, t));
    p(this, "matchTfootHandler", (e, t) => this.matchTfoot(e, t));
    p(this, "matchYouTubeLinkHandler", (e, t) => this.matchYouTubeLink(e, t));
    p(this, "tableId", C());
    p(this, "rowId", C());
    p(this, "colIds", []);
    p(this, "rowspanCount", []);
    p(this, "cellCount", 0);
    p(this, "colCount", 0);
    this.quill = e, this.addMatcher("a", this.matchYouTubeLinkHandler), this.addMatcher("table", this.matchTableHandler), this.addMatcher("thead", this.matchTheadHandler), this.addMatcher("tbody", this.matchTbodyHandler), this.addMatcher("tfoot", this.matchTfootHandler), this.addMatcher("colgroup", this.matchColgroupHandler), this.addMatcher("col", this.matchColHandler), this.addMatcher("tr", this.matchTrHandler), this.addMatcher("td", this.matchTdHandler), this.addMatcher("th", this.matchTdHandler), this.addMatcher("caption", this.matchCaptionHandler), this.addMatcher(Node.ELEMENT_NODE, this.matchTdAttributorHandler);
  }
  resetTableState() {
    this.tableId = C(), this.rowId = C(), this.colIds = [], this.rowspanCount = [], this.cellCount = 0, this.colCount = 0;
  }
  getStyleBackgroundColor(e, t) {
    var r;
    const o = e.style.backgroundColor;
    if (o)
      for (const i of t.ops) {
        if (!((r = i.attributes) != null && r[d.tableCellInner])) continue;
        const {
          style: c,
          ...s
        } = i.attributes[d.tableCellInner];
        if (ot(c)) continue;
        const a = I(c, `background-color:${o}`);
        i.attributes[d.tableCellInner] = {
          ...s,
          style: a
        };
      }
  }
  matchYouTubeLink(e, t) {
    const r = e.getAttribute("href") || "";
    return L(r) ?? t;
  }
  readPreprocessedColumnWidths(e) {
    const t = e.getAttribute(R);
    if (!t) return null;
    const o = t.split(",").map((r) => Number.parseFloat(r)).filter((r) => Number.isFinite(r) && r > 0).map((r) => w(r));
    return o.length ? o : null;
  }
  matchTable(e, t) {
    if (t.ops.length === 0) return t;
    const o = [], r = [];
    let i = -1;
    for (const m of t.ops) {
      const {
        attributes: b,
        insert: u
      } = m;
      if (!y.isObject(u) && (!b || !b[d.tableCellInner] && !b[d.tableCaption]))
        continue;
      const {
        table: g,
        [d.tableCell]: S,
        ...f
      } = b || {};
      if (y.isObject(u) && u[d.tableCol]) {
        r.push({
          insert: u
        });
        continue;
      }
      o.push({
        attributes: f,
        insert: u
      }), !(f != null && f[d.tableCellInner]) && !(f != null && f[d.tableCaption]) && y.isString(u) && u.trim().length > 0 && (i = o.length - 1);
    }
    const c = e, a = (this.readPreprocessedColumnWidths(c) ?? W(c, this.colIds.length)).map((m, b) => {
      var f;
      const u = (f = r[b]) == null ? void 0 : f.insert, g = y.isObject(u) ? u[d.tableCol] : void 0, S = y.isObject(g) ? g : void 0;
      return {
        insert: {
          [d.tableCol]: {
            ...S,
            tableId: this.tableId,
            colId: this.colIds[b],
            width: tt(S, m),
            full: et(S, c)
          }
        }
      };
    });
    o.splice(i + 1, 0, ...a);
    const h = new T(o);
    return this.getStyleBackgroundColor(e, h), this.resetTableState(), h;
  }
  createEmptyRowIdsForPlainInsert(e) {
    let t = 0;
    e && (t = y.isString(e) ? e.split(`
`).length - 1 : 1);
    const o = [];
    for (let r = 0; r < t; r += 1) o.push(C());
    return o;
  }
  mergeEmptyRowsIntoCellValue(e, t) {
    const o = k(e.rowspan), r = Math.max(o - 1, 0);
    if (t.length === 0 || r === 0) return;
    const i = t.slice(0, r);
    e.emptyRow ?? (e.emptyRow = []), i.length > e.emptyRow.length && e.emptyRow.push(...i.slice(e.emptyRow.length));
  }
  matchTbody(e, t) {
    var r, i;
    this.getStyleBackgroundColor(e, t);
    let o = [];
    for (let c = t.ops.length - 1; c >= 0; c -= 1) {
      const s = t.ops[c];
      if (!((r = s.attributes) != null && r[d.tableCellInner])) {
        o = (i = s.attributes) != null && i[N] ? this.createEmptyRowIdsForPlainInsert(s.insert) : [];
        continue;
      }
      const a = s.attributes[d.tableCellInner];
      if (k(a.rowspan) <= 1) {
        o = [];
        continue;
      }
      this.mergeEmptyRowsIntoCellValue(a, o);
    }
    return this.rowspanCount = [], t;
  }
  matchThead(e, t) {
    const o = this.matchTbody(e, t);
    return this.applySectionWrapTag(o, "thead"), o;
  }
  matchTfoot(e, t) {
    const o = this.matchTbody(e, t);
    return this.applySectionWrapTag(o, "tfoot"), o;
  }
  applySectionWrapTag(e, t) {
    var o;
    for (const r of e.ops)
      (o = r.attributes) != null && o[d.tableCellInner] && (r.attributes[d.tableCellInner].wrapTag = t);
  }
  matchColgroup(e, t) {
    const o = t.ops.filter((r) => y.isObject(r.insert) && r.insert[d.tableCol]);
    return new T(o);
  }
  matchCol(e, t) {
    let o = Number.parseInt(e.getAttribute("span") || "1", 10);
    (Number.isNaN(o) || o < 1) && (o = 1);
    const r = new T();
    for (let i = 0; i < o; i += 1)
      this.colIds[this.colCount] = C(), r.insert({
        [d.tableCol]: Object.assign(G.value(e), {
          tableId: this.tableId,
          colId: this.colIds[this.colCount]
        })
      }), this.colCount += 1;
    return r;
  }
  matchTr(e, t) {
    return this.rowId = C(), this.cellCount = A(0, O(this.rowspanCount)), this.getStyleBackgroundColor(e, t), t.ops.length === 0 ? new T([{
      attributes: {
        [N]: !0
      },
      insert: `
`
    }]) : t;
  }
  matchTd(e, t) {
    const o = e, r = E.formats(o), i = Math.max(r.colspan || 1, 1);
    this.cellCount = A(this.cellCount, this.rowspanCount), this.ensureColumnSlots(this.cellCount + i), P(this.rowspanCount, this.cellCount, i, r.rowspan || 1);
    const c = this.colIds[this.cellCount];
    this.cellCount += i;
    const s = Object.assign(r, {
      tableId: this.tableId,
      rowId: this.rowId,
      colId: c
    });
    this.handleBorderNoneStyles(o, s);
    const a = t.ops.map((m) => {
      const {
        attributes: b = {},
        ...u
      } = m, {
        [d.tableCell]: g,
        ...S
      } = b;
      return {
        ...u,
        attributes: {
          ...S,
          [d.tableCellInner]: s
        }
      };
    }), h = a.at(-1);
    return (!a.length || !y.isString(h == null ? void 0 : h.insert) || !h.insert.endsWith(`
`)) && a.push({
      insert: `
`,
      attributes: {
        [d.tableCellInner]: s
      }
    }), new T(a);
  }
  ensureColumnSlots(e) {
    for (let t = 0; t < e; t += 1)
      this.colIds[t] || (this.colIds[t] = C()), typeof this.rowspanCount[t] != "number" && (this.rowspanCount[t] = 0);
  }
  handleBorderNoneStyles(e, t) {
    if (!t.style) return;
    const o = ["border", "border-top-style", "border-right-style", "border-bottom-style", "border-left-style"];
    let r = t.style;
    o.filter((i) => e.style.getPropertyValue(i) === "none").forEach((i) => {
      r = r.replaceAll(new RegExp(String.raw`${i}\s*:\s*none;?`, "gi"), "");
    }), t.style = I(r);
  }
  matchTdAttributor(e, t) {
    const o = e;
    if (o.tagName.toLowerCase() !== "td" && o.tagName.toLowerCase() !== "th") return t;
    const r = [];
    for (const i of t.ops) {
      const {
        attributes: c,
        ...s
      } = i, a = c == null ? void 0 : c[d.tableCellInner];
      if (c && (a != null && a.style)) {
        const {
          background: h,
          ...m
        } = c, b = document.createElement("div");
        b.style.background = h;
        const u = document.createElement("div");
        if (u.style.cssText = a.style, b.style.background === u.style.backgroundColor) {
          r.push({
            ...s,
            attributes: {
              ...m
            }
          });
          continue;
        }
      }
      r.push(i);
    }
    return new T(r);
  }
  convert({
    html: e,
    text: t
  }, o = {}) {
    const r = (t == null ? void 0 : t.trim()) ?? "", i = !e && r ? L(r) : null;
    if (i) return i;
    if (e && J.test(e)) {
      const s = e;
      try {
        const a = new DOMParser().parseFromString(s, "text/html");
        this.preprocessTableHtml(a), e = a.body.innerHTML;
      } catch (a) {
        console.warn("Failed to preprocess pasted table HTML.", a), e = s;
      }
    }
    const c = super.convert({
      html: e,
      text: t
    }, o);
    if (o[d.tableCellInner])
      for (const s of c.ops) {
        if (y.isObject(s.insert) && s.insert[d.tableCol]) {
          s.insert = "";
          continue;
        }
        s.attributes ?? (s.attributes = {}), s.attributes[d.tableCellInner] = o[d.tableCellInner];
      }
    return c;
  }
  matchCaption(e, t) {
    for (const o of t.ops) {
      const r = o.attributes;
      r != null && r[d.tableCaption] && (r[d.tableCaption].tableId = this.tableId, o.attributes = r);
    }
    return t;
  }
  preprocessTableHtml(e) {
    const t = Array.from(e.querySelectorAll("table"));
    t.length && (this.inlineComputedTableStyles(e, t), this.normalizeTableMarkup(e));
  }
  inlineComputedTableStyles(e, t) {
    const o = this.quill.root.ownerDocument, r = o.defaultView;
    if (!r) return;
    const i = o.createElement("div");
    i.style.cssText = "position:fixed;left:-9999px;top:0;opacity:0;pointer-events:none;";
    const c = o.createElement("div");
    c.innerHTML = "<table><tbody><tr><td></td></tr></tbody></table>";
    const s = o.createElement("div");
    Array.from(e.head.querySelectorAll("style")).forEach((a) => {
      s.appendChild(o.importNode(a, !0));
    }), Array.from(e.body.childNodes).forEach((a) => s.appendChild(o.importNode(a, !0))), i.appendChild(c), i.appendChild(s), o.body.appendChild(i);
    try {
      const a = c.querySelector("td");
      if (!a) return;
      const h = {
        cell: r.getComputedStyle(a)
      }, m = Array.from(s.querySelectorAll("table"));
      t.forEach((b, u) => {
        const g = m[u];
        g && this.inlineComputedTableStylesFromRendered(b, g, h, r);
      });
    } finally {
      i.remove();
    }
  }
  inlineComputedTableStylesFromRendered(e, t, o, r) {
    const i = $(t);
    if (i > 0) {
      const a = W(t, i, (h) => V(h, r)).map(w);
      e.setAttribute(R, a.join(","));
    }
    const c = Array.from(e.querySelectorAll("td, th")), s = Array.from(t.querySelectorAll("td, th"));
    c.forEach((a, h) => {
      const m = s[h];
      if (!m) return;
      const b = this.buildComputedCellStyle(a, m, o, r);
      b ? a.setAttribute("style", b) : a.removeAttribute("style"), a.removeAttribute("width"), a.removeAttribute("class");
    });
  }
  buildComputedCellStyle(e, t, o, r) {
    const i = e.parentElement, c = t.closest("table"), s = j(r.getComputedStyle(t), U, o.cell, (h, m) => !(h === "background-color" && m === "transparent"));
    if (!s["background-color"] && c) {
      const h = rt(t, c, r);
      h && !H.has(h) && (s["background-color"] = h);
    }
    const a = this.resolveExplicitHeightStyle(e, i);
    return I(Y(s), a);
  }
  resolveExplicitHeightStyle(...e) {
    const t = e.filter((o) => !!o).flatMap((o) => {
      const r = [], i = o.getAttribute("height");
      i && r.push(`height:${i}`);
      const c = o.getAttribute("style") || "", s = new RegExp(/height\s*:[^;]+/i).exec(c);
      return s && r.push(s[0]), r;
    });
    if (t.length)
      return I(...t);
  }
  normalizeTableMarkup(e) {
    e.querySelectorAll("style").forEach((t) => t.remove()), e.querySelectorAll("table, caption, colgroup, col, thead, tbody, tfoot, tr, td, th").forEach((t) => {
      const o = I(t.getAttribute("style"));
      o ? t.setAttribute("style", o) : t.removeAttribute("style"), t.removeAttribute("class");
    });
  }
}
export {
  dt as TableClipboard
};
