import { mapTableCell as I, UnreachableCaseError as T, Exporter as O, COLORS_DEFAULT as k } from "@blocknote/core";
import { Table as F, TableRow as S, TableCell as v, Paragraph as s, ShadingType as m, ImageRun as L, PageBreak as M, TextRun as u, CheckBox as R, ExternalHyperlink as B, Tab as E, AlignmentType as C, LevelFormat as b, Packer as U, Document as _ } from "docx";
async function H(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 W = (e, t) => {
  const r = new Array(e.headerRows ?? 0).fill(!0), o = new Array(e.headerCols ?? 0).fill(!0);
  return new F({
    layout: "autofit",
    columnWidths: e.columnWidths.map(
      (a) => (a ?? 120) * /* to points */
      0.75 * /* to twips */
      20
    ),
    rows: e.rows.map((a, p) => {
      const c = r[p];
      return new S({
        tableHeader: c,
        children: a.cells.map((g, w) => {
          var x;
          const y = (x = e.columnWidths) == null ? void 0 : x[w], i = I(g), D = o[w];
          return new v({
            width: y ? {
              size: `${y * 0.75}pt`,
              type: "dxa"
            } : void 0,
            columnSpan: i.props.colspan,
            rowSpan: i.props.rowspan,
            shading: i.props.backgroundColor === "default" || !i.props.backgroundColor ? void 0 : {
              type: m.SOLID,
              color: t.options.colors[i.props.backgroundColor].background.slice(1)
            },
            children: [
              new s({
                children: t.transformInlineContent(i.content),
                alignment: !i.props.textAlignment || i.props.textAlignment === "left" ? void 0 : i.props.textAlignment === "center" ? "center" : i.props.textAlignment === "right" ? "right" : i.props.textAlignment === "justify" ? "distribute" : (() => {
                  throw new T(
                    i.props.textAlignment
                  );
                })(),
                run: {
                  // TODO add support for table headers exporting, bolding seems to not be working at the moment
                  bold: c || D,
                  // TODO table paragraph color seems to not be working at the moment
                  // Probably because the runs are setting their own color
                  color: i.props.textColor === "default" || !i.props.textColor ? void 0 : t.options.colors[i.props.textColor].text.slice(1)
                }
              })
            ]
          });
        })
      });
    })
  });
};
function l(e, t) {
  return {
    shading: e.backgroundColor === "default" || !e.backgroundColor ? void 0 : {
      type: m.SOLID,
      color: t[e.backgroundColor].background.slice(1)
    },
    run: e.textColor === "default" || !e.textColor ? void 0 : {
      color: t[e.textColor].text.slice(1)
    },
    alignment: !e.textAlignment || e.textAlignment === "left" ? void 0 : e.textAlignment === "center" ? "center" : e.textAlignment === "right" ? "right" : e.textAlignment === "justify" ? "distribute" : (() => {
      throw new T(e.textAlignment);
    })()
  };
}
const P = {
  paragraph: (e, t) => new s({
    ...l(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    style: "Normal",
    run: {
      font: "Inter"
    }
  }),
  toggleListItem: (e, t) => new s({
    ...l(e.props, t.options.colors),
    children: [
      new u({
        children: ["> "]
      }),
      ...t.transformInlineContent(e.content)
    ]
  }),
  numberedListItem: (e, t, n) => new s({
    ...l(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    numbering: {
      reference: "blocknote-numbered-list",
      level: n
    }
  }),
  bulletListItem: (e, t, n) => new s({
    ...l(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    numbering: {
      reference: "blocknote-bullet-list",
      level: n
    }
  }),
  checkListItem: (e, t) => new s({
    ...l(e.props, t.options.colors),
    children: [
      new R({ checked: e.props.checked }),
      new u({
        children: [" "]
      }),
      ...t.transformInlineContent(e.content)
    ]
  }),
  heading: (e, t) => new s({
    ...l(e.props, t.options.colors),
    children: t.transformInlineContent(e.content),
    heading: `Heading${e.props.level}`
  }),
  quote: (e, t) => new s({
    shading: {
      color: "#7D797A"
    },
    border: {
      left: {
        color: "#7D797A",
        space: 100,
        style: "single",
        size: 8
      }
    },
    ...l(e.props, t.options.colors),
    children: t.transformInlineContent(e.content)
  }),
  audio: (e, t) => [
    h(e.props, "Open audio", t),
    ...f(e.props, t)
  ],
  video: (e, t) => [
    h(e.props, "Open video", t),
    ...f(e.props, t)
  ],
  file: (e, t) => [
    h(e.props, "Open file", t),
    ...f(e.props, t)
  ],
  codeBlock: (e) => {
    var n;
    const t = ((n = e.content[0]) == null ? void 0 : n.text) || "";
    return new s({
      style: "Codeblock",
      shading: {
        type: m.SOLID,
        fill: "161616",
        color: "161616"
      },
      children: [
        ...t.split(`
`).map((r, o) => new u({
          text: r,
          break: o > 0 ? 1 : 0
        }))
      ]
    });
  },
  pageBreak: () => new s({
    children: [new M()]
  }),
  image: async (e, t) => {
    const n = await t.resolveFile(e.props.url), { width: r, height: o } = await H(n);
    return [
      new s({
        ...l(e.props, t.options.colors),
        children: [
          new L({
            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
            }
          })
        ]
      }),
      ...f(e.props, t)
    ];
  },
  table: (e, t) => W(e.content, t)
};
function h(e, t, n) {
  return new s({
    ...l(e, n.options.colors),
    children: [
      new B({
        children: [
          new u({
            text: e.name || t,
            style: "Hyperlink"
          })
        ],
        link: e.url
      })
    ]
  });
}
function f(e, t) {
  return e.caption ? [
    new s({
      ...l(e, t.options.colors),
      children: [
        new u({
          text: e.caption
        })
      ],
      style: "Caption"
    })
  ] : [];
}
const j = {
  link: (e, t) => new B({
    children: e.content.map((n) => t.transformStyledText(
      n,
      !0
    )),
    link: e.href
  }),
  text: (e, t) => t.transformStyledText(e)
}, $ = {
  bold: (e) => e ? {
    bold: e
  } : {},
  italic: (e) => e ? {
    italics: e
  } : {},
  underline: (e) => e ? {
    underline: {
      type: "single"
    }
  } : {},
  strike: (e) => e ? {
    strike: e
  } : {},
  backgroundColor: (e, t) => e ? {
    shading: {
      fill: t.options.colors[e].background.slice(1)
    }
  } : {},
  textColor: (e, t) => e ? {
    color: t.options.colors[e].text.slice(1)
  } : {},
  code: (e) => e ? {
    font: "GeistMono"
  } : {}
}, J = {
  blockMapping: P,
  inlineContentMapping: j,
  styleMapping: $
};
async function N(e) {
  return "https://corsproxy.api.blocknotejs.org/corsproxy/?url=" + encodeURIComponent(e);
}
async function A(e) {
  {
    const t = e.default;
    return await (await fetch(t)).arrayBuffer();
  }
}
const d = (
  /* 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 O {
  constructor(t, n, r) {
    const a = {
      ...{
        colors: k,
        resolveFileUrl: N
      },
      ...r
    };
    super(t, n, a), 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 u({
      ...o,
      style: n ? "Hyperlink" : void 0,
      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 a = await this.transformBlocks(o.children, n + 1);
      a = a.map((c, g) => (c instanceof s && !c.properties.numberingReferences.length && c.addRunToFront(
        new u({
          children: [new E()]
        })
      ), c));
      const p = await this.mapBlock(
        o,
        n,
        0
        /*unused*/
      );
      Array.isArray(p) ? r.push(...p, ...a) : r.push(p, ...a);
    }
    return r;
  }
  async getFonts() {
    let t = await A(
      await import("./Inter_18pt-Regular-byxnNS-8.js")
    ), n = await A(
      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() {
    const t = (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: b.DECIMAL,
              text: `%${o + 1}.`,
              alignment: C.LEFT,
              style: {
                paragraph: {
                  indent: {
                    left: d * (o + 1),
                    hanging: d
                  }
                }
              }
            }))
          },
          {
            reference: "blocknote-bullet-list",
            levels: Array.from({ length: 9 }, (r, o) => ({
              start: 1,
              level: o,
              format: b.BULLET,
              text: n[o % n.length],
              alignment: C.LEFT,
              style: {
                paragraph: {
                  indent: {
                    left: d * (o + 1),
                    hanging: d
                  }
                }
              }
            }))
          }
        ]
      },
      fonts: await this.getFonts(),
      defaultTabStop: 200,
      externalStyles: t
    };
  }
  /**
   * 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), U.toBlob(r);
    } finally {
      globalThis.Buffer = o;
    }
  }
  /**
   * Convert a document (array of Blocks to a docxjs Document)
   */
  async toDocxJsDocument(t, n = {
    sectionOptions: {},
    documentOptions: {}
  }) {
    const r = new _({
      ...await this.createDefaultDocumentOptions(),
      ...n.documentOptions,
      sections: [
        {
          children: await this.transformBlocks(t),
          ...n.sectionOptions
        }
      ]
    });
    return r.Document.Relationships.createRelationship(
      r.Document.Relationships.RelationshipCount + 1,
      "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
      "fontTable.xml"
    ), r;
  }
}
export {
  q as DOCXExporter,
  J as docxDefaultSchemaMappings
};
//# sourceMappingURL=blocknote-xl-docx-exporter.js.map
