import { PmNodeType } from "./../../_shared/pm-node-types.js";
import { findParentNodeClosestToPos } from "./../../tiptap/core/index.js";
import { NodeSelection, Plugin, PluginKey } from "./../../tiptap/pm/state.js";
import { Decoration, DecorationSet } from "./../../tiptap/pm/view.js";
const SMART_BLOCK_COLOR_PREVIEW_KEY = new PluginKey(
  "smartBlockColorPreview"
);
const resolveTargetBlock = (state) => {
  const { selection } = state;
  if (selection instanceof NodeSelection && selection.node.type.name === PmNodeType.SMART_BLOCK) {
    return { node: selection.node, pos: selection.from };
  }
  const block = findParentNodeClosestToPos(
    state.doc.resolve(selection.from),
    (node) => node.type.name === PmNodeType.SMART_BLOCK
  );
  return block ? { node: block.node, pos: block.pos } : null;
};
const resolveTargetCells = (state) => {
  const { selection } = state;
  if (selection instanceof NodeSelection && selection.node.type.name === PmNodeType.SMART_BLOCK_CELL) {
    return [{ node: selection.node, pos: selection.from }];
  }
  const block = resolveTargetBlock(state);
  if (!block) {
    return [];
  }
  const cells = [];
  block.node.forEach((child, offset) => {
    if (child.type.name === PmNodeType.SMART_BLOCK_CELL) {
      cells.push({ node: child, pos: block.pos + 1 + offset });
    }
  });
  return cells;
};
const createSmartBlockColorPreviewPlugin = () => new Plugin({
  key: SMART_BLOCK_COLOR_PREVIEW_KEY,
  state: {
    init: () => null,
    apply(tr, value) {
      const meta = tr.getMeta(SMART_BLOCK_COLOR_PREVIEW_KEY);
      return meta === void 0 ? value : meta;
    }
  },
  props: {
    decorations(state) {
      const preview = SMART_BLOCK_COLOR_PREVIEW_KEY.getState(state);
      if (!preview) {
        return null;
      }
      if (preview.attr === "borderColor") {
        const block = resolveTargetBlock(state);
        if (block?.node.attrs.type === "SOLID_JOINED_BOXES") {
          return DecorationSet.create(state.doc, [
            Decoration.node(
              block.pos,
              block.pos + block.node.nodeSize,
              {},
              { sbPreviewAttr: preview.attr, sbPreviewColor: preview.color }
            )
          ]);
        }
      }
      const cells = resolveTargetCells(state);
      if (cells.length === 0) {
        return null;
      }
      return DecorationSet.create(
        state.doc,
        cells.map(
          ({ node, pos }) => (
            // Data rides on the decoration spec (4th arg) so nothing is written
            // to the cell DOM; SmartBlockCell reads it from its `decorations` prop.
            Decoration.node(
              pos,
              pos + node.nodeSize,
              {},
              { sbPreviewAttr: preview.attr, sbPreviewColor: preview.color }
            )
          )
        )
      );
    }
  }
});
export {
  SMART_BLOCK_COLOR_PREVIEW_KEY,
  createSmartBlockColorPreviewPlugin
};
//# sourceMappingURL=smart-block-color-preview-plugin.js.map
