import { UnreachableCaseError as b, Exporter as x, COLORS_DEFAULT as D } from "@blocknote/core";
import { Table as B, TableRow as T, TableCell as C, Paragraph as i, CheckBox as O, TextRun as u, ShadingType as w, PageBreak as A, ImageRun as S, ExternalHyperlink as y, Tab as E, LevelFormat as h, AlignmentType as m, Packer as I, Document as _ } from "docx";
var v = { BASE_URL: "/", MODE: "production", DEV: !1, PROD: !0, SSR: !1 };
async function F(t) {
  if (typeof window < "u" && v.NODE_ENV !== "test") {
    const e = await createImageBitmap(t), { width: n, height: r } = e;
    return e.close(), { width: n, height: r };
  } else {
    const e = await require("sharp"), n = await t.arrayBuffer(), r = await e(n).metadata();
    if (!r.width || !r.height)
      throw new Error("Image has no width or height");
    return { width: r.width, height: r.height };
  }
}
const L = (t, e) => new B({
  layout: "autofit",
  columnWidths: t.columnWidths.map(
    (r) => (r ?? 120) * /* to points */
    0.75 * /* to twips */
    20
  ),
  rows: t.rows.map(
    (r) => new T({
      children: r.cells.map((o, a) => {
        var l;
        const c = (l = t.columnWidths) == null ? void 0 : l[a];
        return new C({
          width: c ? {
            size: `${c * 0.75}pt`,
            type: "dxa"
          } : void 0,
          children: [
            new i({
              children: e.transformInlineContent(o)
            })
          ]
        });
      })
    })
  )
});
function s(t, e) {
  return {
    shading: t.backgroundColor === "default" || !t.backgroundColor ? void 0 : {
      type: w.SOLID,
      color: e[t.backgroundColor].background.slice(1)
    },
    run: t.textColor === "default" || !t.textColor ? void 0 : {
      color: e[t.textColor].text.slice(1)
    },
    alignment: !t.textAlignment || t.textAlignment === "left" ? void 0 : t.textAlignment === "center" ? "center" : t.textAlignment === "right" ? "right" : t.textAlignment === "justify" ? "distribute" : (() => {
      throw new b(t.textAlignment);
    })()
  };
}
const k = {
  paragraph: (t, e) => new i({
    ...s(t.props, e.options.colors),
    children: e.transformInlineContent(t.content),
    style: "Normal",
    run: {
      font: "Inter"
    }
  }),
  numberedListItem: (t, e, n) => new i({
    ...s(t.props, e.options.colors),
    children: e.transformInlineContent(t.content),
    numbering: {
      reference: "blocknote-numbered-list",
      level: n
    }
  }),
  bulletListItem: (t, e, n) => new i({
    ...s(t.props, e.options.colors),
    children: e.transformInlineContent(t.content),
    numbering: {
      reference: "blocknote-bullet-list",
      level: n
    }
  }),
  checkListItem: (t, e) => new i({
    ...s(t.props, e.options.colors),
    children: [
      new O({ checked: t.props.checked }),
      new u({
        children: [" "]
      }),
      ...e.transformInlineContent(t.content)
    ]
  }),
  heading: (t, e) => new i({
    ...s(t.props, e.options.colors),
    children: e.transformInlineContent(t.content),
    heading: `Heading${t.props.level}`
  }),
  audio: (t, e) => [
    d(t.props, "Open audio", e),
    ...f(t.props, e)
  ],
  video: (t, e) => [
    d(t.props, "Open video", e),
    ...f(t.props, e)
  ],
  file: (t, e) => [
    d(t.props, "Open file", e),
    ...f(t.props, e)
  ],
  codeBlock: (t) => {
    var n;
    const e = ((n = t.content[0]) == null ? void 0 : n.text) || "";
    return new i({
      style: "Codeblock",
      shading: {
        type: w.SOLID,
        fill: "161616",
        color: "161616"
      },
      children: [
        ...e.split(`
`).map((r, o) => new u({
          text: r,
          break: o > 0 ? 1 : 0
        }))
      ]
    });
  },
  pageBreak: () => new i({
    children: [new A()]
  }),
  image: async (t, e) => {
    const n = await e.resolveFile(t.props.url), { width: r, height: o } = await F(n);
    return [
      new i({
        ...s(t.props, e.options.colors),
        children: [
          new S({
            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: t.props.caption ? {
              description: t.props.caption,
              name: t.props.caption,
              title: t.props.caption
            } : void 0,
            transformation: {
              width: t.props.previewWidth,
              height: t.props.previewWidth / r * o
            }
          })
        ]
      }),
      ...f(t.props, e)
    ];
  },
  table: (t, e) => L(t.content, e)
};
function d(t, e, n) {
  return new i({
    ...s(t, n.options.colors),
    children: [
      new y({
        children: [
          new u({
            text: t.name || e,
            style: "Hyperlink"
          })
        ],
        link: t.url
      })
    ]
  });
}
function f(t, e) {
  return t.caption ? [
    new i({
      ...s(t, e.options.colors),
      children: [
        new u({
          text: t.caption
        })
      ],
      style: "Caption"
    })
  ] : [];
}
const R = {
  link: (t, e) => new y({
    children: t.content.map((n) => e.transformStyledText(
      n,
      !0
    )),
    link: t.href
  }),
  text: (t, e) => e.transformStyledText(t)
}, M = {
  bold: (t) => t ? {
    bold: t
  } : {},
  italic: (t) => t ? {
    italics: t
  } : {},
  underline: (t) => t ? {
    underline: {
      type: "single"
    }
  } : {},
  strike: (t) => t ? {
    strike: t
  } : {},
  backgroundColor: (t, e) => t ? {
    shading: {
      fill: e.options.colors[t].background.slice(1)
    }
  } : {},
  textColor: (t, e) => t ? {
    color: e.options.colors[t].text.slice(1)
  } : {},
  code: (t) => t ? {
    font: "GeistMono"
  } : {}
}, $ = {
  blockMapping: k,
  inlineContentMapping: R,
  styleMapping: M
};
async function U(t) {
  return "https://corsproxy.api.blocknotejs.org/corsproxy/?url=" + encodeURIComponent(t);
}
var P = { BASE_URL: "/", MODE: "production", DEV: !1, PROD: !0, SSR: !1 };
async function g(t) {
  if (P.NODE_ENV === "test") {
    const e = require("fs");
    let n = t.default;
    return n.startsWith("/@fs/") && (n = n.substring(4)), e.readFileSync(n);
  } else {
    const e = t.default;
    return await (await fetch(e)).arrayBuffer();
  }
}
const p = (
  /* default font size */
  16 * /* 1 pixel is 0.75 points */
  0.75 * /* 1.5em*/
  1.5 * /* 1 point is 20 twips */
  20
);
class V extends x {
  constructor(e, n, r) {
    const a = {
      ...{
        colors: D,
        resolveFileUrl: U
      },
      ...r
    };
    super(e, n, a), this.schema = e, this.mappings = n;
  }
  /**
   * Mostly for internal use, you probably want to use `toBlob` or `toDocxJsDocument` instead.
   */
  transformStyledText(e, n) {
    const r = this.mapStyles(e.styles), o = Object.assign(
      {},
      ...r
    );
    return new u({
      ...o,
      style: n ? "Hyperlink" : void 0,
      text: e.text
    });
  }
  /**
   * Mostly for internal use, you probably want to use `toBlob` or `toDocxJsDocument` instead.
   */
  async transformBlocks(e, n = 0) {
    const r = [];
    for (const o of e) {
      let a = await this.transformBlocks(o.children, n + 1);
      a = a.map((l, W) => (l instanceof i && !l.properties.numberingReferences.length && l.addRunToFront(
        new u({
          children: [new E()]
        })
      ), l));
      const c = await this.mapBlock(
        o,
        n,
        0
        /*unused*/
      );
      Array.isArray(c) ? r.push(...c, ...a) : r.push(c, ...a);
    }
    return r;
  }
  async getFonts() {
    let e = await g(
      await import("./Inter_18pt-Regular-byxnNS-8.js")
    ), n = await g(
      await import("./GeistMono-Regular-D4rKXxwr.js")
    );
    if (e instanceof ArrayBuffer || n instanceof Uint8Array) {
      const r = (await import("buffer")).Buffer;
      e instanceof ArrayBuffer && (e = r.from(e)), n instanceof ArrayBuffer && (n = r.from(n));
    }
    return [
      { name: "Inter", data: e },
      {
        name: "GeistMono",
        data: n
      }
    ];
  }
  async createDefaultDocumentOptions() {
    const e = (await import("./styles-CujW8HHo.js")).default, n = ["•"];
    return {
      numbering: {
        config: [
          {
            reference: "blocknote-numbered-list",
            levels: Array.from({ length: 9 }, (r, o) => ({
              start: 1,
              level: o,
              format: h.DECIMAL,
              text: `%${o + 1}.`,
              alignment: m.LEFT,
              style: {
                paragraph: {
                  indent: {
                    left: p * (o + 1),
                    hanging: p
                  }
                }
              }
            }))
          },
          {
            reference: "blocknote-bullet-list",
            levels: Array.from({ length: 9 }, (r, o) => ({
              start: 1,
              level: o,
              format: h.BULLET,
              text: n[o % n.length],
              alignment: m.LEFT,
              style: {
                paragraph: {
                  indent: {
                    left: p * (o + 1),
                    hanging: p
                  }
                }
              }
            }))
          }
        ]
      },
      fonts: await this.getFonts(),
      defaultTabStop: 200,
      externalStyles: e
    };
  }
  /**
   * Convert a document (array of Blocks to a Blob representing a .docx file)
   */
  async toBlob(e, n = {
    sectionOptions: {},
    documentOptions: {}
  }) {
    const r = await this.toDocxJsDocument(e, n), o = globalThis.Buffer;
    try {
      return globalThis.Buffer || (globalThis.Buffer = (await import("buffer")).Buffer), I.toBlob(r);
    } finally {
      globalThis.Buffer = o;
    }
  }
  /**
   * Convert a document (array of Blocks to a docxjs Document)
   */
  async toDocxJsDocument(e, n = {
    sectionOptions: {},
    documentOptions: {}
  }) {
    const r = new _({
      ...await this.createDefaultDocumentOptions(),
      ...n.documentOptions,
      sections: [
        {
          children: await this.transformBlocks(e),
          ...n.sectionOptions
        }
      ]
    });
    return r.Document.Relationships.createRelationship(
      r.Document.Relationships.RelationshipCount + 1,
      "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
      "fontTable.xml"
    ), r;
  }
}
export {
  V as DOCXExporter,
  $ as docxDefaultSchemaMappings
};
//# sourceMappingURL=blocknote-xl-docx-exporter.js.map
