import { mapTableCell as O, UnreachableCaseError as L, Exporter as S, COLORS_DEFAULT as _ } from "@blocknote/core";
import { Table as I, TableRow as D, TableCell as y, Paragraph as a, ShadingType as x, ImageRun as E, PageBreak as M, TextRun as p, CheckBox as U, ExternalHyperlink as k, Tab as R, AlignmentType as B, LevelFormat as T, Packer as H, Document as $ } from "docx";
async function W(e) {
  if (typeof window < "u") {
    const t = await createImageBitmap(e), { width: n, height: r } = t;
    return t.close(), { width: n, height: r };
  } else {
    const t = (await import("image-meta")).imageMeta, n = new Uint8Array(await e.arrayBuffer()), r = t(n);
    if (!r.width || !r.height)
      throw new Error("Image dimensions not found");
    return { width: r.width, height: r.height };
  }
}
const z = (e, t) => {
  const r = new Array(e.headerRows ?? 0).fill(!0), o = new Array(e.headerCols ?? 0).fill(!0);
  return new I({
    layout: "autofit",
    columnWidths: e.columnWidths.map(
      (i) => (i ?? 120) * /* to points */
      0.75 * /* to twips */
      20
    ),
    rows: e.rows.map((i, s) => {
      const u = r[s];
      return new D({
        tableHeader: u,
        children: i.cells.map((d, b) => {
          var A;
          const C = (A = e.columnWidths) == null ? void 0 : A[b], l = O(d), F = o[b];
          return new y({
            width: C ? {
              // The type is twentieths of a point (dxa)
              size: C * 0.75 * 20,
              type: "dxa"
            } : void 0,
            columnSpan: l.props.colspan,
            rowSpan: l.props.rowspan,
            shading: l.props.backgroundColor === "default" || !l.props.backgroundColor ? void 0 : {
              type: x.SOLID,
              color: (() => {
                var m;
                const f = (m = t.options.colors[l.props.backgroundColor]) == null ? void 0 : m.background;
                if (f)
                  return f.slice(1);
              })()
            },
            children: [
              new a({
                children: t.transformInlineContent(l.content),
                alignment: !l.props.textAlignment || l.props.textAlignment === "left" ? void 0 : l.props.textAlignment === "center" ? "center" : l.props.textAlignment === "right" ? "right" : l.props.textAlignment === "justify" ? "distribute" : (() => {
                  throw new L(
                    l.props.textAlignment
                  );
                })(),
                run: {
                  // TODO add support for table headers exporting, bolding seems to not be working at the moment
                  bold: u || F,
                  // TODO table paragraph color seems to not be working at the moment
                  // Probably because the runs are setting their own color
                  color: l.props.textColor === "default" || !l.props.textColor ? void 0 : (() => {
                    var m;
                    const f = (m = t.options.colors[l.props.textColor]) == null ? void 0 : m.text;
                    if (f)
                      return f.slice(1);
                  })()
                }
              })
            ]
          });
        })
      });
    })
  });
};
function c(e, t) {
  return {
    shading: e.backgroundColor === "default" || !e.backgroundColor ? void 0 : {
      type: x.CLEAR,
      fill: (() => {
        var r;
        const n = (r = t[e.backgroundColor]) == null ? void 0 : r.background;
        if (n)
          return n.slice(1);
      })()
    },
    run: e.textColor === "default" || !e.textColor ? void 0 : {
      color: (() => {
        var r;
        const n = (r = t[e.textColor]) == null ? void 0 : r.text;
        if (n)
          return n.slice(1);
      })()
    },
    alignment: !e.textAlignment || e.textAlignment === "left" ? void 0 : e.textAlignment === "center" ? "center" : e.textAlignment === "right" ? "right" : e.textAlignment === "justify" ? "distribute" : (() => {
      throw new L(e.textAlignment);
    })()
  };
}
const P = {
  paragraph: (e, t) => new a({
    ...c(e.props, t.options.colors),
    children: t.transformInlineContent(e.content)
  }),
  toggleListItem: (e, t) => new a({
    ...c(e.props, t.options.colors),
    children: [
      new p({
        children: ["> "]
      }),
      ...t.transformInlineContent(e.content)
    ]
  }),
  numberedListItem: (e, t, n) => new a({
    ...c(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    numbering: {
      reference: "blocknote-numbered-list",
      level: n
    }
  }),
  bulletListItem: (e, t, n) => new a({
    ...c(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    numbering: {
      reference: "blocknote-bullet-list",
      level: n
    }
  }),
  checkListItem: (e, t) => new a({
    ...c(e.props, t.options.colors),
    children: [
      new U({ checked: e.props.checked }),
      new p({
        children: [" "]
      }),
      ...t.transformInlineContent(e.content)
    ]
  }),
  heading: (e, t) => new a({
    ...c(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    heading: `Heading${e.props.level}`
  }),
  quote: (e, t) => new a({
    style: "BlockQuote",
    ...c(e.props, t.options.colors),
    children: t.transformInlineContent(e.content)
  }),
  audio: (e, t) => [
    w(e.props, "Open audio", t),
    ...h(e.props, t)
  ],
  video: (e, t) => [
    w(e.props, "Open video", t),
    ...h(e.props, t)
  ],
  file: (e, t) => [
    w(e.props, "Open file", t),
    ...h(e.props, t)
  ],
  codeBlock: (e) => {
    var n;
    const t = ((n = e.content[0]) == null ? void 0 : n.text) || "";
    return new a({
      style: "SourceCode",
      children: [
        ...t.split(`
`).map((r, o) => new p({
          text: r,
          break: o > 0 ? 1 : 0
        }))
      ]
    });
  },
  pageBreak: () => new a({
    children: [new M()]
  }),
  divider: () => new a({
    border: {
      top: {
        color: "auto",
        space: 1,
        style: "single",
        size: 1
      }
    }
  }),
  column: (e, t, n, r, o) => new y({
    width: {
      size: `${e.props.width * 100}%`,
      type: "pct"
    },
    children: (o || []).flatMap((i) => Array.isArray(i) ? i : [i])
  }),
  columnList: (e, t, n, r, o) => new I({
    layout: "autofit",
    borders: {
      bottom: { style: "nil" },
      top: { style: "nil" },
      left: { style: "nil" },
      right: { style: "nil" },
      insideHorizontal: { style: "nil" },
      insideVertical: { style: "nil" }
    },
    rows: [
      new D({
        children: o.map(
          (i, s, u) => {
            var d;
            return new y({
              width: {
                size: `${parseFloat(`${((d = i.options.width) == null ? void 0 : d.size) || "100%"}`) / (u.length * 100) * 100}%`,
                type: "pct"
              },
              children: i.options.children
            });
          }
        )
      })
    ]
  }),
  image: async (e, t) => {
    const n = await t.resolveFile(e.props.url), { width: r, height: o } = await W(n);
    return [
      new a({
        ...c(e.props, t.options.colors),
        children: [
          new E({
            data: await n.arrayBuffer(),
            // it would be nicer to set the actual data type here, but then we'd need to use a mime type / image type
            // detector. atm passing gif does not seem to be causing issues as the "type" is mainly used by docxjs internally
            // (i.e.: to make sure it's not svg)
            type: "gif",
            altText: e.props.caption ? {
              description: e.props.caption,
              name: e.props.caption,
              title: e.props.caption
            } : void 0,
            transformation: {
              width: e.props.previewWidth || r,
              height: (e.props.previewWidth || r) / r * o
            }
          })
        ]
      }),
      ...h(e.props, t)
    ];
  },
  table: (e, t) => z(e.content, t)
};
function w(e, t, n) {
  return new a({
    ...c(e, n.options.colors),
    children: [
      new k({
        children: [
          new p({
            text: e.name || t,
            style: "Hyperlink"
          })
        ],
        link: e.url
      })
    ]
  });
}
function h(e, t) {
  return e.caption ? [
    new a({
      ...c(e, t.options.colors),
      children: [
        new p({
          text: e.caption
        })
      ],
      style: "Caption"
    })
  ] : [];
}
const j = {
  link: (e, t) => new k({
    children: e.content.map((n) => t.transformStyledText(
      n,
      !0
    )),
    link: e.href
  }),
  text: (e, t) => t.transformStyledText(e)
}, J = {
  bold: (e) => e ? {
    bold: e
  } : {},
  italic: (e) => e ? {
    italics: e
  } : {},
  underline: (e) => e ? {
    underline: {
      type: "single"
    }
  } : {},
  strike: (e) => e ? {
    strike: e
  } : {},
  backgroundColor: (e, t) => {
    var r;
    if (!e)
      return {};
    const n = (r = t.options.colors[e]) == null ? void 0 : r.background;
    return n ? {
      shading: {
        type: x.CLEAR,
        fill: n.slice(1)
      }
    } : {};
  },
  textColor: (e, t) => {
    var r;
    if (!e)
      return {};
    const n = (r = t.options.colors[e]) == null ? void 0 : r.text;
    return n ? {
      color: n.slice(1)
    } : {};
  },
  code: (e) => e ? {
    style: "VerbatimChar"
  } : {}
}, G = {
  blockMapping: P,
  inlineContentMapping: j,
  styleMapping: J
};
async function N(e) {
  return "https://corsproxy.api.blocknotejs.org/corsproxy/?url=" + encodeURIComponent(e);
}
async function v(e) {
  {
    const t = e.default;
    return await (await fetch(t)).arrayBuffer();
  }
}
const g = (
  /* default font size */
  16 * /* 1 pixel is 0.75 points */
  0.75 * /* 1.5em*/
  1.5 * /* 1 point is 20 twips */
  20
);
class Q extends S {
  constructor(t, n, r) {
    const i = {
      ...{
        colors: _,
        resolveFileUrl: N
      },
      ...r
    };
    super(t, n, i), this.schema = t, this.mappings = n;
  }
  /**
   * Mostly for internal use, you probably want to use `toBlob` or `toDocxJsDocument` instead.
   */
  transformStyledText(t, n) {
    const r = this.mapStyles(t.styles), o = Object.assign(
      {},
      ...r
    );
    return new p({
      ...o,
      style: n ? "Hyperlink" : o.style,
      text: t.text
    });
  }
  /**
   * Mostly for internal use, you probably want to use `toBlob` or `toDocxJsDocument` instead.
   */
  async transformBlocks(t, n = 0) {
    const r = [];
    for (const o of t) {
      let i = await this.transformBlocks(o.children, n + 1);
      ["columnList", "column"].includes(o.type) || (i = i.map((u, d) => (u instanceof a && !u.properties.numberingReferences.length && u.addRunToFront(
        new p({
          children: [new R()]
        })
      ), u)));
      const s = await this.mapBlock(
        o,
        n,
        0,
        i
      );
      ["columnList", "column"].includes(o.type) ? r.push(s) : Array.isArray(s) ? r.push(...s, ...i) : r.push(s, ...i);
    }
    return r;
  }
  async getFonts() {
    let t = await v(
      await import("./Inter_18pt-Regular-byxnNS-8.js")
    ), n = await v(
      await import("./GeistMono-Regular-D4rKXxwr.js")
    );
    if (t instanceof ArrayBuffer || n instanceof ArrayBuffer) {
      const r = (await import("./index-cA_PmnZy.js").then((o) => o.i)).Buffer;
      t instanceof ArrayBuffer && (t = r.from(t)), n instanceof ArrayBuffer && (n = r.from(n));
    }
    return [
      { name: "Inter", data: t },
      {
        name: "GeistMono",
        data: n
      }
    ];
  }
  async createDefaultDocumentOptions(t) {
    let n = (await import("./styles-Bw_Yt1z6.js")).default;
    const r = t && t.trim() || "en-US";
    n = n.replace(
      /(<w:lang\b[^>]*\bw:val=")([^"]+)("[^>]*\/>)/g,
      `$1${r}$3`
    );
    const o = ["•"];
    return {
      numbering: {
        config: [
          {
            reference: "blocknote-numbered-list",
            levels: Array.from({ length: 9 }, (i, s) => ({
              start: 1,
              level: s,
              format: T.DECIMAL,
              text: `%${s + 1}.`,
              alignment: B.LEFT,
              style: {
                paragraph: {
                  indent: {
                    left: g * (s + 1),
                    hanging: g
                  }
                }
              }
            }))
          },
          {
            reference: "blocknote-bullet-list",
            levels: Array.from({ length: 9 }, (i, s) => ({
              start: 1,
              level: s,
              format: T.BULLET,
              text: o[s % o.length],
              alignment: B.LEFT,
              style: {
                paragraph: {
                  indent: {
                    left: g * (s + 1),
                    hanging: g
                  }
                }
              }
            }))
          }
        ]
      },
      fonts: await this.getFonts(),
      defaultTabStop: 200,
      externalStyles: n
    };
  }
  /**
   * Convert a document (array of Blocks to a Blob representing a .docx file)
   */
  async toBlob(t, n = {
    sectionOptions: {},
    documentOptions: {}
  }) {
    const r = await this.toDocxJsDocument(t, n), o = globalThis.Buffer;
    try {
      return globalThis.Buffer || (globalThis.Buffer = (await import("buffer")).default.Buffer), H.toBlob(r);
    } finally {
      globalThis.Buffer = o;
    }
  }
  /**
   * Convert a document (array of Blocks to a docxjs Document)
   */
  async toDocxJsDocument(t, n = {
    sectionOptions: {},
    documentOptions: {}
  }) {
    return new $({
      ...await this.createDefaultDocumentOptions(n.locale),
      ...n.documentOptions,
      sections: [
        {
          children: await this.transformBlocks(t),
          ...n.sectionOptions
        }
      ]
    });
  }
}
export {
  Q as DOCXExporter,
  G as docxDefaultSchemaMappings
};
//# sourceMappingURL=blocknote-xl-docx-exporter.js.map
