@wordpress/global-styles-ui
Version:
Global Styles UI components for WordPress.
197 lines (196 loc) • 7.1 kB
JavaScript
import { Progress } from "@wordpress/ui";
import { __, sprintf } from "@wordpress/i18n";
import { Button, DropZone, FlexItem, FormFileUpload, Notice, __experimentalText, __experimentalVStack } from "@wordpress/components";
import { useContext, useState } from "@wordpress/element";
import { ALLOWED_FILE_EXTENSIONS } from "./utils/constants.mjs";
import { FontLibraryContext } from "./context.mjs";
import { Font } from "./lib/lib-font.browser.mjs";
import makeFamiliesFromFaces from "./utils/make-families-from-faces.mjs";
import { loadFontFaceInBrowser } from "./utils/index.mjs";
import { jsx, jsxs } from "react/jsx-runtime";
// packages/global-styles-ui/src/font-library/upload-fonts.tsx
function UploadFonts() {
const { installFonts } = useContext(FontLibraryContext);
const [isUploading, setIsUploading] = useState(false);
const [notice, setNotice] = useState(null);
const handleDropZone = (files) => {
handleFilesUpload(files);
};
const onFilesUpload = (event) => {
handleFilesUpload(event.target.files);
};
/**
* Filters the selected files to only allow the ones with the allowed extensions
*
* @param {Array} files The files to be filtered
* @return {void}
*/
const handleFilesUpload = async (files) => {
if (!files) return;
setNotice(null);
setIsUploading(true);
const uniqueFilenames = /* @__PURE__ */ new Set();
const selectedFiles = [...files];
let hasInvalidFiles = false;
const checkFilesPromises = selectedFiles.map(async (file) => {
if (!await isFontFile(file)) {
hasInvalidFiles = true;
return null;
}
if (uniqueFilenames.has(file.name)) return null;
const fileExtension = (((file.name ?? "").split(".") ?? []).pop() ?? "").toLowerCase();
if (ALLOWED_FILE_EXTENSIONS.includes(fileExtension)) {
uniqueFilenames.add(file.name);
return file;
}
return null;
});
const allowedFiles = (await Promise.all(checkFilesPromises)).filter((file) => null !== file);
if (allowedFiles.length > 0) loadFiles(allowedFiles);
else {
const message = hasInvalidFiles ? __("Sorry, you are not allowed to upload this file type.") : __("No fonts found to install.");
setNotice({
type: "error",
message
});
setIsUploading(false);
}
};
/**
* Loads the selected files and reads the font metadata
*
* @param {Array} files The files to be loaded
* @return {void}
*/
const loadFiles = async (files) => {
let fontFacesLoaded;
try {
fontFacesLoaded = await Promise.all(files.map(async (fontFile) => {
const fontFaceData = await getFontFaceMetadata(fontFile);
await loadFontFaceInBrowser(fontFaceData, fontFaceData.file, "all");
return fontFaceData;
}));
} catch (error) {
setNotice({
type: "error",
message: error.message
});
setIsUploading(false);
return;
}
handleInstall(fontFacesLoaded);
};
/**
* Checks if a file is a valid Font file.
*
* @param {File} file The file to be checked.
* @return {boolean} Whether the file is a valid font file.
*/
async function isFontFile(file) {
const font = new Font("Uploaded Font");
try {
const buffer = await readFileAsArrayBuffer(file);
await font.fromDataBuffer(buffer, "font");
return true;
} catch {
return false;
}
}
async function readFileAsArrayBuffer(file) {
return new Promise((resolve, reject) => {
const reader = new window.FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
}
/**
* Reads the family, style, and weight metadata from an uploaded font.
*
* @param fontFile The font file to parse.
* @return The font face metadata and the uploaded file.
*/
const getFontFaceMetadata = async (fontFile) => {
const buffer = await readFileAsArrayBuffer(fontFile);
const fontObj = new Font("Uploaded Font");
fontObj.fromDataBuffer(buffer, fontFile.name);
const font = (await new Promise((resolve) => fontObj.onload = resolve)).detail.font;
const { name } = font.opentype.tables;
const fontName = name?.get(16) || name?.get(1);
if (!fontName) throw new Error(sprintf(__("%s cannot be installed because it does not include a font family name. Try a different version of this font, for example one downloaded from the font's official source."), fontFile.name));
const isItalic = (name?.get(2) || "").toLowerCase().includes("italic");
const fontWeight = font.opentype.tables["OS/2"]?.usWeightClass || "normal";
const weightAxis = font.opentype.tables.fvar?.axes.find(({ tag }) => tag === "wght");
const weightRange = weightAxis ? `${weightAxis.minValue} ${weightAxis.maxValue}` : null;
return {
file: fontFile,
fontFamily: fontName,
fontStyle: isItalic ? "italic" : "normal",
fontWeight: weightRange || fontWeight
};
};
/**
* Creates the font family definition and sends it to the server
*
* @param {Array} fontFaces The font faces to be installed
* @return {void}
*/
const handleInstall = async (fontFaces) => {
try {
const fontFamilies = makeFamiliesFromFaces(fontFaces);
await installFonts(fontFamilies);
setNotice({
type: "success",
message: __("Fonts were installed successfully.")
});
} catch (error) {
const typedError = error;
setNotice({
type: "error",
message: typedError.message,
errors: typedError?.installationErrors
});
}
setIsUploading(false);
};
return /* @__PURE__ */ jsxs("div", {
className: "font-library__tabpanel-layout",
children: [/* @__PURE__ */ jsx(DropZone, { onFilesDrop: handleDropZone }), /* @__PURE__ */ jsxs(__experimentalVStack, {
className: "font-library__local-fonts",
justify: "start",
children: [
notice && /* @__PURE__ */ jsxs(Notice, {
status: notice.type,
__unstableHTML: true,
onRemove: () => setNotice(null),
children: [notice.message, notice.errors && /* @__PURE__ */ jsx("ul", { children: notice.errors.map((error, index) => /* @__PURE__ */ jsx("li", { children: error }, index)) })]
}),
isUploading && /* @__PURE__ */ jsx(FlexItem, { children: /* @__PURE__ */ jsx("div", {
className: "font-library__upload-area",
children: /* @__PURE__ */ jsx(Progress.Root, {
value: null,
"aria-label": __("Uploading fonts"),
children: /* @__PURE__ */ jsx(Progress.Track, { children: /* @__PURE__ */ jsx(Progress.Indicator, {}) })
})
}) }),
!isUploading && /* @__PURE__ */ jsx(FormFileUpload, {
accept: ALLOWED_FILE_EXTENSIONS.map((ext) => `.${ext}`).join(","),
multiple: true,
onChange: onFilesUpload,
render: ({ openFileDialog }) => /* @__PURE__ */ jsx(Button, {
__next40pxDefaultSize: true,
className: "font-library__upload-area",
onClick: openFileDialog,
children: __("Upload font")
})
}),
/* @__PURE__ */ jsx(__experimentalText, {
className: "font-library__upload-area__text",
children: __("Uploaded fonts appear in your library and can be used in your theme. Supported formats: .ttf, .otf, .woff, and .woff2.")
})
]
})]
});
}
export { UploadFonts as default };
//# sourceMappingURL=upload-fonts.mjs.map