@wordpress/widget-dashboard
Version:
Stateless rendering engine for widget dashboards: the WidgetDashboard compound component and its grid-settings kit.
222 lines (221 loc) • 9.73 kB
JavaScript
import { useSelect } from "@wordpress/data";
import { useCallback, useEffect, useMemo, useState } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { plus } from "@wordpress/icons";
import { store } from "@wordpress/viewport";
import { Button, Stack } from "@wordpress/ui";
import { useDashboardInternalContext } from "../../context/dashboard-context.mjs";
import { useDashboardUIContext } from "../../context/ui-context.mjs";
import { ActionsMenu } from "../actions-menu/index.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/style-runtime/src/index.ts
const STYLE_HASH_ATTRIBUTE = "data-wp-hash";
/**
* Returns the shared style runtime registry.
*
* The registry is stored on `globalThis` so separately bundled copies of this
* package can coordinate through the same document and style maps.
*
* @return The shared runtime registry.
*/
function getRuntime() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) return globalScope.__wpStyleRuntime;
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") registerDocument(document);
return globalScope.__wpStyleRuntime;
}
/**
* Checks whether a document already contains a style tag for a hash.
*
* @param targetDocument Document to inspect.
* @param hash Stable hash for the transformed CSS.
*
* @return Whether the style hash already exists in the document.
*/
function documentContainsStyleHash(targetDocument, hash) {
if (!targetDocument.head) return false;
for (const style of targetDocument.head.querySelectorAll(`style[${STYLE_HASH_ATTRIBUTE}]`)) if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) return true;
return false;
}
/**
* Injects a registered style into a document, unless that document already
* contains a style tag for the same hash.
*
* @param targetDocument Document to inject the style into.
* @param hash Stable hash for the transformed CSS.
* @param css CSS text to inject.
*/
function injectStyle(targetDocument, hash, css) {
if (!targetDocument.head) return;
const runtime = getRuntime();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) return;
if (documentContainsStyleHash(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
/**
* Registers a document as a style injection target.
*
* Existing registered styles are replayed into the document immediately.
* Documents are reference-counted so multiple providers can safely register the
* same document without one cleanup removing it while another registration is
* still active.
*
* @param targetDocument Document to receive registered styles.
* @return Cleanup function that unregisters this document registration.
*/
function registerDocument(targetDocument) {
const runtime = getRuntime();
runtime.documents.set(targetDocument, (runtime.documents.get(targetDocument) ?? 0) + 1);
for (const [hash, css] of runtime.styles) injectStyle(targetDocument, hash, css);
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) return;
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
/**
* Registers a style and injects it into all registered documents.
*
* The hash is used as the deduplication key, so calling this repeatedly with
* the same hash will not add duplicate style tags to a document.
* Registered styles are retained for the lifetime of the page so they can be
* replayed into documents that are registered later.
*
* @param hash Stable hash for the transformed CSS.
* @param css CSS text to inject.
*/
function registerStyle(hash, css) {
const runtime = getRuntime();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) injectStyle(targetDocument, hash, css);
}
// packages/widget-dashboard/src/components/actions/actions.module.css
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("b4998f1f9d", "._2e866fc6b26dceee__edit-actions-exit,.fda4da8523cf356f__edit-actions-enter{align-items:center;display:inline-flex;gap:var(--wp--preset--spacing--20);transform-origin:right center}.a79a0cc99f354c89__edit-actions-divider{align-self:center;background-color:var(--wpds-color-stroke-surface-neutral,#dbdbdb);flex-shrink:0;height:var(--wpds-dimension-size-2xs,16px);width:1px}@media not (prefers-reduced-motion){._2e866fc6b26dceee__edit-actions-exit,.fda4da8523cf356f__edit-actions-enter{will-change:opacity,transform}.fda4da8523cf356f__edit-actions-enter{animation:_8cf70e166469c924__actions-slide-in var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-expressive,cubic-bezier(.25,0,0,1)) forwards}._2e866fc6b26dceee__edit-actions-exit{animation:_059a77c5cd2cd736__actions-fold-out var(--wpds-motion-duration-sm,.1s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) forwards}@keyframes _8cf70e166469c924__actions-slide-in{0%{opacity:0;transform:translateX(12px) scaleX(.92)}to{opacity:1;transform:translateX(0) scaleX(1)}}@keyframes _059a77c5cd2cd736__actions-fold-out{0%{opacity:1;transform:translateX(0) scaleX(1)}to{opacity:0;transform:translateX(12px) scaleX(.92)}}}");
var actions_module_default = {
"edit-actions-enter": "fda4da8523cf356f__edit-actions-enter",
"edit-actions-exit": "_2e866fc6b26dceee__edit-actions-exit",
"edit-actions-divider": "a79a0cc99f354c89__edit-actions-divider",
"actions-slide-in": "_8cf70e166469c924__actions-slide-in",
"actions-fold-out": "_059a77c5cd2cd736__actions-fold-out"
};
// packages/widget-dashboard/src/components/actions/actions.tsx
/**
* Edit toolbar for the dashboard. In customize mode it surfaces Add widget,
* Layout settings (when grid settings are editable), Cancel, and Done;
* otherwise a single Customize button. Buttons and the overflow menu are
* triggers that flip the shared UI state the overlays react to.
*
* Returns `null` when mounted without `onEditChange`, so hosts that don't
* expose edit mode can keep `Actions` in their tree unconditionally. The
* Customize button also needs the policy in effect to allow `customize`,
* and the Reset to default item needs it to allow `reset`.
*/
function Actions() {
const { editMode, onEditChange, onLayoutReset, commit, cancel: cancelStaging, hasUncommittedChanges, canPerform, widgetTypes } = useDashboardInternalContext();
const canInsertAny = useMemo(() => widgetTypes.some((widgetType) => canPerform({
operation: "insert",
widgetType
})), [widgetTypes, canPerform]);
const [isEditActionsMounted, setIsEditActionsMounted] = useState(editMode);
const [isExitingEditActions, setIsExitingEditActions] = useState(false);
useEffect(() => {
if (editMode) {
setIsEditActionsMounted(true);
setIsExitingEditActions(false);
return;
}
if (!isEditActionsMounted) return;
setIsExitingEditActions(true);
const exitTimeout = setTimeout(() => {
setIsEditActionsMounted(false);
setIsExitingEditActions(false);
}, 220);
return () => clearTimeout(exitTimeout);
}, [editMode, isEditActionsMounted]);
const { setInserterOpen, setResetDialogOpen } = useDashboardUIContext();
const isMobileViewport = useSelect((select) => select(store).isViewportMatch("< small"), []);
const handleEditMode = useCallback(() => {
onEditChange?.(!editMode);
}, [editMode, onEditChange]);
const insert = useCallback(() => {
setInserterOpen(true);
}, [setInserterOpen]);
const cancel = useCallback(() => {
cancelStaging();
}, [cancelStaging]);
const done = useCallback(() => {
commit();
}, [commit]);
const menuItems = canPerform({ operation: "reset" }) ? [{
label: __("Reset to default…"),
onClick: () => setResetDialogOpen(true),
disabled: !onLayoutReset
}] : [];
if (!onEditChange) return null;
const canCustomize = canPerform({ operation: "customize" });
return /* @__PURE__ */ jsxs(Stack, {
direction: "row",
gap: "sm",
children: [isEditActionsMounted ? /* @__PURE__ */ jsxs(Stack, {
direction: "row",
gap: "sm",
className: isExitingEditActions ? actions_module_default["edit-actions-exit"] : actions_module_default["edit-actions-enter"],
children: [
canInsertAny && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Button, {
variant: "minimal",
tone: "brand",
size: "compact",
onClick: insert,
children: [!isMobileViewport && /* @__PURE__ */ jsx(Button.Icon, { icon: plus }), __("Add widget")]
}), /* @__PURE__ */ jsx("div", {
className: actions_module_default["edit-actions-divider"],
"aria-hidden": "true"
})] }),
/* @__PURE__ */ jsx(Button, {
variant: "minimal",
tone: "brand",
size: "compact",
onClick: cancel,
children: __("Cancel")
}),
/* @__PURE__ */ jsx(Button, {
variant: "solid",
tone: "brand",
size: "compact",
onClick: done,
disabled: !hasUncommittedChanges,
children: __("Done")
})
]
}) : canCustomize && /* @__PURE__ */ jsx(Button, {
variant: "minimal",
tone: "brand",
size: "compact",
onClick: handleEditMode,
children: __("Customize")
}), /* @__PURE__ */ jsx(ActionsMenu, { items: menuItems })]
});
}
export { Actions };
//# sourceMappingURL=actions.mjs.map