// packages/editor/src/store/private-selectors.js
import fastDeepEqual from "fast-deep-equal";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { createSelector, createRegistrySelector } from "@wordpress/data";
import {
  layout,
  symbol,
  navigation,
  page as pageIcon,
  verse
} from "@wordpress/icons";
import { store as coreStore } from "@wordpress/core-data";
import { store as preferencesStore } from "@wordpress/preferences";
import {
  getRenderingMode,
  getCurrentPost,
  getEditorSettings,
  getCurrentPostRevisionsCount
} from "./selectors.mjs";
import {
  getEntityActions as _getEntityActions,
  getEntityFields as _getEntityFields,
  isEntityReady as _isEntityReady
} from "../dataviews/store/private-selectors.mjs";
import { getTemplatePartIcon } from "../utils/index.mjs";
var EMPTY_INSERTION_POINT = {
  rootClientId: void 0,
  insertionIndex: void 0,
  filterValue: void 0
};
var RENDERING_MODES = ["post-only", "template-locked"];
var getInserter = createRegistrySelector(
  (select) => createSelector(
    (state) => {
      if (typeof state.blockInserterPanel === "object") {
        return state.blockInserterPanel;
      }
      if (getRenderingMode(state) === "template-locked") {
        const {
          getBlocksByName,
          getSelectedBlockClientId,
          getBlockParents,
          getBlockOrder
        } = select(blockEditorStore);
        const [postContentClientId] = getBlocksByName("core/post-content");
        if (postContentClientId) {
          const selectedBlockClientId = getSelectedBlockClientId();
          if (selectedBlockClientId && selectedBlockClientId !== postContentClientId && getBlockParents(selectedBlockClientId).includes(
            postContentClientId
          )) {
            return EMPTY_INSERTION_POINT;
          }
          return {
            rootClientId: postContentClientId,
            insertionIndex: getBlockOrder(postContentClientId).length,
            filterValue: void 0
          };
        }
      }
      return EMPTY_INSERTION_POINT;
    },
    (state) => {
      const {
        getBlocksByName,
        getSelectedBlockClientId,
        getBlockParents,
        getBlockOrder
      } = select(blockEditorStore);
      const [postContentClientId] = getBlocksByName("core/post-content");
      const selectedBlockClientId = getSelectedBlockClientId();
      return [
        state.blockInserterPanel,
        getRenderingMode(state),
        postContentClientId,
        selectedBlockClientId,
        selectedBlockClientId ? getBlockParents(selectedBlockClientId) : void 0,
        postContentClientId ? getBlockOrder(postContentClientId).length : void 0
      ];
    }
  )
);
function getListViewToggleRef(state) {
  return state.listViewToggleRef;
}
function getInserterSidebarToggleRef(state) {
  return state.inserterSidebarToggleRef;
}
var CARD_ICONS = {
  wp_block: symbol,
  wp_navigation: navigation,
  page: pageIcon,
  post: verse
};
var getPostIcon = createRegistrySelector(
  (select) => (state, postType, options) => {
    {
      if (postType === "wp_template_part" || postType === "wp_template") {
        const templateAreas = select(coreStore).getCurrentTheme()?.default_template_part_areas || [];
        const areaData = templateAreas.find(
          (item) => options.area === item.area
        );
        if (areaData?.icon) {
          return getTemplatePartIcon(areaData.icon);
        }
        return layout;
      }
      if (CARD_ICONS[postType]) {
        return CARD_ICONS[postType];
      }
      const postTypeEntity = select(coreStore).getPostType(postType);
      if (typeof postTypeEntity?.icon === "string" && postTypeEntity.icon.startsWith("dashicons-")) {
        return postTypeEntity.icon.slice(10);
      }
      return pageIcon;
    }
  }
);
var hasPostMetaChanges = createRegistrySelector(
  (select) => (state, postType, postId) => {
    const { type: currentPostType, id: currentPostId } = getCurrentPost(state);
    const edits = select(coreStore).getEntityRecordNonTransientEdits(
      "postType",
      postType || currentPostType,
      postId || currentPostId
    );
    if (!edits?.meta) {
      return false;
    }
    const originalPostMeta = select(coreStore).getEntityRecord(
      "postType",
      postType || currentPostType,
      postId || currentPostId
    )?.meta;
    return !fastDeepEqual(
      { ...originalPostMeta, footnotes: void 0 },
      { ...edits.meta, footnotes: void 0 }
    );
  }
);
function getEntityActions(state, ...args) {
  return _getEntityActions(state.dataviews, ...args);
}
function isEntityReady(state, ...args) {
  return _isEntityReady(state.dataviews, ...args);
}
function getEntityFields(state, ...args) {
  return _getEntityFields(state.dataviews, ...args);
}
var getPostBlocksByName = createRegistrySelector(
  (select) => createSelector(
    (state, blockNames) => {
      blockNames = Array.isArray(blockNames) ? blockNames : [blockNames];
      const { getBlocksByName, getBlockParents, getBlockName } = select(blockEditorStore);
      return getBlocksByName(blockNames).filter(
        (clientId) => getBlockParents(clientId).every((parentClientId) => {
          const parentBlockName = getBlockName(parentClientId);
          return (
            // Ignore descendents of the query block.
            parentBlockName !== "core/query" && // Enable only the top-most block.
            !blockNames.includes(parentBlockName)
          );
        })
      );
    },
    (state, blockNames) => {
      blockNames = Array.isArray(blockNames) ? blockNames : [blockNames];
      const { getBlocksByName, getBlockParents } = select(blockEditorStore);
      const clientIds = getBlocksByName(blockNames);
      const parentsOfClientIds = clientIds.map(
        (id) => getBlockParents(id)
      );
      return [clientIds, ...parentsOfClientIds];
    }
  )
);
var getDefaultRenderingMode = createRegistrySelector(
  (select) => (state, postType) => {
    const { getPostType, getCurrentTheme, hasFinishedResolution } = select(coreStore);
    const currentTheme = getCurrentTheme();
    const postTypeEntity = getPostType(postType);
    if (!hasFinishedResolution("getPostType", [postType]) || !hasFinishedResolution("getCurrentTheme")) {
      return void 0;
    }
    const theme = currentTheme?.stylesheet;
    const defaultModePreference = select(preferencesStore).get(
      "core",
      "renderingModes"
    )?.[theme]?.[postType];
    if (RENDERING_MODES.includes(defaultModePreference)) {
      return defaultModePreference;
    }
    const postTypeDefaultMode = Array.isArray(
      postTypeEntity?.supports?.editor
    ) ? postTypeEntity.supports.editor.find(
      (features) => "default-mode" in features
    )?.["default-mode"] : void 0;
    if (RENDERING_MODES.includes(postTypeDefaultMode)) {
      return postTypeDefaultMode;
    }
    const settingsDefaultMode = getEditorSettings(state).defaultRenderingMode;
    if (RENDERING_MODES.includes(settingsDefaultMode)) {
      return settingsDefaultMode;
    }
    return "post-only";
  }
);
function getStylesPath(state) {
  return state.stylesPath ?? "/";
}
function getShowStylebook(state) {
  return state.showStylebook ?? false;
}
function getRevisionPage(state) {
  return state.revisionPage;
}
function buildRevisionsPageQuery(revisionKey, page) {
  return {
    per_page: REVISIONS_PER_PAGE,
    page,
    context: "edit",
    orderby: "date",
    order: "desc",
    _fields: [
      .../* @__PURE__ */ new Set([
        "id",
        "date",
        "modified",
        "author",
        "meta",
        "title.raw",
        "excerpt.raw",
        "content.raw",
        revisionKey
      ])
    ].join()
  };
}
var REVISIONS_PER_PAGE = 100;
function getRevisionsPerPage() {
  return REVISIONS_PER_PAGE;
}
var getPageRevisions = createRegistrySelector(
  (select) => (state, page) => {
    if (!page) {
      return null;
    }
    const { type: postType, id: postId } = getCurrentPost(state);
    if (!postType || !postId) {
      return null;
    }
    const entityConfig = select(coreStore).getEntityConfig(
      "postType",
      postType
    );
    const revisionKey = entityConfig?.revisionKey || "id";
    return select(coreStore).getRevisions(
      "postType",
      postType,
      postId,
      buildRevisionsPageQuery(revisionKey, page)
    );
  }
);
function isRevisionsMode(state) {
  return state.revisionId !== null;
}
function isShowingRevisionDiff(state) {
  return state.showRevisionDiff;
}
function getCurrentRevisionId(state) {
  return state.revisionId;
}
var getCurrentRevision = createRegistrySelector(
  (select) => (state) => {
    const revisionId = getCurrentRevisionId(state);
    if (!revisionId) {
      return void 0;
    }
    const page = getRevisionPage(state);
    if (!page) {
      return null;
    }
    const { type: postType, id: postId } = getCurrentPost(state);
    const entityConfig = select(coreStore).getEntityConfig(
      "postType",
      postType
    );
    const revisionKey = entityConfig?.revisionKey || "id";
    const revisions = select(coreStore).getRevisions(
      "postType",
      postType,
      postId,
      buildRevisionsPageQuery(revisionKey, page)
    );
    if (!revisions) {
      return null;
    }
    return revisions.find((r) => r[revisionKey] === revisionId) ?? null;
  }
);
function getSelectedNote(state) {
  return state.selectedNote?.noteId;
}
function isNoteFocused(state) {
  return !!state.selectedNote?.options?.focus;
}
var getPreviousRevision = createRegistrySelector(
  (select) => (state) => {
    const currentRevisionId = getCurrentRevisionId(state);
    if (!currentRevisionId) {
      return void 0;
    }
    const page = getRevisionPage(state);
    if (!page) {
      return null;
    }
    const { type: postType, id: postId } = getCurrentPost(state);
    const entityConfig = select(coreStore).getEntityConfig(
      "postType",
      postType
    );
    const revisionKey = entityConfig?.revisionKey || "id";
    const query = buildRevisionsPageQuery(revisionKey, page);
    const revisions = select(coreStore).getRevisions(
      "postType",
      postType,
      postId,
      query
    );
    if (!revisions) {
      return null;
    }
    const currentIndex = revisions.findIndex(
      (r) => r[revisionKey] === currentRevisionId
    );
    if (currentIndex >= 0 && currentIndex < revisions.length - 1) {
      return revisions[currentIndex + 1];
    }
    const totalRevisions = getCurrentPostRevisionsCount(state);
    const totalPages = Math.ceil(totalRevisions / query.per_page) || 1;
    if (currentIndex === revisions.length - 1 && page < totalPages) {
      const nextPageRevisions = select(coreStore).getRevisions(
        "postType",
        postType,
        postId,
        buildRevisionsPageQuery(revisionKey, page + 1)
      );
      return nextPageRevisions?.[0] ?? null;
    }
    return null;
  }
);
export {
  buildRevisionsPageQuery,
  getCurrentRevision,
  getCurrentRevisionId,
  getDefaultRenderingMode,
  getEntityActions,
  getEntityFields,
  getInserter,
  getInserterSidebarToggleRef,
  getListViewToggleRef,
  getPageRevisions,
  getPostBlocksByName,
  getPostIcon,
  getPreviousRevision,
  getRevisionPage,
  getRevisionsPerPage,
  getSelectedNote,
  getShowStylebook,
  getStylesPath,
  hasPostMetaChanges,
  isEntityReady,
  isNoteFocused,
  isRevisionsMode,
  isShowingRevisionDiff
};
//# sourceMappingURL=private-selectors.mjs.map
