@wordpress/components
Version:
UI components for WordPress.
396 lines (395 loc) • 22.6 kB
JavaScript
import clsx from "clsx";
import { __, isRTL } from "@wordpress/i18n";
import { forwardRef, useRef, useState } from "@wordpress/element";
import { useInstanceId, useMergeRefs } from "@wordpress/compose";
import BaseControl from "../base-control/index.mjs";
import Button from "../button/index.mjs";
import Icon from "../icon/index.mjs";
import { floatClamp, getCSSWideKeyword, useControlledRangeValue } from "./utils.mjs";
import { clamp } from "../utils/math.mjs";
import InputRange from "./input-range.mjs";
import RangeRail from "./rail.mjs";
import SimpleTooltip from "./tooltip.mjs";
import NumberControl from "../number-control/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/range-control/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("4d5e856f6b", "._6a1e01adf97c4762__root{-webkit-tap-highlight-color:transparent;align-items:center;display:flex;justify-content:flex-start;min-height:40px;padding:0;position:relative;touch-action:none;width:100%}._6a1e01adf97c4762__root:where(._2495fc3509946926__is-compact){min-height:32px}._811431d1b36d2890__wrapper{--_wp-components-range-control-color:initial;color:var(--_wp-components-range-control-color);display:block;flex:1;height:30px;min-height:30px;position:relative;width:100%}._2bab18807adcbaf7__default-color{color:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9))}._325bd79ef1e3c6cc__before-icon,._4c163a0fe307fef3__after-icon{display:flex;margin-top:4px}:where(._6a1e01adf97c4762__root:not(._4e480ef72e95c007__is-rtl)) ._325bd79ef1e3c6cc__before-icon{margin-right:6px}:where(._6a1e01adf97c4762__root._4e480ef72e95c007__is-rtl) ._325bd79ef1e3c6cc__before-icon{margin-left:6px}:where(._6a1e01adf97c4762__root:not(._4e480ef72e95c007__is-rtl)) ._4c163a0fe307fef3__after-icon{margin-left:6px}:where(._6a1e01adf97c4762__root._4e480ef72e95c007__is-rtl) ._4c163a0fe307fef3__after-icon{margin-right:6px}._7f1276e73f11c614__rail{--_wp-components-range-control-rail-color:initial;background:var(--_wp-components-range-control-rail-color,var(--wpds-color-background-track-neutral,#dbdbdb));border-radius:9999px;display:block;height:4px;left:0;margin-top:13px;pointer-events:none;position:absolute;right:0;top:0}._7f1276e73f11c614__rail:where(._42c8b908ae7f250e__is-disabled){background:var(--wp-components-color-gray-100,var(--wpds-color-background-surface-neutral,#fcfcfc))}._404ee8010545d96e__track{--_wp-components-range-control-track-color:initial;background:var(--_wp-components-range-control-track-color);border-radius:9999px;display:block;height:4px;margin-top:13px;pointer-events:none;position:absolute;top:0}._404ee8010545d96e__track:where(._42c8b908ae7f250e__is-disabled){background:var(--wp-components-color-gray-400,var(--wpds-color-stroke-interactive-neutral,#8b8b8b))}@media not (prefers-reduced-motion){.is-marked ._404ee8010545d96e__track{transition:width .1s ease}}.cc773bc17fc1e078__marks{display:block;margin-top:17px;pointer-events:none;position:relative;user-select:none;width:100%}.f723c0a62c1430b7__mark{background-color:var(--wp-components-color-background,var(--wpds-color-background-surface-neutral-strong,#fff));height:4px;left:0;position:absolute;top:-4px;transform:translateX(-50%);width:2px;z-index:1}.d32fdc2beb8f564b__mark-label{color:var(--wp-components-color-gray-300,var(--wpds-color-stroke-surface-neutral,#dbdbdb));font-size:11px;position:absolute;top:8px;transform:translateX(-50%);white-space:nowrap}.d32fdc2beb8f564b__mark-label:where(:not(._4e480ef72e95c007__is-rtl)){left:0}.d32fdc2beb8f564b__mark-label:where(._4e480ef72e95c007__is-rtl){right:0;transform:translateX(50%)}.d32fdc2beb8f564b__mark-label:where(.a76ff600efef8300__is-filled){color:var(--wp-components-color-gray-700,var(--wpds-color-foreground-content-neutral-weak,#6e6e6e))}._4e662f841e7693d5__thumb-wrapper{align-items:center;background:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9));border-radius:50%;display:flex;height:12px;justify-content:center;margin-top:9px;outline:0;pointer-events:none;position:absolute;top:0;user-select:none;width:12px;z-index:3}._4e662f841e7693d5__thumb-wrapper:where(._42c8b908ae7f250e__is-disabled){background:var(--wp-components-color-gray-400,var(--wpds-color-stroke-interactive-neutral,#8b8b8b))}._4e662f841e7693d5__thumb-wrapper{transform:translateX(4.5px)}:where(._6a1e01adf97c4762__root:not(._4e480ef72e95c007__is-rtl)) ._4e662f841e7693d5__thumb-wrapper{margin-left:-10px}:where(._6a1e01adf97c4762__root._4e480ef72e95c007__is-rtl) ._4e662f841e7693d5__thumb-wrapper{margin-right:-10px;transform:translateX(-4.5px)}@media not (prefers-reduced-motion){.is-marked ._4e662f841e7693d5__thumb-wrapper{transition:left .1s ease}}.c291efee9339b385__thumb{align-items:center;background:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9));border-radius:50%;box-shadow:0 1px 1px rgba(0,0,0,.03),0 1px 2px rgba(0,0,0,.02),0 3px 3px rgba(0,0,0,.02),0 4px 4px rgba(0,0,0,.01);height:100%;outline:0;position:absolute;user-select:none;width:100%}.c291efee9339b385__thumb:where(._42c8b908ae7f250e__is-disabled){background:var(--wp-components-color-gray-400,var(--wpds-color-stroke-interactive-neutral,#8b8b8b))}.c291efee9339b385__thumb:where(._4c40282bc4b85f01__is-focused){outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--focus-color,var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9)));outline-offset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}._9f9d2d76949b6e97__input{box-sizing:border-box;cursor:var(--wpds-cursor-control,pointer);display:block;height:100%;left:0;margin:0 -6px;opacity:0;outline:none;position:absolute;right:0;top:0;width:calc(100% + 12px)}.e5e0e57fa03659d3__tooltip{background:rgba(0,0,0,.8);border-radius:2px;color:#fff;display:none;font-size:12px;line-height:1.4;min-width:32px;opacity:0;padding:4px 8px;pointer-events:none;position:absolute;text-align:center;transform:translateX(-50%);user-select:none}.e5e0e57fa03659d3__tooltip:where(._4e480ef72e95c007__is-rtl){transform:translateX(50%)}.e5e0e57fa03659d3__tooltip:where(._3d76f75f23a3b86b__is-visible){display:inline-block;opacity:1}.e5e0e57fa03659d3__tooltip:where(:not(.a2c1548960f4840f__is-bottom)){top:-80%}.e5e0e57fa03659d3__tooltip:where(.a2c1548960f4840f__is-bottom){bottom:-80%}@media not (prefers-reduced-motion){.e5e0e57fa03659d3__tooltip{transition:opacity .12s ease,display allow-discrete .12s ease}}@starting-style{.e5e0e57fa03659d3__tooltip{opacity:0}}.ce0552937139bab7__input-number{display:inline-block;font-size:13px;margin-top:0}:where(._6a1e01adf97c4762__root:not(._4e480ef72e95c007__is-rtl)) .ce0552937139bab7__input-number{margin-left:16px!important}:where(._6a1e01adf97c4762__root._4e480ef72e95c007__is-rtl) .ce0552937139bab7__input-number{margin-right:16px!important}._17a230bac5de238b__action-right{display:block;margin-top:0}:where(._6a1e01adf97c4762__root:not(._4e480ef72e95c007__is-rtl)) ._17a230bac5de238b__action-right{margin-left:8px}:where(._6a1e01adf97c4762__root._4e480ef72e95c007__is-rtl) ._17a230bac5de238b__action-right{margin-right:8px}._17a230bac5de238b__action-right button,._17a230bac5de238b__action-right button.is-small{height:30px;margin-left:0;min-height:30px}._21ecef0ddd6b30cc__color-inherit{color:inherit}._09208cae4be0d86a__background-inherit{background:inherit}._0912537971ff850a__color-initial{color:initial}._2725e6ff88306d8d__background-initial{background:initial}._5ced90e174221615__color-unset{color:unset}.d26df97a68a49058__background-unset{background:unset}._6ffdbff3c2cce7b1__color-revert{color:revert}._39937b8ec4d503f0__background-revert{background:revert}._7f42d7000a4d1141__color-revert-layer{color:revert-layer}._869689f01bfa7a3a__background-revert-layer{background:revert-layer}@media (forced-colors:active){._7f1276e73f11c614__rail{background:GrayText}._404ee8010545d96e__track,._4e662f841e7693d5__thumb-wrapper,.c291efee9339b385__thumb{background:CanvasText}._404ee8010545d96e__track:where(._42c8b908ae7f250e__is-disabled),._4e662f841e7693d5__thumb-wrapper:where(._42c8b908ae7f250e__is-disabled),.c291efee9339b385__thumb:where(._42c8b908ae7f250e__is-disabled){background:GrayText}}");
var style_module_default = {
"root": "_6a1e01adf97c4762__root",
"is-compact": "_2495fc3509946926__is-compact",
"wrapper": "_811431d1b36d2890__wrapper",
"default-color": "_2bab18807adcbaf7__default-color",
"before-icon": "_325bd79ef1e3c6cc__before-icon",
"after-icon": "_4c163a0fe307fef3__after-icon",
"is-rtl": "_4e480ef72e95c007__is-rtl",
"rail": "_7f1276e73f11c614__rail",
"is-disabled": "_42c8b908ae7f250e__is-disabled",
"track": "_404ee8010545d96e__track",
"marks": "cc773bc17fc1e078__marks",
"mark": "f723c0a62c1430b7__mark",
"mark-label": "d32fdc2beb8f564b__mark-label",
"is-filled": "a76ff600efef8300__is-filled",
"thumb-wrapper": "_4e662f841e7693d5__thumb-wrapper",
"thumb": "c291efee9339b385__thumb",
"is-focused": "_4c40282bc4b85f01__is-focused",
"input": "_9f9d2d76949b6e97__input",
"tooltip": "e5e0e57fa03659d3__tooltip",
"is-visible": "_3d76f75f23a3b86b__is-visible",
"is-bottom": "a2c1548960f4840f__is-bottom",
"input-number": "ce0552937139bab7__input-number",
"action-right": "_17a230bac5de238b__action-right",
"color-inherit": "_21ecef0ddd6b30cc__color-inherit",
"background-inherit": "_09208cae4be0d86a__background-inherit",
"color-initial": "_0912537971ff850a__color-initial",
"background-initial": "_2725e6ff88306d8d__background-initial",
"color-unset": "_5ced90e174221615__color-unset",
"background-unset": "d26df97a68a49058__background-unset",
"color-revert": "_6ffdbff3c2cce7b1__color-revert",
"background-revert": "_39937b8ec4d503f0__background-revert",
"color-revert-layer": "_7f42d7000a4d1141__color-revert-layer",
"background-revert-layer": "_869689f01bfa7a3a__background-revert-layer"
};
// packages/components/src/range-control/index.tsx
const NUMBER_CONTROL_WIDTH = 80;
const noop = () => {};
/**
* Computes the value that `RangeControl` should reset to when pressing
* the reset button.
*/
function computeResetValue({ resetFallbackValue, initialPosition }) {
if (resetFallbackValue !== void 0) return !Number.isNaN(resetFallbackValue) ? resetFallbackValue : null;
if (initialPosition !== void 0) return !Number.isNaN(initialPosition) ? initialPosition : null;
return null;
}
function UnforwardedRangeControl(props, forwardedRef) {
const { __nextHasNoMarginBottom: _, __next40pxDefaultSize: _next40pxDefaultSize, afterIcon, allowReset = false, beforeIcon, className, color: colorProp, currentInput, disabled = false, help, hideLabelFromVision = false, initialPosition, isShiftStepEnabled = true, label, marks = false, max = 100, min = 0, onBlur = noop, onChange = noop, onFocus = noop, onMouseLeave = noop, onMouseMove = noop, railColor, renderTooltipContent = (v) => v, resetFallbackValue, shiftStep = 10, showTooltip: showTooltipProp, size = "default", step = 1, trackColor, value: valueProp, withInputField = true, ...otherProps } = props;
const [value, setValue] = useControlledRangeValue({
min,
max,
value: valueProp ?? null,
initial: initialPosition
});
const isResetPendent = useRef(false);
let hasTooltip = showTooltipProp;
let hasInputField = withInputField;
if (step === "any") {
hasTooltip = false;
hasInputField = false;
}
const [showTooltip, setShowTooltip] = useState(hasTooltip);
const [isFocused, setIsFocused] = useState(false);
const inputRef = useRef(null);
const isCurrentlyFocused = inputRef.current?.matches(":focus");
const isThumbFocused = !disabled && isFocused;
const isValueReset = value === null;
const inputSliderValue = isValueReset ? "" : value !== void 0 ? value : currentInput;
const rangeFillValue = isValueReset ? (max - min) / 2 + min : value;
const fillValue = isValueReset ? 50 : (value - min) / (max - min) * 100;
const fillValueOffset = `${clamp(fillValue, 0, 100)}%`;
const classes = clsx("components-range-control", className);
const colorKeyword = getCSSWideKeyword(colorProp);
const trackColorKeyword = getCSSWideKeyword(trackColor);
const wrapperClasses = clsx("components-range-control__wrapper", style_module_default.wrapper, colorProp === void 0 && style_module_default["default-color"], colorKeyword && style_module_default[`color-${colorKeyword}`], !!marks && "is-marked");
const id = useInstanceId(UnforwardedRangeControl, "inspector-range-control");
const describedBy = !!help ? `${id}__help` : void 0;
const enableTooltip = hasTooltip !== false && Number.isFinite(value);
const handleOnRangeChange = (event) => {
const nextValue = parseFloat(event.target.value);
setValue(nextValue);
onChange(nextValue);
};
const handleOnChange = (next) => {
let nextValue = parseFloat(next);
setValue(nextValue);
if (!isNaN(nextValue)) {
if (nextValue < min || nextValue > max) nextValue = floatClamp(nextValue, min, max);
onChange(nextValue);
isResetPendent.current = false;
} else if (allowReset) isResetPendent.current = true;
};
const handleOnInputNumberBlur = () => {
if (isResetPendent.current) {
handleOnReset();
isResetPendent.current = false;
}
};
const handleOnReset = () => {
const resetValue = Number.isNaN(resetFallbackValue) ? null : resetFallbackValue ?? null;
setValue(resetValue);
/**
* Previously, this callback would always receive undefined as
* an argument. This behavior is unexpected, specifically
* when resetFallbackValue is defined.
*
* The value of undefined is not ideal. Passing it through
* to internal <input /> elements would change it from a
* controlled component to an uncontrolled component.
*
* For now, to minimize unexpected regressions, we're going to
* preserve the undefined callback argument, except when a
* resetFallbackValue is defined.
*/
onChange(resetValue ?? void 0);
};
const handleShowTooltip = () => setShowTooltip(true);
const handleHideTooltip = () => setShowTooltip(false);
const handleOnBlur = (event) => {
onBlur(event);
setIsFocused(false);
handleHideTooltip();
};
const handleOnFocus = (event) => {
onFocus(event);
setIsFocused(true);
handleShowTooltip();
};
const offsetStyle = { [isRTL() ? "right" : "left"]: fillValueOffset };
return /* @__PURE__ */ jsx(BaseControl, {
className: classes,
label,
hideLabelFromVision,
id: `${id}`,
help,
children: /* @__PURE__ */ jsxs("div", {
className: clsx("components-range-control__root", style_module_default.root, {
[style_module_default["is-rtl"]]: isRTL(),
[style_module_default["is-compact"]]: size === "compact"
}),
children: [
beforeIcon && /* @__PURE__ */ jsx("span", {
className: style_module_default["before-icon"],
children: /* @__PURE__ */ jsx(Icon, { icon: beforeIcon })
}),
/* @__PURE__ */ jsxs("div", {
className: wrapperClasses,
style: { "--_wp-components-range-control-color": colorProp },
children: [
/* @__PURE__ */ jsx(InputRange, {
...otherProps,
className: "components-range-control__slider",
describedBy,
disabled,
id: `${id}`,
label,
max,
min,
onBlur: handleOnBlur,
onChange: handleOnRangeChange,
onFocus: handleOnFocus,
onMouseMove,
onMouseLeave,
ref: useMergeRefs([inputRef, forwardedRef]),
step,
value: inputSliderValue ?? void 0
}),
/* @__PURE__ */ jsx(RangeRail, {
"aria-hidden": true,
disabled,
marks,
max,
min,
railColor,
step,
value: rangeFillValue
}),
/* @__PURE__ */ jsx("span", {
"aria-hidden": true,
className: clsx("components-range-control__track", style_module_default.track, { [style_module_default["is-disabled"]]: disabled }, !disabled && trackColorKeyword && style_module_default[`background-${trackColorKeyword}`]),
disabled,
style: {
width: fillValueOffset,
"--_wp-components-range-control-track-color": trackColor || "currentColor"
}
}),
/* @__PURE__ */ jsx("span", {
className: clsx("components-range-control__thumb-wrapper", style_module_default["thumb-wrapper"], { [style_module_default["is-disabled"]]: disabled }),
style: offsetStyle,
disabled,
children: /* @__PURE__ */ jsx("span", {
"aria-hidden": true,
className: clsx(style_module_default.thumb, {
[style_module_default["is-disabled"]]: disabled,
[style_module_default["is-focused"]]: isThumbFocused
}),
disabled
})
}),
enableTooltip && /* @__PURE__ */ jsx(SimpleTooltip, {
className: "components-range-control__tooltip",
inputRef,
tooltipPlacement: "bottom",
renderTooltipContent,
show: isCurrentlyFocused || showTooltip,
style: offsetStyle,
value
})
]
}),
afterIcon && /* @__PURE__ */ jsx("span", {
className: style_module_default["after-icon"],
children: /* @__PURE__ */ jsx(Icon, { icon: afterIcon })
}),
hasInputField && /* @__PURE__ */ jsx(NumberControl, {
"aria-label": label,
className: clsx("components-range-control__number", style_module_default["input-number"]),
disabled,
inputMode: "decimal",
isShiftStepEnabled,
max,
min,
onBlur: handleOnInputNumberBlur,
onChange: handleOnChange,
shiftStep,
size,
__unstableInputWidth: `${NUMBER_CONTROL_WIDTH}px`,
step,
value: inputSliderValue
}),
allowReset && /* @__PURE__ */ jsx("span", {
className: style_module_default["action-right"],
children: /* @__PURE__ */ jsx(Button, {
className: "components-range-control__reset",
accessibleWhenDisabled: !disabled,
disabled: disabled || value === computeResetValue({
resetFallbackValue,
initialPosition
}),
variant: "secondary",
size: "small",
onClick: handleOnReset,
children: __("Reset")
})
})
]
})
});
}
/**
* RangeControls are used to make selections from a range of incremental values.
*
* ```jsx
* import { RangeControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyRangeControl = () => {
* const [ value, setValue ] = useState();
* return (
* <RangeControl
* help="Please select how transparent you would like this."
* initialPosition={ 50 }
* label="Opacity"
* max={ 100 }
* min={ 0 }
* value={ value }
* onChange={ setValue }
* />
* );
* };
* ```
*/
const RangeControl = forwardRef(UnforwardedRangeControl);
RangeControl.displayName = "RangeControl";
export { RangeControl, RangeControl as default };
//# sourceMappingURL=index.mjs.map