@wordpress/global-styles-ui
Version:
Global Styles UI components for WordPress.
374 lines (373 loc) • 15.4 kB
JavaScript
import { createInterpolateElement, useContext, useEffect, useMemo, useState } from "@wordpress/element";
import { Button, CheckboxControl, Flex, Navigator, Notice, SearchControl, __experimentalHStack, __experimentalHeading, __experimentalSpacer, __experimentalText, __experimentalVStack } from "@wordpress/components";
import { Menu, Progress, Select, SelectControl, useEnableWpCompatOverlaySlot } from "@wordpress/ui";
import { debounce } from "@wordpress/compose";
import { __, _n, _x, isRTL, sprintf } from "@wordpress/i18n";
import { speak } from "@wordpress/a11y";
import { chevronLeft, chevronRight, moreVertical, next, previous } from "@wordpress/icons";
import { useEntityRecord } from "@wordpress/core-data";
import { FontLibraryContext } from "./context.mjs";
import FontCard from "./font-card.mjs";
import filterFonts from "./utils/filter-fonts.mjs";
import { toggleFont } from "./utils/toggleFont.mjs";
import { getFontsOutline, isFontFontFaceInOutline } from "./utils/fonts-outline.mjs";
import GoogleFontsConfirmDialog from "./google-fonts-confirm-dialog.mjs";
import { downloadFontFaceAssets } from "./utils/index.mjs";
import { sortFontFaces } from "./utils/sort-font-faces.mjs";
import CollectionFontVariant from "./collection-font-variant.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/global-styles-ui/src/font-library/font-collection.tsx
const DEFAULT_CATEGORY = {
slug: "all",
name: _x("All", "font categories")
};
const LOCAL_STORAGE_ITEM = "wp-font-library-google-fonts-permission";
const MIN_WINDOW_HEIGHT = 500;
function FontCollection({ slug }) {
useEnableWpCompatOverlaySlot();
const requiresPermission = slug === "google-fonts";
const getGoogleFontsPermissionFromStorage = () => {
return window.localStorage.getItem(LOCAL_STORAGE_ITEM) === "true";
};
const [selectedFont, setSelectedFont] = useState(null);
const [lastSelectedFontSlug, setLastSelectedFontSlug] = useState(void 0);
const [notice, setNotice] = useState(null);
const [fontsToInstall, setFontsToInstall] = useState([]);
const [page, setPage] = useState(1);
const [filters, setFilters] = useState({});
const [renderConfirmDialog, setRenderConfirmDialog] = useState(requiresPermission && !getGoogleFontsPermissionFromStorage());
const { installFonts, isInstalling, baseCustomFonts } = useContext(FontLibraryContext);
const { record: selectedCollection, isResolving: isLoading } = useEntityRecord("root", "fontCollection", slug);
useEffect(() => {
const handleStorage = () => {
setRenderConfirmDialog(requiresPermission && !getGoogleFontsPermissionFromStorage());
};
handleStorage();
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, [slug, requiresPermission]);
const revokeAccess = () => {
window.localStorage.setItem(LOCAL_STORAGE_ITEM, "false");
window.dispatchEvent(new Event("storage"));
};
useEffect(() => {
setSelectedFont(null);
}, [slug]);
useEffect(() => {
setFontsToInstall([]);
}, [selectedFont]);
const collectionFonts = useMemo(() => selectedCollection?.font_families ?? [], [selectedCollection]);
const collectionCategories = selectedCollection?.categories ?? [];
const categoryItems = [DEFAULT_CATEGORY, ...collectionCategories].map((category) => ({
label: category.name,
value: category.slug
}));
const selectedCategoryItem = categoryItems.find((item) => item.value === filters.category) ?? categoryItems[0];
const fonts = useMemo(() => filterFonts(collectionFonts, filters), [collectionFonts, filters]);
const hasFilters = filters.search !== void 0 || filters.category !== void 0;
useEffect(() => {
if (!hasFilters) return;
speak(fonts.length ? sprintf(_n("%d font found.", "%d fonts found.", fonts.length), fonts.length) : __("No fonts found. Try with a different search term."));
}, [hasFilters, fonts]);
const windowHeight = Math.max(window.innerHeight, MIN_WINDOW_HEIGHT);
const pageSize = Math.floor((windowHeight - 417) / 61);
const totalPages = Math.ceil(fonts.length / pageSize);
const itemsStart = (page - 1) * pageSize;
const itemsLimit = page * pageSize;
const items = fonts.slice(itemsStart, itemsLimit);
const handleCategoryFilter = (category) => {
setFilters({
...filters,
category
});
setPage(1);
};
const handleUpdateSearchInput = (value) => {
setFilters({
...filters,
search: value
});
setPage(1);
};
const debouncedUpdateSearchInput = debounce(handleUpdateSearchInput, 300);
const handleToggleVariant = (font, face) => {
const newFontsToInstall = toggleFont(font, face, fontsToInstall);
setFontsToInstall(newFontsToInstall);
};
const fontToInstallOutline = getFontsOutline(fontsToInstall);
const installedFontsOutline = getFontsOutline(baseCustomFonts);
const isFontFaceInstalled = (face) => !!selectedFont && isFontFontFaceInOutline(selectedFont.slug, selectedFont.fontFace ? face : null, installedFontsOutline);
const installableFontFaces = selectedFont?.fontFace?.filter((face) => !isFontFaceInstalled(face));
const isAllInstalled = !!selectedFont && (selectedFont.fontFace?.length ? installableFontFaces?.length === 0 : isFontFontFaceInOutline(selectedFont.slug, null, installedFontsOutline));
const resetFontsToInstall = () => {
setFontsToInstall([]);
};
const selectFontCount = fontsToInstall.length > 0 ? fontsToInstall[0]?.fontFace?.length ?? 0 : 0;
const isIndeterminate = selectFontCount > 0 && selectFontCount !== installableFontFaces?.length;
const isSelectAllChecked = selectFontCount === installableFontFaces?.length;
const toggleSelectAll = () => {
const newFonts = [];
if (!isSelectAllChecked && selectedFont) newFonts.push(selectedFont.fontFace ? {
...selectedFont,
fontFace: installableFontFaces
} : selectedFont);
setFontsToInstall(newFonts);
};
const handleInstall = async () => {
setNotice(null);
const fontFamily = fontsToInstall[0];
try {
if (fontFamily?.fontFace) await Promise.all(fontFamily.fontFace.map(async (fontFace) => {
if (fontFace.src) fontFace.file = await downloadFontFaceAssets(fontFace.src);
}));
} catch {
setNotice({
type: "error",
message: __("Error installing the fonts, could not be downloaded.")
});
return;
}
try {
await installFonts([fontFamily]);
setNotice({
type: "success",
message: __("Fonts were installed successfully.")
});
} catch (error) {
setNotice({
type: "error",
message: error.message
});
}
resetFontsToInstall();
};
const getSortedFontFaces = (fontFamily) => {
if (!fontFamily) return [];
if (!fontFamily.fontFace || !fontFamily.fontFace.length) return [{
fontFamily: fontFamily.fontFamily,
fontStyle: "normal",
fontWeight: "400"
}];
return sortFontFaces(fontFamily.fontFace);
};
if (renderConfirmDialog) return /* @__PURE__ */ jsx(GoogleFontsConfirmDialog, {});
const showActions = slug === "google-fonts" && !renderConfirmDialog && !selectedFont;
return /* @__PURE__ */ jsxs("div", {
className: "font-library__tabpanel-layout",
children: [isLoading && /* @__PURE__ */ jsx("div", {
className: "font-library__loading",
children: /* @__PURE__ */ jsx(Progress.Root, {
value: null,
"aria-label": __("Loading fonts"),
children: /* @__PURE__ */ jsx(Progress.Track, { children: /* @__PURE__ */ jsx(Progress.Indicator, {}) })
})
}), !isLoading && selectedCollection && /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(Navigator, {
initialPath: "/",
className: "font-library__tabpanel-layout",
children: [/* @__PURE__ */ jsxs(Navigator.Screen, {
path: "/",
children: [
/* @__PURE__ */ jsxs(__experimentalHStack, {
justify: "space-between",
children: [/* @__PURE__ */ jsxs(__experimentalVStack, { children: [/* @__PURE__ */ jsx(__experimentalHeading, {
level: 2,
size: 13,
children: selectedCollection.name
}), /* @__PURE__ */ jsx(__experimentalText, { children: selectedCollection.description })] }), showActions && /* @__PURE__ */ jsxs(Menu.Root, { children: [/* @__PURE__ */ jsx(Menu.Trigger, { render: /* @__PURE__ */ jsx(Button, {
size: "small",
icon: moreVertical,
label: __("Actions")
}) }), /* @__PURE__ */ jsx(Menu.Popup, {
positioner: /* @__PURE__ */ jsx(Menu.Positioner, {
side: "bottom",
align: "end"
}),
children: /* @__PURE__ */ jsx(Menu.Item, {
onClick: revokeAccess,
children: /* @__PURE__ */ jsx(Menu.ItemLabel, { children: __("Revoke access to Google Fonts") })
})
})] })]
}),
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 4 }),
/* @__PURE__ */ jsxs(__experimentalHStack, {
spacing: 4,
justify: "space-between",
children: [/* @__PURE__ */ jsx(SearchControl, {
className: "font-library__search",
value: filters.search,
placeholder: __("Font name…"),
label: __("Search"),
onChange: debouncedUpdateSearchInput,
hideLabelFromVision: false
}), /* @__PURE__ */ jsx(SelectControl, {
className: "font-library__category",
label: __("Category"),
items: categoryItems,
value: selectedCategoryItem,
itemToStringValue: (item) => JSON.stringify(item.value),
onValueChange: (item) => {
if (item && item.value !== null && item.value !== selectedCategoryItem.value) handleCategoryFilter(item.value);
}
})]
}),
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 4 }),
!!selectedCollection?.font_families?.length && !fonts.length && /* @__PURE__ */ jsx(__experimentalText, { children: __("No fonts found. Try with a different search term.") }),
/* @__PURE__ */ jsx("div", {
className: "font-library__fonts-grid__main",
children: /* @__PURE__ */ jsx("ul", {
role: "list",
className: "font-library__fonts-list",
children: items.map((font) => /* @__PURE__ */ jsx("li", {
className: "font-library__fonts-list-item",
children: /* @__PURE__ */ jsx(FontCard, {
font: font.font_family_settings,
navigatorPath: "/fontFamily",
shouldFocus: font.font_family_settings.slug === lastSelectedFontSlug,
onClick: () => {
setSelectedFont(font.font_family_settings);
}
})
}, font.font_family_settings.slug))
})
})
]
}), /* @__PURE__ */ jsxs(Navigator.Screen, {
path: "/fontFamily",
children: [
/* @__PURE__ */ jsxs(Flex, {
justify: "flex-start",
children: [/* @__PURE__ */ jsx(Navigator.BackButton, {
icon: isRTL() ? chevronRight : chevronLeft,
size: "small",
onClick: () => {
setLastSelectedFontSlug(selectedFont?.slug);
setSelectedFont(null);
setNotice(null);
},
label: __("Back")
}), /* @__PURE__ */ jsx(__experimentalHeading, {
level: 2,
size: 13,
className: "global-styles-ui-header",
children: selectedFont?.name
})]
}),
notice && /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 1 }),
/* @__PURE__ */ jsx(Notice, {
status: notice.type,
onRemove: () => setNotice(null),
children: notice.message
}),
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 1 })
] }),
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 4 }),
/* @__PURE__ */ jsx(__experimentalText, { children: __("Select font variants to install.") }),
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 4 }),
/* @__PURE__ */ jsx(CheckboxControl, {
className: "font-library__select-all",
label: __("Select all"),
checked: isSelectAllChecked || isAllInstalled,
onChange: toggleSelectAll,
indeterminate: isIndeterminate,
disabled: isAllInstalled
}),
/* @__PURE__ */ jsx(__experimentalVStack, {
spacing: 0,
children: /* @__PURE__ */ jsx("ul", {
role: "list",
className: "font-library__fonts-list",
children: selectedFont && getSortedFontFaces(selectedFont).map((face, i) => /* @__PURE__ */ jsx("li", {
className: "font-library__fonts-list-item",
children: /* @__PURE__ */ jsx(CollectionFontVariant, {
font: selectedFont,
face,
handleToggleVariant,
selected: isFontFontFaceInOutline(selectedFont.slug, selectedFont.fontFace ? face : null, fontToInstallOutline),
installed: isFontFaceInstalled(face)
})
}, `face${i}`))
})
}),
/* @__PURE__ */ jsx(__experimentalSpacer, { margin: 16 })
]
})]
}),
selectedFont && /* @__PURE__ */ jsx(Flex, {
justify: "flex-end",
className: "font-library__footer",
children: /* @__PURE__ */ jsx(Button, {
__next40pxDefaultSize: true,
variant: "primary",
onClick: handleInstall,
isBusy: isInstalling,
disabled: fontsToInstall.length === 0 || isInstalling,
accessibleWhenDisabled: true,
children: __("Install")
})
}),
!selectedFont && /* @__PURE__ */ jsxs(__experimentalHStack, {
expanded: false,
className: "font-library__footer",
justify: "end",
spacing: 6,
children: [/* @__PURE__ */ jsx(__experimentalHStack, {
justify: "flex-start",
expanded: false,
spacing: 1,
className: "font-library__page-selection",
children: createInterpolateElement(sprintf(_x("<div>Page</div>%1$s<div>of %2$d</div>", "paging"), "<CurrentPage />", totalPages), {
div: /* @__PURE__ */ jsx("div", { "aria-hidden": true }),
CurrentPage: /* @__PURE__ */ jsxs(Select.Root, {
value: page.toString(),
onValueChange: (newPage) => {
if (newPage !== null) setPage(parseInt(newPage));
},
children: [/* @__PURE__ */ jsx(Select.Trigger, {
className: "font-library__page-selection-trigger",
size: "small",
variant: "minimal",
"aria-label": __("Current page")
}), /* @__PURE__ */ jsx(Select.Popup, {
width: "content",
children: [...Array(totalPages)].map((e, i) => {
const value = (i + 1).toString();
return /* @__PURE__ */ jsx(Select.Item, {
value,
size: "small",
children: /* @__PURE__ */ jsx(Select.ItemLabel, { children: value })
}, value);
})
})]
})
})
}), /* @__PURE__ */ jsxs(__experimentalHStack, {
expanded: false,
spacing: 1,
children: [/* @__PURE__ */ jsx(Button, {
onClick: () => setPage(page - 1),
disabled: page === 1,
accessibleWhenDisabled: true,
label: __("Previous page"),
icon: isRTL() ? next : previous,
showTooltip: true,
size: "compact",
tooltipPosition: "top"
}), /* @__PURE__ */ jsx(Button, {
onClick: () => setPage(page + 1),
disabled: page === totalPages,
accessibleWhenDisabled: true,
label: __("Next page"),
icon: isRTL() ? previous : next,
showTooltip: true,
size: "compact",
tooltipPosition: "top"
})]
})]
})
] })]
});
}
export { FontCollection as default };
//# sourceMappingURL=font-collection.mjs.map