import { anyCssColorToHex } from "./../ricos-styles/themeStrategy/theme-utils.js";
import { isThemeColorToken } from "./../_shared/theme-color-token.js";
import { Plugin } from "./../tiptap/pm/state.js";
import { BACKGROUND_COLOR_VALUE_ATTR, FOREGROUND_COLOR_VALUE_ATTR } from "./data-hooks.js";
const THEME_COLOR_CLIPBOARD_ATTRS = [
  { attr: BACKGROUND_COLOR_VALUE_ATTR, property: "background-color" },
  { attr: FOREGROUND_COLOR_VALUE_ATTR, property: "color" }
];
const createThemeColorClipboardPlugin = () => new Plugin({
  props: {
    handleDOMEvents: {
      copy: copyThemeColorHtml,
      cut: copyThemeColorHtml
    }
  }
});
const resolveThemeColorsInClipboardDom = (clipboardRoot, themeRoot) => {
  let hasResolvedColor = false;
  for (const element of Array.from(clipboardRoot.querySelectorAll("[style]"))) {
    for (const { attr, property } of THEME_COLOR_CLIPBOARD_ATTRS) {
      const color = element.getAttribute(attr);
      if (!isThemeColorToken(color)) {
        continue;
      }
      const resolved = resolveColorForClipboard(
        element.style.getPropertyValue(property),
        themeRoot
      );
      if (resolved) {
        element.style.setProperty(property, resolved);
        hasResolvedColor = true;
      }
    }
  }
  return hasResolvedColor;
};
const copyThemeColorHtml = (view, event) => {
  const clipboardEvent = event;
  const { clipboardData } = clipboardEvent;
  if (!clipboardData || view.state.selection.empty) {
    return false;
  }
  const { dom, text } = view.serializeForClipboard(view.state.selection.content());
  if (!resolveThemeColorsInClipboardDom(dom, view.dom)) {
    return false;
  }
  clipboardEvent.preventDefault();
  clipboardData.clearData();
  clipboardData.setData("text/html", dom.innerHTML);
  clipboardData.setData("text/plain", text);
  if (clipboardEvent.type === "cut") {
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
  }
  return true;
};
const resolveColorForClipboard = (color, themeRoot) => {
  if (!color) {
    return void 0;
  }
  try {
    return anyCssColorToHex(color, themeRoot);
  } catch {
    return void 0;
  }
};
export {
  createThemeColorClipboardPlugin
};
//# sourceMappingURL=tiptap-theme-color-clipboard.js.map
