@wordpress/global-styles-ui
Version:
Global Styles UI components for WordPress.
224 lines (223 loc) • 9.14 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
// \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
let _wordpress_ui = require("@wordpress/ui");
let _wordpress_i18n = require("@wordpress/i18n");
let _wordpress_components = require("@wordpress/components");
let _wordpress_element = require("@wordpress/element");
let __utils_constants_ts = require("./utils/constants.cjs");
let __context_tsx = require("./context.cjs");
let __lib_lib_font_browser_js = require("./lib/lib-font.browser.cjs");
let __utils_make_families_from_faces_ts = require("./utils/make-families-from-faces.cjs");
__utils_make_families_from_faces_ts = __toESM(__utils_make_families_from_faces_ts);
let __utils_index_ts = require("./utils/index.cjs");
let react_jsx_runtime = require("react/jsx-runtime");
// packages/global-styles-ui/src/font-library/upload-fonts.tsx
function UploadFonts() {
const { installFonts } = (0, _wordpress_element.useContext)(__context_tsx.FontLibraryContext);
const [isUploading, setIsUploading] = (0, _wordpress_element.useState)(false);
const [notice, setNotice] = (0, _wordpress_element.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 (__utils_constants_ts.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 ? (0, _wordpress_i18n.__)("Sorry, you are not allowed to upload this file type.") : (0, _wordpress_i18n.__)("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 (0, __utils_index_ts.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 __lib_lib_font_browser_js.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 __lib_lib_font_browser_js.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((0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("%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 = (0, __utils_make_families_from_faces_ts.default)(fontFaces);
await installFonts(fontFamilies);
setNotice({
type: "success",
message: (0, _wordpress_i18n.__)("Fonts were installed successfully.")
});
} catch (error) {
const typedError = error;
setNotice({
type: "error",
message: typedError.message,
errors: typedError?.installationErrors
});
}
setIsUploading(false);
};
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "font-library__tabpanel-layout",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.DropZone, { onFilesDrop: handleDropZone }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_components.__experimentalVStack, {
className: "font-library__local-fonts",
justify: "start",
children: [
notice && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_components.Notice, {
status: notice.type,
__unstableHTML: true,
onRemove: () => setNotice(null),
children: [notice.message, notice.errors && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", { children: notice.errors.map((error, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", { children: error }, index)) })]
}),
isUploading && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.FlexItem, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "font-library__upload-area",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Progress.Root, {
value: null,
"aria-label": (0, _wordpress_i18n.__)("Uploading fonts"),
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Progress.Track, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Progress.Indicator, {}) })
})
}) }),
!isUploading && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.FormFileUpload, {
accept: __utils_constants_ts.ALLOWED_FILE_EXTENSIONS.map((ext) => `.${ext}`).join(","),
multiple: true,
onChange: onFilesUpload,
render: ({ openFileDialog }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.Button, {
__next40pxDefaultSize: true,
className: "font-library__upload-area",
onClick: openFileDialog,
children: (0, _wordpress_i18n.__)("Upload font")
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.__experimentalText, {
className: "font-library__upload-area__text",
children: (0, _wordpress_i18n.__)("Uploaded fonts appear in your library and can be used in your theme. Supported formats: .ttf, .otf, .woff, and .woff2.")
})
]
})]
});
}
exports.default = UploadFonts;
//# sourceMappingURL=upload-fonts.cjs.map