"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 toc_view_exports = {};
__export(toc_view_exports, {
  TocView: () => TocView,
  getScrollBehavior: () => getScrollBehavior
});
module.exports = __toCommonJS(toc_view_exports);
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../ricos-context/index.js");
var import_markers = require("./markers.js");
var import_resolve_styles = require("./resolve-styles.js");
var import_toc_view_scss = __toESM(require("./toc-view-scss.js"));
var import_tree_builder = require("./tree-builder.js");
const getScrollBehavior = () => {
  if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
    return "smooth";
  }
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth";
};
const renderItems = ({
  items,
  data,
  depth,
  parentIndices,
  onNavigate,
  onSelect,
  getNextVisibleIndex,
  resolvedLinkStyle,
  resolvedListItemStyle
}) => {
  const ListTag = (0, import_markers.getListTag)(data.listStyle);
  return /* @__PURE__ */ import_react.default.createElement(ListTag, { role: "list", style: (0, import_resolve_styles.listDepthStyle)(depth) }, items.map((item, index) => {
    const indices = [...parentIndices, index + 1];
    const marker = (0, import_markers.getMarker)({
      data,
      depth,
      indices,
      visibleIndex: getNextVisibleIndex()
    });
    return /* @__PURE__ */ import_react.default.createElement("li", { key: item.nodeId, style: resolvedListItemStyle }, /* @__PURE__ */ import_react.default.createElement(
      "a",
      {
        href: `#${item.anchor}`,
        className: import_toc_view_scss.default.tocLink,
        onClick: (event) => {
          event.preventDefault();
          if (onSelect?.()) {
            return;
          }
          onNavigate?.(item);
        },
        style: {
          ...resolvedLinkStyle,
          marginLeft: 0
        }
      },
      marker ? /* @__PURE__ */ import_react.default.createElement("span", { "aria-hidden": "true", style: import_resolve_styles.markerStyle }, marker) : null,
      /* @__PURE__ */ import_react.default.createElement("span", null, item.text)
    ), data.indentation !== "FLAT" && item.children.length > 0 ? renderItems({
      items: item.children,
      data,
      depth: depth + 1,
      parentIndices: indices,
      onNavigate,
      onSelect,
      getNextVisibleIndex,
      resolvedLinkStyle,
      resolvedListItemStyle
    }) : null);
  }));
};
const renderAlphabeticalIndex = ({
  data,
  headings,
  tocId,
  onNavigate,
  onSelect,
  resolvedStyles,
  t
}) => {
  const groups = (0, import_tree_builder.buildAlphabeticalGroups)(headings);
  const tocAnchorPrefix = tocId || "toc";
  const isCompact = data.listStyle === "ALPHABETICAL_INDEX_COMPACT";
  return /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("ul", { role: "list", style: import_resolve_styles.alphabeticalIndexNavListStyle }, groups.map((group) => {
    const sectionAnchor = `${tocAnchorPrefix}-${group.letter.toLowerCase()}`;
    const firstHeading = group.items[0];
    if (!firstHeading) {
      return null;
    }
    return /* @__PURE__ */ import_react.default.createElement("li", { key: group.letter }, /* @__PURE__ */ import_react.default.createElement(
      "a",
      {
        href: isCompact ? `#${firstHeading.anchor}` : `#${sectionAnchor}`,
        "aria-label": t("TocPlugin_AlphabeticalIndex_JumpTo", { letter: group.letter }),
        className: import_toc_view_scss.default.tocLink,
        onClick: (event) => {
          event.preventDefault();
          if (onSelect?.()) {
            return;
          }
          if (isCompact) {
            onNavigate?.(firstHeading);
            return;
          }
          if (typeof document === "undefined") {
            return;
          }
          const target = document.getElementById(sectionAnchor);
          target?.scrollIntoView?.({
            behavior: getScrollBehavior(),
            block: "start"
          });
          target?.focus?.({ preventScroll: true });
        },
        style: resolvedStyles.alphabeticalIndexGroupLinkStyle
      },
      group.letter
    ));
  })), isCompact ? null : groups.map((group) => {
    const sectionAnchor = `${tocAnchorPrefix}-${group.letter.toLowerCase()}`;
    return /* @__PURE__ */ import_react.default.createElement("div", { key: group.letter, style: import_resolve_styles.alphabeticalIndexSectionStyle }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        id: sectionAnchor,
        tabIndex: -1,
        role: "heading",
        "aria-level": 2,
        style: resolvedStyles.alphabeticalIndexLetterStyle
      },
      group.letter
    ), /* @__PURE__ */ import_react.default.createElement("div", { "aria-hidden": "true", style: resolvedStyles.alphabeticalIndexDividerStyle }), /* @__PURE__ */ import_react.default.createElement("ul", { role: "list", style: import_resolve_styles.alphabeticalIndexEntryListStyle }, group.items.map((item) => /* @__PURE__ */ import_react.default.createElement("li", { key: item.nodeId, style: resolvedStyles.alphabeticalIndexEntryStyle }, /* @__PURE__ */ import_react.default.createElement(
      "a",
      {
        href: `#${item.anchor}`,
        className: import_toc_view_scss.default.tocLink,
        onClick: (event) => {
          event.preventDefault();
          if (onSelect?.()) {
            return;
          }
          onNavigate?.(item);
        },
        style: resolvedStyles.alphabeticalIndexEntryLinkStyle
      },
      item.text
    )))));
  }));
};
const TocView = ({ data, headings, mode, onNavigate, onSelect, tocId }) => {
  const { t, theme } = import_react.default.useContext(import_ricos_context.RicosContext);
  const resolvedStyles = (0, import_resolve_styles.resolveViewStyles)({ data, theme });
  if (headings.length === 0) {
    return mode === "editor" ? /* @__PURE__ */ import_react.default.createElement("div", { style: resolvedStyles.containerStyle }, /* @__PURE__ */ import_react.default.createElement("div", { style: import_resolve_styles.placeholderStyle }, t("TocPlugin_Placeholder"))) : null;
  }
  const items = data.indentation !== "FLAT" ? (0, import_tree_builder.buildTree)(headings) : headings.map((heading) => ({
    ...heading,
    children: []
  }));
  let visibleIndex = 0;
  const getNextVisibleIndex = () => {
    visibleIndex += 1;
    return visibleIndex;
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "nav",
    {
      contentEditable: false,
      style: resolvedStyles.containerStyle,
      "aria-label": t("TocPlugin_AriaLabel")
    },
    data.listStyle === "ALPHABETICAL_INDEX" || data.listStyle === "ALPHABETICAL_INDEX_COMPACT" ? renderAlphabeticalIndex({
      data,
      headings,
      tocId,
      onNavigate,
      onSelect,
      resolvedStyles,
      t
    }) : renderItems({
      items,
      data,
      depth: 0,
      parentIndices: [],
      onNavigate,
      onSelect,
      getNextVisibleIndex,
      resolvedLinkStyle: resolvedStyles.linkStyle,
      resolvedListItemStyle: resolvedStyles.listItemStyle
    })
  );
};
//# sourceMappingURL=toc-view.js.map
