@wordpress/components
Version:
UI components for WordPress.
265 lines (264 loc) • 9.93 kB
JavaScript
import { __, sprintf } from "@wordpress/i18n";
import { useInstanceId } from "@wordpress/compose";
import { useCallback, useMemo } from "@wordpress/element";
import CircularOptionPicker, { getComputeCircularOptionPickerCommonProps, warnIfCircularOptionPickerAsButtonsIsSet } from "../circular-option-picker/index.mjs";
import CustomGradientPicker from "../custom-gradient-picker/index.mjs";
import { VStack } from "../v-stack/index.mjs";
import { Heading } from "../heading/index.mjs";
import { 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/components/src/color-palette/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("ba988b4dc4", ".d557a658e7010f86__color-heading{text-transform:uppercase}.d557a658e7010f86__color-heading.d557a658e7010f86__color-heading.d557a658e7010f86__color-heading{font-size:11px;line-height:24px;margin-bottom:0}");
var style_module_default = { "color-heading": "d557a658e7010f86__color-heading" };
// packages/components/src/gradient-picker/index.tsx
const isMultipleOriginObject = (obj) => Array.isArray(obj.gradients) && !("gradient" in obj);
const isMultipleOriginArray = (arr) => {
return arr.length > 0 && arr.every((gradientObj) => isMultipleOriginObject(gradientObj));
};
function SingleOrigin({ className, clearGradient, gradients, onChange, value, selectedSlug, presentation, ...additionalProps }) {
const gradientOptions = useMemo(() => {
return gradients.map(({ gradient, name, slug }, index) => {
const isSelected = presentation !== "command-buttons" && (selectedSlug ? slug === selectedSlug : value === gradient);
return /* @__PURE__ */ jsx(CircularOptionPicker.Option, {
value: gradient,
isSelected,
tooltipText: name || sprintf(__("Gradient code: %s"), gradient),
style: {
color: "rgba( 0,0,0,0 )",
background: gradient
},
onClick: isSelected ? clearGradient : () => onChange(gradient, index, slug),
"aria-label": name ? sprintf(__("Gradient: %s"), name) : sprintf(__("Gradient code: %s"), gradient)
}, slug);
});
}, [
gradients,
value,
onChange,
clearGradient,
selectedSlug,
presentation
]);
return /* @__PURE__ */ jsx(CircularOptionPicker.OptionGroup, {
className,
options: gradientOptions,
...additionalProps
});
}
function MultipleOrigin({ className, clearGradient, gradients, onChange, value, selectedSlug, headingLevel, presentation }) {
const instanceId = useInstanceId(MultipleOrigin);
return /* @__PURE__ */ jsx(VStack, {
spacing: 3,
className,
children: gradients.map(({ name, gradients: gradientSet }, index) => {
const id = `color-palette-${instanceId}-${index}`;
return /* @__PURE__ */ jsxs(VStack, {
spacing: 2,
children: [/* @__PURE__ */ jsx(Heading, {
className: style_module_default["color-heading"],
level: headingLevel,
id,
children: name
}), /* @__PURE__ */ jsx(SingleOrigin, {
clearGradient,
gradients: gradientSet,
onChange: (gradient, _index, slug) => onChange(gradient, index, slug),
value,
selectedSlug,
presentation,
"aria-labelledby": id
})]
}, index);
})
});
}
function Component(props) {
const { asButtons, presentation, loop, actions, headingLevel, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, ...additionalProps } = props;
warnIfCircularOptionPickerAsButtonsIsSet("GradientPicker", asButtons);
const { metaProps, labelProps, resolvedPresentation } = getComputeCircularOptionPickerCommonProps(asButtons, loop, ariaLabel, ariaLabelledby, presentation);
const options = isMultipleOriginArray(props.gradients) ? /* @__PURE__ */ jsx(MultipleOrigin, {
headingLevel,
...additionalProps,
presentation: resolvedPresentation
}) : /* @__PURE__ */ jsx(SingleOrigin, {
...additionalProps,
presentation: resolvedPresentation
});
return /* @__PURE__ */ jsx(CircularOptionPicker, {
...metaProps,
...labelProps,
actions,
options
});
}
/**
* GradientPicker is a React component that renders a color gradient picker to
* define a multi step gradient. There's either a _linear_ or a _radial_ type
* available.
*
* ```jsx
* import { useState } from 'react';
* import { GradientPicker } from '@wordpress/components';
*
* const MyGradientPicker = () => {
* const [ gradient, setGradient ] = useState( null );
*
* return (
* <GradientPicker
* value={ gradient }
* onChange={ ( currentGradient ) => setGradient( currentGradient ) }
* gradients={ [
* {
* name: 'JShine',
* gradient:
* 'linear-gradient(135deg,#12c2e9 0%,#c471ed 50%,#f64f59 100%)',
* slug: 'jshine',
* },
* {
* name: 'Moonlit Asteroid',
* gradient:
* 'linear-gradient(135deg,#0F2027 0%, #203A43 0%, #2c5364 100%)',
* slug: 'moonlit-asteroid',
* },
* {
* name: 'Rastafarie',
* gradient:
* 'linear-gradient(135deg,#1E9600 0%, #FFF200 0%, #FF0000 100%)',
* slug: 'rastafari',
* },
* ] }
* />
* );
* };
*```
*
*/
function GradientPicker({ className, gradients = [], onChange, value, clearable = true, enableAlpha = true, disableCustomGradients = false, __experimentalIsRenderedInSidebar, headingLevel = 2, ...additionalProps }) {
const clearGradient = useCallback(() => onChange(void 0), [onChange]);
return /* @__PURE__ */ jsxs(VStack, {
spacing: gradients.length ? 4 : 0,
children: [!disableCustomGradients && /* @__PURE__ */ jsx(CustomGradientPicker, {
__experimentalIsRenderedInSidebar,
enableAlpha,
value,
onChange
}), (gradients.length > 0 || clearable) && /* @__PURE__ */ jsx(Component, {
...additionalProps,
className,
clearGradient,
gradients,
onChange,
value,
actions: clearable && !disableCustomGradients && /* @__PURE__ */ jsx(CircularOptionPicker.ButtonAction, {
onClick: clearGradient,
accessibleWhenDisabled: true,
disabled: !value,
children: __("Clear")
}),
headingLevel
})]
});
}
export { GradientPicker, GradientPicker as default };
//# sourceMappingURL=index.mjs.map