"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _clsx = _interopRequireDefault(require("clsx"));
var _components = require("@wordpress/components");
var _i18n = require("@wordpress/i18n");
var _blockEditor = require("@wordpress/block-editor");
var _editor = require("@wordpress/editor");
var _data = require("@wordpress/data");
var _compose = require("@wordpress/compose");
var _element = require("@wordpress/element");
var _keycodes = require("@wordpress/keycodes");
var _lockUnlock = require("../../lock-unlock");
var _editorCanvasContainer = _interopRequireDefault(require("../editor-canvas-container"));
var _constants = require("./constants");
var _categories = require("./categories");
var _examples = require("./examples");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  ExperimentalBlockEditorProvider,
  useGlobalStyle,
  GlobalStylesContext,
  useGlobalStylesOutputWithConfig
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
const {
  mergeBaseAndUserConfigs
} = (0, _lockUnlock.unlock)(_editor.privateApis);
const {
  Tabs
} = (0, _lockUnlock.unlock)(_components.privateApis);
function isObjectEmpty(object) {
  return !object || Object.keys(object).length === 0;
}
function StyleBook({
  enableResizing = true,
  isSelected,
  onClick,
  onSelect,
  showCloseButton = true,
  onClose,
  showTabs = true,
  userConfig = {}
}) {
  const [resizeObserver, sizes] = (0, _compose.useResizeObserver)();
  const [textColor] = useGlobalStyle('color.text');
  const [backgroundColor] = useGlobalStyle('color.background');
  const [examples] = (0, _element.useState)(_examples.getExamples);
  const tabs = (0, _element.useMemo)(() => (0, _categories.getTopLevelStyleBookCategories)().filter(category => examples.some(example => example.category === category.slug)), [examples]);
  const {
    base: baseConfig
  } = (0, _element.useContext)(GlobalStylesContext);
  const mergedConfig = (0, _element.useMemo)(() => {
    if (!isObjectEmpty(userConfig) && !isObjectEmpty(baseConfig)) {
      return mergeBaseAndUserConfigs(baseConfig, userConfig);
    }
    return {};
  }, [baseConfig, userConfig]);

  // Copied from packages/edit-site/src/components/revisions/index.js
  // could we create a shared hook?
  const originalSettings = (0, _data.useSelect)(select => select(_blockEditor.store).getSettings(), []);
  const settings = (0, _element.useMemo)(() => ({
    ...originalSettings,
    __unstableIsPreviewMode: true
  }), [originalSettings]);
  const [globalStyles] = useGlobalStylesOutputWithConfig(mergedConfig);
  settings.styles = !isObjectEmpty(globalStyles) && !isObjectEmpty(userConfig) ? globalStyles : settings.styles;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_editorCanvasContainer.default, {
    onClose: onClose,
    enableResizing: enableResizing,
    closeButtonLabel: showCloseButton ? (0, _i18n.__)('Close') : null,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: (0, _clsx.default)('edit-site-style-book', {
        'is-wide': sizes.width > 600,
        'is-button': !!onClick
      }),
      style: {
        color: textColor,
        background: backgroundColor
      },
      children: [resizeObserver, showTabs ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "edit-site-style-book__tabs",
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(Tabs, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "edit-site-style-book__tablist-container",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Tabs.TabList, {
              children: tabs.map(tab => /*#__PURE__*/(0, _jsxRuntime.jsx)(Tabs.Tab, {
                tabId: tab.slug,
                children: tab.title
              }, tab.slug))
            })
          }), tabs.map(tab => /*#__PURE__*/(0, _jsxRuntime.jsx)(Tabs.TabPanel, {
            tabId: tab.slug,
            focusable: false,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(StyleBookBody, {
              category: tab.slug,
              examples: examples,
              isSelected: isSelected,
              onSelect: onSelect,
              settings: settings,
              sizes: sizes,
              title: tab.title
            })
          }, tab.slug))]
        })
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(StyleBookBody, {
        examples: examples,
        isSelected: isSelected,
        onClick: onClick,
        onSelect: onSelect,
        settings: settings,
        sizes: sizes
      })]
    })
  });
}
const StyleBookBody = ({
  category,
  examples,
  isSelected,
  onClick,
  onSelect,
  settings,
  sizes,
  title
}) => {
  const [isFocused, setIsFocused] = (0, _element.useState)(false);

  // The presence of an `onClick` prop indicates that the Style Book is being used as a button.
  // In this case, add additional props to the iframe to make it behave like a button.
  const buttonModeProps = {
    role: 'button',
    onFocus: () => setIsFocused(true),
    onBlur: () => setIsFocused(false),
    onKeyDown: event => {
      if (event.defaultPrevented) {
        return;
      }
      const {
        keyCode
      } = event;
      if (onClick && (keyCode === _keycodes.ENTER || keyCode === _keycodes.SPACE)) {
        event.preventDefault();
        onClick(event);
      }
    },
    onClick: event => {
      if (event.defaultPrevented) {
        return;
      }
      if (onClick) {
        event.preventDefault();
        onClick(event);
      }
    },
    readonly: true
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_blockEditor.__unstableIframe, {
    className: (0, _clsx.default)('edit-site-style-book__iframe', {
      'is-focused': isFocused && !!onClick,
      'is-button': !!onClick
    }),
    name: "style-book-canvas",
    tabIndex: 0,
    ...(onClick ? buttonModeProps : {}),
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.__unstableEditorStyles, {
      styles: settings.styles
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("style", {
      children: [_constants.STYLE_BOOK_IFRAME_STYLES, !!onClick && 'body { cursor: pointer; } body * { pointer-events: none; }']
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(Examples, {
      className: (0, _clsx.default)('edit-site-style-book__examples', {
        'is-wide': sizes.width > 600
      }),
      examples: examples,
      category: category,
      label: title ? (0, _i18n.sprintf)(
      // translators: %s: Category of blocks, e.g. Text.
      (0, _i18n.__)('Examples of blocks in the %s category'), title) : (0, _i18n.__)('Examples of blocks'),
      isSelected: isSelected,
      onSelect: onSelect
    }, category)]
  });
};
const Examples = (0, _element.memo)(({
  className,
  examples,
  category,
  label,
  isSelected,
  onSelect
}) => {
  const categoryDefinition = category ? (0, _categories.getTopLevelStyleBookCategories)().find(_category => _category.slug === category) : null;
  const filteredExamples = categoryDefinition ? (0, _categories.getExamplesByCategory)(categoryDefinition, examples) : {
    examples
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Composite, {
    orientation: "vertical",
    className: className,
    "aria-label": label,
    role: "grid",
    children: [!!filteredExamples?.examples?.length && filteredExamples.examples.map(example => /*#__PURE__*/(0, _jsxRuntime.jsx)(Example, {
      id: `example-${example.name}`,
      title: example.title,
      blocks: example.blocks,
      isSelected: isSelected(example.name),
      onClick: () => {
        onSelect?.(example.name);
      }
    }, example.name)), !!filteredExamples?.subcategories?.length && filteredExamples.subcategories.map(subcategory => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Composite.Group, {
      className: "edit-site-style-book__subcategory",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Composite.GroupLabel, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
          className: "edit-site-style-book__subcategory-title",
          children: subcategory.title
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(Subcategory, {
        examples: subcategory.examples,
        isSelected: isSelected,
        onSelect: onSelect
      })]
    }, `subcategory-${subcategory.slug}`))]
  });
});
const Subcategory = ({
  examples,
  isSelected,
  onSelect
}) => {
  return !!examples?.length && examples.map(example => /*#__PURE__*/(0, _jsxRuntime.jsx)(Example, {
    id: `example-${example.name}`,
    title: example.title,
    blocks: example.blocks,
    isSelected: isSelected(example.name),
    onClick: () => {
      onSelect?.(example.name);
    }
  }, example.name));
};
const Example = ({
  id,
  title,
  blocks,
  isSelected,
  onClick
}) => {
  const originalSettings = (0, _data.useSelect)(select => select(_blockEditor.store).getSettings(), []);
  const settings = (0, _element.useMemo)(() => ({
    ...originalSettings,
    focusMode: false,
    // Disable "Spotlight mode".
    __unstableIsPreviewMode: true
  }), [originalSettings]);

  // Cache the list of blocks to avoid additional processing when the component is re-rendered.
  const renderedBlocks = (0, _element.useMemo)(() => Array.isArray(blocks) ? blocks : [blocks], [blocks]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    role: "row",
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      role: "gridcell",
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Composite.Item, {
        className: (0, _clsx.default)('edit-site-style-book__example', {
          'is-selected': isSelected
        }),
        id: id,
        "aria-label": (0, _i18n.sprintf)(
        // translators: %s: Title of a block, e.g. Heading.
        (0, _i18n.__)('Open %s styles in Styles panel'), title),
        render: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {}),
        role: "button",
        onClick: onClick,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "edit-site-style-book__example-title",
          children: title
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "edit-site-style-book__example-preview",
          "aria-hidden": true,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Disabled, {
            className: "edit-site-style-book__example-preview__content",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(ExperimentalBlockEditorProvider, {
              value: renderedBlocks,
              settings: settings,
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.BlockList, {
                renderAppender: false
              })
            })
          })
        })]
      })
    })
  });
};
var _default = exports.default = StyleBook;
//# sourceMappingURL=index.js.map