@wordpress/components
Version:
UI components for WordPress.
349 lines (348 loc) • 14.8 kB
JavaScript
import clsx from "clsx";
import { __ } from "@wordpress/i18n";
import { useEffect, useRef, useState } from "@wordpress/element";
import { __experimentalUseDragging, useIsomorphicLayoutEffect } from "@wordpress/compose";
import Controls from "./controls.mjs";
import FocalPoint from "./focal-point.mjs";
import Grid from "./grid.mjs";
import Media from "./media.mjs";
import { View } from "../view/index.mjs";
import { INITIAL_BOUNDS } from "./utils.mjs";
import { useUpdateEffect } from "../utils/hooks/index.mjs";
import { StyledHelp, StyledLabel } from "../base-control/styles/base-control-styles.mjs";
import { VisuallyHidden } from "../visually-hidden/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/focal-point-picker/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("0ed1e26ed0", "._4f91cfcb0c85cc41__root{border:0;box-sizing:border-box;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,\"Segoe UI\",\"Roboto\",\"Oxygen-Sans\",\"Ubuntu\",\"Cantarell\",\"Helvetica Neue\",sans-serif);font-size:13px;margin:0;padding:0}._4f91cfcb0c85cc41__root *,._4f91cfcb0c85cc41__root :after,._4f91cfcb0c85cc41__root :before{box-sizing:inherit}._8124adaa57f886a6__media-wrapper{background-color:transparent;contain:layout;display:flex;text-align:center;width:100%}._14038b3fb0a03b00__media-container{align-items:center;border-radius:2px;cursor:pointer;display:inline-flex;height:100%;justify-content:center;margin:auto;position:relative}._14038b3fb0a03b00__media-container:after{border-radius:inherit;box-shadow:inset 0 0 0 1px rgba(0,0,0,.1);content:\"\";inset:0;pointer-events:none;position:absolute}._14038b3fb0a03b00__media-container img,._14038b3fb0a03b00__media-container video{border-radius:inherit;box-sizing:border-box;display:block;height:auto;margin:0;max-height:100%;max-width:100%;pointer-events:none;user-select:none;width:100%}._278f7ba1e9ea0dbd__media-placeholder{background:#f0f0f0;border-radius:inherit;box-sizing:border-box;height:170px;max-width:280px;min-width:200px;width:100%}._0fd08c338d5d1ae3__unit-control{width:100%}._24e8123162458442__controls{max-width:320px;padding-top:1em}._24e8123162458442__controls:where(._18c8dc3c0d7e4db5__has-help-text){padding-bottom:1em}._1c53809aed7335a6__grid{left:50%;opacity:0;overflow:hidden;pointer-events:none;position:absolute;top:50%;transform:translate3d(-50%,-50%,0);z-index:1}@media not (prefers-reduced-motion){._1c53809aed7335a6__grid{transition:opacity .1s linear}}._1c53809aed7335a6__grid:where(._140336f4ad6dd49c__show-overlay){opacity:1}._72bef77b62749ecc__grid-line{backdrop-filter:blur(16px) saturate(180%);background:hsla(0,0%,100%,.4);position:absolute;transform:translateZ(0)}._5e72b27b9deb5c57__grid-line-x{height:1px;inset-inline:1px}.b9c3347d2b89441c__grid-line-y{inset-block:1px;width:1px}.ca89efddd89ad211__pointer{backdrop-filter:blur(16px) saturate(180%);background:hsla(0,0%,100%,.4);border:1px solid hsla(0,0%,100%,.4);border-radius:50%;box-shadow:0 0 8px rgba(0,0,0,.1);cursor:grab;height:40px;margin-left:-20px;margin-top:-20px;position:absolute;user-select:none;width:40px;will-change:transform;z-index:10000}@media not (prefers-reduced-motion){.ca89efddd89ad211__pointer{transition:transform .1s linear}}.ca89efddd89ad211__pointer:where(.be014e404db56b57__is-dragging){box-shadow:0 0 10px rgba(0,0,0,.12);cursor:grabbing;transform:scale(1.1)}");
var style_module_default = {
"root": "_4f91cfcb0c85cc41__root",
"media-wrapper": "_8124adaa57f886a6__media-wrapper",
"media-container": "_14038b3fb0a03b00__media-container",
"media-placeholder": "_278f7ba1e9ea0dbd__media-placeholder",
"unit-control": "_0fd08c338d5d1ae3__unit-control",
"controls": "_24e8123162458442__controls",
"has-help-text": "_18c8dc3c0d7e4db5__has-help-text",
"grid": "_1c53809aed7335a6__grid",
"show-overlay": "_140336f4ad6dd49c__show-overlay",
"grid-line": "_72bef77b62749ecc__grid-line",
"grid-line-x": "_5e72b27b9deb5c57__grid-line-x",
"grid-line-y": "b9c3347d2b89441c__grid-line-y",
"pointer": "ca89efddd89ad211__pointer",
"is-dragging": "be014e404db56b57__is-dragging"
};
// packages/components/src/focal-point-picker/index.tsx
const GRID_OVERLAY_TIMEOUT = 600;
/**
* Focal Point Picker is a component which creates a UI for identifying the most important visual point of an image.
*
* It addresses two common issues when displaying images in cropped containers. First, large
* background images can be cropped in undesirable ways, especially on smaller viewports such as
* mobile devices. Second, the CSS aspect-ratio property can inadvertently crop out the area of
* highest visual interest. This component allows the selection of the point with the most
* important visual information and returns it as a pair of numbers between 0 and 1.
* The output value can be applied to either CSS `background-position` (for elements with
* `background-image`) or `object-position` (for `<img>` / `<video>` elements rendered with
* `object-fit: cover`).
*
* - Example focal point picker value: `{ x: 0.5, y: 0.1 }`;
* - Corresponding CSS: `object-position: 50% 10%`;
*
* ```jsx
* import { FocalPointPicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ focalPoint, setFocalPoint ] = useState( {
* x: 0.5,
* y: 0.1,
* } );
*
* const url = '/path/to/image';
*
* // Example function to render the CSS styles based on Focal Point Picker value
* const style = {
* width: '100%',
* aspectRatio: '16 / 9',
* objectFit: 'cover',
* objectPosition: `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`,
* };
*
* return (
* <>
* <FocalPointPicker
* url={ url }
* value={ focalPoint }
* onDragStart={ setFocalPoint }
* onDrag={ setFocalPoint }
* onChange={ setFocalPoint }
* />
* <img src={ url } alt="" style={ style } />
* </>
* );
* };
* ```
*/
function FocalPointPicker({ __nextHasNoMarginBottom: _, __next40pxDefaultSize: _next40pxDefaultSize, autoPlay = true, className, help, hideLabelFromVision, label, onChange, onDrag, onDragEnd, onDragStart, resolvePoint, url, value: valueProp = {
x: .5,
y: .5
}, ...restProps }) {
const [point, setPoint] = useState(valueProp);
const [showGridOverlay, setShowGridOverlay] = useState(false);
const { startDrag, endDrag, isDragging } = __experimentalUseDragging({
onDragStart: (event) => {
dragAreaRef.current?.focus();
const value = getValueWithinDragArea(event);
if (!value) return;
onDragStart?.(value, event);
setPoint(value);
},
onDragMove: (event) => {
event.preventDefault();
const value = getValueWithinDragArea(event);
if (!value) return;
onDrag?.(value, event);
setPoint(value);
},
onDragEnd: () => {
onDragEnd?.();
onChange?.(point);
}
});
const { x, y } = isDragging ? point : valueProp;
const dragAreaRef = useRef(null);
const [bounds, setBounds] = useState(INITIAL_BOUNDS);
const refUpdateBounds = useRef(() => {
if (!dragAreaRef.current) return;
const { clientWidth: width, clientHeight: height } = dragAreaRef.current;
setBounds(width > 0 && height > 0 ? {
width,
height
} : { ...INITIAL_BOUNDS });
});
useEffect(() => {
const updateBounds = refUpdateBounds.current;
if (!dragAreaRef.current) return;
const { defaultView } = dragAreaRef.current.ownerDocument;
defaultView?.addEventListener("resize", updateBounds);
return () => defaultView?.removeEventListener("resize", updateBounds);
}, []);
useIsomorphicLayoutEffect(() => void refUpdateBounds.current(), []);
const getValueWithinDragArea = ({ clientX, clientY, shiftKey }) => {
if (!dragAreaRef.current) return;
const { top, left } = dragAreaRef.current.getBoundingClientRect();
let nextX = (clientX - left) / bounds.width;
let nextY = (clientY - top) / bounds.height;
if (shiftKey) {
nextX = Math.round(nextX / .1) * .1;
nextY = Math.round(nextY / .1) * .1;
}
return getFinalValue({
x: nextX,
y: nextY
});
};
const getFinalValue = (value) => {
const resolvedValue = resolvePoint?.(value) ?? value;
resolvedValue.x = Math.max(0, Math.min(resolvedValue.x, 1));
resolvedValue.y = Math.max(0, Math.min(resolvedValue.y, 1));
const roundToTwoDecimalPlaces = (n) => Math.round(n * 100) / 100;
return {
x: roundToTwoDecimalPlaces(resolvedValue.x),
y: roundToTwoDecimalPlaces(resolvedValue.y)
};
};
const arrowKeyStep = (event) => {
const { code, shiftKey } = event;
if (![
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight"
].includes(code)) return;
event.preventDefault();
const value = {
x,
y
};
const step = shiftKey ? .1 : .01;
const delta = code === "ArrowUp" || code === "ArrowLeft" ? -1 * step : step;
const axis = code === "ArrowUp" || code === "ArrowDown" ? "y" : "x";
value[axis] = value[axis] + delta;
onChange?.(getFinalValue(value));
};
const focalPointPosition = {
left: x !== void 0 ? x * bounds.width : .5 * bounds.width,
top: y !== void 0 ? y * bounds.height : .5 * bounds.height
};
const classes = clsx(style_module_default.root, "components-focal-point-picker-control", className);
useUpdateEffect(() => {
setShowGridOverlay(true);
const timeout = window.setTimeout(() => {
setShowGridOverlay(false);
}, GRID_OVERLAY_TIMEOUT);
return () => window.clearTimeout(timeout);
}, [x, y]);
return /* @__PURE__ */ jsxs(View, {
...restProps,
as: "fieldset",
className: classes,
children: [
!!label && (hideLabelFromVision ? /* @__PURE__ */ jsx(VisuallyHidden, {
as: "legend",
children: label
}) : /* @__PURE__ */ jsx(StyledLabel, {
as: "legend",
children: label
})),
/* @__PURE__ */ jsx("div", {
className: clsx(style_module_default["media-wrapper"], "components-focal-point-picker-wrapper"),
children: /* @__PURE__ */ jsxs("div", {
className: clsx(style_module_default["media-container"], "components-focal-point-picker"),
onKeyDown: arrowKeyStep,
onPointerDown: (event) => {
if (event.button !== 0) return;
event.currentTarget.setPointerCapture(event.pointerId);
},
onMouseDown: startDrag,
onBlur: () => {
if (isDragging) endDrag();
},
ref: dragAreaRef,
role: "button",
tabIndex: -1,
children: [
/* @__PURE__ */ jsx(Grid, {
bounds,
showOverlay: showGridOverlay
}),
/* @__PURE__ */ jsx(Media, {
alt: __("Media preview"),
autoPlay,
onLoad: refUpdateBounds.current,
src: url
}),
/* @__PURE__ */ jsx(FocalPoint, {
...focalPointPosition,
isDragging
})
]
})
}),
/* @__PURE__ */ jsx(Controls, {
hasHelpText: !!help,
point: {
x,
y
},
onChange: (value) => {
onChange?.(getFinalValue(value));
}
}),
!!help && /* @__PURE__ */ jsx(StyledHelp, { children: help })
]
});
}
export { FocalPointPicker, FocalPointPicker as default };
//# sourceMappingURL=index.mjs.map