"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _components = require("@wordpress/components");
var _coreData = require("@wordpress/core-data");
var _data = require("@wordpress/data");
var _element = require("@wordpress/element");
var _i18n = require("@wordpress/i18n");
var _icons = require("@wordpress/icons");
var _blockEditor = require("@wordpress/block-editor");
var _context = require("./context");
var _fontCard = _interopRequireDefault(require("./font-card"));
var _libraryFontVariant = _interopRequireDefault(require("./library-font-variant"));
var _sortFontFaces = require("./utils/sort-font-faces");
var _utils = require("./utils");
var _lockUnlock = require("../../../lock-unlock");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  useGlobalSetting
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
function InstalledFonts() {
  var _libraryFontSelected$;
  const {
    baseCustomFonts,
    libraryFontSelected,
    handleSetLibraryFontSelected,
    refreshLibrary,
    uninstallFontFamily,
    isResolvingLibrary,
    isInstalling,
    saveFontFamilies,
    getFontFacesActivated
  } = (0, _element.useContext)(_context.FontLibraryContext);
  const [fontFamilies, setFontFamilies] = useGlobalSetting('typography.fontFamilies');
  const [isConfirmDeleteOpen, setIsConfirmDeleteOpen] = (0, _element.useState)(false);
  const [notice, setNotice] = (0, _element.useState)(false);
  const [baseFontFamilies] = useGlobalSetting('typography.fontFamilies', undefined, 'base');
  const globalStylesId = (0, _data.useSelect)(select => {
    const {
      __experimentalGetCurrentGlobalStylesId
    } = select(_coreData.store);
    return __experimentalGetCurrentGlobalStylesId();
  });
  const globalStyles = (0, _coreData.useEntityRecord)('root', 'globalStyles', globalStylesId);
  const fontFamiliesHasChanges = !!globalStyles?.edits?.settings?.typography?.fontFamilies;
  const themeFonts = fontFamilies?.theme ? fontFamilies.theme.map(f => (0, _utils.setUIValuesNeeded)(f, {
    source: 'theme'
  })).sort((a, b) => a.name.localeCompare(b.name)) : [];
  const themeFontsSlugs = new Set(themeFonts.map(f => f.slug));
  const baseThemeFonts = baseFontFamilies?.theme ? themeFonts.concat(baseFontFamilies.theme.filter(f => !themeFontsSlugs.has(f.slug)).map(f => (0, _utils.setUIValuesNeeded)(f, {
    source: 'theme'
  })).sort((a, b) => a.name.localeCompare(b.name))) : [];
  const customFontFamilyId = libraryFontSelected?.source === 'custom' && libraryFontSelected?.id;
  const canUserDelete = (0, _data.useSelect)(select => {
    const {
      canUser
    } = select(_coreData.store);
    return customFontFamilyId && canUser('delete', {
      kind: 'postType',
      name: 'wp_font_family',
      id: customFontFamilyId
    });
  }, [customFontFamilyId]);
  const shouldDisplayDeleteButton = !!libraryFontSelected && libraryFontSelected?.source !== 'theme' && canUserDelete;
  const handleUninstallClick = () => {
    setIsConfirmDeleteOpen(true);
  };
  const handleUpdate = async () => {
    setNotice(null);
    try {
      await saveFontFamilies(fontFamilies);
      setNotice({
        type: 'success',
        message: (0, _i18n.__)('Font family updated successfully.')
      });
    } catch (error) {
      setNotice({
        type: 'error',
        message: (0, _i18n.sprintf)(/* translators: %s: error message */
        (0, _i18n.__)('There was an error updating the font family. %s'), error.message)
      });
    }
  };
  const getFontFacesToDisplay = font => {
    if (!font) {
      return [];
    }
    if (!font.fontFace || !font.fontFace.length) {
      return [{
        fontFamily: font.fontFamily,
        fontStyle: 'normal',
        fontWeight: '400'
      }];
    }
    return (0, _sortFontFaces.sortFontFaces)(font.fontFace);
  };
  const getFontCardVariantsText = font => {
    const variantsInstalled = font?.fontFace?.length > 0 ? font.fontFace.length : 1;
    const variantsActive = getFontFacesActivated(font.slug, font.source).length;
    return (0, _i18n.sprintf)(/* translators: 1: Active font variants, 2: Total font variants. */
    (0, _i18n.__)('%1$s/%2$s variants active'), variantsActive, variantsInstalled);
  };
  (0, _element.useEffect)(() => {
    handleSetLibraryFontSelected(libraryFontSelected);
    refreshLibrary();
  }, []);

  // Get activated fonts count.
  const activeFontsCount = libraryFontSelected ? getFontFacesActivated(libraryFontSelected.slug, libraryFontSelected.source).length : 0;
  const selectedFontsCount = (_libraryFontSelected$ = libraryFontSelected?.fontFace?.length) !== null && _libraryFontSelected$ !== void 0 ? _libraryFontSelected$ : libraryFontSelected?.fontFamily ? 1 : 0;

  // Check if any fonts are selected.
  const isIndeterminate = activeFontsCount > 0 && activeFontsCount !== selectedFontsCount;

  // Check if all fonts are selected.
  const isSelectAllChecked = activeFontsCount === selectedFontsCount;

  // Toggle select all fonts.
  const toggleSelectAll = () => {
    var _fontFamilies$library;
    const initialFonts = (_fontFamilies$library = fontFamilies?.[libraryFontSelected.source]?.filter(f => f.slug !== libraryFontSelected.slug)) !== null && _fontFamilies$library !== void 0 ? _fontFamilies$library : [];
    const newFonts = isSelectAllChecked ? initialFonts : [...initialFonts, libraryFontSelected];
    setFontFamilies({
      ...fontFamilies,
      [libraryFontSelected.source]: newFonts
    });
    if (libraryFontSelected.fontFace) {
      libraryFontSelected.fontFace.forEach(face => {
        if (isSelectAllChecked) {
          (0, _utils.unloadFontFaceInBrowser)(face, 'all');
        } else {
          (0, _utils.loadFontFaceInBrowser)(face, (0, _utils.getDisplaySrcFromFontFace)(face?.src), 'all');
        }
      });
    }
  };
  const hasFonts = baseThemeFonts.length > 0 || baseCustomFonts.length > 0;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "font-library-modal__tabpanel-layout",
    children: [isResolvingLibrary && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "font-library-modal__loading",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.ProgressBar, {})
    }), !isResolvingLibrary && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Navigator, {
        initialPath: libraryFontSelected ? '/fontFamily' : '/',
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Navigator.Screen, {
          path: "/",
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
            spacing: "8",
            children: [notice && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Notice, {
              status: notice.type,
              onRemove: () => setNotice(null),
              children: notice.message
            }), !hasFonts && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalText, {
              as: "p",
              children: (0, _i18n.__)('No fonts installed.')
            }), baseThemeFonts.length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
                className: "font-library-modal__fonts-title",
                children: /* translators: Heading for a list of fonts provided by the theme. */
                (0, _i18n._x)('Theme', 'font source')
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)("ul", {
                role: "list",
                className: "font-library-modal__fonts-list",
                children: baseThemeFonts.map(font => /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
                  className: "font-library-modal__fonts-list-item",
                  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontCard.default, {
                    font: font,
                    navigatorPath: "/fontFamily",
                    variantsText: getFontCardVariantsText(font),
                    onClick: () => {
                      setNotice(null);
                      handleSetLibraryFontSelected(font);
                    }
                  })
                }, font.slug))
              })]
            }), baseCustomFonts.length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
                className: "font-library-modal__fonts-title",
                children: /* translators: Heading for a list of fonts installed by the user. */
                (0, _i18n._x)('Custom', 'font source')
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)("ul", {
                role: "list",
                className: "font-library-modal__fonts-list",
                children: baseCustomFonts.map(font => /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
                  className: "font-library-modal__fonts-list-item",
                  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontCard.default, {
                    font: font,
                    navigatorPath: "/fontFamily",
                    variantsText: getFontCardVariantsText(font),
                    onClick: () => {
                      setNotice(null);
                      handleSetLibraryFontSelected(font);
                    }
                  })
                }, font.slug))
              })]
            })]
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Navigator.Screen, {
          path: "/fontFamily",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(ConfirmDeleteDialog, {
            font: libraryFontSelected,
            isOpen: isConfirmDeleteOpen,
            setIsOpen: setIsConfirmDeleteOpen,
            setNotice: setNotice,
            uninstallFontFamily: uninstallFontFamily,
            handleSetLibraryFontSelected: handleSetLibraryFontSelected
          }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Flex, {
            justify: "flex-start",
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Navigator.BackButton, {
              icon: (0, _i18n.isRTL)() ? _icons.chevronRight : _icons.chevronLeft,
              size: "small",
              onClick: () => {
                handleSetLibraryFontSelected(null);
                setNotice(null);
              },
              label: (0, _i18n.__)('Back')
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalHeading, {
              level: 2,
              size: 13,
              className: "edit-site-global-styles-header",
              children: libraryFontSelected?.name
            })]
          }), notice && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
              margin: 1
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Notice, {
              status: notice.type,
              onRemove: () => setNotice(null),
              children: notice.message
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
              margin: 1
            })]
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
            margin: 4
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalText, {
            children: (0, _i18n.__)('Choose font variants. Keep in mind that too many variants could make your site slower.')
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
            margin: 4
          }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
            spacing: 0,
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.CheckboxControl, {
              className: "font-library-modal__select-all",
              label: (0, _i18n.__)('Select all'),
              checked: isSelectAllChecked,
              onChange: toggleSelectAll,
              indeterminate: isIndeterminate,
              __nextHasNoMarginBottom: true
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
              margin: 8
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)("ul", {
              role: "list",
              className: "font-library-modal__fonts-list",
              children: getFontFacesToDisplay(libraryFontSelected).map((face, i) => /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
                className: "font-library-modal__fonts-list-item",
                children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_libraryFontVariant.default, {
                  font: libraryFontSelected,
                  face: face
                }, `face${i}`)
              }, `face${i}`))
            })]
          })]
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
        justify: "flex-end",
        className: "font-library-modal__footer",
        children: [isInstalling && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.ProgressBar, {}), shouldDisplayDeleteButton && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          __next40pxDefaultSize: true,
          isDestructive: true,
          variant: "tertiary",
          onClick: handleUninstallClick,
          children: (0, _i18n.__)('Delete')
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          __next40pxDefaultSize: true,
          variant: "primary",
          onClick: handleUpdate,
          disabled: !fontFamiliesHasChanges,
          accessibleWhenDisabled: true,
          children: (0, _i18n.__)('Update')
        })]
      })]
    })]
  });
}
function ConfirmDeleteDialog({
  font,
  isOpen,
  setIsOpen,
  setNotice,
  uninstallFontFamily,
  handleSetLibraryFontSelected
}) {
  const navigator = (0, _components.useNavigator)();
  const handleConfirmUninstall = async () => {
    setNotice(null);
    setIsOpen(false);
    try {
      await uninstallFontFamily(font);
      navigator.goBack();
      handleSetLibraryFontSelected(null);
      setNotice({
        type: 'success',
        message: (0, _i18n.__)('Font family uninstalled successfully.')
      });
    } catch (error) {
      setNotice({
        type: 'error',
        message: (0, _i18n.__)('There was an error uninstalling the font family.') + error.message
      });
    }
  };
  const handleCancelUninstall = () => {
    setIsOpen(false);
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalConfirmDialog, {
    isOpen: isOpen,
    cancelButtonText: (0, _i18n.__)('Cancel'),
    confirmButtonText: (0, _i18n.__)('Delete'),
    onCancel: handleCancelUninstall,
    onConfirm: handleConfirmUninstall,
    size: "medium",
    children: font && (0, _i18n.sprintf)(/* translators: %s: Name of the font. */
    (0, _i18n.__)('Are you sure you want to delete "%s" font and all its variants and assets?'), font.name)
  });
}
var _default = exports.default = InstalledFonts;
//# sourceMappingURL=installed-fonts.js.map