@wordpress/components
Version:
UI components for WordPress.
259 lines (258 loc) • 10.7 kB
JavaScript
import { throttle } from "@wordpress/compose";
import { createPortal, useEffect, useRef, useState } from "@wordpress/element";
import { getWpCompatOverlaySlot } from "@wordpress/ui";
import { Fragment, 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/draggable/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("0e5c181860", ".e4c42312beb32cba__invisible-drag-image{height:50px;left:-1000px;position:fixed;width:50px}.f91f725dd8978caf__clone{background:transparent;padding:0;pointer-events:none;position:fixed}.f91f725dd8978caf__clone:not(.f9eeed97a2a62f5e__is-in-compat-slot){z-index:1000000000}body.is-dragging-components-draggable{cursor:move;cursor:grabbing!important}");
var style_module_default = {
"invisible-drag-image": "e4c42312beb32cba__invisible-drag-image",
"clone": "f91f725dd8978caf__clone",
"is-in-compat-slot": "f9eeed97a2a62f5e__is-in-compat-slot"
};
// packages/components/src/draggable/index.tsx
const dragImageClasses = [style_module_default["invisible-drag-image"], "components-draggable__invisible-drag-image"].filter(Boolean);
const cloneWrapperClasses = [style_module_default.clone, "components-draggable__clone"].filter(Boolean);
const bodyClass = "is-dragging-components-draggable";
const clonePadding = 0;
/**
* `Draggable` is a Component that provides a way to set up a cross-browser
* (including IE) customizable drag image and the transfer data for the drag
* event. It decouples the drag handle and the element to drag: use it by
* wrapping the component that will become the drag handle and providing the DOM
* ID of the element to drag.
*
* Note that the drag handle needs to declare the `draggable="true"` property
* and bind the `Draggable`s `onDraggableStart` and `onDraggableEnd` event
* handlers to its own `onDragStart` and `onDragEnd` respectively. `Draggable`
* takes care of the logic to setup the drag image and the transfer data, but is
* not concerned with creating an actual DOM element that is draggable.
*
* ```jsx
* import { Draggable, Panel, PanelBody } from '@wordpress/components';
* import { Icon, more } from '@wordpress/icons';
*
* const MyDraggable = () => (
* <div id="draggable-panel">
* <Panel header="Draggable panel">
* <PanelBody>
* <Draggable elementId="draggable-panel" transferData={ {} }>
* { ( { onDraggableStart, onDraggableEnd } ) => (
* <div
* className="example-drag-handle"
* draggable
* onDragStart={ onDraggableStart }
* onDragEnd={ onDraggableEnd }
* >
* <Icon icon={ more } />
* </div>
* ) }
* </Draggable>
* </PanelBody>
* </Panel>
* </div>
* );
* ```
*/
function Draggable({ children, onDragStart, onDragOver, onDragEnd, appendToOwnerDocument = false, cloneClassname, elementId, transferData, __experimentalTransferDataType: transferDataType = "text", __experimentalDragComponent: dragComponent }) {
const cleanupRef = useRef(() => {});
const [dragComponentContainer, setDragComponentContainer] = useState(null);
/**
* Removes the element clone, resets cursor, and removes drag listener.
*
* @param event The non-custom DragEvent.
*/
function end(event) {
event.preventDefault();
cleanupRef.current();
onDragEnd?.(event);
}
/**
* This method does a couple of things:
*
* - Clones the current element and spawns clone over original element.
* - Adds a fake temporary drag image to avoid browser defaults.
* - Sets transfer data.
* - Adds dragover listener.
*
* @param event The non-custom DragEvent.
*/
function start(event) {
const { ownerDocument } = event.target;
const slot = getWpCompatOverlaySlot();
const compatSlot = slot?.ownerDocument === ownerDocument ? slot : null;
event.dataTransfer.setData(transferDataType, JSON.stringify(transferData));
const cloneWrapper = ownerDocument.createElement("div");
cloneWrapper.style.top = "0";
cloneWrapper.style.left = "0";
const dragImage = ownerDocument.createElement("div");
if ("function" === typeof event.dataTransfer.setDragImage) {
dragImage.classList.add(...dragImageClasses);
ownerDocument.body.appendChild(dragImage);
event.dataTransfer.setDragImage(dragImage, 0, 0);
}
cloneWrapper.classList.add(...cloneWrapperClasses);
const inSlotClass = style_module_default["is-in-compat-slot"];
if (compatSlot && inSlotClass) cloneWrapper.classList.add(inSlotClass);
if (cloneClassname) cloneWrapper.classList.add(cloneClassname);
let x = 0;
let y = 0;
if (dragComponent) {
x = event.clientX;
y = event.clientY;
cloneWrapper.style.transform = `translate( ${x}px, ${y}px )`;
(compatSlot ?? ownerDocument.body).appendChild(cloneWrapper);
setDragComponentContainer(cloneWrapper);
} else {
const element = ownerDocument.getElementById(elementId);
const elementRect = element.getBoundingClientRect();
const elementWrapper = element.parentNode;
const elementTopOffset = elementRect.top;
const elementLeftOffset = elementRect.left;
cloneWrapper.style.width = `${elementRect.width + 0}px`;
const clone = element.cloneNode(true);
clone.id = `clone-${elementId}`;
x = elementLeftOffset - clonePadding;
y = elementTopOffset - clonePadding;
cloneWrapper.style.transform = `translate( ${x}px, ${y}px )`;
Array.from(clone.querySelectorAll("iframe")).forEach((child) => child.parentNode?.removeChild(child));
cloneWrapper.appendChild(clone);
if (compatSlot) compatSlot.appendChild(cloneWrapper);
else if (appendToOwnerDocument) ownerDocument.body.appendChild(cloneWrapper);
else elementWrapper?.appendChild(cloneWrapper);
}
let cursorLeft = event.clientX;
let cursorTop = event.clientY;
function over(e) {
if (cursorLeft === e.clientX && cursorTop === e.clientY) return;
const nextX = x + e.clientX - cursorLeft;
const nextY = y + e.clientY - cursorTop;
cloneWrapper.style.transform = `translate( ${nextX}px, ${nextY}px )`;
cursorLeft = e.clientX;
cursorTop = e.clientY;
x = nextX;
y = nextY;
onDragOver?.(e);
}
const throttledDragOver = throttle(over, 16);
ownerDocument.addEventListener("dragover", throttledDragOver);
ownerDocument.body.classList.add(bodyClass);
onDragStart?.(event);
cleanupRef.current = () => {
cloneWrapper.remove();
dragImage.remove();
setDragComponentContainer(null);
ownerDocument.body.classList.remove(bodyClass);
ownerDocument.removeEventListener("dragover", throttledDragOver);
cleanupRef.current = () => {};
};
}
useEffect(() => () => cleanupRef.current(), []);
return /* @__PURE__ */ jsxs(Fragment, { children: [children({
onDraggableStart: start,
onDraggableEnd: end
}), dragComponentContainer && createPortal(dragComponent, dragComponentContainer)] });
}
export { Draggable, Draggable as default };
//# sourceMappingURL=index.mjs.map