WordPress/wp-includes/js/dist/components.js

77085 lines
2.5 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 4403:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
var nativeCodeString = '[native code]';
function classNames() {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
if (arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
}
} else if (argType === 'object') {
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
classes.push(arg.toString());
continue;
}
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ }),
/***/ 1919:
/***/ (function(module) {
"use strict";
var isMergeableObject = function isMergeableObject(value) {
return isNonNullObject(value)
&& !isSpecial(value)
};
function isNonNullObject(value) {
return !!value && typeof value === 'object'
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === '[object RegExp]'
|| stringValue === '[object Date]'
|| isReactElement(value)
}
// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {}
}
function cloneUnlessOtherwiseSpecified(value, options) {
return (options.clone !== false && options.isMergeableObject(value))
? deepmerge(emptyTarget(value), value, options)
: value
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options)
})
}
function getMergeFunction(key, options) {
if (!options.customMerge) {
return deepmerge
}
var customMerge = options.customMerge(key);
return typeof customMerge === 'function' ? customMerge : deepmerge
}
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols
? Object.getOwnPropertySymbols(target).filter(function(symbol) {
return Object.propertyIsEnumerable.call(target, symbol)
})
: []
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
}
function propertyIsOnObject(object, property) {
try {
return property in object
} catch(_) {
return false
}
}
// Protects from prototype poisoning and unexpected merging up the prototype chain.
function propertyIsUnsafe(target, key) {
return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) {
getKeys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
}
getKeys(source).forEach(function(key) {
if (propertyIsUnsafe(target, key)) {
return
}
if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
} else {
destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
}
});
return destination
}
function deepmerge(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
// implementations can use it. The caller may not replace it.
options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
var sourceIsArray = Array.isArray(source);
var targetIsArray = Array.isArray(target);
var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
if (!sourceAndTargetTypesMatch) {
return cloneUnlessOtherwiseSpecified(source, options)
} else if (sourceIsArray) {
return options.arrayMerge(target, source, options)
} else {
return mergeObject(target, source, options)
}
}
deepmerge.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error('first argument should be an array')
}
return array.reduce(function(prev, next) {
return deepmerge(prev, next, options)
}, {})
};
var deepmerge_1 = deepmerge;
module.exports = deepmerge_1;
/***/ }),
/***/ 1345:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(5022);
function scrollIntoView(elem, container, config) {
config = config || {};
// document 归一化到 window
if (container.nodeType === 9) {
container = util.getWindow(container);
}
var allowHorizontalScroll = config.allowHorizontalScroll;
var onlyScrollIfNeeded = config.onlyScrollIfNeeded;
var alignWithTop = config.alignWithTop;
var alignWithLeft = config.alignWithLeft;
var offsetTop = config.offsetTop || 0;
var offsetLeft = config.offsetLeft || 0;
var offsetBottom = config.offsetBottom || 0;
var offsetRight = config.offsetRight || 0;
allowHorizontalScroll = allowHorizontalScroll === undefined ? true : allowHorizontalScroll;
var isWin = util.isWindow(container);
var elemOffset = util.offset(elem);
var eh = util.outerHeight(elem);
var ew = util.outerWidth(elem);
var containerOffset = undefined;
var ch = undefined;
var cw = undefined;
var containerScroll = undefined;
var diffTop = undefined;
var diffBottom = undefined;
var win = undefined;
var winScroll = undefined;
var ww = undefined;
var wh = undefined;
if (isWin) {
win = container;
wh = util.height(win);
ww = util.width(win);
winScroll = {
left: util.scrollLeft(win),
top: util.scrollTop(win)
};
// elem 相对 container 可视视窗的距离
diffTop = {
left: elemOffset.left - winScroll.left - offsetLeft,
top: elemOffset.top - winScroll.top - offsetTop
};
diffBottom = {
left: elemOffset.left + ew - (winScroll.left + ww) + offsetRight,
top: elemOffset.top + eh - (winScroll.top + wh) + offsetBottom
};
containerScroll = winScroll;
} else {
containerOffset = util.offset(container);
ch = container.clientHeight;
cw = container.clientWidth;
containerScroll = {
left: container.scrollLeft,
top: container.scrollTop
};
// elem 相对 container 可视视窗的距离
// 注意边框, offset 是边框到根节点
diffTop = {
left: elemOffset.left - (containerOffset.left + (parseFloat(util.css(container, 'borderLeftWidth')) || 0)) - offsetLeft,
top: elemOffset.top - (containerOffset.top + (parseFloat(util.css(container, 'borderTopWidth')) || 0)) - offsetTop
};
diffBottom = {
left: elemOffset.left + ew - (containerOffset.left + cw + (parseFloat(util.css(container, 'borderRightWidth')) || 0)) + offsetRight,
top: elemOffset.top + eh - (containerOffset.top + ch + (parseFloat(util.css(container, 'borderBottomWidth')) || 0)) + offsetBottom
};
}
if (diffTop.top < 0 || diffBottom.top > 0) {
// 强制向上
if (alignWithTop === true) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else if (alignWithTop === false) {
util.scrollTop(container, containerScroll.top + diffBottom.top);
} else {
// 自动调整
if (diffTop.top < 0) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else {
util.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
} else {
if (!onlyScrollIfNeeded) {
alignWithTop = alignWithTop === undefined ? true : !!alignWithTop;
if (alignWithTop) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else {
util.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
}
if (allowHorizontalScroll) {
if (diffTop.left < 0 || diffBottom.left > 0) {
// 强制向上
if (alignWithLeft === true) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else if (alignWithLeft === false) {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
} else {
// 自动调整
if (diffTop.left < 0) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
} else {
if (!onlyScrollIfNeeded) {
alignWithLeft = alignWithLeft === undefined ? true : !!alignWithLeft;
if (alignWithLeft) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
}
}
}
module.exports = scrollIntoView;
/***/ }),
/***/ 5425:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(1345);
/***/ }),
/***/ 5022:
/***/ (function(module) {
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;
function getClientPosition(elem) {
var box = undefined;
var x = undefined;
var y = undefined;
var doc = elem.ownerDocument;
var body = doc.body;
var docElem = doc && doc.documentElement;
// 根据 GBS 最新数据A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式
box = elem.getBoundingClientRect();
// 注jQuery 还考虑减去 docElem.clientLeft/clientTop
// 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确
// 此外ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin
x = box.left;
y = box.top;
// In IE, most of the time, 2 extra pixels are added to the top and left
// due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
// IE6 standards mode, this border can be overridden by setting the
// document element's border to zero -- thus, we cannot rely on the
// offset always being 2 pixels.
// In quirks mode, the offset can be determined by querying the body's
// clientLeft/clientTop, but in standards mode, it is found by querying
// the document element's clientLeft/clientTop. Since we already called
// getClientBoundingRect we have already forced a reflow, so it is not
// too expensive just to query them all.
// ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的
// 窗口边框标准是设 documentElement ,quirks 时设置 body
// 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去
// 但是非 ie 不可能设置窗口边框body html 也不是窗口 ,ie 可以通过 html,body 设置
// 标准 ie 下 docElem.clientTop 就是 border-top
// ie7 html 即窗口边框改变不了。永远为 2
// 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
return {
left: x,
top: y
};
}
function getScroll(w, top) {
var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
var method = 'scroll' + (top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function getScrollLeft(w) {
return getScroll(w);
}
function getScrollTop(w) {
return getScroll(w, true);
}
function getOffset(el) {
var pos = getClientPosition(el);
var doc = el.ownerDocument;
var w = doc.defaultView || doc.parentWindow;
pos.left += getScrollLeft(w);
pos.top += getScrollTop(w);
return pos;
}
function _getComputedStyle(elem, name, computedStyle_) {
var val = '';
var d = elem.ownerDocument;
var computedStyle = computedStyle_ || d.defaultView.getComputedStyle(elem, null);
// https://github.com/kissyteam/kissy/issues/61
if (computedStyle) {
val = computedStyle.getPropertyValue(name) || computedStyle[name];
}
return val;
}
var _RE_NUM_NO_PX = new RegExp('^(' + RE_NUM + ')(?!px)[a-z%]+$', 'i');
var RE_POS = /^(top|right|bottom|left)$/;
var CURRENT_STYLE = 'currentStyle';
var RUNTIME_STYLE = 'runtimeStyle';
var LEFT = 'left';
var PX = 'px';
function _getComputedStyleIE(elem, name) {
// currentStyle maybe null
// http://msdn.microsoft.com/en-us/library/ms535231.aspx
var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];
// 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值
// 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19
// 在 ie 下不对,需要直接用 offset 方式
// borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// exclude left right for relativity
if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {
// Remember the original values
var style = elem.style;
var left = style[LEFT];
var rsLeft = elem[RUNTIME_STYLE][LEFT];
// prevent flashing of content
elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];
// Put in the new values to get a computed value out
style[LEFT] = name === 'fontSize' ? '1em' : ret || 0;
ret = style.pixelLeft + PX;
// Revert the changed values
style[LEFT] = left;
elem[RUNTIME_STYLE][LEFT] = rsLeft;
}
return ret === '' ? 'auto' : ret;
}
var getComputedStyleX = undefined;
if (typeof window !== 'undefined') {
getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE;
}
function each(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i]);
}
}
function isBorderBoxFn(elem) {
return getComputedStyleX(elem, 'boxSizing') === 'border-box';
}
var BOX_MODELS = ['margin', 'border', 'padding'];
var CONTENT_INDEX = -1;
var PADDING_INDEX = 2;
var BORDER_INDEX = 1;
var MARGIN_INDEX = 0;
function swap(elem, options, callback) {
var old = {};
var style = elem.style;
var name = undefined;
// Remember the old values, and insert the new ones
for (name in options) {
if (options.hasOwnProperty(name)) {
old[name] = style[name];
style[name] = options[name];
}
}
callback.call(elem);
// Revert the old values
for (name in options) {
if (options.hasOwnProperty(name)) {
style[name] = old[name];
}
}
}
function getPBMWidth(elem, props, which) {
var value = 0;
var prop = undefined;
var j = undefined;
var i = undefined;
for (j = 0; j < props.length; j++) {
prop = props[j];
if (prop) {
for (i = 0; i < which.length; i++) {
var cssProp = undefined;
if (prop === 'border') {
cssProp = prop + which[i] + 'Width';
} else {
cssProp = prop + which[i];
}
value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;
}
}
}
return value;
}
/**
* A crude way of determining if an object is a window
* @member util
*/
function isWindow(obj) {
// must use == for ie8
/* eslint eqeqeq:0 */
return obj != null && obj == obj.window;
}
var domUtils = {};
each(['Width', 'Height'], function (name) {
domUtils['doc' + name] = function (refWin) {
var d = refWin.document;
return Math.max(
// firefox chrome documentElement.scrollHeight< body.scrollHeight
// ie standard mode : documentElement.scrollHeight> body.scrollHeight
d.documentElement['scroll' + name],
// quirks : documentElement.scrollHeight 最大等于可视窗口多一点?
d.body['scroll' + name], domUtils['viewport' + name](d));
};
domUtils['viewport' + name] = function (win) {
// pc browser includes scrollbar in window.innerWidth
var prop = 'client' + name;
var doc = win.document;
var body = doc.body;
var documentElement = doc.documentElement;
var documentElementProp = documentElement[prop];
// 标准模式取 documentElement
// backcompat 取 body
return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp;
};
});
/*
得到元素的大小信息
@param elem
@param name
@param {String} [extra] 'padding' : (css width) + padding
'border' : (css width) + padding + border
'margin' : (css width) + padding + border + margin
*/
function getWH(elem, name, extra) {
if (isWindow(elem)) {
return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem);
} else if (elem.nodeType === 9) {
return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem);
}
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
var borderBoxValue = name === 'width' ? elem.offsetWidth : elem.offsetHeight;
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem, computedStyle);
var cssBoxValue = 0;
if (borderBoxValue == null || borderBoxValue <= 0) {
borderBoxValue = undefined;
// Fall back to computed then un computed css if necessary
cssBoxValue = getComputedStyleX(elem, name);
if (cssBoxValue == null || Number(cssBoxValue) < 0) {
cssBoxValue = elem.style[name] || 0;
}
// Normalize '', auto, and prepare for extra
cssBoxValue = parseFloat(cssBoxValue) || 0;
}
if (extra === undefined) {
extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;
}
var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox;
var val = borderBoxValue || cssBoxValue;
if (extra === CONTENT_INDEX) {
if (borderBoxValueOrIsBorderBox) {
return val - getPBMWidth(elem, ['border', 'padding'], which, computedStyle);
}
return cssBoxValue;
}
if (borderBoxValueOrIsBorderBox) {
var padding = extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which, computedStyle) : getPBMWidth(elem, ['margin'], which, computedStyle);
return val + (extra === BORDER_INDEX ? 0 : padding);
}
return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which, computedStyle);
}
var cssShow = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
// fix #119 : https://github.com/kissyteam/kissy/issues/119
function getWHIgnoreDisplay(elem) {
var val = undefined;
var args = arguments;
// in case elem is window
// elem.offsetWidth === undefined
if (elem.offsetWidth !== 0) {
val = getWH.apply(undefined, args);
} else {
swap(elem, cssShow, function () {
val = getWH.apply(undefined, args);
});
}
return val;
}
function css(el, name, v) {
var value = v;
if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
for (var i in name) {
if (name.hasOwnProperty(i)) {
css(el, i, name[i]);
}
}
return undefined;
}
if (typeof value !== 'undefined') {
if (typeof value === 'number') {
value += 'px';
}
el.style[name] = value;
return undefined;
}
return getComputedStyleX(el, name);
}
each(['width', 'height'], function (name) {
var first = name.charAt(0).toUpperCase() + name.slice(1);
domUtils['outer' + first] = function (el, includeMargin) {
return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX);
};
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
domUtils[name] = function (elem, val) {
if (val !== undefined) {
if (elem) {
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem);
if (isBorderBox) {
val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle);
}
return css(elem, name, val);
}
return undefined;
}
return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);
};
});
// 设置 elem 相对 elem.ownerDocument 的坐标
function setOffset(elem, offset) {
// set position first, in-case top/left are set even on static elem
if (css(elem, 'position') === 'static') {
elem.style.position = 'relative';
}
var old = getOffset(elem);
var ret = {};
var current = undefined;
var key = undefined;
for (key in offset) {
if (offset.hasOwnProperty(key)) {
current = parseFloat(css(elem, key)) || 0;
ret[key] = current + offset[key] - old[key];
}
}
css(elem, ret);
}
module.exports = _extends({
getWindow: function getWindow(node) {
var doc = node.ownerDocument || node;
return doc.defaultView || doc.parentWindow;
},
offset: function offset(el, value) {
if (typeof value !== 'undefined') {
setOffset(el, value);
} else {
return getOffset(el);
}
},
isWindow: isWindow,
each: each,
css: css,
clone: function clone(obj) {
var ret = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ret[i] = obj[i];
}
}
var overflow = obj.overflow;
if (overflow) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ret.overflow[i] = obj.overflow[i];
}
}
}
return ret;
},
scrollLeft: function scrollLeft(w, v) {
if (isWindow(w)) {
if (v === undefined) {
return getScrollLeft(w);
}
window.scrollTo(v, getScrollTop(w));
} else {
if (v === undefined) {
return w.scrollLeft;
}
w.scrollLeft = v;
}
},
scrollTop: function scrollTop(w, v) {
if (isWindow(w)) {
if (v === undefined) {
return getScrollTop(w);
}
window.scrollTo(getScrollLeft(w), v);
} else {
if (v === undefined) {
return w.scrollTop;
}
w.scrollTop = v;
}
},
viewportWidth: 0,
viewportHeight: 0
}, domUtils);
/***/ }),
/***/ 9214:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var __webpack_unused_export__;
/** @license React v17.0.2
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131;
if("function"===typeof Symbol&&Symbol.for){var x=Symbol.for;b=x("react.element");c=x("react.portal");d=x("react.fragment");e=x("react.strict_mode");f=x("react.profiler");g=x("react.provider");h=x("react.context");k=x("react.forward_ref");l=x("react.suspense");m=x("react.suspense_list");n=x("react.memo");p=x("react.lazy");q=x("react.block");r=x("react.server.block");u=x("react.fundamental");v=x("react.debug_trace_mode");w=x("react.legacy_hidden")}
function y(a){if("object"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type,a){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof,a){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}var z=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;__webpack_unused_export__=h;__webpack_unused_export__=z;__webpack_unused_export__=A;__webpack_unused_export__=B;__webpack_unused_export__=C;__webpack_unused_export__=D;__webpack_unused_export__=E;__webpack_unused_export__=F;__webpack_unused_export__=G;__webpack_unused_export__=H;
__webpack_unused_export__=I;__webpack_unused_export__=function(){return!1};__webpack_unused_export__=function(){return!1};__webpack_unused_export__=function(a){return y(a)===h};__webpack_unused_export__=function(a){return y(a)===g};__webpack_unused_export__=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===b};__webpack_unused_export__=function(a){return y(a)===k};__webpack_unused_export__=function(a){return y(a)===d};__webpack_unused_export__=function(a){return y(a)===p};__webpack_unused_export__=function(a){return y(a)===n};
__webpack_unused_export__=function(a){return y(a)===c};__webpack_unused_export__=function(a){return y(a)===f};__webpack_unused_export__=function(a){return y(a)===e};__webpack_unused_export__=function(a){return y(a)===l};__webpack_unused_export__=function(a){return"string"===typeof a||"function"===typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||"object"===typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)?!0:!1};
__webpack_unused_export__=y;
/***/ }),
/***/ 2797:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
/* unused reexport */ __webpack_require__(9214);
} else {}
/***/ }),
/***/ 5619:
/***/ (function(module) {
"use strict";
// do not edit .js files directly - edit src/index.jst
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/***/ 7115:
/***/ (function(__unused_webpack_module, exports) {
// Copyright (c) 2014 Rafael Caricio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var GradientParser = {};
GradientParser.parse = (function() {
var tokens = {
linearGradient: /^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,
repeatingLinearGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,
radialGradient: /^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,
repeatingRadialGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,
sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|left|right|top|bottom)/i,
extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
positionKeywords: /^(left|center|right|top|bottom)/i,
pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
startCall: /^\(/,
endCall: /^\)/,
comma: /^,/,
hexColor: /^\#([0-9a-fA-F]+)/,
literalColor: /^([a-zA-Z]+)/,
rgbColor: /^rgb/i,
rgbaColor: /^rgba/i,
number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
};
var input = '';
function error(msg) {
var err = new Error(input + ': ' + msg);
err.source = input;
throw err;
}
function getAST() {
var ast = matchListDefinitions();
if (input.length > 0) {
error('Invalid input not EOF');
}
return ast;
}
function matchListDefinitions() {
return matchListing(matchDefinition);
}
function matchDefinition() {
return matchGradient(
'linear-gradient',
tokens.linearGradient,
matchLinearOrientation) ||
matchGradient(
'repeating-linear-gradient',
tokens.repeatingLinearGradient,
matchLinearOrientation) ||
matchGradient(
'radial-gradient',
tokens.radialGradient,
matchListRadialOrientations) ||
matchGradient(
'repeating-radial-gradient',
tokens.repeatingRadialGradient,
matchListRadialOrientations);
}
function matchGradient(gradientType, pattern, orientationMatcher) {
return matchCall(pattern, function(captures) {
var orientation = orientationMatcher();
if (orientation) {
if (!scan(tokens.comma)) {
error('Missing comma before color stops');
}
}
return {
type: gradientType,
orientation: orientation,
colorStops: matchListing(matchColorStop)
};
});
}
function matchCall(pattern, callback) {
var captures = scan(pattern);
if (captures) {
if (!scan(tokens.startCall)) {
error('Missing (');
}
result = callback(captures);
if (!scan(tokens.endCall)) {
error('Missing )');
}
return result;
}
}
function matchLinearOrientation() {
return matchSideOrCorner() ||
matchAngle();
}
function matchSideOrCorner() {
return match('directional', tokens.sideOrCorner, 1);
}
function matchAngle() {
return match('angular', tokens.angleValue, 1);
}
function matchListRadialOrientations() {
var radialOrientations,
radialOrientation = matchRadialOrientation(),
lookaheadCache;
if (radialOrientation) {
radialOrientations = [];
radialOrientations.push(radialOrientation);
lookaheadCache = input;
if (scan(tokens.comma)) {
radialOrientation = matchRadialOrientation();
if (radialOrientation) {
radialOrientations.push(radialOrientation);
} else {
input = lookaheadCache;
}
}
}
return radialOrientations;
}
function matchRadialOrientation() {
var radialType = matchCircle() ||
matchEllipse();
if (radialType) {
radialType.at = matchAtPosition();
} else {
var defaultPosition = matchPositioning();
if (defaultPosition) {
radialType = {
type: 'default-radial',
at: defaultPosition
};
}
}
return radialType;
}
function matchCircle() {
var circle = match('shape', /^(circle)/i, 0);
if (circle) {
circle.style = matchLength() || matchExtentKeyword();
}
return circle;
}
function matchEllipse() {
var ellipse = match('shape', /^(ellipse)/i, 0);
if (ellipse) {
ellipse.style = matchDistance() || matchExtentKeyword();
}
return ellipse;
}
function matchExtentKeyword() {
return match('extent-keyword', tokens.extentKeywords, 1);
}
function matchAtPosition() {
if (match('position', /^at/, 0)) {
var positioning = matchPositioning();
if (!positioning) {
error('Missing positioning value');
}
return positioning;
}
}
function matchPositioning() {
var location = matchCoordinates();
if (location.x || location.y) {
return {
type: 'position',
value: location
};
}
}
function matchCoordinates() {
return {
x: matchDistance(),
y: matchDistance()
};
}
function matchListing(matcher) {
var captures = matcher(),
result = [];
if (captures) {
result.push(captures);
while (scan(tokens.comma)) {
captures = matcher();
if (captures) {
result.push(captures);
} else {
error('One extra comma');
}
}
}
return result;
}
function matchColorStop() {
var color = matchColor();
if (!color) {
error('Expected color definition');
}
color.length = matchDistance();
return color;
}
function matchColor() {
return matchHexColor() ||
matchRGBAColor() ||
matchRGBColor() ||
matchLiteralColor();
}
function matchLiteralColor() {
return match('literal', tokens.literalColor, 0);
}
function matchHexColor() {
return match('hex', tokens.hexColor, 1);
}
function matchRGBColor() {
return matchCall(tokens.rgbColor, function() {
return {
type: 'rgb',
value: matchListing(matchNumber)
};
});
}
function matchRGBAColor() {
return matchCall(tokens.rgbaColor, function() {
return {
type: 'rgba',
value: matchListing(matchNumber)
};
});
}
function matchNumber() {
return scan(tokens.number)[1];
}
function matchDistance() {
return match('%', tokens.percentageValue, 1) ||
matchPositionKeyword() ||
matchLength();
}
function matchPositionKeyword() {
return match('position-keyword', tokens.positionKeywords, 1);
}
function matchLength() {
return match('px', tokens.pixelValue, 1) ||
match('em', tokens.emValue, 1);
}
function match(type, pattern, captureIndex) {
var captures = scan(pattern);
if (captures) {
return {
type: type,
value: captures[captureIndex]
};
}
}
function scan(regexp) {
var captures,
blankCaptures;
blankCaptures = /^[\n\r\t\s]+/.exec(input);
if (blankCaptures) {
consume(blankCaptures[0].length);
}
captures = regexp.exec(input);
if (captures) {
consume(captures[0].length);
}
return captures;
}
function consume(size) {
input = input.substr(size);
}
return function(code) {
input = code.toString();
return getAST();
};
})();
exports.parse = (GradientParser || {}).parse;
/***/ }),
/***/ 3138:
/***/ (function(module) {
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __nested_webpack_require_187__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_187__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __nested_webpack_require_187__.m = modules;
/******/
/******/ // expose the module cache
/******/ __nested_webpack_require_187__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __nested_webpack_require_187__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __nested_webpack_require_187__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __nested_webpack_require_1468__) {
module.exports = __nested_webpack_require_1468__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __nested_webpack_require_1587__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __nested_webpack_require_1587__(2);
Object.defineProperty(exports, 'combineChunks', {
enumerable: true,
get: function get() {
return _utils.combineChunks;
}
});
Object.defineProperty(exports, 'fillInChunks', {
enumerable: true,
get: function get() {
return _utils.fillInChunks;
}
});
Object.defineProperty(exports, 'findAll', {
enumerable: true,
get: function get() {
return _utils.findAll;
}
});
Object.defineProperty(exports, 'findChunks', {
enumerable: true,
get: function get() {
return _utils.findChunks;
}
});
/***/ }),
/* 2 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word.
* @return Array of "chunks" (where a Chunk is { start:number, end:number, highlight:boolean })
*/
var findAll = exports.findAll = function findAll(_ref) {
var autoEscape = _ref.autoEscape,
_ref$caseSensitive = _ref.caseSensitive,
caseSensitive = _ref$caseSensitive === undefined ? false : _ref$caseSensitive,
_ref$findChunks = _ref.findChunks,
findChunks = _ref$findChunks === undefined ? defaultFindChunks : _ref$findChunks,
sanitize = _ref.sanitize,
searchWords = _ref.searchWords,
textToHighlight = _ref.textToHighlight;
return fillInChunks({
chunksToHighlight: combineChunks({
chunks: findChunks({
autoEscape: autoEscape,
caseSensitive: caseSensitive,
sanitize: sanitize,
searchWords: searchWords,
textToHighlight: textToHighlight
})
}),
totalLength: textToHighlight ? textToHighlight.length : 0
});
};
/**
* Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks.
* @return {start:number, end:number}[]
*/
var combineChunks = exports.combineChunks = function combineChunks(_ref2) {
var chunks = _ref2.chunks;
chunks = chunks.sort(function (first, second) {
return first.start - second.start;
}).reduce(function (processedChunks, nextChunk) {
// First chunk just goes straight in the array...
if (processedChunks.length === 0) {
return [nextChunk];
} else {
// ... subsequent chunks get checked to see if they overlap...
var prevChunk = processedChunks.pop();
if (nextChunk.start <= prevChunk.end) {
// It may be the case that prevChunk completely surrounds nextChunk, so take the
// largest of the end indeces.
var endIndex = Math.max(prevChunk.end, nextChunk.end);
processedChunks.push({ highlight: false, start: prevChunk.start, end: endIndex });
} else {
processedChunks.push(prevChunk, nextChunk);
}
return processedChunks;
}
}, []);
return chunks;
};
/**
* Examine text for any matches.
* If we find matches, add them to the returned array as a "chunk" object ({start:number, end:number}).
* @return {start:number, end:number}[]
*/
var defaultFindChunks = function defaultFindChunks(_ref3) {
var autoEscape = _ref3.autoEscape,
caseSensitive = _ref3.caseSensitive,
_ref3$sanitize = _ref3.sanitize,
sanitize = _ref3$sanitize === undefined ? defaultSanitize : _ref3$sanitize,
searchWords = _ref3.searchWords,
textToHighlight = _ref3.textToHighlight;
textToHighlight = sanitize(textToHighlight);
return searchWords.filter(function (searchWord) {
return searchWord;
}) // Remove empty words
.reduce(function (chunks, searchWord) {
searchWord = sanitize(searchWord);
if (autoEscape) {
searchWord = escapeRegExpFn(searchWord);
}
var regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi');
var match = void 0;
while (match = regex.exec(textToHighlight)) {
var _start = match.index;
var _end = regex.lastIndex;
// We do not return zero-length matches
if (_end > _start) {
chunks.push({ highlight: false, start: _start, end: _end });
}
// Prevent browsers like Firefox from getting stuck in an infinite loop
// See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/
if (match.index === regex.lastIndex) {
regex.lastIndex++;
}
}
return chunks;
}, []);
};
// Allow the findChunks to be overridden in findAll,
// but for backwards compatibility we export as the old name
exports.findChunks = defaultFindChunks;
/**
* Given a set of chunks to highlight, create an additional set of chunks
* to represent the bits of text between the highlighted text.
* @param chunksToHighlight {start:number, end:number}[]
* @param totalLength number
* @return {start:number, end:number, highlight:boolean}[]
*/
var fillInChunks = exports.fillInChunks = function fillInChunks(_ref4) {
var chunksToHighlight = _ref4.chunksToHighlight,
totalLength = _ref4.totalLength;
var allChunks = [];
var append = function append(start, end, highlight) {
if (end - start > 0) {
allChunks.push({
start: start,
end: end,
highlight: highlight
});
}
};
if (chunksToHighlight.length === 0) {
append(0, totalLength, false);
} else {
var lastIndex = 0;
chunksToHighlight.forEach(function (chunk) {
append(lastIndex, chunk.start, false);
append(chunk.start, chunk.end, true);
lastIndex = chunk.end;
});
append(lastIndex, totalLength, false);
}
return allChunks;
};
function defaultSanitize(string) {
return string;
}
function escapeRegExpFn(string) {
return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/***/ })
/******/ ]);
/***/ }),
/***/ 1281:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var reactIs = __webpack_require__(338);
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
/***/ }),
/***/ 5372:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = __webpack_require__(9567);
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/***/ 2652:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (false) { var throwOnDirectAccess, ReactIs; } else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(5372)();
}
/***/ }),
/***/ 9567:
/***/ (function(module) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/***/ 4821:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;
exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};
exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;
/***/ }),
/***/ 338:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
module.exports = __webpack_require__(4821);
} else {}
/***/ }),
/***/ 2455:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var f=__webpack_require__(9196),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};
function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}__webpack_unused_export__=l;exports.jsx=q;__webpack_unused_export__=q;
/***/ }),
/***/ 7557:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
module.exports = __webpack_require__(2455);
} else {}
/***/ }),
/***/ 4793:
/***/ (function(module) {
var characterMap = {
"À": "A",
"Á": "A",
"Â": "A",
"Ã": "A",
"Ä": "A",
"Å": "A",
"Ấ": "A",
"Ắ": "A",
"Ẳ": "A",
"Ẵ": "A",
"Ặ": "A",
"Æ": "AE",
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
"É": "E",
"Ê": "E",
"Ë": "E",
"Ế": "E",
"Ḗ": "E",
"Ề": "E",
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
"Ó": "O",
"Ô": "O",
"Õ": "O",
"Ö": "O",
"Ø": "O",
"Ố": "O",
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ý": "Y",
"à": "a",
"á": "a",
"â": "a",
"ã": "a",
"ä": "a",
"å": "a",
"ấ": "a",
"ắ": "a",
"ẳ": "a",
"ẵ": "a",
"ặ": "a",
"æ": "ae",
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
"é": "e",
"ê": "e",
"ë": "e",
"ế": "e",
"ḗ": "e",
"ề": "e",
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
"ó": "o",
"ô": "o",
"õ": "o",
"ö": "o",
"ø": "o",
"ố": "o",
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
"ā": "a",
"Ă": "A",
"ă": "a",
"Ą": "A",
"ą": "a",
"Ć": "C",
"ć": "c",
"Ĉ": "C",
"ĉ": "c",
"Ċ": "C",
"ċ": "c",
"Č": "C",
"č": "c",
"C̆": "C",
"c̆": "c",
"Ď": "D",
"ď": "d",
"Đ": "D",
"đ": "d",
"Ē": "E",
"ē": "e",
"Ĕ": "E",
"ĕ": "e",
"Ė": "E",
"ė": "e",
"Ę": "E",
"ę": "e",
"Ě": "E",
"ě": "e",
"Ĝ": "G",
"Ǵ": "G",
"ĝ": "g",
"ǵ": "g",
"Ğ": "G",
"ğ": "g",
"Ġ": "G",
"ġ": "g",
"Ģ": "G",
"ģ": "g",
"Ĥ": "H",
"ĥ": "h",
"Ħ": "H",
"ħ": "h",
"Ḫ": "H",
"ḫ": "h",
"Ĩ": "I",
"ĩ": "i",
"Ī": "I",
"ī": "i",
"Ĭ": "I",
"ĭ": "i",
"Į": "I",
"į": "i",
"İ": "I",
"ı": "i",
"IJ": "IJ",
"ij": "ij",
"Ĵ": "J",
"ĵ": "j",
"Ķ": "K",
"ķ": "k",
"Ḱ": "K",
"ḱ": "k",
"K̆": "K",
"k̆": "k",
"Ĺ": "L",
"ĺ": "l",
"Ļ": "L",
"ļ": "l",
"Ľ": "L",
"ľ": "l",
"Ŀ": "L",
"ŀ": "l",
"Ł": "l",
"ł": "l",
"Ḿ": "M",
"ḿ": "m",
"M̆": "M",
"m̆": "m",
"Ń": "N",
"ń": "n",
"Ņ": "N",
"ņ": "n",
"Ň": "N",
"ň": "n",
"ʼn": "n",
"N̆": "N",
"n̆": "n",
"Ō": "O",
"ō": "o",
"Ŏ": "O",
"ŏ": "o",
"Ő": "O",
"ő": "o",
"Œ": "OE",
"œ": "oe",
"P̆": "P",
"p̆": "p",
"Ŕ": "R",
"ŕ": "r",
"Ŗ": "R",
"ŗ": "r",
"Ř": "R",
"ř": "r",
"R̆": "R",
"r̆": "r",
"Ȓ": "R",
"ȓ": "r",
"Ś": "S",
"ś": "s",
"Ŝ": "S",
"ŝ": "s",
"Ş": "S",
"Ș": "S",
"ș": "s",
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
"Ț": "T",
"Ť": "T",
"ť": "t",
"Ŧ": "T",
"ŧ": "t",
"T̆": "T",
"t̆": "t",
"Ũ": "U",
"ũ": "u",
"Ū": "U",
"ū": "u",
"Ŭ": "U",
"ŭ": "u",
"Ů": "U",
"ů": "u",
"Ű": "U",
"ű": "u",
"Ų": "U",
"ų": "u",
"Ȗ": "U",
"ȗ": "u",
"V̆": "V",
"v̆": "v",
"Ŵ": "W",
"ŵ": "w",
"Ẃ": "W",
"ẃ": "w",
"X̆": "X",
"x̆": "x",
"Ŷ": "Y",
"ŷ": "y",
"Ÿ": "Y",
"Y̆": "Y",
"y̆": "y",
"Ź": "Z",
"ź": "z",
"Ż": "Z",
"ż": "z",
"Ž": "Z",
"ž": "z",
"ſ": "s",
"ƒ": "f",
"Ơ": "O",
"ơ": "o",
"Ư": "U",
"ư": "u",
"Ǎ": "A",
"ǎ": "a",
"Ǐ": "I",
"ǐ": "i",
"Ǒ": "O",
"ǒ": "o",
"Ǔ": "U",
"ǔ": "u",
"Ǖ": "U",
"ǖ": "u",
"Ǘ": "U",
"ǘ": "u",
"Ǚ": "U",
"ǚ": "u",
"Ǜ": "U",
"ǜ": "u",
"Ứ": "U",
"ứ": "u",
"Ṹ": "U",
"ṹ": "u",
"Ǻ": "A",
"ǻ": "a",
"Ǽ": "AE",
"ǽ": "ae",
"Ǿ": "O",
"ǿ": "o",
"Þ": "TH",
"þ": "th",
"Ṕ": "P",
"ṕ": "p",
"Ṥ": "S",
"ṥ": "s",
"X́": "X",
"x́": "x",
"Ѓ": "Г",
"ѓ": "г",
"Ќ": "К",
"ќ": "к",
"A̋": "A",
"a̋": "a",
"E̋": "E",
"e̋": "e",
"I̋": "I",
"i̋": "i",
"Ǹ": "N",
"ǹ": "n",
"Ồ": "O",
"ồ": "o",
"Ṑ": "O",
"ṑ": "o",
"Ừ": "U",
"ừ": "u",
"Ẁ": "W",
"ẁ": "w",
"Ỳ": "Y",
"ỳ": "y",
"Ȁ": "A",
"ȁ": "a",
"Ȅ": "E",
"ȅ": "e",
"Ȉ": "I",
"ȉ": "i",
"Ȍ": "O",
"ȍ": "o",
"Ȑ": "R",
"ȑ": "r",
"Ȕ": "U",
"ȕ": "u",
"B̌": "B",
"b̌": "b",
"Č̣": "C",
"č̣": "c",
"Ê̌": "E",
"ê̌": "e",
"F̌": "F",
"f̌": "f",
"Ǧ": "G",
"ǧ": "g",
"Ȟ": "H",
"ȟ": "h",
"J̌": "J",
"ǰ": "j",
"Ǩ": "K",
"ǩ": "k",
"M̌": "M",
"m̌": "m",
"P̌": "P",
"p̌": "p",
"Q̌": "Q",
"q̌": "q",
"Ř̩": "R",
"ř̩": "r",
"Ṧ": "S",
"ṧ": "s",
"V̌": "V",
"v̌": "v",
"W̌": "W",
"w̌": "w",
"X̌": "X",
"x̌": "x",
"Y̌": "Y",
"y̌": "y",
"A̧": "A",
"a̧": "a",
"B̧": "B",
"b̧": "b",
"Ḑ": "D",
"ḑ": "d",
"Ȩ": "E",
"ȩ": "e",
"Ɛ̧": "E",
"ɛ̧": "e",
"Ḩ": "H",
"ḩ": "h",
"I̧": "I",
"i̧": "i",
"Ɨ̧": "I",
"ɨ̧": "i",
"M̧": "M",
"m̧": "m",
"O̧": "O",
"o̧": "o",
"Q̧": "Q",
"q̧": "q",
"U̧": "U",
"u̧": "u",
"X̧": "X",
"x̧": "x",
"Z̧": "Z",
"z̧": "z",
"й":"и",
"Й":"И",
"ё":"е",
"Ё":"Е",
};
var chars = Object.keys(characterMap).join('|');
var allAccents = new RegExp(chars, 'g');
var firstAccent = new RegExp(chars, '');
function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents;
module.exports.has = hasAccents;
module.exports.remove = removeAccents;
/***/ }),
/***/ 7755:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/**
* @license React
* use-sync-external-store-shim.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var e=__webpack_require__(9196);function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k="function"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}
function r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;
/***/ }),
/***/ 635:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
module.exports = __webpack_require__(7755);
} else {}
/***/ }),
/***/ 9196:
/***/ (function(module) {
"use strict";
module.exports = window["React"];
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/create fake namespace object */
/******/ !function() {
/******/ var getProto = Object.getPrototypeOf ? function(obj) { return Object.getPrototypeOf(obj); } : function(obj) { return obj.__proto__; };
/******/ var leafPrototypes;
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 16: return value when it's Promise-like
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = this(value);
/******/ if(mode & 8) return value;
/******/ if(typeof value === 'object' && value) {
/******/ if((mode & 4) && value.__esModule) return value;
/******/ if((mode & 16) && typeof value.then === 'function') return value;
/******/ }
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ var def = {};
/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
/******/ Object.getOwnPropertyNames(current).forEach(function(key) { def[key] = function() { return value[key]; }; });
/******/ }
/******/ def['default'] = function() { return value; };
/******/ __webpack_require__.d(ns, def);
/******/ return ns;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/nonce */
/******/ !function() {
/******/ __webpack_require__.nc = undefined;
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"AnglePickerControl": function() { return /* reexport */ angle_picker_control; },
"Animate": function() { return /* reexport */ animate; },
"Autocomplete": function() { return /* reexport */ Autocomplete; },
"BaseControl": function() { return /* reexport */ base_control; },
"BlockQuotation": function() { return /* reexport */ external_wp_primitives_namespaceObject.BlockQuotation; },
"Button": function() { return /* reexport */ build_module_button; },
"ButtonGroup": function() { return /* reexport */ button_group; },
"Card": function() { return /* reexport */ card_component; },
"CardBody": function() { return /* reexport */ card_body_component; },
"CardDivider": function() { return /* reexport */ card_divider_component; },
"CardFooter": function() { return /* reexport */ card_footer_component; },
"CardHeader": function() { return /* reexport */ card_header_component; },
"CardMedia": function() { return /* reexport */ card_media_component; },
"CheckboxControl": function() { return /* reexport */ checkbox_control; },
"Circle": function() { return /* reexport */ external_wp_primitives_namespaceObject.Circle; },
"ClipboardButton": function() { return /* reexport */ ClipboardButton; },
"ColorIndicator": function() { return /* reexport */ color_indicator; },
"ColorPalette": function() { return /* reexport */ color_palette; },
"ColorPicker": function() { return /* reexport */ LegacyAdapter; },
"ComboboxControl": function() { return /* reexport */ combobox_control; },
"CustomGradientPicker": function() { return /* reexport */ custom_gradient_picker; },
"CustomSelectControl": function() { return /* reexport */ StableCustomSelectControl; },
"Dashicon": function() { return /* reexport */ dashicon; },
"DatePicker": function() { return /* reexport */ date; },
"DateTimePicker": function() { return /* reexport */ build_module_date_time; },
"Disabled": function() { return /* reexport */ disabled; },
"Draggable": function() { return /* reexport */ draggable; },
"DropZone": function() { return /* reexport */ drop_zone; },
"DropZoneProvider": function() { return /* reexport */ DropZoneProvider; },
"Dropdown": function() { return /* reexport */ dropdown; },
"DropdownMenu": function() { return /* reexport */ dropdown_menu; },
"DuotonePicker": function() { return /* reexport */ duotone_picker; },
"DuotoneSwatch": function() { return /* reexport */ duotone_swatch; },
"ExternalLink": function() { return /* reexport */ external_link; },
"Fill": function() { return /* reexport */ slot_fill_Fill; },
"Flex": function() { return /* reexport */ flex_component; },
"FlexBlock": function() { return /* reexport */ flex_block_component; },
"FlexItem": function() { return /* reexport */ flex_item_component; },
"FocalPointPicker": function() { return /* reexport */ focal_point_picker; },
"FocusReturnProvider": function() { return /* reexport */ with_focus_return_Provider; },
"FocusableIframe": function() { return /* reexport */ FocusableIframe; },
"FontSizePicker": function() { return /* reexport */ font_size_picker; },
"FormFileUpload": function() { return /* reexport */ form_file_upload; },
"FormToggle": function() { return /* reexport */ form_toggle; },
"FormTokenField": function() { return /* reexport */ form_token_field; },
"G": function() { return /* reexport */ external_wp_primitives_namespaceObject.G; },
"GradientPicker": function() { return /* reexport */ gradient_picker; },
"Guide": function() { return /* reexport */ guide; },
"GuidePage": function() { return /* reexport */ GuidePage; },
"HorizontalRule": function() { return /* reexport */ external_wp_primitives_namespaceObject.HorizontalRule; },
"Icon": function() { return /* reexport */ build_module_icon; },
"IconButton": function() { return /* reexport */ deprecated; },
"IsolatedEventContainer": function() { return /* reexport */ isolated_event_container; },
"KeyboardShortcuts": function() { return /* reexport */ keyboard_shortcuts; },
"Line": function() { return /* reexport */ external_wp_primitives_namespaceObject.Line; },
"MenuGroup": function() { return /* reexport */ menu_group; },
"MenuItem": function() { return /* reexport */ menu_item; },
"MenuItemsChoice": function() { return /* reexport */ menu_items_choice; },
"Modal": function() { return /* reexport */ modal; },
"NavigableMenu": function() { return /* reexport */ navigable_container_menu; },
"Notice": function() { return /* reexport */ build_module_notice; },
"NoticeList": function() { return /* reexport */ list; },
"Panel": function() { return /* reexport */ panel; },
"PanelBody": function() { return /* reexport */ body; },
"PanelHeader": function() { return /* reexport */ panel_header; },
"PanelRow": function() { return /* reexport */ row; },
"Path": function() { return /* reexport */ external_wp_primitives_namespaceObject.Path; },
"Placeholder": function() { return /* reexport */ placeholder; },
"Polygon": function() { return /* reexport */ external_wp_primitives_namespaceObject.Polygon; },
"Popover": function() { return /* reexport */ popover; },
"QueryControls": function() { return /* reexport */ query_controls; },
"RadioControl": function() { return /* reexport */ radio_control; },
"RangeControl": function() { return /* reexport */ range_control; },
"Rect": function() { return /* reexport */ external_wp_primitives_namespaceObject.Rect; },
"ResizableBox": function() { return /* reexport */ resizable_box; },
"ResponsiveWrapper": function() { return /* reexport */ responsive_wrapper; },
"SVG": function() { return /* reexport */ external_wp_primitives_namespaceObject.SVG; },
"SandBox": function() { return /* reexport */ sandbox; },
"ScrollLock": function() { return /* reexport */ scroll_lock; },
"SearchControl": function() { return /* reexport */ search_control; },
"SelectControl": function() { return /* reexport */ select_control; },
"Slot": function() { return /* reexport */ slot_fill_Slot; },
"SlotFillProvider": function() { return /* reexport */ Provider; },
"Snackbar": function() { return /* reexport */ snackbar; },
"SnackbarList": function() { return /* reexport */ snackbar_list; },
"Spinner": function() { return /* reexport */ spinner; },
"TabPanel": function() { return /* reexport */ tab_panel; },
"TabbableContainer": function() { return /* reexport */ tabbable; },
"TextControl": function() { return /* reexport */ text_control; },
"TextHighlight": function() { return /* reexport */ text_highlight; },
"TextareaControl": function() { return /* reexport */ textarea_control; },
"TimePicker": function() { return /* reexport */ time; },
"Tip": function() { return /* reexport */ build_module_tip; },
"ToggleControl": function() { return /* reexport */ toggle_control; },
"Toolbar": function() { return /* reexport */ toolbar; },
"ToolbarButton": function() { return /* reexport */ toolbar_button; },
"ToolbarDropdownMenu": function() { return /* reexport */ toolbar_dropdown_menu; },
"ToolbarGroup": function() { return /* reexport */ toolbar_group; },
"ToolbarItem": function() { return /* reexport */ toolbar_item; },
"Tooltip": function() { return /* reexport */ tooltip; },
"TreeSelect": function() { return /* reexport */ tree_select; },
"VisuallyHidden": function() { return /* reexport */ visually_hidden_component; },
"__experimentalAlignmentMatrixControl": function() { return /* reexport */ alignment_matrix_control; },
"__experimentalApplyValueToSides": function() { return /* reexport */ applyValueToSides; },
"__experimentalBorderBoxControl": function() { return /* reexport */ border_box_control_component; },
"__experimentalBorderControl": function() { return /* reexport */ border_control_component; },
"__experimentalBoxControl": function() { return /* reexport */ box_control; },
"__experimentalConfirmDialog": function() { return /* reexport */ confirm_dialog_component; },
"__experimentalDimensionControl": function() { return /* reexport */ dimension_control; },
"__experimentalDivider": function() { return /* reexport */ divider_component; },
"__experimentalDropdownContentWrapper": function() { return /* reexport */ dropdown_content_wrapper; },
"__experimentalElevation": function() { return /* reexport */ elevation_component; },
"__experimentalGrid": function() { return /* reexport */ grid_component; },
"__experimentalHStack": function() { return /* reexport */ h_stack_component; },
"__experimentalHasSplitBorders": function() { return /* reexport */ hasSplitBorders; },
"__experimentalHeading": function() { return /* reexport */ heading_component; },
"__experimentalInputControl": function() { return /* reexport */ input_control; },
"__experimentalInputControlPrefixWrapper": function() { return /* reexport */ input_prefix_wrapper; },
"__experimentalInputControlSuffixWrapper": function() { return /* reexport */ input_suffix_wrapper; },
"__experimentalIsDefinedBorder": function() { return /* reexport */ isDefinedBorder; },
"__experimentalIsEmptyBorder": function() { return /* reexport */ isEmptyBorder; },
"__experimentalItem": function() { return /* reexport */ item_component; },
"__experimentalItemGroup": function() { return /* reexport */ item_group_component; },
"__experimentalNavigation": function() { return /* reexport */ navigation; },
"__experimentalNavigationBackButton": function() { return /* reexport */ back_button; },
"__experimentalNavigationGroup": function() { return /* reexport */ group; },
"__experimentalNavigationItem": function() { return /* reexport */ navigation_item; },
"__experimentalNavigationMenu": function() { return /* reexport */ navigation_menu; },
"__experimentalNavigatorBackButton": function() { return /* reexport */ navigator_back_button_component; },
"__experimentalNavigatorButton": function() { return /* reexport */ navigator_button_component; },
"__experimentalNavigatorProvider": function() { return /* reexport */ navigator_provider_component; },
"__experimentalNavigatorScreen": function() { return /* reexport */ navigator_screen_component; },
"__experimentalNavigatorToParentButton": function() { return /* reexport */ navigator_to_parent_button_component; },
"__experimentalNumberControl": function() { return /* reexport */ number_control; },
"__experimentalPaletteEdit": function() { return /* reexport */ palette_edit; },
"__experimentalParseQuantityAndUnitFromRawValue": function() { return /* reexport */ parseQuantityAndUnitFromRawValue; },
"__experimentalRadio": function() { return /* reexport */ radio_group_radio; },
"__experimentalRadioGroup": function() { return /* reexport */ radio_group; },
"__experimentalScrollable": function() { return /* reexport */ scrollable_component; },
"__experimentalSpacer": function() { return /* reexport */ spacer_component; },
"__experimentalStyleProvider": function() { return /* reexport */ style_provider; },
"__experimentalSurface": function() { return /* reexport */ surface_component; },
"__experimentalText": function() { return /* reexport */ text_component; },
"__experimentalToggleGroupControl": function() { return /* reexport */ toggle_group_control_component; },
"__experimentalToggleGroupControlOption": function() { return /* reexport */ toggle_group_control_option_component; },
"__experimentalToggleGroupControlOptionIcon": function() { return /* reexport */ toggle_group_control_option_icon_component; },
"__experimentalToolbarContext": function() { return /* reexport */ toolbar_context; },
"__experimentalToolsPanel": function() { return /* reexport */ tools_panel_component; },
"__experimentalToolsPanelContext": function() { return /* reexport */ ToolsPanelContext; },
"__experimentalToolsPanelItem": function() { return /* reexport */ tools_panel_item_component; },
"__experimentalTreeGrid": function() { return /* reexport */ tree_grid; },
"__experimentalTreeGridCell": function() { return /* reexport */ cell; },
"__experimentalTreeGridItem": function() { return /* reexport */ tree_grid_item; },
"__experimentalTreeGridRow": function() { return /* reexport */ tree_grid_row; },
"__experimentalTruncate": function() { return /* reexport */ truncate_component; },
"__experimentalUnitControl": function() { return /* reexport */ unit_control; },
"__experimentalUseCustomUnits": function() { return /* reexport */ useCustomUnits; },
"__experimentalUseNavigator": function() { return /* reexport */ use_navigator; },
"__experimentalUseSlot": function() { return /* reexport */ useSlot; },
"__experimentalUseSlotFills": function() { return /* reexport */ useSlotFills; },
"__experimentalVStack": function() { return /* reexport */ v_stack_component; },
"__experimentalView": function() { return /* reexport */ component; },
"__experimentalZStack": function() { return /* reexport */ z_stack_component; },
"__unstableAnimatePresence": function() { return /* reexport */ AnimatePresence; },
"__unstableComposite": function() { return /* reexport */ Composite; },
"__unstableCompositeGroup": function() { return /* reexport */ CompositeGroup; },
"__unstableCompositeItem": function() { return /* reexport */ CompositeItem; },
"__unstableDisclosureContent": function() { return /* reexport */ DisclosureContent; },
"__unstableGetAnimateClassName": function() { return /* reexport */ getAnimateClassName; },
"__unstableMotion": function() { return /* reexport */ motion; },
"__unstableUseAutocompleteProps": function() { return /* reexport */ useAutocompleteProps; },
"__unstableUseCompositeState": function() { return /* reexport */ useCompositeState; },
"__unstableUseNavigateRegions": function() { return /* reexport */ useNavigateRegions; },
"createSlotFill": function() { return /* reexport */ createSlotFill; },
"navigateRegions": function() { return /* reexport */ navigate_regions; },
"privateApis": function() { return /* reexport */ privateApis; },
"useBaseControlProps": function() { return /* reexport */ useBaseControlProps; },
"withConstrainedTabbing": function() { return /* reexport */ with_constrained_tabbing; },
"withFallbackStyles": function() { return /* reexport */ with_fallback_styles; },
"withFilters": function() { return /* reexport */ withFilters; },
"withFocusOutside": function() { return /* reexport */ with_focus_outside; },
"withFocusReturn": function() { return /* reexport */ with_focus_return; },
"withNotices": function() { return /* reexport */ with_notices; },
"withSpokenMessages": function() { return /* reexport */ with_spoken_messages; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/components/build-module/text/styles.js
var text_styles_namespaceObject = {};
__webpack_require__.r(text_styles_namespaceObject);
__webpack_require__.d(text_styles_namespaceObject, {
"Text": function() { return Text; },
"block": function() { return styles_block; },
"destructive": function() { return destructive; },
"highlighterText": function() { return highlighterText; },
"muted": function() { return muted; },
"positive": function() { return positive; },
"upperCase": function() { return upperCase; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/components/build-module/ui/tooltip/styles.js
var tooltip_styles_namespaceObject = {};
__webpack_require__.r(tooltip_styles_namespaceObject);
__webpack_require__.d(tooltip_styles_namespaceObject, {
"TooltipContent": function() { return TooltipContent; },
"TooltipPopoverView": function() { return TooltipPopoverView; },
"TooltipShortcut": function() { return TooltipShortcut; },
"noOutline": function() { return noOutline; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-base/styles.js
var toggle_group_control_option_base_styles_namespaceObject = {};
__webpack_require__.r(toggle_group_control_option_base_styles_namespaceObject);
__webpack_require__.d(toggle_group_control_option_base_styles_namespaceObject, {
"ButtonContentView": function() { return ButtonContentView; },
"LabelView": function() { return LabelView; },
"buttonView": function() { return buttonView; },
"labelBlock": function() { return labelBlock; }
});
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(4403);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/reakit/es/_rollupPluginBabelHelpers-1f0bf8c2.js
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
// EXTERNAL MODULE: external "React"
var external_React_ = __webpack_require__(9196);
var external_React_namespaceObject = /*#__PURE__*/__webpack_require__.t(external_React_, 2);
var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_);
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/_rollupPluginBabelHelpers-0c84a174.js
function _rollupPluginBabelHelpers_0c84a174_defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _rollupPluginBabelHelpers_0c84a174_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _rollupPluginBabelHelpers_0c84a174_objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
_rollupPluginBabelHelpers_0c84a174_ownKeys(Object(source), true).forEach(function (key) {
_rollupPluginBabelHelpers_0c84a174_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
_rollupPluginBabelHelpers_0c84a174_ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _rollupPluginBabelHelpers_0c84a174_unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _rollupPluginBabelHelpers_0c84a174_arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _rollupPluginBabelHelpers_0c84a174_arrayLikeToArray(o, minLen);
}
function _rollupPluginBabelHelpers_0c84a174_arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _rollupPluginBabelHelpers_0c84a174_createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _rollupPluginBabelHelpers_0c84a174_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/SystemContext.js
var SystemContext = /*#__PURE__*/(0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useCreateElement.js
function isRenderProp(children) {
return typeof children === "function";
}
/**
* Custom hook that will call `children` if it's a function. If
* `useCreateElement` has been passed to the context, it'll be used instead.
*
* @example
* import React from "react";
* import { SystemProvider, useCreateElement } from "reakit-system";
*
* const system = {
* useCreateElement(type, props, children = props.children) {
* // very similar to what `useCreateElement` does already
* if (typeof children === "function") {
* const { children: _, ...rest } = props;
* return children(rest);
* }
* return React.createElement(type, props, children);
* },
* };
*
* function Component(props) {
* return useCreateElement("div", props);
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <Component url="url">{({ url }) => <a href={url}>link</a>}</Component>
* </SystemProvider>
* );
* }
*/
var useCreateElement = function useCreateElement(type, props, children) {
if (children === void 0) {
children = props.children;
}
var context = (0,external_React_.useContext)(SystemContext);
if (context.useCreateElement) {
return context.useCreateElement(type, props, children);
}
if (typeof type === "string" && isRenderProp(children)) {
var _ = props.children,
rest = _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(props, ["children"]);
return children(rest);
}
return /*#__PURE__*/(0,external_React_.createElement)(type, props, children);
};
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/_rollupPluginBabelHelpers-1f0bf8c2.js
function _rollupPluginBabelHelpers_1f0bf8c2_defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _rollupPluginBabelHelpers_1f0bf8c2_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
_rollupPluginBabelHelpers_1f0bf8c2_ownKeys(Object(source), true).forEach(function (key) {
_rollupPluginBabelHelpers_1f0bf8c2_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
_rollupPluginBabelHelpers_1f0bf8c2_ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _rollupPluginBabelHelpers_1f0bf8c2_objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _rollupPluginBabelHelpers_1f0bf8c2_unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _rollupPluginBabelHelpers_1f0bf8c2_arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _rollupPluginBabelHelpers_1f0bf8c2_arrayLikeToArray(o, minLen);
}
function _rollupPluginBabelHelpers_1f0bf8c2_arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _rollupPluginBabelHelpers_1f0bf8c2_createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _rollupPluginBabelHelpers_1f0bf8c2_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isObject.js
/**
* Checks whether `arg` is an object or not.
*
* @returns {boolean}
*/
function isObject_isObject(arg) {
return typeof arg === "object" && arg != null;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isPlainObject.js
/**
* Checks whether `arg` is a plain object or not.
*
* @returns {boolean}
*/
function isPlainObject(arg) {
var _proto$constructor;
if (!isObject_isObject(arg)) return false;
var proto = Object.getPrototypeOf(arg);
if (proto == null) return true;
return ((_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.toString()) === Object.toString();
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/splitProps.js
/**
* Splits an object (`props`) into a tuple where the first item is an object
* with the passed `keys`, and the second item is an object with these keys
* omitted.
*
* @deprecated will be removed in version 2
*
* @example
* import { splitProps } from "reakit-utils";
*
* splitProps({ a: "a", b: "b" }, ["a"]); // [{ a: "a" }, { b: "b" }]
*/
function __deprecatedSplitProps(props, keys) {
var propsKeys = Object.keys(props);
var picked = {};
var omitted = {};
for (var _i = 0, _propsKeys = propsKeys; _i < _propsKeys.length; _i++) {
var key = _propsKeys[_i];
if (keys.indexOf(key) >= 0) {
picked[key] = props[key];
} else {
omitted[key] = props[key];
}
}
return [picked, omitted];
}
/**
* Splits an object (`props`) into a tuple where the first item
* is the `state` property, and the second item is the rest of the properties.
*
* It is also backward compatible with version 1. If `keys` are passed then
* splits an object (`props`) into a tuple where the first item is an object
* with the passed `keys`, and the second item is an object with these keys
* omitted.
*
* @example
* import { splitProps } from "reakit-utils";
*
* splitProps({ a: "a", b: "b" }, ["a"]); // [{ a: "a" }, { b: "b" }]
*
* @example
* import { splitProps } from "reakit-utils";
*
* splitProps({ state: { a: "a" }, b: "b" }); // [{ a: "a" }, { b: "b" }]
*/
function splitProps(props, keys) {
if (keys === void 0) {
keys = [];
}
if (!isPlainObject(props.state)) {
return __deprecatedSplitProps(props, keys);
}
var _deprecatedSplitProp = __deprecatedSplitProps(props, [].concat(keys, ["state"])),
picked = _deprecatedSplitProp[0],
omitted = _deprecatedSplitProp[1];
var state = picked.state,
restPicked = _rollupPluginBabelHelpers_1f0bf8c2_objectWithoutPropertiesLoose(picked, ["state"]);
return [_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, state), restPicked), omitted];
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/shallowEqual.js
/**
* Compares two objects.
*
* @example
* import { shallowEqual } from "reakit-utils";
*
* shallowEqual({ a: "a" }, {}); // false
* shallowEqual({ a: "a" }, { b: "b" }); // false
* shallowEqual({ a: "a" }, { a: "a" }); // true
* shallowEqual({ a: "a" }, { a: "a", b: "b" }); // false
*/
function shallowEqual(objA, objB) {
if (objA === objB) return true;
if (!objA) return false;
if (!objB) return false;
if (typeof objA !== "object") return false;
if (typeof objB !== "object") return false;
var aKeys = Object.keys(objA);
var bKeys = Object.keys(objB);
var length = aKeys.length;
if (bKeys.length !== length) return false;
for (var _i = 0, _aKeys = aKeys; _i < _aKeys.length; _i++) {
var key = _aKeys[_i];
if (objA[key] !== objB[key]) {
return false;
}
}
return true;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/normalizePropsAreEqual.js
/**
* This higher order functions take `propsAreEqual` function and
* returns a new function which normalizes the props.
*
* Normalizing in our case is making sure the `propsAreEqual` works with
* both version 1 (object spreading) and version 2 (state object) state passing.
*
* To achieve this, the returned function in case of a state object
* will spread the state object in both `prev` and `next props.
*
* Other case it just returns the function as is which makes sure
* that we are still backward compatible
*/
function normalizePropsAreEqual(propsAreEqual) {
if (propsAreEqual.name === "normalizePropsAreEqualInner") {
return propsAreEqual;
}
return function normalizePropsAreEqualInner(prev, next) {
if (!isPlainObject(prev.state) || !isPlainObject(next.state)) {
return propsAreEqual(prev, next);
}
return propsAreEqual(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, prev.state), prev), _rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, next.state), next));
};
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/createComponent.js
function forwardRef(component) {
return /*#__PURE__*/(0,external_React_.forwardRef)(component);
}
function memo(component, propsAreEqual) {
return /*#__PURE__*/(0,external_React_.memo)(component, propsAreEqual);
}
/**
* Creates a React component.
*
* @example
* import { createComponent } from "reakit-system";
*
* const A = createComponent({ as: "a" });
*
* @param options
*/
function createComponent(_ref) {
var type = _ref.as,
useHook = _ref.useHook,
shouldMemo = _ref.memo,
_ref$propsAreEqual = _ref.propsAreEqual,
propsAreEqual = _ref$propsAreEqual === void 0 ? useHook === null || useHook === void 0 ? void 0 : useHook.unstable_propsAreEqual : _ref$propsAreEqual,
_ref$keys = _ref.keys,
keys = _ref$keys === void 0 ? (useHook === null || useHook === void 0 ? void 0 : useHook.__keys) || [] : _ref$keys,
_ref$useCreateElement = _ref.useCreateElement,
useCreateElement$1 = _ref$useCreateElement === void 0 ? useCreateElement : _ref$useCreateElement;
var Comp = function Comp(_ref2, ref) {
var _ref2$as = _ref2.as,
as = _ref2$as === void 0 ? type : _ref2$as,
props = _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(_ref2, ["as"]);
if (useHook) {
var _as$render;
var _splitProps = splitProps(props, keys),
_options = _splitProps[0],
htmlProps = _splitProps[1];
var _useHook = useHook(_options, _rollupPluginBabelHelpers_0c84a174_objectSpread2({
ref: ref
}, htmlProps)),
wrapElement = _useHook.wrapElement,
elementProps = _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(_useHook, ["wrapElement"]); // @ts-ignore
var asKeys = ((_as$render = as.render) === null || _as$render === void 0 ? void 0 : _as$render.__keys) || as.__keys;
var asOptions = asKeys && splitProps(props, asKeys)[0];
var allProps = asOptions ? _rollupPluginBabelHelpers_0c84a174_objectSpread2(_rollupPluginBabelHelpers_0c84a174_objectSpread2({}, elementProps), asOptions) : elementProps;
var _element = useCreateElement$1(as, allProps);
if (wrapElement) {
return wrapElement(_element);
}
return _element;
}
return useCreateElement$1(as, _rollupPluginBabelHelpers_0c84a174_objectSpread2({
ref: ref
}, props));
};
if (false) {}
Comp = forwardRef(Comp);
if (shouldMemo) {
Comp = memo(Comp, propsAreEqual && normalizePropsAreEqual(propsAreEqual));
}
Comp.__keys = keys;
Comp.unstable_propsAreEqual = normalizePropsAreEqual(propsAreEqual || shallowEqual);
return Comp;
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useToken.js
/**
* React custom hook that returns the value of any token defined in the
* SystemContext. It's mainly used internally in [`useOptions`](#useoptions)
* and [`useProps`](#useprops).
*
* @example
* import { SystemProvider, useToken } from "reakit-system";
*
* const system = {
* token: "value",
* };
*
* function Component(props) {
* const token = useToken("token", "default value");
* return <div {...props}>{token}</div>;
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <Component />
* </SystemProvider>
* );
* }
*/
function useToken(token, defaultValue) {
(0,external_React_.useDebugValue)(token);
var context = (0,external_React_.useContext)(SystemContext);
return context[token] != null ? context[token] : defaultValue;
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useProps.js
/**
* React custom hook that returns the props returned by a given
* `use${name}Props` in the SystemContext.
*
* @example
* import { SystemProvider, useProps } from "reakit-system";
*
* const system = {
* useAProps(options, htmlProps) {
* return {
* ...htmlProps,
* href: options.url,
* };
* },
* };
*
* function A({ url, ...htmlProps }) {
* const props = useProps("A", { url }, htmlProps);
* return <a {...props} />;
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <A url="url">It will convert url into href in useAProps</A>
* </SystemProvider>
* );
* }
*/
function useProps(name, options, htmlProps) {
if (options === void 0) {
options = {};
}
if (htmlProps === void 0) {
htmlProps = {};
}
var hookName = "use" + name + "Props";
(0,external_React_.useDebugValue)(hookName);
var useHook = useToken(hookName);
if (useHook) {
return useHook(options, htmlProps);
}
return htmlProps;
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useOptions.js
/**
* React custom hook that returns the options returned by a given
* `use${name}Options` in the SystemContext.
*
* @example
* import React from "react";
* import { SystemProvider, useOptions } from "reakit-system";
*
* const system = {
* useAOptions(options, htmlProps) {
* return {
* ...options,
* url: htmlProps.href,
* };
* },
* };
*
* function A({ url, ...htmlProps }) {
* const options = useOptions("A", { url }, htmlProps);
* return <a href={options.url} {...htmlProps} />;
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <A href="url">
* It will convert href into url in useAOptions and then url into href in A
* </A>
* </SystemProvider>
* );
* }
*/
function useOptions(name, options, htmlProps) {
if (options === void 0) {
options = {};
}
if (htmlProps === void 0) {
htmlProps = {};
}
var hookName = "use" + name + "Options";
(0,external_React_.useDebugValue)(hookName);
var useHook = useToken(hookName);
if (useHook) {
return _rollupPluginBabelHelpers_0c84a174_objectSpread2(_rollupPluginBabelHelpers_0c84a174_objectSpread2({}, options), useHook(options, htmlProps));
}
return options;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/toArray.js
/**
* Transforms `arg` into an array if it's not already.
*
* @example
* import { toArray } from "reakit-utils";
*
* toArray("a"); // ["a"]
* toArray(["a"]); // ["a"]
*/
function toArray(arg) {
if (Array.isArray(arg)) {
return arg;
}
return typeof arg !== "undefined" ? [arg] : [];
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/createHook.js
/**
* Creates a React custom hook that will return component props.
*
* @example
* import { createHook } from "reakit-system";
*
* const useA = createHook({
* name: "A",
* keys: ["url"], // custom props/options keys
* useProps(options, htmlProps) {
* return {
* ...htmlProps,
* href: options.url,
* };
* },
* });
*
* function A({ url, ...htmlProps }) {
* const props = useA({ url }, htmlProps);
* return <a {...props} />;
* }
*
* @param options
*/
function createHook(options) {
var _options$useState, _composedHooks$;
var composedHooks = toArray(options.compose);
var __useOptions = function __useOptions(hookOptions, htmlProps) {
// Call the current hook's useOptions first
if (options.useOptions) {
hookOptions = options.useOptions(hookOptions, htmlProps);
} // If there's name, call useOptions from the system context
if (options.name) {
hookOptions = useOptions(options.name, hookOptions, htmlProps);
} // Run composed hooks useOptions
if (options.compose) {
for (var _iterator = _rollupPluginBabelHelpers_0c84a174_createForOfIteratorHelperLoose(composedHooks), _step; !(_step = _iterator()).done;) {
var hook = _step.value;
hookOptions = hook.__useOptions(hookOptions, htmlProps);
}
}
return hookOptions;
};
var useHook = function useHook(hookOptions, htmlProps, unstable_ignoreUseOptions) {
if (hookOptions === void 0) {
hookOptions = {};
}
if (htmlProps === void 0) {
htmlProps = {};
}
if (unstable_ignoreUseOptions === void 0) {
unstable_ignoreUseOptions = false;
}
// This won't execute when useHook was called from within another useHook
if (!unstable_ignoreUseOptions) {
hookOptions = __useOptions(hookOptions, htmlProps);
} // Call the current hook's useProps
if (options.useProps) {
htmlProps = options.useProps(hookOptions, htmlProps);
} // If there's name, call useProps from the system context
if (options.name) {
htmlProps = useProps(options.name, hookOptions, htmlProps);
}
if (options.compose) {
if (options.useComposeOptions) {
hookOptions = options.useComposeOptions(hookOptions, htmlProps);
}
if (options.useComposeProps) {
htmlProps = options.useComposeProps(hookOptions, htmlProps);
} else {
for (var _iterator2 = _rollupPluginBabelHelpers_0c84a174_createForOfIteratorHelperLoose(composedHooks), _step2; !(_step2 = _iterator2()).done;) {
var hook = _step2.value;
htmlProps = hook(hookOptions, htmlProps, true);
}
}
} // Remove undefined values from htmlProps
var finalHTMLProps = {};
var definedHTMLProps = htmlProps || {};
for (var prop in definedHTMLProps) {
if (definedHTMLProps[prop] !== undefined) {
finalHTMLProps[prop] = definedHTMLProps[prop];
}
}
return finalHTMLProps;
};
useHook.__useOptions = __useOptions;
var composedKeys = composedHooks.reduce(function (keys, hook) {
keys.push.apply(keys, hook.__keys || []);
return keys;
}, []); // It's used by createComponent to split option props (keys) and html props
useHook.__keys = [].concat(composedKeys, ((_options$useState = options.useState) === null || _options$useState === void 0 ? void 0 : _options$useState.__keys) || [], options.keys || []);
useHook.unstable_propsAreEqual = options.propsAreEqual || ((_composedHooks$ = composedHooks[0]) === null || _composedHooks$ === void 0 ? void 0 : _composedHooks$.unstable_propsAreEqual) || shallowEqual;
if (false) {}
return useHook;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useForkRef.js
// https://github.com/mui-org/material-ui/blob/2bcc874cf07b81202968f769cb9c2398c7c11311/packages/material-ui/src/utils/useForkRef.js
function setRef(ref, value) {
if (value === void 0) {
value = null;
}
if (!ref) return;
if (typeof ref === "function") {
ref(value);
} else {
ref.current = value;
}
}
/**
* Merges up to two React Refs into a single memoized function React Ref so you
* can pass it to an element.
*
* @example
* import React from "react";
* import { useForkRef } from "reakit-utils";
*
* const Component = React.forwardRef((props, ref) => {
* const internalRef = React.useRef();
* return <div {...props} ref={useForkRef(internalRef, ref)} />;
* });
*/
function useForkRef(refA, refB) {
return (0,external_React_.useMemo)(function () {
if (refA == null && refB == null) {
return null;
}
return function (value) {
setRef(refA, value);
setRef(refB, value);
};
}, [refA, refB]);
}
;// CONCATENATED MODULE: ./node_modules/reakit-warning/es/useWarning.js
function isRefObject(ref) {
return isObject(ref) && "current" in ref;
}
/**
* Logs `messages` to the console using `console.warn` based on a `condition`.
* This should be used inside components.
*/
function useWarning(condition) {
for (var _len = arguments.length, messages = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
messages[_key - 1] = arguments[_key];
}
if (false) {}
}
;// CONCATENATED MODULE: ./node_modules/reakit-warning/es/index.js
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getDocument.js
/**
* Returns `element.ownerDocument || document`.
*/
function getDocument_getDocument(element) {
return element ? element.ownerDocument || element : document;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getWindow.js
// Thanks to Fluent UI for doing the [research on IE11 memory leak](https://github.com/microsoft/fluentui/pull/9010#issuecomment-490768427)
var _window; // Note: Accessing "window" in IE11 is somewhat expensive, and calling "typeof window"
// hits a memory leak, whereas aliasing it and calling "typeof _window" does not.
// Caching the window value at the file scope lets us minimize the impact.
try {
_window = window;
} catch (e) {
/* no-op */
}
/**
* Returns `element.ownerDocument.defaultView || window`.
*/
function getWindow(element) {
if (!element) {
return _window;
}
return getDocument_getDocument(element).defaultView || _window;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/canUseDOM.js
function checkIsBrowser() {
var _window = getWindow();
return Boolean(typeof _window !== "undefined" && _window.document && _window.document.createElement);
}
/**
* It's `true` if it is running in a browser environment or `false` if it is not (SSR).
*
* @example
* import { canUseDOM } from "reakit-utils";
*
* const title = canUseDOM ? document.title : "";
*/
var canUseDOM_canUseDOM = checkIsBrowser();
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useIsomorphicEffect.js
/**
* `React.useLayoutEffect` that fallbacks to `React.useEffect` on server side
* rendering.
*/
var useIsomorphicEffect = !canUseDOM_canUseDOM ? external_React_.useEffect : external_React_.useLayoutEffect;
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useLiveRef.js
/**
* A `React.Ref` that keeps track of the passed `value`.
*/
function useLiveRef(value) {
var ref = (0,external_React_.useRef)(value);
useIsomorphicEffect(function () {
ref.current = value;
});
return ref;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isSelfTarget.js
/**
* Returns `true` if `event.target` and `event.currentTarget` are the same.
*/
function isSelfTarget(event) {
return event.target === event.currentTarget;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getActiveElement.js
/**
* Returns `element.ownerDocument.activeElement`.
*/
function getActiveElement_getActiveElement(element) {
var _getDocument = getDocument_getDocument(element),
activeElement = _getDocument.activeElement;
if (!(activeElement !== null && activeElement !== void 0 && activeElement.nodeName)) {
// In IE11, activeElement might be an empty object if we're interacting
// with elements inside of an iframe.
return null;
}
return activeElement;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/contains.js
/**
* Similar to `Element.prototype.contains`, but a little bit faster when
* `element` is the same as `child`.
*
* @example
* import { contains } from "reakit-utils";
*
* contains(document.getElementById("parent"), document.getElementById("child"));
*/
function contains(parent, child) {
return parent === child || parent.contains(child);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/hasFocusWithin.js
/**
* Checks if `element` has focus within. Elements that are referenced by
* `aria-activedescendant` are also considered.
*
* @example
* import { hasFocusWithin } from "reakit-utils";
*
* hasFocusWithin(document.getElementById("id"));
*/
function hasFocusWithin(element) {
var activeElement = getActiveElement_getActiveElement(element);
if (!activeElement) return false;
if (contains(element, activeElement)) return true;
var activeDescendant = activeElement.getAttribute("aria-activedescendant");
if (!activeDescendant) return false;
if (activeDescendant === element.id) return true;
return !!element.querySelector("#" + activeDescendant);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isPortalEvent.js
/**
* Returns `true` if `event` has been fired within a React Portal element.
*/
function isPortalEvent(event) {
return !contains(event.currentTarget, event.target);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isButton.js
var buttonInputTypes = ["button", "color", "file", "image", "reset", "submit"];
/**
* Checks whether `element` is a native HTML button element.
*
* @example
* import { isButton } from "reakit-utils";
*
* isButton(document.querySelector("button")); // true
* isButton(document.querySelector("input[type='button']")); // true
* isButton(document.querySelector("div")); // false
* isButton(document.querySelector("input[type='text']")); // false
* isButton(document.querySelector("div[role='button']")); // false
*
* @returns {boolean}
*/
function isButton(element) {
if (element.tagName === "BUTTON") return true;
if (element.tagName === "INPUT") {
var input = element;
return buttonInputTypes.indexOf(input.type) !== -1;
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/dom.js
/**
* Checks if a given string exists in the user agent string.
*/
function isUA(string) {
if (!canUseDOM_canUseDOM) return false;
return window.navigator.userAgent.indexOf(string) !== -1;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/matches.js
/**
* Ponyfill for `Element.prototype.matches`
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
*/
function matches(element, selectors) {
if ("matches" in element) {
return element.matches(selectors);
}
if ("msMatchesSelector" in element) {
return element.msMatchesSelector(selectors);
}
return element.webkitMatchesSelector(selectors);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/tabbable.js
/** @module tabbable */
var selector = "input:not([type='hidden']):not([disabled]), select:not([disabled]), " + "textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], " + "iframe, object, embed, area[href], audio[controls], video[controls], " + "[contenteditable]:not([contenteditable='false'])";
function isVisible(element) {
var htmlElement = element;
return htmlElement.offsetWidth > 0 || htmlElement.offsetHeight > 0 || element.getClientRects().length > 0;
}
function hasNegativeTabIndex(element) {
var tabIndex = parseInt(element.getAttribute("tabindex") || "0", 10);
return tabIndex < 0;
}
/**
* Checks whether `element` is focusable or not.
*
* @memberof tabbable
*
* @example
* import { isFocusable } from "reakit-utils";
*
* isFocusable(document.querySelector("input")); // true
* isFocusable(document.querySelector("input[tabindex='-1']")); // true
* isFocusable(document.querySelector("input[hidden]")); // false
* isFocusable(document.querySelector("input:disabled")); // false
*/
function isFocusable(element) {
return matches(element, selector) && isVisible(element);
}
/**
* Checks whether `element` is tabbable or not.
*
* @memberof tabbable
*
* @example
* import { isTabbable } from "reakit-utils";
*
* isTabbable(document.querySelector("input")); // true
* isTabbable(document.querySelector("input[tabindex='-1']")); // false
* isTabbable(document.querySelector("input[hidden]")); // false
* isTabbable(document.querySelector("input:disabled")); // false
*/
function isTabbable(element) {
return isFocusable(element) && !hasNegativeTabIndex(element);
}
/**
* Returns all the focusable elements in `container`.
*
* @memberof tabbable
*
* @param {Element} container
*
* @returns {Element[]}
*/
function getAllFocusableIn(container) {
var allFocusable = Array.from(container.querySelectorAll(selector));
allFocusable.unshift(container);
return allFocusable.filter(isFocusable);
}
/**
* Returns the first focusable element in `container`.
*
* @memberof tabbable
*
* @param {Element} container
*
* @returns {Element|null}
*/
function getFirstFocusableIn(container) {
var _getAllFocusableIn = getAllFocusableIn(container),
first = _getAllFocusableIn[0];
return first || null;
}
/**
* Returns all the tabbable elements in `container`, including the container
* itself.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return focusable elements if there are no tabbable ones.
*
* @returns {Element[]}
*/
function getAllTabbableIn(container, fallbackToFocusable) {
var allFocusable = Array.from(container.querySelectorAll(selector));
var allTabbable = allFocusable.filter(isTabbable);
if (isTabbable(container)) {
allTabbable.unshift(container);
}
if (!allTabbable.length && fallbackToFocusable) {
return allFocusable;
}
return allTabbable;
}
/**
* Returns the first tabbable element in `container`, including the container
* itself if it's tabbable.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the first focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getFirstTabbableIn(container, fallbackToFocusable) {
var _getAllTabbableIn = getAllTabbableIn(container, fallbackToFocusable),
first = _getAllTabbableIn[0];
return first || null;
}
/**
* Returns the last tabbable element in `container`, including the container
* itself if it's tabbable.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the last focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getLastTabbableIn(container, fallbackToFocusable) {
var allTabbable = getAllTabbableIn(container, fallbackToFocusable);
return allTabbable[allTabbable.length - 1] || null;
}
/**
* Returns the next tabbable element in `container`.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the next focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getNextTabbableIn(container, fallbackToFocusable) {
var activeElement = getActiveElement(container);
var allFocusable = getAllFocusableIn(container);
var index = allFocusable.indexOf(activeElement);
var slice = allFocusable.slice(index + 1);
return slice.find(isTabbable) || allFocusable.find(isTabbable) || (fallbackToFocusable ? slice[0] : null);
}
/**
* Returns the previous tabbable element in `container`.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the previous focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getPreviousTabbableIn(container, fallbackToFocusable) {
var activeElement = getActiveElement(container);
var allFocusable = getAllFocusableIn(container).reverse();
var index = allFocusable.indexOf(activeElement);
var slice = allFocusable.slice(index + 1);
return slice.find(isTabbable) || allFocusable.find(isTabbable) || (fallbackToFocusable ? slice[0] : null);
}
/**
* Returns the closest focusable element.
*
* @memberof tabbable
*
* @param {Element} container
*
* @returns {Element|null}
*/
function getClosestFocusable(element) {
while (element && !isFocusable(element)) {
element = closest(element, selector);
}
return element;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Role/Role.js
// Automatically generated
var ROLE_KEYS = ["unstable_system"];
var useRole = createHook({
name: "Role",
keys: ROLE_KEYS,
propsAreEqual: function propsAreEqual(prev, next) {
var prevSystem = prev.unstable_system,
prevProps = _objectWithoutPropertiesLoose(prev, ["unstable_system"]);
var nextSystem = next.unstable_system,
nextProps = _objectWithoutPropertiesLoose(next, ["unstable_system"]);
if (prevSystem !== nextSystem && !shallowEqual(prevSystem, nextSystem)) {
return false;
}
return shallowEqual(prevProps, nextProps);
}
});
var Role = createComponent({
as: "div",
useHook: useRole
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tabbable/Tabbable.js
// Automatically generated
var TABBABLE_KEYS = ["disabled", "focusable"];
var isSafariOrFirefoxOnMac = isUA("Mac") && !isUA("Chrome") && (isUA("Safari") || isUA("Firefox"));
function focusIfNeeded(element) {
if (!hasFocusWithin(element) && isFocusable(element)) {
element.focus();
}
}
function isNativeTabbable(element) {
return ["BUTTON", "INPUT", "SELECT", "TEXTAREA", "A"].includes(element.tagName);
}
function supportsDisabledAttribute(element) {
return ["BUTTON", "INPUT", "SELECT", "TEXTAREA"].includes(element.tagName);
}
function getTabIndex(trulyDisabled, nativeTabbable, supportsDisabled, htmlTabIndex) {
if (trulyDisabled) {
if (nativeTabbable && !supportsDisabled) {
// Anchor, audio and video tags don't support the `disabled` attribute.
// We must pass tabIndex={-1} so they don't receive focus on tab.
return -1;
} // Elements that support the `disabled` attribute don't need tabIndex.
return undefined;
}
if (nativeTabbable) {
// If the element is enabled and it's natively tabbable, we don't need to
// specify a tabIndex attribute unless it's explicitly set by the user.
return htmlTabIndex;
} // If the element is enabled and is not natively tabbable, we have to
// fallback tabIndex={0}.
return htmlTabIndex || 0;
}
function useDisableEvent(htmlEventRef, disabled) {
return (0,external_React_.useCallback)(function (event) {
var _htmlEventRef$current;
(_htmlEventRef$current = htmlEventRef.current) === null || _htmlEventRef$current === void 0 ? void 0 : _htmlEventRef$current.call(htmlEventRef, event);
if (event.defaultPrevented) return;
if (disabled) {
event.stopPropagation();
event.preventDefault();
}
}, [htmlEventRef, disabled]);
}
var useTabbable = createHook({
name: "Tabbable",
compose: useRole,
keys: TABBABLE_KEYS,
useOptions: function useOptions(options, _ref) {
var disabled = _ref.disabled;
return _objectSpread2({
disabled: disabled
}, options);
},
useProps: function useProps(options, _ref2) {
var htmlRef = _ref2.ref,
htmlTabIndex = _ref2.tabIndex,
htmlOnClickCapture = _ref2.onClickCapture,
htmlOnMouseDownCapture = _ref2.onMouseDownCapture,
htmlOnMouseDown = _ref2.onMouseDown,
htmlOnKeyPressCapture = _ref2.onKeyPressCapture,
htmlStyle = _ref2.style,
htmlProps = _objectWithoutPropertiesLoose(_ref2, ["ref", "tabIndex", "onClickCapture", "onMouseDownCapture", "onMouseDown", "onKeyPressCapture", "style"]);
var ref = (0,external_React_.useRef)(null);
var onClickCaptureRef = useLiveRef(htmlOnClickCapture);
var onMouseDownCaptureRef = useLiveRef(htmlOnMouseDownCapture);
var onMouseDownRef = useLiveRef(htmlOnMouseDown);
var onKeyPressCaptureRef = useLiveRef(htmlOnKeyPressCapture);
var trulyDisabled = !!options.disabled && !options.focusable;
var _React$useState = (0,external_React_.useState)(true),
nativeTabbable = _React$useState[0],
setNativeTabbable = _React$useState[1];
var _React$useState2 = (0,external_React_.useState)(true),
supportsDisabled = _React$useState2[0],
setSupportsDisabled = _React$useState2[1];
var style = options.disabled ? _objectSpread2({
pointerEvents: "none"
}, htmlStyle) : htmlStyle;
useIsomorphicEffect(function () {
var tabbable = ref.current;
if (!tabbable) {
false ? 0 : void 0;
return;
}
if (!isNativeTabbable(tabbable)) {
setNativeTabbable(false);
}
if (!supportsDisabledAttribute(tabbable)) {
setSupportsDisabled(false);
}
}, []);
var onClickCapture = useDisableEvent(onClickCaptureRef, options.disabled);
var onMouseDownCapture = useDisableEvent(onMouseDownCaptureRef, options.disabled);
var onKeyPressCapture = useDisableEvent(onKeyPressCaptureRef, options.disabled);
var onMouseDown = (0,external_React_.useCallback)(function (event) {
var _onMouseDownRef$curre;
(_onMouseDownRef$curre = onMouseDownRef.current) === null || _onMouseDownRef$curre === void 0 ? void 0 : _onMouseDownRef$curre.call(onMouseDownRef, event);
var element = event.currentTarget;
if (event.defaultPrevented) return; // Safari and Firefox on MacOS don't focus on buttons on mouse down
// like other browsers/platforms. Instead, they focus on the closest
// focusable ancestor element, which is ultimately the body element. So
// we make sure to give focus to the tabbable element on mouse down so
// it works consistently across browsers.
if (!isSafariOrFirefoxOnMac) return;
if (isPortalEvent(event)) return;
if (!isButton(element)) return; // We can't focus right away after on mouse down, otherwise it would
// prevent drag events from happening. So we schedule the focus to the
// next animation frame.
var raf = requestAnimationFrame(function () {
element.removeEventListener("mouseup", focusImmediately, true);
focusIfNeeded(element);
}); // If mouseUp happens before the next animation frame (which is common
// on touch screens or by just tapping the trackpad on MacBook's), we
// cancel the animation frame and immediately focus on the element.
var focusImmediately = function focusImmediately() {
cancelAnimationFrame(raf);
focusIfNeeded(element);
}; // By listening to the event in the capture phase, we make sure the
// focus event is fired before the onMouseUp and onMouseUpCapture React
// events, which is aligned with the default browser behavior.
element.addEventListener("mouseup", focusImmediately, {
once: true,
capture: true
});
}, []);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
style: style,
tabIndex: getTabIndex(trulyDisabled, nativeTabbable, supportsDisabled, htmlTabIndex),
disabled: trulyDisabled && supportsDisabled ? true : undefined,
"aria-disabled": options.disabled ? true : undefined,
onClickCapture: onClickCapture,
onMouseDownCapture: onMouseDownCapture,
onMouseDown: onMouseDown,
onKeyPressCapture: onKeyPressCapture
}, htmlProps);
}
});
var Tabbable = createComponent({
as: "div",
useHook: useTabbable
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Clickable/Clickable.js
// Automatically generated
var CLICKABLE_KEYS = ["unstable_clickOnEnter", "unstable_clickOnSpace"];
function isNativeClick(event) {
var element = event.currentTarget;
if (!event.isTrusted) return false; // istanbul ignore next: can't test trusted events yet
return isButton(element) || element.tagName === "INPUT" || element.tagName === "TEXTAREA" || element.tagName === "A" || element.tagName === "SELECT";
}
var useClickable = createHook({
name: "Clickable",
compose: useTabbable,
keys: CLICKABLE_KEYS,
useOptions: function useOptions(_ref) {
var _ref$unstable_clickOn = _ref.unstable_clickOnEnter,
unstable_clickOnEnter = _ref$unstable_clickOn === void 0 ? true : _ref$unstable_clickOn,
_ref$unstable_clickOn2 = _ref.unstable_clickOnSpace,
unstable_clickOnSpace = _ref$unstable_clickOn2 === void 0 ? true : _ref$unstable_clickOn2,
options = _objectWithoutPropertiesLoose(_ref, ["unstable_clickOnEnter", "unstable_clickOnSpace"]);
return _objectSpread2({
unstable_clickOnEnter: unstable_clickOnEnter,
unstable_clickOnSpace: unstable_clickOnSpace
}, options);
},
useProps: function useProps(options, _ref2) {
var htmlOnKeyDown = _ref2.onKeyDown,
htmlOnKeyUp = _ref2.onKeyUp,
htmlProps = _objectWithoutPropertiesLoose(_ref2, ["onKeyDown", "onKeyUp"]);
var _React$useState = (0,external_React_.useState)(false),
active = _React$useState[0],
setActive = _React$useState[1];
var onKeyDownRef = useLiveRef(htmlOnKeyDown);
var onKeyUpRef = useLiveRef(htmlOnKeyUp);
var onKeyDown = (0,external_React_.useCallback)(function (event) {
var _onKeyDownRef$current;
(_onKeyDownRef$current = onKeyDownRef.current) === null || _onKeyDownRef$current === void 0 ? void 0 : _onKeyDownRef$current.call(onKeyDownRef, event);
if (event.defaultPrevented) return;
if (options.disabled) return;
if (event.metaKey) return;
if (!isSelfTarget(event)) return;
var isEnter = options.unstable_clickOnEnter && event.key === "Enter";
var isSpace = options.unstable_clickOnSpace && event.key === " ";
if (isEnter || isSpace) {
if (isNativeClick(event)) return;
event.preventDefault();
if (isEnter) {
event.currentTarget.click();
} else if (isSpace) {
setActive(true);
}
}
}, [options.disabled, options.unstable_clickOnEnter, options.unstable_clickOnSpace]);
var onKeyUp = (0,external_React_.useCallback)(function (event) {
var _onKeyUpRef$current;
(_onKeyUpRef$current = onKeyUpRef.current) === null || _onKeyUpRef$current === void 0 ? void 0 : _onKeyUpRef$current.call(onKeyUpRef, event);
if (event.defaultPrevented) return;
if (options.disabled) return;
if (event.metaKey) return;
var isSpace = options.unstable_clickOnSpace && event.key === " ";
if (active && isSpace) {
setActive(false);
event.currentTarget.click();
}
}, [options.disabled, options.unstable_clickOnSpace, active]);
return _objectSpread2({
"data-active": active || undefined,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp
}, htmlProps);
}
});
var Clickable = createComponent({
as: "button",
memo: true,
useHook: useClickable
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/getCurrentId-5aa9849e.js
function findFirstEnabledItem(items, excludeId) {
if (excludeId) {
return items.find(function (item) {
return !item.disabled && item.id !== excludeId;
});
}
return items.find(function (item) {
return !item.disabled;
});
}
function getCurrentId(options, passedId) {
var _findFirstEnabledItem;
if (passedId || passedId === null) {
return passedId;
}
if (options.currentId || options.currentId === null) {
return options.currentId;
}
return (_findFirstEnabledItem = findFirstEnabledItem(options.items || [])) === null || _findFirstEnabledItem === void 0 ? void 0 : _findFirstEnabledItem.id;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-6742f591.js
// Automatically generated
var COMPOSITE_STATE_KEYS = ["baseId", "unstable_idCountRef", "setBaseId", "unstable_virtual", "rtl", "orientation", "items", "groups", "currentId", "loop", "wrap", "shift", "unstable_moves", "unstable_hasActiveWidget", "unstable_includesBaseElement", "registerItem", "unregisterItem", "registerGroup", "unregisterGroup", "move", "next", "previous", "up", "down", "first", "last", "sort", "unstable_setVirtual", "setRTL", "setOrientation", "setCurrentId", "setLoop", "setWrap", "setShift", "reset", "unstable_setIncludesBaseElement", "unstable_setHasActiveWidget"];
var COMPOSITE_KEYS = COMPOSITE_STATE_KEYS;
var COMPOSITE_GROUP_KEYS = COMPOSITE_KEYS;
var COMPOSITE_ITEM_KEYS = COMPOSITE_GROUP_KEYS;
var COMPOSITE_ITEM_WIDGET_KEYS = (/* unused pure expression or super */ null && (COMPOSITE_ITEM_KEYS));
;// CONCATENATED MODULE: ./node_modules/reakit/es/userFocus-e16425e3.js
function userFocus(element) {
element.userFocus = true;
element.focus();
element.userFocus = false;
}
function hasUserFocus(element) {
return !!element.userFocus;
}
function setUserFocus(element, value) {
element.userFocus = value;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isTextField.js
/**
* Check whether the given element is a text field, where text field is defined
* by the ability to select within the input, or that it is contenteditable.
*
* @example
* import { isTextField } from "reakit-utils";
*
* isTextField(document.querySelector("div")); // false
* isTextField(document.querySelector("input")); // true
* isTextField(document.querySelector("input[type='button']")); // false
* isTextField(document.querySelector("textarea")); // true
* isTextField(document.querySelector("div[contenteditable='true']")); // true
*/
function isTextField_isTextField(element) {
try {
var isTextInput = element instanceof HTMLInputElement && element.selectionStart !== null;
var isTextArea = element.tagName === "TEXTAREA";
var isContentEditable = element.contentEditable === "true";
return isTextInput || isTextArea || isContentEditable || false;
} catch (error) {
// Safari throws an exception when trying to get `selectionStart`
// on non-text <input> elements (which, understandably, don't
// have the text selection API). We catch this via a try/catch
// block, as opposed to a more explicit check of the element's
// input types, because of Safari's non-standard behavior. This
// also means we don't have to worry about the list of input
// types that support `selectionStart` changing as the HTML spec
// evolves over time.
return false;
}
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/hasFocus.js
/**
* Checks if `element` has focus. Elements that are referenced by
* `aria-activedescendant` are also considered.
*
* @example
* import { hasFocus } from "reakit-utils";
*
* hasFocus(document.getElementById("id"));
*/
function hasFocus(element) {
var activeElement = getActiveElement_getActiveElement(element);
if (!activeElement) return false;
if (activeElement === element) return true;
var activeDescendant = activeElement.getAttribute("aria-activedescendant");
if (!activeDescendant) return false;
return activeDescendant === element.id;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/ensureFocus.js
/**
* Ensures `element` will receive focus if it's not already.
*
* @example
* import { ensureFocus } from "reakit-utils";
*
* ensureFocus(document.activeElement); // does nothing
*
* const element = document.querySelector("input");
*
* ensureFocus(element); // focuses element
* ensureFocus(element, { preventScroll: true }); // focuses element preventing scroll jump
*
* function isActive(el) {
* return el.dataset.active === "true";
* }
*
* ensureFocus(document.querySelector("[data-active='true']"), { isActive }); // does nothing
*
* @returns {number} `requestAnimationFrame` call ID so it can be passed to `cancelAnimationFrame` if needed.
*/
function ensureFocus(element, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
preventScroll = _ref.preventScroll,
_ref$isActive = _ref.isActive,
isActive = _ref$isActive === void 0 ? hasFocus : _ref$isActive;
if (isActive(element)) return -1;
element.focus({
preventScroll: preventScroll
});
if (isActive(element)) return -1;
return requestAnimationFrame(function () {
element.focus({
preventScroll: preventScroll
});
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Id/IdProvider.js
var defaultPrefix = "id";
function generateRandomString(prefix) {
if (prefix === void 0) {
prefix = defaultPrefix;
}
return "" + (prefix ? prefix + "-" : "") + Math.random().toString(32).substr(2, 6);
}
var unstable_IdContext = /*#__PURE__*/(0,external_React_.createContext)(generateRandomString);
function unstable_IdProvider(_ref) {
var children = _ref.children,
_ref$prefix = _ref.prefix,
prefix = _ref$prefix === void 0 ? defaultPrefix : _ref$prefix;
var count = useRef(0);
var generateId = useCallback(function (localPrefix) {
if (localPrefix === void 0) {
localPrefix = prefix;
}
return "" + (localPrefix ? localPrefix + "-" : "") + ++count.current;
}, [prefix]);
return /*#__PURE__*/createElement(unstable_IdContext.Provider, {
value: generateId
}, children);
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Id/Id.js
// Automatically generated
var ID_STATE_KEYS = ["baseId", "unstable_idCountRef", "setBaseId"];
var ID_KEYS = [].concat(ID_STATE_KEYS, ["id"]);
var unstable_useId = createHook({
keys: ID_KEYS,
useOptions: function useOptions(options, htmlProps) {
var generateId = (0,external_React_.useContext)(unstable_IdContext);
var _React$useState = (0,external_React_.useState)(function () {
// This comes from useIdState
if (options.unstable_idCountRef) {
options.unstable_idCountRef.current += 1;
return "-" + options.unstable_idCountRef.current;
} // If there's no useIdState, we check if `baseId` was passed (as a prop,
// not from useIdState).
if (options.baseId) {
return "-" + generateId("");
}
return "";
}),
suffix = _React$useState[0]; // `baseId` will be the prop passed directly as a prop or via useIdState.
// If there's neither, then it'll fallback to Context's generateId.
// This generateId can result in a sequential ID (if there's a Provider)
// or a random string (without Provider).
var baseId = (0,external_React_.useMemo)(function () {
return options.baseId || generateId();
}, [options.baseId, generateId]);
var id = htmlProps.id || options.id || "" + baseId + suffix;
return _objectSpread2(_objectSpread2({}, options), {}, {
id: id
});
},
useProps: function useProps(options, htmlProps) {
return _objectSpread2({
id: options.id
}, htmlProps);
}
});
var unstable_Id = createComponent({
as: "div",
useHook: unstable_useId
});
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/createEvent.js
/**
* Creates an `Event` in a way that also works on IE 11.
*
* @example
* import { createEvent } from "reakit-utils";
*
* const el = document.getElementById("id");
* el.dispatchEvent(createEvent(el, "blur", { bubbles: false }));
*/
function createEvent(element, type, eventInit) {
if (typeof Event === "function") {
return new Event(type, eventInit);
} // IE 11 doesn't support Event constructors
var event = getDocument_getDocument(element).createEvent("Event");
event.initEvent(type, eventInit === null || eventInit === void 0 ? void 0 : eventInit.bubbles, eventInit === null || eventInit === void 0 ? void 0 : eventInit.cancelable);
return event;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/fireEvent.js
/**
* Creates and dispatches `Event` in a way that also works on IE 11.
*
* @example
* import { fireEvent } from "reakit-utils";
*
* fireEvent(document.getElementById("id"), "blur", {
* bubbles: true,
* cancelable: true,
* });
*/
function fireEvent(element, type, eventInit) {
return element.dispatchEvent(createEvent(element, type, eventInit));
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/setTextFieldValue-0a221f4e.js
function setTextFieldValue(element, value) {
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
var _Object$getOwnPropert;
var proto = Object.getPrototypeOf(element);
var setValue = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(proto, "value")) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.set;
if (setValue) {
setValue.call(element, value);
fireEvent(element, "input", {
bubbles: true
});
}
}
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/CompositeItem.js
function getWidget(itemElement) {
return itemElement.querySelector("[data-composite-item-widget]");
}
function useItem(options) {
return (0,external_React_.useMemo)(function () {
var _options$items;
return (_options$items = options.items) === null || _options$items === void 0 ? void 0 : _options$items.find(function (item) {
return options.id && item.id === options.id;
});
}, [options.items, options.id]);
}
function targetIsAnotherItem(event, items) {
if (isSelfTarget(event)) return false;
for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
var item = _step.value;
if (item.ref.current === event.target) {
return true;
}
}
return false;
}
var useCompositeItem = createHook({
name: "CompositeItem",
compose: [useClickable, unstable_useId],
keys: COMPOSITE_ITEM_KEYS,
propsAreEqual: function propsAreEqual(prev, next) {
if (!next.id || prev.id !== next.id) {
return useClickable.unstable_propsAreEqual(prev, next);
}
var prevCurrentId = prev.currentId,
prevMoves = prev.unstable_moves,
prevProps = _objectWithoutPropertiesLoose(prev, ["currentId", "unstable_moves"]);
var nextCurrentId = next.currentId,
nextMoves = next.unstable_moves,
nextProps = _objectWithoutPropertiesLoose(next, ["currentId", "unstable_moves"]);
if (nextCurrentId !== prevCurrentId) {
if (next.id === nextCurrentId || next.id === prevCurrentId) {
return false;
}
} else if (prevMoves !== nextMoves) {
return false;
}
return useClickable.unstable_propsAreEqual(prevProps, nextProps);
},
useOptions: function useOptions(options) {
return _objectSpread2(_objectSpread2({}, options), {}, {
id: options.id,
currentId: getCurrentId(options),
unstable_clickOnSpace: options.unstable_hasActiveWidget ? false : options.unstable_clickOnSpace
});
},
useProps: function useProps(options, _ref) {
var _options$items2;
var htmlRef = _ref.ref,
_ref$tabIndex = _ref.tabIndex,
htmlTabIndex = _ref$tabIndex === void 0 ? 0 : _ref$tabIndex,
htmlOnMouseDown = _ref.onMouseDown,
htmlOnFocus = _ref.onFocus,
htmlOnBlurCapture = _ref.onBlurCapture,
htmlOnKeyDown = _ref.onKeyDown,
htmlOnClick = _ref.onClick,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref", "tabIndex", "onMouseDown", "onFocus", "onBlurCapture", "onKeyDown", "onClick"]);
var ref = (0,external_React_.useRef)(null);
var id = options.id;
var trulyDisabled = options.disabled && !options.focusable;
var isCurrentItem = options.currentId === id;
var isCurrentItemRef = useLiveRef(isCurrentItem);
var hasFocusedComposite = (0,external_React_.useRef)(false);
var item = useItem(options);
var onMouseDownRef = useLiveRef(htmlOnMouseDown);
var onFocusRef = useLiveRef(htmlOnFocus);
var onBlurCaptureRef = useLiveRef(htmlOnBlurCapture);
var onKeyDownRef = useLiveRef(htmlOnKeyDown);
var onClickRef = useLiveRef(htmlOnClick);
var shouldTabIndex = !options.unstable_virtual && !options.unstable_hasActiveWidget && isCurrentItem || // We don't want to set tabIndex="-1" when using CompositeItem as a
// standalone component, without state props.
!((_options$items2 = options.items) !== null && _options$items2 !== void 0 && _options$items2.length);
(0,external_React_.useEffect)(function () {
var _options$registerItem;
if (!id) return undefined;
(_options$registerItem = options.registerItem) === null || _options$registerItem === void 0 ? void 0 : _options$registerItem.call(options, {
id: id,
ref: ref,
disabled: !!trulyDisabled
});
return function () {
var _options$unregisterIt;
(_options$unregisterIt = options.unregisterItem) === null || _options$unregisterIt === void 0 ? void 0 : _options$unregisterIt.call(options, id);
};
}, [id, trulyDisabled, options.registerItem, options.unregisterItem]);
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (!element) {
false ? 0 : void 0;
return;
} // `moves` will be incremented whenever next, previous, up, down, first,
// last or move have been called. This means that the composite item will
// be focused whenever some of these functions are called. We're using
// isCurrentItemRef instead of isCurrentItem because we don't want to
// focus the item if isCurrentItem changes (and options.moves doesn't).
if (options.unstable_moves && isCurrentItemRef.current) {
userFocus(element);
}
}, [options.unstable_moves]);
var onMouseDown = (0,external_React_.useCallback)(function (event) {
var _onMouseDownRef$curre;
(_onMouseDownRef$curre = onMouseDownRef.current) === null || _onMouseDownRef$curre === void 0 ? void 0 : _onMouseDownRef$curre.call(onMouseDownRef, event);
setUserFocus(event.currentTarget, true);
}, []);
var onFocus = (0,external_React_.useCallback)(function (event) {
var _onFocusRef$current, _options$setCurrentId;
var shouldFocusComposite = hasUserFocus(event.currentTarget);
setUserFocus(event.currentTarget, false);
(_onFocusRef$current = onFocusRef.current) === null || _onFocusRef$current === void 0 ? void 0 : _onFocusRef$current.call(onFocusRef, event);
if (event.defaultPrevented) return;
if (isPortalEvent(event)) return;
if (!id) return;
if (targetIsAnotherItem(event, options.items)) return;
(_options$setCurrentId = options.setCurrentId) === null || _options$setCurrentId === void 0 ? void 0 : _options$setCurrentId.call(options, id); // When using aria-activedescendant, we want to make sure that the
// composite container receives focus, not the composite item.
// But we don't want to do this if the target is another focusable
// element inside the composite item, such as CompositeItemWidget.
if (shouldFocusComposite && options.unstable_virtual && options.baseId && isSelfTarget(event)) {
var target = event.target;
var composite = getDocument_getDocument(target).getElementById(options.baseId);
if (composite) {
hasFocusedComposite.current = true;
ensureFocus(composite);
}
}
}, [id, options.items, options.setCurrentId, options.unstable_virtual, options.baseId]);
var onBlurCapture = (0,external_React_.useCallback)(function (event) {
var _onBlurCaptureRef$cur;
(_onBlurCaptureRef$cur = onBlurCaptureRef.current) === null || _onBlurCaptureRef$cur === void 0 ? void 0 : _onBlurCaptureRef$cur.call(onBlurCaptureRef, event);
if (event.defaultPrevented) return;
if (options.unstable_virtual && hasFocusedComposite.current) {
// When hasFocusedComposite is true, composite has been focused right
// after focusing this item. This is an intermediate blur event, so
// we ignore it.
hasFocusedComposite.current = false;
event.preventDefault();
event.stopPropagation();
}
}, [options.unstable_virtual]);
var onKeyDown = (0,external_React_.useCallback)(function (event) {
var _onKeyDownRef$current;
if (!isSelfTarget(event)) return;
var isVertical = options.orientation !== "horizontal";
var isHorizontal = options.orientation !== "vertical";
var isGrid = !!(item !== null && item !== void 0 && item.groupId);
var keyMap = {
ArrowUp: (isGrid || isVertical) && options.up,
ArrowRight: (isGrid || isHorizontal) && options.next,
ArrowDown: (isGrid || isVertical) && options.down,
ArrowLeft: (isGrid || isHorizontal) && options.previous,
Home: function Home() {
if (!isGrid || event.ctrlKey) {
var _options$first;
(_options$first = options.first) === null || _options$first === void 0 ? void 0 : _options$first.call(options);
} else {
var _options$previous;
(_options$previous = options.previous) === null || _options$previous === void 0 ? void 0 : _options$previous.call(options, true);
}
},
End: function End() {
if (!isGrid || event.ctrlKey) {
var _options$last;
(_options$last = options.last) === null || _options$last === void 0 ? void 0 : _options$last.call(options);
} else {
var _options$next;
(_options$next = options.next) === null || _options$next === void 0 ? void 0 : _options$next.call(options, true);
}
},
PageUp: function PageUp() {
if (isGrid) {
var _options$up;
(_options$up = options.up) === null || _options$up === void 0 ? void 0 : _options$up.call(options, true);
} else {
var _options$first2;
(_options$first2 = options.first) === null || _options$first2 === void 0 ? void 0 : _options$first2.call(options);
}
},
PageDown: function PageDown() {
if (isGrid) {
var _options$down;
(_options$down = options.down) === null || _options$down === void 0 ? void 0 : _options$down.call(options, true);
} else {
var _options$last2;
(_options$last2 = options.last) === null || _options$last2 === void 0 ? void 0 : _options$last2.call(options);
}
}
};
var action = keyMap[event.key];
if (action) {
event.preventDefault();
action();
return;
}
(_onKeyDownRef$current = onKeyDownRef.current) === null || _onKeyDownRef$current === void 0 ? void 0 : _onKeyDownRef$current.call(onKeyDownRef, event);
if (event.defaultPrevented) return;
if (event.key.length === 1 && event.key !== " ") {
var widget = getWidget(event.currentTarget);
if (widget && isTextField_isTextField(widget)) {
widget.focus();
setTextFieldValue(widget, "");
}
} else if (event.key === "Delete" || event.key === "Backspace") {
var _widget = getWidget(event.currentTarget);
if (_widget && isTextField_isTextField(_widget)) {
event.preventDefault();
setTextFieldValue(_widget, "");
}
}
}, [options.orientation, item, options.up, options.next, options.down, options.previous, options.first, options.last]);
var onClick = (0,external_React_.useCallback)(function (event) {
var _onClickRef$current;
(_onClickRef$current = onClickRef.current) === null || _onClickRef$current === void 0 ? void 0 : _onClickRef$current.call(onClickRef, event);
if (event.defaultPrevented) return;
var element = event.currentTarget;
var widget = getWidget(element);
if (widget && !hasFocusWithin(widget)) {
// If there's a widget inside the composite item, we make sure it's
// focused when pressing enter, space or clicking on the composite item.
widget.focus();
}
}, []);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
id: id,
tabIndex: shouldTabIndex ? htmlTabIndex : -1,
"aria-selected": options.unstable_virtual && isCurrentItem ? true : undefined,
onMouseDown: onMouseDown,
onFocus: onFocus,
onBlurCapture: onBlurCapture,
onKeyDown: onKeyDown,
onClick: onClick
}, htmlProps);
}
});
var CompositeItem = createComponent({
as: "button",
memo: true,
useHook: useCompositeItem
});
;// CONCATENATED MODULE: ./node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs
function t(t){return t.split("-")[1]}function floating_ui_core_browser_min_e(t){return"y"===t?"height":"width"}function floating_ui_core_browser_min_n(t){return t.split("-")[0]}function floating_ui_core_browser_min_o(t){return["top","bottom"].includes(floating_ui_core_browser_min_n(t))?"x":"y"}function i(i,r,a){let{reference:l,floating:s}=i;const c=l.x+l.width/2-s.width/2,f=l.y+l.height/2-s.height/2,m=floating_ui_core_browser_min_o(r),u=floating_ui_core_browser_min_e(m),g=l[u]/2-s[u]/2,d="x"===m;let p;switch(floating_ui_core_browser_min_n(r)){case"top":p={x:c,y:l.y-s.height};break;case"bottom":p={x:c,y:l.y+l.height};break;case"right":p={x:l.x+l.width,y:f};break;case"left":p={x:l.x-s.width,y:f};break;default:p={x:l.x,y:l.y}}switch(t(r)){case"start":p[m]-=g*(a&&d?-1:1);break;case"end":p[m]+=g*(a&&d?-1:1)}return p}const floating_ui_core_browser_min_r=async(t,e,n)=>{const{placement:o="bottom",strategy:r="absolute",middleware:a=[],platform:l}=n,s=a.filter(Boolean),c=await(null==l.isRTL?void 0:l.isRTL(e));let f=await l.getElementRects({reference:t,floating:e,strategy:r}),{x:m,y:u}=i(f,o,c),g=o,d={},p=0;for(let n=0;n<s.length;n++){const{name:a,fn:h}=s[n],{x:y,y:x,data:w,reset:v}=await h({x:m,y:u,initialPlacement:o,placement:g,strategy:r,middlewareData:d,rects:f,platform:l,elements:{reference:t,floating:e}});m=null!=y?y:m,u=null!=x?x:u,d={...d,[a]:{...d[a],...w}},v&&p<=50&&(p++,"object"==typeof v&&(v.placement&&(g=v.placement),v.rects&&(f=!0===v.rects?await l.getElementRects({reference:t,floating:e,strategy:r}):v.rects),({x:m,y:u}=i(f,g,c))),n=-1)}return{x:m,y:u,placement:g,strategy:r,middlewareData:d}};function floating_ui_core_browser_min_a(t,e){return"function"==typeof t?t(e):t}function l(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}function floating_ui_core_browser_min_s(t){return{...t,top:t.y,left:t.x,right:t.x+t.width,bottom:t.y+t.height}}async function c(t,e){var n;void 0===e&&(e={});const{x:o,y:i,platform:r,rects:c,elements:f,strategy:m}=t,{boundary:u="clippingAncestors",rootBoundary:g="viewport",elementContext:d="floating",altBoundary:p=!1,padding:h=0}=floating_ui_core_browser_min_a(e,t),y=l(h),x=f[p?"floating"===d?"reference":"floating":d],w=floating_ui_core_browser_min_s(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(x)))||n?x:x.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(f.floating)),boundary:u,rootBoundary:g,strategy:m})),v="floating"===d?{...c.floating,x:o,y:i}:c.reference,b=await(null==r.getOffsetParent?void 0:r.getOffsetParent(f.floating)),A=await(null==r.isElement?void 0:r.isElement(b))&&await(null==r.getScale?void 0:r.getScale(b))||{x:1,y:1},R=floating_ui_core_browser_min_s(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({rect:v,offsetParent:b,strategy:m}):v);return{top:(w.top-R.top+y.top)/A.y,bottom:(R.bottom-w.bottom+y.bottom)/A.y,left:(w.left-R.left+y.left)/A.x,right:(R.right-w.right+y.right)/A.x}}const f=Math.min,m=Math.max;function u(t,e,n){return m(t,f(e,n))}const g=n=>({name:"arrow",options:n,async fn(i){const{x:r,y:s,placement:c,rects:m,platform:g,elements:d}=i,{element:p,padding:h=0}=floating_ui_core_browser_min_a(n,i)||{};if(null==p)return{};const y=l(h),x={x:r,y:s},w=floating_ui_core_browser_min_o(c),v=floating_ui_core_browser_min_e(w),b=await g.getDimensions(p),A="y"===w,R=A?"top":"left",P=A?"bottom":"right",E=A?"clientHeight":"clientWidth",T=m.reference[v]+m.reference[w]-x[w]-m.floating[v],D=x[w]-m.reference[w],L=await(null==g.getOffsetParent?void 0:g.getOffsetParent(p));let k=L?L[E]:0;k&&await(null==g.isElement?void 0:g.isElement(L))||(k=d.floating[E]||m.floating[v]);const O=T/2-D/2,B=k/2-b[v]/2-1,C=f(y[R],B),H=f(y[P],B),S=C,F=k-b[v]-H,M=k/2-b[v]/2+O,V=u(S,M,F),W=null!=t(c)&&M!=V&&m.reference[v]/2-(M<S?C:H)-b[v]/2<0?M<S?S-M:F-M:0;return{[w]:x[w]-W,data:{[w]:V,centerOffset:M-V+W}}}}),d=["top","right","bottom","left"],p=d.reduce(((t,e)=>t.concat(e,e+"-start",e+"-end")),[]),h={left:"right",right:"left",bottom:"top",top:"bottom"};function y(t){return t.replace(/left|right|bottom|top/g,(t=>h[t]))}function x(n,i,r){void 0===r&&(r=!1);const a=t(n),l=floating_ui_core_browser_min_o(n),s=floating_ui_core_browser_min_e(l);let c="x"===l?a===(r?"end":"start")?"right":"left":"start"===a?"bottom":"top";return i.reference[s]>i.floating[s]&&(c=y(c)),{main:c,cross:y(c)}}const w={start:"end",end:"start"};function v(t){return t.replace(/start|end/g,(t=>w[t]))}const b=function(e){return void 0===e&&(e={}),{name:"autoPlacement",options:e,async fn(o){var i,r,l;const{rects:s,middlewareData:f,placement:m,platform:u,elements:g}=o,{crossAxis:d=!1,alignment:h,allowedPlacements:y=p,autoAlignment:w=!0,...b}=floating_ui_core_browser_min_a(e,o),A=void 0!==h||y===p?function(e,o,i){return(e?[...i.filter((n=>t(n)===e)),...i.filter((n=>t(n)!==e))]:i.filter((t=>floating_ui_core_browser_min_n(t)===t))).filter((n=>!e||t(n)===e||!!o&&v(n)!==n))}(h||null,w,y):y,R=await c(o,b),P=(null==(i=f.autoPlacement)?void 0:i.index)||0,E=A[P];if(null==E)return{};const{main:T,cross:D}=x(E,s,await(null==u.isRTL?void 0:u.isRTL(g.floating)));if(m!==E)return{reset:{placement:A[0]}};const L=[R[floating_ui_core_browser_min_n(E)],R[T],R[D]],k=[...(null==(r=f.autoPlacement)?void 0:r.overflows)||[],{placement:E,overflows:L}],O=A[P+1];if(O)return{data:{index:P+1,overflows:k},reset:{placement:O}};const B=k.map((e=>{const n=t(e.placement);return[e.placement,n&&d?e.overflows.slice(0,2).reduce(((t,e)=>t+e),0):e.overflows[0],e.overflows]})).sort(((t,e)=>t[1]-e[1])),C=(null==(l=B.filter((e=>e[2].slice(0,t(e[0])?2:3).every((t=>t<=0))))[0])?void 0:l[0])||B[0][0];return C!==m?{data:{index:P+1,overflows:k},reset:{placement:C}}:{}}}};const A=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(o){var i;const{placement:r,middlewareData:l,rects:s,initialPlacement:f,platform:m,elements:u}=o,{mainAxis:g=!0,crossAxis:d=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:w="none",flipAlignment:b=!0,...A}=floating_ui_core_browser_min_a(e,o),R=floating_ui_core_browser_min_n(r),P=floating_ui_core_browser_min_n(f)===f,E=await(null==m.isRTL?void 0:m.isRTL(u.floating)),T=p||(P||!b?[y(f)]:function(t){const e=y(t);return[v(t),e,v(e)]}(f));p||"none"===w||T.push(...function(e,o,i,r){const a=t(e);let l=function(t,e,n){const o=["left","right"],i=["right","left"],r=["top","bottom"],a=["bottom","top"];switch(t){case"top":case"bottom":return n?e?i:o:e?o:i;case"left":case"right":return e?r:a;default:return[]}}(floating_ui_core_browser_min_n(e),"start"===i,r);return a&&(l=l.map((t=>t+"-"+a)),o&&(l=l.concat(l.map(v)))),l}(f,b,w,E));const D=[f,...T],L=await c(o,A),k=[];let O=(null==(i=l.flip)?void 0:i.overflows)||[];if(g&&k.push(L[R]),d){const{main:t,cross:e}=x(r,s,E);k.push(L[t],L[e])}if(O=[...O,{placement:r,overflows:k}],!k.every((t=>t<=0))){var B,C;const t=((null==(B=l.flip)?void 0:B.index)||0)+1,e=D[t];if(e)return{data:{index:t,overflows:O},reset:{placement:e}};let n=null==(C=O.filter((t=>t.overflows[0]<=0)).sort(((t,e)=>t.overflows[1]-e.overflows[1]))[0])?void 0:C.placement;if(!n)switch(h){case"bestFit":{var H;const t=null==(H=O.map((t=>[t.placement,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:H[0];t&&(n=t);break}case"initialPlacement":n=f}if(r!==n)return{reset:{placement:n}}}return{}}}};function R(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function P(t){return d.some((e=>t[e]>=0))}const E=function(t){return void 0===t&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:o="referenceHidden",...i}=floating_ui_core_browser_min_a(t,e);switch(o){case"referenceHidden":{const t=R(await c(e,{...i,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:t,referenceHidden:P(t)}}}case"escaped":{const t=R(await c(e,{...i,altBoundary:!0}),n.floating);return{data:{escapedOffsets:t,escaped:P(t)}}}default:return{}}}}};function T(t){const e=f(...t.map((t=>t.left))),n=f(...t.map((t=>t.top)));return{x:e,y:n,width:m(...t.map((t=>t.right)))-e,height:m(...t.map((t=>t.bottom)))-n}}const D=function(t){return void 0===t&&(t={}),{name:"inline",options:t,async fn(e){const{placement:i,elements:r,rects:c,platform:u,strategy:g}=e,{padding:d=2,x:p,y:h}=floating_ui_core_browser_min_a(t,e),y=Array.from(await(null==u.getClientRects?void 0:u.getClientRects(r.reference))||[]),x=function(t){const e=t.slice().sort(((t,e)=>t.y-e.y)),n=[];let o=null;for(let t=0;t<e.length;t++){const i=e[t];!o||i.y-o.y>o.height/2?n.push([i]):n[n.length-1].push(i),o=i}return n.map((t=>floating_ui_core_browser_min_s(T(t))))}(y),w=floating_ui_core_browser_min_s(T(y)),v=l(d);const b=await u.getElementRects({reference:{getBoundingClientRect:function(){if(2===x.length&&x[0].left>x[1].right&&null!=p&&null!=h)return x.find((t=>p>t.left-v.left&&p<t.right+v.right&&h>t.top-v.top&&h<t.bottom+v.bottom))||w;if(x.length>=2){if("x"===floating_ui_core_browser_min_o(i)){const t=x[0],e=x[x.length-1],o="top"===floating_ui_core_browser_min_n(i),r=t.top,a=e.bottom,l=o?t.left:e.left,s=o?t.right:e.right;return{top:r,bottom:a,left:l,right:s,width:s-l,height:a-r,x:l,y:r}}const t="left"===floating_ui_core_browser_min_n(i),e=m(...x.map((t=>t.right))),r=f(...x.map((t=>t.left))),a=x.filter((n=>t?n.left===r:n.right===e)),l=a[0].top,s=a[a.length-1].bottom;return{top:l,bottom:s,left:r,right:e,width:e-r,height:s-l,x:r,y:l}}return w}},floating:r.floating,strategy:g});return c.reference.x!==b.reference.x||c.reference.y!==b.reference.y||c.reference.width!==b.reference.width||c.reference.height!==b.reference.height?{reset:{rects:b}}:{}}}};const L=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(i){const{x:r,y:l}=i,s=await async function(e,i){const{placement:r,platform:l,elements:s}=e,c=await(null==l.isRTL?void 0:l.isRTL(s.floating)),f=floating_ui_core_browser_min_n(r),m=t(r),u="x"===floating_ui_core_browser_min_o(r),g=["left","top"].includes(f)?-1:1,d=c&&u?-1:1,p=floating_ui_core_browser_min_a(i,e);let{mainAxis:h,crossAxis:y,alignmentAxis:x}="number"==typeof p?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return m&&"number"==typeof x&&(y="end"===m?-1*x:x),u?{x:y*d,y:h*g}:{x:h*g,y:y*d}}(i,e);return{x:r+s.x,y:l+s.y,data:s}}}};function k(t){return"x"===t?"y":"x"}const O=function(t){return void 0===t&&(t={}),{name:"shift",options:t,async fn(e){const{x:i,y:r,placement:l}=e,{mainAxis:s=!0,crossAxis:f=!1,limiter:m={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...g}=floating_ui_core_browser_min_a(t,e),d={x:i,y:r},p=await c(e,g),h=floating_ui_core_browser_min_o(floating_ui_core_browser_min_n(l)),y=k(h);let x=d[h],w=d[y];if(s){const t="y"===h?"bottom":"right";x=u(x+p["y"===h?"top":"left"],x,x-p[t])}if(f){const t="y"===y?"bottom":"right";w=u(w+p["y"===y?"top":"left"],w,w-p[t])}const v=m.fn({...e,[h]:x,[y]:w});return{...v,data:{x:v.x-i,y:v.y-r}}}}},B=function(t){return void 0===t&&(t={}),{options:t,fn(e){const{x:i,y:r,placement:l,rects:s,middlewareData:c}=e,{offset:f=0,mainAxis:m=!0,crossAxis:u=!0}=floating_ui_core_browser_min_a(t,e),g={x:i,y:r},d=floating_ui_core_browser_min_o(l),p=k(d);let h=g[d],y=g[p];const x=floating_ui_core_browser_min_a(f,e),w="number"==typeof x?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(m){const t="y"===d?"height":"width",e=s.reference[d]-s.floating[t]+w.mainAxis,n=s.reference[d]+s.reference[t]-w.mainAxis;h<e?h=e:h>n&&(h=n)}if(u){var v,b;const t="y"===d?"width":"height",e=["top","left"].includes(floating_ui_core_browser_min_n(l)),o=s.reference[p]-s.floating[t]+(e&&(null==(v=c.offset)?void 0:v[p])||0)+(e?0:w.crossAxis),i=s.reference[p]+s.reference[t]+(e?0:(null==(b=c.offset)?void 0:b[p])||0)-(e?w.crossAxis:0);y<o?y=o:y>i&&(y=i)}return{[d]:h,[p]:y}}}},C=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(i){const{placement:r,rects:l,platform:s,elements:u}=i,{apply:g=(()=>{}),...d}=floating_ui_core_browser_min_a(e,i),p=await c(i,d),h=floating_ui_core_browser_min_n(r),y=t(r),x="x"===floating_ui_core_browser_min_o(r),{width:w,height:v}=l.floating;let b,A;"top"===h||"bottom"===h?(b=h,A=y===(await(null==s.isRTL?void 0:s.isRTL(u.floating))?"start":"end")?"left":"right"):(A=h,b="end"===y?"top":"bottom");const R=v-p[b],P=w-p[A],E=!i.middlewareData.shift;let T=R,D=P;if(x){const t=w-p.left-p.right;D=y||E?f(P,t):t}else{const t=v-p.top-p.bottom;T=y||E?f(R,t):t}if(E&&!y){const t=m(p.left,0),e=m(p.right,0),n=m(p.top,0),o=m(p.bottom,0);x?D=w-2*(0!==t||0!==e?t+e:m(p.left,p.right)):T=v-2*(0!==n||0!==o?n+o:m(p.top,p.bottom))}await g({...i,availableWidth:D,availableHeight:T});const L=await s.getDimensions(u.floating);return w!==L.width||v!==L.height?{reset:{rects:!0}}:{}}}};
;// CONCATENATED MODULE: ./node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs
function floating_ui_dom_browser_min_n(t){var e;return(null==t||null==(e=t.ownerDocument)?void 0:e.defaultView)||window}function floating_ui_dom_browser_min_o(t){return floating_ui_dom_browser_min_n(t).getComputedStyle(t)}function floating_ui_dom_browser_min_i(t){return t instanceof floating_ui_dom_browser_min_n(t).Node}function r(t){return floating_ui_dom_browser_min_i(t)?(t.nodeName||"").toLowerCase():"#document"}function floating_ui_dom_browser_min_c(t){return t instanceof HTMLElement||t instanceof floating_ui_dom_browser_min_n(t).HTMLElement}function floating_ui_dom_browser_min_l(t){return"undefined"!=typeof ShadowRoot&&(t instanceof floating_ui_dom_browser_min_n(t).ShadowRoot||t instanceof ShadowRoot)}function s(t){const{overflow:e,overflowX:n,overflowY:i,display:r}=floating_ui_dom_browser_min_o(t);return/auto|scroll|overlay|hidden|clip/.test(e+i+n)&&!["inline","contents"].includes(r)}function floating_ui_dom_browser_min_f(t){return["table","td","th"].includes(r(t))}function floating_ui_dom_browser_min_u(t){const e=floating_ui_dom_browser_min_a(),n=floating_ui_dom_browser_min_o(t);return"none"!==n.transform||"none"!==n.perspective||!!n.containerType&&"normal"!==n.containerType||!e&&!!n.backdropFilter&&"none"!==n.backdropFilter||!e&&!!n.filter&&"none"!==n.filter||["transform","perspective","filter"].some((t=>(n.willChange||"").includes(t)))||["paint","layout","strict","content"].some((t=>(n.contain||"").includes(t)))}function floating_ui_dom_browser_min_a(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function floating_ui_dom_browser_min_d(t){return["html","body","#document"].includes(r(t))}const floating_ui_dom_browser_min_h=Math.min,floating_ui_dom_browser_min_p=Math.max,floating_ui_dom_browser_min_m=Math.round,floating_ui_dom_browser_min_g=Math.floor,floating_ui_dom_browser_min_y=t=>({x:t,y:t});function floating_ui_dom_browser_min_w(t){const e=floating_ui_dom_browser_min_o(t);let n=parseFloat(e.width)||0,i=parseFloat(e.height)||0;const r=floating_ui_dom_browser_min_c(t),l=r?t.offsetWidth:n,s=r?t.offsetHeight:i,f=floating_ui_dom_browser_min_m(n)!==l||floating_ui_dom_browser_min_m(i)!==s;return f&&(n=l,i=s),{width:n,height:i,$:f}}function floating_ui_dom_browser_min_x(t){return t instanceof Element||t instanceof floating_ui_dom_browser_min_n(t).Element}function floating_ui_dom_browser_min_v(t){return floating_ui_dom_browser_min_x(t)?t:t.contextElement}function floating_ui_dom_browser_min_b(t){const e=floating_ui_dom_browser_min_v(t);if(!floating_ui_dom_browser_min_c(e))return floating_ui_dom_browser_min_y(1);const n=e.getBoundingClientRect(),{width:o,height:i,$:r}=floating_ui_dom_browser_min_w(e);let l=(r?floating_ui_dom_browser_min_m(n.width):n.width)/o,s=(r?floating_ui_dom_browser_min_m(n.height):n.height)/i;return l&&Number.isFinite(l)||(l=1),s&&Number.isFinite(s)||(s=1),{x:l,y:s}}const floating_ui_dom_browser_min_L=floating_ui_dom_browser_min_y(0);function floating_ui_dom_browser_min_T(t){const e=floating_ui_dom_browser_min_n(t);return floating_ui_dom_browser_min_a()&&e.visualViewport?{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}:floating_ui_dom_browser_min_L}function floating_ui_dom_browser_min_R(e,o,i,r){void 0===o&&(o=!1),void 0===i&&(i=!1);const c=e.getBoundingClientRect(),l=floating_ui_dom_browser_min_v(e);let s=floating_ui_dom_browser_min_y(1);o&&(r?floating_ui_dom_browser_min_x(r)&&(s=floating_ui_dom_browser_min_b(r)):s=floating_ui_dom_browser_min_b(e));const f=function(t,e,o){return void 0===e&&(e=!1),!(!o||e&&o!==floating_ui_dom_browser_min_n(t))&&e}(l,i,r)?floating_ui_dom_browser_min_T(l):floating_ui_dom_browser_min_y(0);let u=(c.left+f.x)/s.x,a=(c.top+f.y)/s.y,d=c.width/s.x,h=c.height/s.y;if(l){const t=floating_ui_dom_browser_min_n(l),e=r&&floating_ui_dom_browser_min_x(r)?floating_ui_dom_browser_min_n(r):r;let o=t.frameElement;for(;o&&r&&e!==t;){const t=floating_ui_dom_browser_min_b(o),e=o.getBoundingClientRect(),i=getComputedStyle(o),r=e.left+(o.clientLeft+parseFloat(i.paddingLeft))*t.x,c=e.top+(o.clientTop+parseFloat(i.paddingTop))*t.y;u*=t.x,a*=t.y,d*=t.x,h*=t.y,u+=r,a+=c,o=floating_ui_dom_browser_min_n(o).frameElement}}return floating_ui_core_browser_min_s({width:d,height:h,x:u,y:a})}function floating_ui_dom_browser_min_E(t){return floating_ui_dom_browser_min_x(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.pageXOffset,scrollTop:t.pageYOffset}}function S(t){var e;return null==(e=(floating_ui_dom_browser_min_i(t)?t.ownerDocument:t.document)||window.document)?void 0:e.documentElement}function floating_ui_dom_browser_min_C(t){return floating_ui_dom_browser_min_R(S(t)).left+floating_ui_dom_browser_min_E(t).scrollLeft}function F(t){if("html"===r(t))return t;const e=t.assignedSlot||t.parentNode||floating_ui_dom_browser_min_l(t)&&t.host||S(t);return floating_ui_dom_browser_min_l(e)?e.host:e}function floating_ui_dom_browser_min_O(t){const e=F(t);return floating_ui_dom_browser_min_d(e)?t.ownerDocument?t.ownerDocument.body:t.body:floating_ui_dom_browser_min_c(e)&&s(e)?e:floating_ui_dom_browser_min_O(e)}function floating_ui_dom_browser_min_D(t,e){var o;void 0===e&&(e=[]);const i=floating_ui_dom_browser_min_O(t),r=i===(null==(o=t.ownerDocument)?void 0:o.body),c=floating_ui_dom_browser_min_n(i);return r?e.concat(c,c.visualViewport||[],s(i)?i:[]):e.concat(i,floating_ui_dom_browser_min_D(i))}function H(e,i,r){let l;if("viewport"===i)l=function(t,e){const o=floating_ui_dom_browser_min_n(t),i=S(t),r=o.visualViewport;let c=i.clientWidth,l=i.clientHeight,s=0,f=0;if(r){c=r.width,l=r.height;const t=floating_ui_dom_browser_min_a();(!t||t&&"fixed"===e)&&(s=r.offsetLeft,f=r.offsetTop)}return{width:c,height:l,x:s,y:f}}(e,r);else if("document"===i)l=function(t){const e=S(t),n=floating_ui_dom_browser_min_E(t),i=t.ownerDocument.body,r=floating_ui_dom_browser_min_p(e.scrollWidth,e.clientWidth,i.scrollWidth,i.clientWidth),c=floating_ui_dom_browser_min_p(e.scrollHeight,e.clientHeight,i.scrollHeight,i.clientHeight);let l=-n.scrollLeft+floating_ui_dom_browser_min_C(t);const s=-n.scrollTop;return"rtl"===floating_ui_dom_browser_min_o(i).direction&&(l+=floating_ui_dom_browser_min_p(e.clientWidth,i.clientWidth)-r),{width:r,height:c,x:l,y:s}}(S(e));else if(floating_ui_dom_browser_min_x(i))l=function(t,e){const n=floating_ui_dom_browser_min_R(t,!0,"fixed"===e),o=n.top+t.clientTop,i=n.left+t.clientLeft,r=floating_ui_dom_browser_min_c(t)?floating_ui_dom_browser_min_b(t):floating_ui_dom_browser_min_y(1);return{width:t.clientWidth*r.x,height:t.clientHeight*r.y,x:i*r.x,y:o*r.y}}(i,r);else{const t=floating_ui_dom_browser_min_T(e);l={...i,x:i.x-t.x,y:i.y-t.y}}return floating_ui_core_browser_min_s(l)}function W(t,e){const n=F(t);return!(n===e||!floating_ui_dom_browser_min_x(n)||floating_ui_dom_browser_min_d(n))&&("fixed"===floating_ui_dom_browser_min_o(n).position||W(n,e))}function M(t,e,n){const o=floating_ui_dom_browser_min_c(e),i=S(e),l="fixed"===n,f=floating_ui_dom_browser_min_R(t,!0,l,e);let u={scrollLeft:0,scrollTop:0};const a=floating_ui_dom_browser_min_y(0);if(o||!o&&!l)if(("body"!==r(e)||s(i))&&(u=floating_ui_dom_browser_min_E(e)),floating_ui_dom_browser_min_c(e)){const t=floating_ui_dom_browser_min_R(e,!0,l,e);a.x=t.x+e.clientLeft,a.y=t.y+e.clientTop}else i&&(a.x=floating_ui_dom_browser_min_C(i));return{x:f.left+u.scrollLeft-a.x,y:f.top+u.scrollTop-a.y,width:f.width,height:f.height}}function z(t,e){return floating_ui_dom_browser_min_c(t)&&"fixed"!==floating_ui_dom_browser_min_o(t).position?e?e(t):t.offsetParent:null}function floating_ui_dom_browser_min_P(t,e){const i=floating_ui_dom_browser_min_n(t);if(!floating_ui_dom_browser_min_c(t))return i;let l=z(t,e);for(;l&&floating_ui_dom_browser_min_f(l)&&"static"===floating_ui_dom_browser_min_o(l).position;)l=z(l,e);return l&&("html"===r(l)||"body"===r(l)&&"static"===floating_ui_dom_browser_min_o(l).position&&!floating_ui_dom_browser_min_u(l))?i:l||function(t){let e=F(t);for(;floating_ui_dom_browser_min_c(e)&&!floating_ui_dom_browser_min_d(e);){if(floating_ui_dom_browser_min_u(e))return e;e=F(e)}return null}(t)||i}const V={convertOffsetParentRelativeRectToViewportRelativeRect:function(t){let{rect:e,offsetParent:n,strategy:o}=t;const i=floating_ui_dom_browser_min_c(n),l=S(n);if(n===l)return e;let f={scrollLeft:0,scrollTop:0},u=floating_ui_dom_browser_min_y(1);const a=floating_ui_dom_browser_min_y(0);if((i||!i&&"fixed"!==o)&&(("body"!==r(n)||s(l))&&(f=floating_ui_dom_browser_min_E(n)),floating_ui_dom_browser_min_c(n))){const t=floating_ui_dom_browser_min_R(n);u=floating_ui_dom_browser_min_b(n),a.x=t.x+n.clientLeft,a.y=t.y+n.clientTop}return{width:e.width*u.x,height:e.height*u.y,x:e.x*u.x-f.scrollLeft*u.x+a.x,y:e.y*u.y-f.scrollTop*u.y+a.y}},getDocumentElement:S,getClippingRect:function(t){let{element:e,boundary:n,rootBoundary:i,strategy:c}=t;const l=[..."clippingAncestors"===n?function(t,e){const n=e.get(t);if(n)return n;let i=floating_ui_dom_browser_min_D(t).filter((t=>floating_ui_dom_browser_min_x(t)&&"body"!==r(t))),c=null;const l="fixed"===floating_ui_dom_browser_min_o(t).position;let f=l?F(t):t;for(;floating_ui_dom_browser_min_x(f)&&!floating_ui_dom_browser_min_d(f);){const e=floating_ui_dom_browser_min_o(f),n=floating_ui_dom_browser_min_u(f);n||"fixed"!==e.position||(c=null),(l?!n&&!c:!n&&"static"===e.position&&c&&["absolute","fixed"].includes(c.position)||s(f)&&!n&&W(t,f))?i=i.filter((t=>t!==f)):c=e,f=F(f)}return e.set(t,i),i}(e,this._c):[].concat(n),i],f=l[0],a=l.reduce(((t,n)=>{const o=H(e,n,c);return t.top=floating_ui_dom_browser_min_p(o.top,t.top),t.right=floating_ui_dom_browser_min_h(o.right,t.right),t.bottom=floating_ui_dom_browser_min_h(o.bottom,t.bottom),t.left=floating_ui_dom_browser_min_p(o.left,t.left),t}),H(e,f,c));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}},getOffsetParent:floating_ui_dom_browser_min_P,getElementRects:async function(t){let{reference:e,floating:n,strategy:o}=t;const i=this.getOffsetParent||floating_ui_dom_browser_min_P,r=this.getDimensions;return{reference:M(e,await i(n),o),floating:{x:0,y:0,...await r(n)}}},getClientRects:function(t){return Array.from(t.getClientRects())},getDimensions:function(t){return floating_ui_dom_browser_min_w(t)},getScale:floating_ui_dom_browser_min_b,isElement:floating_ui_dom_browser_min_x,isRTL:function(t){return"rtl"===getComputedStyle(t).direction}};function floating_ui_dom_browser_min_A(t,e,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:c="function"==typeof ResizeObserver,layoutShift:l="function"==typeof IntersectionObserver,animationFrame:s=!1}=o,f=floating_ui_dom_browser_min_v(t),u=i||r?[...f?floating_ui_dom_browser_min_D(f):[],...floating_ui_dom_browser_min_D(e)]:[];u.forEach((t=>{i&&t.addEventListener("scroll",n,{passive:!0}),r&&t.addEventListener("resize",n)}));const a=f&&l?function(t,e){let n,o=null;const i=S(t);function r(){clearTimeout(n),o&&o.disconnect(),o=null}return function c(l,s){void 0===l&&(l=!1),void 0===s&&(s=1),r();const{left:f,top:u,width:a,height:d}=t.getBoundingClientRect();if(l||e(),!a||!d)return;const m={rootMargin:-floating_ui_dom_browser_min_g(u)+"px "+-floating_ui_dom_browser_min_g(i.clientWidth-(f+a))+"px "+-floating_ui_dom_browser_min_g(i.clientHeight-(u+d))+"px "+-floating_ui_dom_browser_min_g(f)+"px",threshold:floating_ui_dom_browser_min_p(0,floating_ui_dom_browser_min_h(1,s))||1};let y=!0;function w(t){const e=t[0].intersectionRatio;if(e!==s){if(!y)return c();e?c(!1,e):n=setTimeout((()=>{c(!1,1e-7)}),100)}y=!1}try{o=new IntersectionObserver(w,{...m,root:i.ownerDocument})}catch(t){o=new IntersectionObserver(w,m)}o.observe(t)}(!0),r}(f,n):null;let d,m=-1,y=null;c&&(y=new ResizeObserver((t=>{let[o]=t;o&&o.target===f&&y&&(y.unobserve(e),cancelAnimationFrame(m),m=requestAnimationFrame((()=>{y&&y.observe(e)}))),n()})),f&&!s&&y.observe(f),y.observe(e));let w=s?floating_ui_dom_browser_min_R(t):null;return s&&function e(){const o=floating_ui_dom_browser_min_R(t);!w||o.x===w.x&&o.y===w.y&&o.width===w.width&&o.height===w.height||n();w=o,d=requestAnimationFrame(e)}(),n(),()=>{u.forEach((t=>{i&&t.removeEventListener("scroll",n),r&&t.removeEventListener("resize",n)})),a&&a(),y&&y.disconnect(),y=null,s&&cancelAnimationFrame(d)}}const floating_ui_dom_browser_min_B=(t,n,o)=>{const i=new Map,r={platform:V,...o},c={...r.platform,_c:i};return floating_ui_core_browser_min_r(t,n,{...r,platform:c})};
;// CONCATENATED MODULE: external "ReactDOM"
var external_ReactDOM_namespaceObject = window["ReactDOM"];
var external_ReactDOM_default = /*#__PURE__*/__webpack_require__.n(external_ReactDOM_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js
var index = typeof document !== 'undefined' ? external_React_.useLayoutEffect : external_React_.useEffect;
// Fork of `fast-deep-equal` that only does the comparisons we need and compares
// functions
function deepEqual(a, b) {
if (a === b) {
return true;
}
if (typeof a !== typeof b) {
return false;
}
if (typeof a === 'function' && a.toString() === b.toString()) {
return true;
}
let length, i, keys;
if (a && b && typeof a == 'object') {
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;) {
if (!deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) {
return false;
}
for (i = length; i-- !== 0;) {
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
return false;
}
}
for (i = length; i-- !== 0;) {
const key = keys[i];
if (key === '_owner' && a.$$typeof) {
continue;
}
if (!deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
return a !== a && b !== b;
}
function useLatestRef(value) {
const ref = external_React_.useRef(value);
index(() => {
ref.current = value;
});
return ref;
}
function useFloating(_temp) {
let {
middleware,
placement = 'bottom',
strategy = 'absolute',
whileElementsMounted
} = _temp === void 0 ? {} : _temp;
const [data, setData] = external_React_.useState({
// Setting these to `null` will allow the consumer to determine if
// `computePosition()` has run yet
x: null,
y: null,
strategy,
placement,
middlewareData: {}
});
const [latestMiddleware, setLatestMiddleware] = external_React_.useState(middleware);
if (!deepEqual(latestMiddleware == null ? void 0 : latestMiddleware.map(_ref => {
let {
name,
options
} = _ref;
return {
name,
options
};
}), middleware == null ? void 0 : middleware.map(_ref2 => {
let {
name,
options
} = _ref2;
return {
name,
options
};
}))) {
setLatestMiddleware(middleware);
}
const reference = external_React_.useRef(null);
const floating = external_React_.useRef(null);
const cleanupRef = external_React_.useRef(null);
const dataRef = external_React_.useRef(data);
const whileElementsMountedRef = useLatestRef(whileElementsMounted);
const update = external_React_.useCallback(() => {
if (!reference.current || !floating.current) {
return;
}
floating_ui_dom_browser_min_B(reference.current, floating.current, {
middleware: latestMiddleware,
placement,
strategy
}).then(data => {
if (isMountedRef.current && !deepEqual(dataRef.current, data)) {
dataRef.current = data;
external_ReactDOM_namespaceObject.flushSync(() => {
setData(data);
});
}
});
}, [latestMiddleware, placement, strategy]);
index(() => {
// Skip first update
if (isMountedRef.current) {
update();
}
}, [update]);
const isMountedRef = external_React_.useRef(false);
index(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
const runElementMountCallback = external_React_.useCallback(() => {
if (typeof cleanupRef.current === 'function') {
cleanupRef.current();
cleanupRef.current = null;
}
if (reference.current && floating.current) {
if (whileElementsMountedRef.current) {
const cleanupFn = whileElementsMountedRef.current(reference.current, floating.current, update);
cleanupRef.current = cleanupFn;
} else {
update();
}
}
}, [update, whileElementsMountedRef]);
const setReference = external_React_.useCallback(node => {
reference.current = node;
runElementMountCallback();
}, [runElementMountCallback]);
const setFloating = external_React_.useCallback(node => {
floating.current = node;
runElementMountCallback();
}, [runElementMountCallback]);
const refs = external_React_.useMemo(() => ({
reference,
floating
}), []);
return external_React_.useMemo(() => ({ ...data,
update,
refs,
reference: setReference,
floating: setFloating
}), [data, update, refs, setReference, setFloating]);
}
/**
* Positions an inner element of the floating element such that it is centered
* to the reference element.
* This wraps the core `arrow` middleware to allow React refs as the element.
* @see https://floating-ui.com/docs/arrow
*/
const arrow = options => {
const {
element,
padding
} = options;
function isRef(value) {
return Object.prototype.hasOwnProperty.call(value, 'current');
}
return {
name: 'arrow',
options,
fn(args) {
if (isRef(element)) {
if (element.current != null) {
return g({
element: element.current,
padding
}).fn(args);
}
return {};
} else if (element) {
return g({
element,
padding
}).fn(args);
}
return {};
}
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-browser.mjs
const isBrowser = typeof document !== "undefined";
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs
// Does this device prefer reduced motion? Returns `null` server-side.
const prefersReducedMotion = { current: null };
const hasReducedMotionListener = { current: false };
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs
function initPrefersReducedMotion() {
hasReducedMotionListener.current = true;
if (!isBrowser)
return;
if (window.matchMedia) {
const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)");
const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches);
motionMediaQuery.addListener(setReducedMotionPreferences);
setReducedMotionPreferences();
}
else {
prefersReducedMotion.current = false;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs
/**
* A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting.
*
* This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing
* `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion.
*
* It will actively respond to changes and re-render your components with the latest setting.
*
* ```jsx
* export function Sidebar({ isOpen }) {
* const shouldReduceMotion = useReducedMotion()
* const closedX = shouldReduceMotion ? 0 : "-100%"
*
* return (
* <motion.div animate={{
* opacity: isOpen ? 1 : 0,
* x: isOpen ? 0 : closedX
* }} />
* )
* }
* ```
*
* @return boolean
*
* @public
*/
function useReducedMotion() {
/**
* Lazy initialisation of prefersReducedMotion
*/
!hasReducedMotionListener.current && initPrefersReducedMotion();
const [shouldReduceMotion] = (0,external_React_.useState)(prefersReducedMotion.current);
if (false) {}
/**
* TODO See if people miss automatically updating shouldReduceMotion setting
*/
return shouldReduceMotion;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs
/**
* @public
*/
const MotionConfigContext = (0,external_React_.createContext)({
transformPagePoint: (p) => p,
isStatic: false,
reducedMotion: "never",
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionContext/index.mjs
const MotionContext = (0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/PresenceContext.mjs
/**
* @public
*/
const PresenceContext_PresenceContext = (0,external_React_.createContext)(null);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs
const useIsomorphicLayoutEffect = isBrowser ? external_React_.useLayoutEffect : external_React_.useEffect;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/LazyContext.mjs
const LazyContext = (0,external_React_.createContext)({ strict: false });
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs
function useVisualElement(Component, visualState, props, createVisualElement) {
const { visualElement: parent } = (0,external_React_.useContext)(MotionContext);
const lazyContext = (0,external_React_.useContext)(LazyContext);
const presenceContext = (0,external_React_.useContext)(PresenceContext_PresenceContext);
const reducedMotionConfig = (0,external_React_.useContext)(MotionConfigContext).reducedMotion;
const visualElementRef = (0,external_React_.useRef)();
/**
* If we haven't preloaded a renderer, check to see if we have one lazy-loaded
*/
createVisualElement = createVisualElement || lazyContext.renderer;
if (!visualElementRef.current && createVisualElement) {
visualElementRef.current = createVisualElement(Component, {
visualState,
parent,
props,
presenceContext,
blockInitialAnimation: presenceContext
? presenceContext.initial === false
: false,
reducedMotionConfig,
});
}
const visualElement = visualElementRef.current;
(0,external_React_.useInsertionEffect)(() => {
visualElement && visualElement.update(props, presenceContext);
});
useIsomorphicLayoutEffect(() => {
visualElement && visualElement.render();
});
(0,external_React_.useEffect)(() => {
visualElement && visualElement.updateFeatures();
});
/**
* Ideally this function would always run in a useEffect.
*
* However, if we have optimised appear animations to handoff from,
* it needs to happen synchronously to ensure there's no flash of
* incorrect styles in the event of a hydration error.
*
* So if we detect a situtation where optimised appear animations
* are running, we use useLayoutEffect to trigger animations.
*/
const useAnimateChangesEffect = window.HandoffAppearAnimations
? useIsomorphicLayoutEffect
: external_React_.useEffect;
useAnimateChangesEffect(() => {
if (visualElement && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
});
return visualElement;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-ref-object.mjs
function is_ref_object_isRefObject(ref) {
return (typeof ref === "object" &&
Object.prototype.hasOwnProperty.call(ref, "current"));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs
/**
* Creates a ref function that, when called, hydrates the provided
* external ref and VisualElement.
*/
function useMotionRef(visualState, visualElement, externalRef) {
return (0,external_React_.useCallback)((instance) => {
instance && visualState.mount && visualState.mount(instance);
if (visualElement) {
instance
? visualElement.mount(instance)
: visualElement.unmount();
}
if (externalRef) {
if (typeof externalRef === "function") {
externalRef(instance);
}
else if (is_ref_object_isRefObject(externalRef)) {
externalRef.current = instance;
}
}
},
/**
* Only pass a new ref callback to React if we've received a visual element
* factory. Otherwise we'll be mounting/remounting every time externalRef
* or other dependencies change.
*/
[visualElement]);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs
/**
* Decides if the supplied variable is variant label
*/
function isVariantLabel(v) {
return typeof v === "string" || Array.isArray(v);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs
function isAnimationControls(v) {
return typeof v === "object" && typeof v.start === "function";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/variant-props.mjs
const variantPriorityOrder = [
"animate",
"whileInView",
"whileFocus",
"whileHover",
"whileTap",
"whileDrag",
"exit",
];
const variantProps = ["initial", ...variantPriorityOrder];
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs
function isControllingVariants(props) {
return (isAnimationControls(props.animate) ||
variantProps.some((name) => isVariantLabel(props[name])));
}
function isVariantNode(props) {
return Boolean(isControllingVariants(props) || props.variants);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs
function getCurrentTreeVariants(props, context) {
if (isControllingVariants(props)) {
const { initial, animate } = props;
return {
initial: initial === false || isVariantLabel(initial)
? initial
: undefined,
animate: isVariantLabel(animate) ? animate : undefined,
};
}
return props.inherit !== false ? context : {};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionContext/create.mjs
function useCreateMotionContext(props) {
const { initial, animate } = getCurrentTreeVariants(props, (0,external_React_.useContext)(MotionContext));
return (0,external_React_.useMemo)(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);
}
function variantLabelsAsDependency(prop) {
return Array.isArray(prop) ? prop.join(" ") : prop;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/definitions.mjs
const featureProps = {
animation: [
"animate",
"variants",
"whileHover",
"whileTap",
"exit",
"whileInView",
"whileFocus",
"whileDrag",
],
exit: ["exit"],
drag: ["drag", "dragControls"],
focus: ["whileFocus"],
hover: ["whileHover", "onHoverStart", "onHoverEnd"],
tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"],
pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"],
inView: ["whileInView", "onViewportEnter", "onViewportLeave"],
layout: ["layout", "layoutId"],
};
const featureDefinitions = {};
for (const key in featureProps) {
featureDefinitions[key] = {
isEnabled: (props) => featureProps[key].some((name) => !!props[name]),
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/load-features.mjs
function loadFeatures(features) {
for (const key in features) {
featureDefinitions[key] = {
...featureDefinitions[key],
...features[key],
};
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-constant.mjs
/**
* Creates a constant value over the lifecycle of a component.
*
* Even if `useMemo` is provided an empty array as its final argument, it doesn't offer
* a guarantee that it won't re-run for performance reasons later on. By using `useConstant`
* you can ensure that initialisers don't execute twice or more.
*/
function useConstant(init) {
const ref = (0,external_React_.useRef)(null);
if (ref.current === null) {
ref.current = init();
}
return ref.current;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/state.mjs
/**
* This should only ever be modified on the client otherwise it'll
* persist through server requests. If we need instanced states we
* could lazy-init via root.
*/
const globalProjectionState = {
/**
* Global flag as to whether the tree has animated since the last time
* we resized the window
*/
hasAnimatedSinceResize: true,
/**
* We set this to true once, on the first update. Any nodes added to the tree beyond that
* update will be given a `data-projection-id` attribute.
*/
hasEverUpdated: false,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/id.mjs
let id = 1;
function useProjectionId() {
return useConstant(() => {
if (globalProjectionState.hasEverUpdated) {
return id++;
}
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs
const LayoutGroupContext = (0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs
/**
* Internal, exported only for usage in Framer
*/
const SwitchLayoutGroupContext = (0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/symbol.mjs
const motionComponentSymbol = Symbol.for("motionComponentSymbol");
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/index.mjs
/**
* Create a `motion` component.
*
* This function accepts a Component argument, which can be either a string (ie "div"
* for `motion.div`), or an actual React component.
*
* Alongside this is a config option which provides a way of rendering the provided
* component "offline", or outside the React render cycle.
*/
function motion_createMotionComponent({ preloadedFeatures, createVisualElement, useRender, useVisualState, Component, }) {
preloadedFeatures && loadFeatures(preloadedFeatures);
function MotionComponent(props, externalRef) {
/**
* If we need to measure the element we load this functionality in a
* separate class component in order to gain access to getSnapshotBeforeUpdate.
*/
let MeasureLayout;
const configAndProps = {
...(0,external_React_.useContext)(MotionConfigContext),
...props,
layoutId: useLayoutId(props),
};
const { isStatic } = configAndProps;
const context = useCreateMotionContext(props);
/**
* Create a unique projection ID for this component. If a new component is added
* during a layout animation we'll use this to query the DOM and hydrate its ref early, allowing
* us to measure it as soon as any layout effect flushes pending layout animations.
*
* Performance note: It'd be better not to have to search the DOM for these elements.
* For newly-entering components it could be enough to only correct treeScale, in which
* case we could mount in a scale-correction mode. This wouldn't be enough for
* shared element transitions however. Perhaps for those we could revert to a root node
* that gets forceRendered and layout animations are triggered on its layout effect.
*/
const projectionId = isStatic ? undefined : useProjectionId();
const visualState = useVisualState(props, isStatic);
if (!isStatic && isBrowser) {
/**
* Create a VisualElement for this component. A VisualElement provides a common
* interface to renderer-specific APIs (ie DOM/Three.js etc) as well as
* providing a way of rendering to these APIs outside of the React render loop
* for more performant animations and interactions
*/
context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement);
/**
* Load Motion gesture and animation features. These are rendered as renderless
* components so each feature can optionally make use of React lifecycle methods.
*/
const initialLayoutGroupConfig = (0,external_React_.useContext)(SwitchLayoutGroupContext);
const isStrict = (0,external_React_.useContext)(LazyContext).strict;
if (context.visualElement) {
MeasureLayout = context.visualElement.loadFeatures(
// Note: Pass the full new combined props to correctly re-render dynamic feature components.
configAndProps, isStrict, preloadedFeatures, projectionId, initialLayoutGroupConfig);
}
}
/**
* The mount order and hierarchy is specific to ensure our element ref
* is hydrated by the time features fire their effects.
*/
return (external_React_.createElement(MotionContext.Provider, { value: context },
MeasureLayout && context.visualElement ? (external_React_.createElement(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null,
useRender(Component, props, projectionId, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, context.visualElement)));
}
const ForwardRefComponent = (0,external_React_.forwardRef)(MotionComponent);
ForwardRefComponent[motionComponentSymbol] = Component;
return ForwardRefComponent;
}
function useLayoutId({ layoutId }) {
const layoutGroupId = (0,external_React_.useContext)(LayoutGroupContext).id;
return layoutGroupId && layoutId !== undefined
? layoutGroupId + "-" + layoutId
: layoutId;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/motion-proxy.mjs
/**
* Convert any React component into a `motion` component. The provided component
* **must** use `React.forwardRef` to the underlying DOM component you want to animate.
*
* ```jsx
* const Component = React.forwardRef((props, ref) => {
* return <div ref={ref} />
* })
*
* const MotionComponent = motion(Component)
* ```
*
* @public
*/
function createMotionProxy(createConfig) {
function custom(Component, customMotionComponentConfig = {}) {
return motion_createMotionComponent(createConfig(Component, customMotionComponentConfig));
}
if (typeof Proxy === "undefined") {
return custom;
}
/**
* A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc.
* Rather than generating them anew every render.
*/
const componentCache = new Map();
return new Proxy(custom, {
/**
* Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc.
* The prop name is passed through as `key` and we can use that to generate a `motion`
* DOM component with that name.
*/
get: (_target, key) => {
/**
* If this element doesn't exist in the component cache, create it and cache.
*/
if (!componentCache.has(key)) {
componentCache.set(key, custom(key));
}
return componentCache.get(key);
},
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs
/**
* We keep these listed seperately as we use the lowercase tag names as part
* of the runtime bundle to detect SVG components
*/
const lowercaseSVGElements = [
"animate",
"circle",
"defs",
"desc",
"ellipse",
"g",
"image",
"line",
"filter",
"marker",
"mask",
"metadata",
"path",
"pattern",
"polygon",
"polyline",
"rect",
"stop",
"switch",
"symbol",
"svg",
"text",
"tspan",
"use",
"view",
];
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs
function isSVGComponent(Component) {
if (
/**
* If it's not a string, it's a custom React component. Currently we only support
* HTML custom React components.
*/
typeof Component !== "string" ||
/**
* If it contains a dash, the element is a custom HTML webcomponent.
*/
Component.includes("-")) {
return false;
}
else if (
/**
* If it's in our list of lowercase SVG tags, it's an SVG component
*/
lowercaseSVGElements.indexOf(Component) > -1 ||
/**
* If it contains a capital letter, it's an SVG component
*/
/[A-Z]/.test(Component)) {
return true;
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs
const scaleCorrectors = {};
function addScaleCorrector(correctors) {
Object.assign(scaleCorrectors, correctors);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/transform.mjs
/**
* Generate a list of every possible transform key.
*/
const transformPropOrder = [
"transformPerspective",
"x",
"y",
"z",
"translateX",
"translateY",
"translateZ",
"scale",
"scaleX",
"scaleY",
"rotate",
"rotateX",
"rotateY",
"rotateZ",
"skew",
"skewX",
"skewY",
];
/**
* A quick lookup for transform props.
*/
const transformProps = new Set(transformPropOrder);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs
function isForcedMotionValue(key, { layout, layoutId }) {
return (transformProps.has(key) ||
key.startsWith("origin") ||
((layout || layoutId !== undefined) &&
(!!scaleCorrectors[key] || key === "opacity")));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/utils/is-motion-value.mjs
const isMotionValue = (value) => Boolean(value && value.getVelocity);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs
const translateAlias = {
x: "translateX",
y: "translateY",
z: "translateZ",
transformPerspective: "perspective",
};
const numTransforms = transformPropOrder.length;
/**
* Build a CSS transform style from individual x/y/scale etc properties.
*
* This outputs with a default order of transforms/scales/rotations, this can be customised by
* providing a transformTemplate function.
*/
function buildTransform(transform, { enableHardwareAcceleration = true, allowTransformNone = true, }, transformIsDefault, transformTemplate) {
// The transform string we're going to build into.
let transformString = "";
/**
* Loop over all possible transforms in order, adding the ones that
* are present to the transform string.
*/
for (let i = 0; i < numTransforms; i++) {
const key = transformPropOrder[i];
if (transform[key] !== undefined) {
const transformName = translateAlias[key] || key;
transformString += `${transformName}(${transform[key]}) `;
}
}
if (enableHardwareAcceleration && !transform.z) {
transformString += "translateZ(0)";
}
transformString = transformString.trim();
// If we have a custom `transform` template, pass our transform values and
// generated transformString to that before returning
if (transformTemplate) {
transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
}
else if (allowTransformNone && transformIsDefault) {
transformString = "none";
}
return transformString;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/is-css-variable.mjs
const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
const isCSSVariableName = checkStringStartsWith("--");
const isCSSVariableToken = checkStringStartsWith("var(--");
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/get-as-type.mjs
/**
* Provided a value and a ValueType, returns the value as that value type.
*/
const getValueAsType = (value, type) => {
return type && typeof value === "number"
? type.transform(value)
: value;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/clamp.mjs
const clamp = (min, max, v) => Math.min(Math.max(v, min), max);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/numbers/index.mjs
const number = {
test: (v) => typeof v === "number",
parse: parseFloat,
transform: (v) => v,
};
const alpha = {
...number,
transform: (v) => clamp(0, 1, v),
};
const scale = {
...number,
default: 1,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/utils.mjs
/**
* TODO: When we move from string as a source of truth to data models
* everything in this folder should probably be referred to as models vs types
*/
// If this number is a decimal, make it just five decimal places
// to avoid exponents
const sanitize = (v) => Math.round(v * 100000) / 100000;
const floatRegex = /(-)?([\d]*\.?[\d])+/g;
const colorRegex = /(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi;
const singleColorRegex = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;
function isString(v) {
return typeof v === "string";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/numbers/units.mjs
const createUnitType = (unit) => ({
test: (v) => isString(v) && v.endsWith(unit) && v.split(" ").length === 1,
parse: parseFloat,
transform: (v) => `${v}${unit}`,
});
const degrees = createUnitType("deg");
const percent = createUnitType("%");
const px = createUnitType("px");
const vh = createUnitType("vh");
const vw = createUnitType("vw");
const progressPercentage = {
...percent,
parse: (v) => percent.parse(v) / 100,
transform: (v) => percent.transform(v * 100),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/type-int.mjs
const type_int_int = {
...number,
transform: Math.round,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/number.mjs
const numberValueTypes = {
// Border props
borderWidth: px,
borderTopWidth: px,
borderRightWidth: px,
borderBottomWidth: px,
borderLeftWidth: px,
borderRadius: px,
radius: px,
borderTopLeftRadius: px,
borderTopRightRadius: px,
borderBottomRightRadius: px,
borderBottomLeftRadius: px,
// Positioning props
width: px,
maxWidth: px,
height: px,
maxHeight: px,
size: px,
top: px,
right: px,
bottom: px,
left: px,
// Spacing props
padding: px,
paddingTop: px,
paddingRight: px,
paddingBottom: px,
paddingLeft: px,
margin: px,
marginTop: px,
marginRight: px,
marginBottom: px,
marginLeft: px,
// Transform props
rotate: degrees,
rotateX: degrees,
rotateY: degrees,
rotateZ: degrees,
scale: scale,
scaleX: scale,
scaleY: scale,
scaleZ: scale,
skew: degrees,
skewX: degrees,
skewY: degrees,
distance: px,
translateX: px,
translateY: px,
translateZ: px,
x: px,
y: px,
z: px,
perspective: px,
transformPerspective: px,
opacity: alpha,
originX: progressPercentage,
originY: progressPercentage,
originZ: px,
// Misc
zIndex: type_int_int,
// SVG
fillOpacity: alpha,
strokeOpacity: alpha,
numOctaves: type_int_int,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs
function buildHTMLStyles(state, latestValues, options, transformTemplate) {
const { style, vars, transform, transformOrigin } = state;
// Track whether we encounter any transform or transformOrigin values.
let hasTransform = false;
let hasTransformOrigin = false;
// Does the calculated transform essentially equal "none"?
let transformIsNone = true;
/**
* Loop over all our latest animated values and decide whether to handle them
* as a style or CSS variable.
*
* Transforms and transform origins are kept seperately for further processing.
*/
for (const key in latestValues) {
const value = latestValues[key];
/**
* If this is a CSS variable we don't do any further processing.
*/
if (isCSSVariableName(key)) {
vars[key] = value;
continue;
}
// Convert the value to its default value type, ie 0 -> "0px"
const valueType = numberValueTypes[key];
const valueAsType = getValueAsType(value, valueType);
if (transformProps.has(key)) {
// If this is a transform, flag to enable further transform processing
hasTransform = true;
transform[key] = valueAsType;
// If we already know we have a non-default transform, early return
if (!transformIsNone)
continue;
// Otherwise check to see if this is a default transform
if (value !== (valueType.default || 0))
transformIsNone = false;
}
else if (key.startsWith("origin")) {
// If this is a transform origin, flag and enable further transform-origin processing
hasTransformOrigin = true;
transformOrigin[key] = valueAsType;
}
else {
style[key] = valueAsType;
}
}
if (!latestValues.transform) {
if (hasTransform || transformTemplate) {
style.transform = buildTransform(state.transform, options, transformIsNone, transformTemplate);
}
else if (style.transform) {
/**
* If we have previously created a transform but currently don't have any,
* reset transform style to none.
*/
style.transform = "none";
}
}
/**
* Build a transformOrigin style. Uses the same defaults as the browser for
* undefined origins.
*/
if (hasTransformOrigin) {
const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin;
style.transformOrigin = `${originX} ${originY} ${originZ}`;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs
const createHtmlRenderState = () => ({
style: {},
transform: {},
transformOrigin: {},
vars: {},
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/use-props.mjs
function copyRawValuesOnly(target, source, props) {
for (const key in source) {
if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) {
target[key] = source[key];
}
}
}
function useInitialMotionValues({ transformTemplate }, visualState, isStatic) {
return (0,external_React_.useMemo)(() => {
const state = createHtmlRenderState();
buildHTMLStyles(state, visualState, { enableHardwareAcceleration: !isStatic }, transformTemplate);
return Object.assign({}, state.vars, state.style);
}, [visualState]);
}
function useStyle(props, visualState, isStatic) {
const styleProp = props.style || {};
const style = {};
/**
* Copy non-Motion Values straight into style
*/
copyRawValuesOnly(style, styleProp, props);
Object.assign(style, useInitialMotionValues(props, visualState, isStatic));
return props.transformValues ? props.transformValues(style) : style;
}
function useHTMLProps(props, visualState, isStatic) {
// The `any` isn't ideal but it is the type of createElement props argument
const htmlProps = {};
const style = useStyle(props, visualState, isStatic);
if (props.drag && props.dragListener !== false) {
// Disable the ghost element when a user drags
htmlProps.draggable = false;
// Disable text selection
style.userSelect =
style.WebkitUserSelect =
style.WebkitTouchCallout =
"none";
// Disable scrolling on the draggable direction
style.touchAction =
props.drag === true
? "none"
: `pan-${props.drag === "x" ? "y" : "x"}`;
}
if (props.tabIndex === undefined &&
(props.onTap || props.onTapStart || props.whileTap)) {
htmlProps.tabIndex = 0;
}
htmlProps.style = style;
return htmlProps;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs
/**
* A list of all valid MotionProps.
*
* @privateRemarks
* This doesn't throw if a `MotionProp` name is missing - it should.
*/
const validMotionProps = new Set([
"animate",
"exit",
"variants",
"initial",
"style",
"values",
"variants",
"transition",
"transformTemplate",
"transformValues",
"custom",
"inherit",
"onLayoutAnimationStart",
"onLayoutAnimationComplete",
"onLayoutMeasure",
"onBeforeLayoutMeasure",
"onAnimationStart",
"onAnimationComplete",
"onUpdate",
"onDragStart",
"onDrag",
"onDragEnd",
"onMeasureDragConstraints",
"onDirectionLock",
"onDragTransitionEnd",
"_dragX",
"_dragY",
"onHoverStart",
"onHoverEnd",
"onViewportEnter",
"onViewportLeave",
"ignoreStrict",
"viewport",
]);
/**
* Check whether a prop name is a valid `MotionProp` key.
*
* @param key - Name of the property to check
* @returns `true` is key is a valid `MotionProp`.
*
* @public
*/
function isValidMotionProp(key) {
return (key.startsWith("while") ||
(key.startsWith("drag") && key !== "draggable") ||
key.startsWith("layout") ||
key.startsWith("onTap") ||
key.startsWith("onPan") ||
validMotionProps.has(key));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs
let shouldForward = (key) => !isValidMotionProp(key);
function loadExternalIsValidProp(isValidProp) {
if (!isValidProp)
return;
// Explicitly filter our events
shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key);
}
/**
* Emotion and Styled Components both allow users to pass through arbitrary props to their components
* to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which
* of these should be passed to the underlying DOM node.
*
* However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props
* as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props
* passed through the `custom` prop so it doesn't *need* the payload or computational overhead of
* `@emotion/is-prop-valid`, however to fix this problem we need to use it.
*
* By making it an optionalDependency we can offer this functionality only in the situations where it's
* actually required.
*/
try {
/**
* We attempt to import this package but require won't be defined in esm environments, in that case
* isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed
* in favour of explicit injection.
*/
loadExternalIsValidProp(require("@emotion/is-prop-valid").default);
}
catch (_a) {
// We don't need to actually do anything here - the fallback is the existing `isPropValid`.
}
function filterProps(props, isDom, forwardMotionProps) {
const filteredProps = {};
for (const key in props) {
/**
* values is considered a valid prop by Emotion, so if it's present
* this will be rendered out to the DOM unless explicitly filtered.
*
* We check the type as it could be used with the `feColorMatrix`
* element, which we support.
*/
if (key === "values" && typeof props.values === "object")
continue;
if (shouldForward(key) ||
(forwardMotionProps === true && isValidMotionProp(key)) ||
(!isDom && !isValidMotionProp(key)) ||
// If trying to use native HTML drag events, forward drag listeners
(props["draggable"] && key.startsWith("onDrag"))) {
filteredProps[key] = props[key];
}
}
return filteredProps;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/transform-origin.mjs
function calcOrigin(origin, offset, size) {
return typeof origin === "string"
? origin
: px.transform(offset + size * origin);
}
/**
* The SVG transform origin defaults are different to CSS and is less intuitive,
* so we use the measured dimensions of the SVG to reconcile these.
*/
function calcSVGTransformOrigin(dimensions, originX, originY) {
const pxOriginX = calcOrigin(originX, dimensions.x, dimensions.width);
const pxOriginY = calcOrigin(originY, dimensions.y, dimensions.height);
return `${pxOriginX} ${pxOriginY}`;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/path.mjs
const dashKeys = {
offset: "stroke-dashoffset",
array: "stroke-dasharray",
};
const camelKeys = {
offset: "strokeDashoffset",
array: "strokeDasharray",
};
/**
* Build SVG path properties. Uses the path's measured length to convert
* our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset
* and stroke-dasharray attributes.
*
* This function is mutative to reduce per-frame GC.
*/
function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {
// Normalise path length by setting SVG attribute pathLength to 1
attrs.pathLength = 1;
// We use dash case when setting attributes directly to the DOM node and camel case
// when defining props on a React component.
const keys = useDashCase ? dashKeys : camelKeys;
// Build the dash offset
attrs[keys.offset] = px.transform(-offset);
// Build the dash array
const pathLength = px.transform(length);
const pathSpacing = px.transform(spacing);
attrs[keys.array] = `${pathLength} ${pathSpacing}`;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs
/**
* Build SVG visual attrbutes, like cx and style.transform
*/
function buildSVGAttrs(state, { attrX, attrY, originX, originY, pathLength, pathSpacing = 1, pathOffset = 0,
// This is object creation, which we try to avoid per-frame.
...latest }, options, isSVGTag, transformTemplate) {
buildHTMLStyles(state, latest, options, transformTemplate);
/**
* For svg tags we just want to make sure viewBox is animatable and treat all the styles
* as normal HTML tags.
*/
if (isSVGTag) {
if (state.style.viewBox) {
state.attrs.viewBox = state.style.viewBox;
}
return;
}
state.attrs = state.style;
state.style = {};
const { attrs, style, dimensions } = state;
/**
* However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs
* and copy it into style.
*/
if (attrs.transform) {
if (dimensions)
style.transform = attrs.transform;
delete attrs.transform;
}
// Parse transformOrigin
if (dimensions &&
(originX !== undefined || originY !== undefined || style.transform)) {
style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== undefined ? originX : 0.5, originY !== undefined ? originY : 0.5);
}
// Treat x/y not as shortcuts but as actual attributes
if (attrX !== undefined)
attrs.x = attrX;
if (attrY !== undefined)
attrs.y = attrY;
// Build SVG path if one has been defined
if (pathLength !== undefined) {
buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs
const createSvgRenderState = () => ({
...createHtmlRenderState(),
attrs: {},
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs
const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg";
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/use-props.mjs
function useSVGProps(props, visualState, _isStatic, Component) {
const visualProps = (0,external_React_.useMemo)(() => {
const state = createSvgRenderState();
buildSVGAttrs(state, visualState, { enableHardwareAcceleration: false }, isSVGTag(Component), props.transformTemplate);
return {
...state.attrs,
style: { ...state.style },
};
}, [visualState]);
if (props.style) {
const rawStyles = {};
copyRawValuesOnly(rawStyles, props.style, props);
visualProps.style = { ...rawStyles, ...visualProps.style };
}
return visualProps;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/use-render.mjs
function createUseRender(forwardMotionProps = false) {
const useRender = (Component, props, projectionId, ref, { latestValues }, isStatic) => {
const useVisualProps = isSVGComponent(Component)
? useSVGProps
: useHTMLProps;
const visualProps = useVisualProps(props, latestValues, isStatic, Component);
const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps);
const elementProps = {
...filteredProps,
...visualProps,
ref,
};
/**
* If component has been handed a motion value as its child,
* memoise its initial value and render that. Subsequent updates
* will be handled by the onChange handler
*/
const { children } = props;
const renderedChildren = (0,external_React_.useMemo)(() => (isMotionValue(children) ? children.get() : children), [children]);
if (projectionId) {
elementProps["data-projection-id"] = projectionId;
}
return (0,external_React_.createElement)(Component, {
...elementProps,
children: renderedChildren,
});
};
return useRender;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs
/**
* Convert camelCase to dash-case properties.
*/
const camelToDash = (str) => str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/render.mjs
function renderHTML(element, { style, vars }, styleProp, projection) {
Object.assign(element.style, style, projection && projection.getProjectionStyles(styleProp));
// Loop over any CSS variables and assign those.
for (const key in vars) {
element.style.setProperty(key, vars[key]);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs
/**
* A set of attribute names that are always read/written as camel case.
*/
const camelCaseAttributes = new Set([
"baseFrequency",
"diffuseConstant",
"kernelMatrix",
"kernelUnitLength",
"keySplines",
"keyTimes",
"limitingConeAngle",
"markerHeight",
"markerWidth",
"numOctaves",
"targetX",
"targetY",
"surfaceScale",
"specularConstant",
"specularExponent",
"stdDeviation",
"tableValues",
"viewBox",
"gradientTransform",
"pathLength",
"startOffset",
"textLength",
"lengthAdjust",
]);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/render.mjs
function renderSVG(element, renderState, _styleProp, projection) {
renderHTML(element, renderState, undefined, projection);
for (const key in renderState.attrs) {
element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs
function scrapeMotionValuesFromProps(props, prevProps) {
const { style } = props;
const newValues = {};
for (const key in style) {
if (isMotionValue(style[key]) ||
(prevProps.style && isMotionValue(prevProps.style[key])) ||
isForcedMotionValue(key, props)) {
newValues[key] = style[key];
}
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs
function scrape_motion_values_scrapeMotionValuesFromProps(props, prevProps) {
const newValues = scrapeMotionValuesFromProps(props, prevProps);
for (const key in props) {
if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) {
const targetKey = key === "x" || key === "y" ? "attr" + key.toUpperCase() : key;
newValues[targetKey] = props[key];
}
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs
function resolveVariantFromProps(props, definition, custom, currentValues = {}, currentVelocity = {}) {
/**
* If the variant definition is a function, resolve.
*/
if (typeof definition === "function") {
definition = definition(custom !== undefined ? custom : props.custom, currentValues, currentVelocity);
}
/**
* If the variant definition is a variant label, or
* the function returned a variant label, resolve.
*/
if (typeof definition === "string") {
definition = props.variants && props.variants[definition];
}
/**
* At this point we've resolved both functions and variant labels,
* but the resolved variant label might itself have been a function.
* If so, resolve. This can only have returned a valid target object.
*/
if (typeof definition === "function") {
definition = definition(custom !== undefined ? custom : props.custom, currentValues, currentVelocity);
}
return definition;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs
const isKeyframesTarget = (v) => {
return Array.isArray(v);
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/resolve-value.mjs
const isCustomValue = (v) => {
return Boolean(v && typeof v === "object" && v.mix && v.toValue);
};
const resolveFinalValueInKeyframes = (v) => {
// TODO maybe throw if v.length - 1 is placeholder token?
return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs
/**
* If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself
*
* TODO: Remove and move to library
*/
function resolveMotionValue(value) {
const unwrappedValue = isMotionValue(value) ? value.get() : value;
return isCustomValue(unwrappedValue)
? unwrappedValue.toValue()
: unwrappedValue;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs
function makeState({ scrapeMotionValuesFromProps, createRenderState, onMount, }, props, context, presenceContext) {
const state = {
latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps),
renderState: createRenderState(),
};
if (onMount) {
state.mount = (instance) => onMount(props, instance, state);
}
return state;
}
const makeUseVisualState = (config) => (props, isStatic) => {
const context = (0,external_React_.useContext)(MotionContext);
const presenceContext = (0,external_React_.useContext)(PresenceContext_PresenceContext);
const make = () => makeState(config, props, context, presenceContext);
return isStatic ? make() : useConstant(make);
};
function makeLatestValues(props, context, presenceContext, scrapeMotionValues) {
const values = {};
const motionValues = scrapeMotionValues(props, {});
for (const key in motionValues) {
values[key] = resolveMotionValue(motionValues[key]);
}
let { initial, animate } = props;
const isControllingVariants$1 = isControllingVariants(props);
const isVariantNode$1 = isVariantNode(props);
if (context &&
isVariantNode$1 &&
!isControllingVariants$1 &&
props.inherit !== false) {
if (initial === undefined)
initial = context.initial;
if (animate === undefined)
animate = context.animate;
}
let isInitialAnimationBlocked = presenceContext
? presenceContext.initial === false
: false;
isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false;
const variantToSet = isInitialAnimationBlocked ? animate : initial;
if (variantToSet &&
typeof variantToSet !== "boolean" &&
!isAnimationControls(variantToSet)) {
const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet];
list.forEach((definition) => {
const resolved = resolveVariantFromProps(props, definition);
if (!resolved)
return;
const { transitionEnd, transition, ...target } = resolved;
for (const key in target) {
let valueTarget = target[key];
if (Array.isArray(valueTarget)) {
/**
* Take final keyframe if the initial animation is blocked because
* we want to initialise at the end of that blocked animation.
*/
const index = isInitialAnimationBlocked
? valueTarget.length - 1
: 0;
valueTarget = valueTarget[index];
}
if (valueTarget !== null) {
values[key] = valueTarget;
}
}
for (const key in transitionEnd)
values[key] = transitionEnd[key];
});
}
return values;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/config-motion.mjs
const svgMotionConfig = {
useVisualState: makeUseVisualState({
scrapeMotionValuesFromProps: scrape_motion_values_scrapeMotionValuesFromProps,
createRenderState: createSvgRenderState,
onMount: (props, instance, { renderState, latestValues }) => {
try {
renderState.dimensions =
typeof instance.getBBox ===
"function"
? instance.getBBox()
: instance.getBoundingClientRect();
}
catch (e) {
// Most likely trying to measure an unrendered element under Firefox
renderState.dimensions = {
x: 0,
y: 0,
width: 0,
height: 0,
};
}
buildSVGAttrs(renderState, latestValues, { enableHardwareAcceleration: false }, isSVGTag(instance.tagName), props.transformTemplate);
renderSVG(instance, renderState);
},
}),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/config-motion.mjs
const htmlMotionConfig = {
useVisualState: makeUseVisualState({
scrapeMotionValuesFromProps: scrapeMotionValuesFromProps,
createRenderState: createHtmlRenderState,
}),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/create-config.mjs
function create_config_createDomMotionConfig(Component, { forwardMotionProps = false }, preloadedFeatures, createVisualElement) {
const baseConfig = isSVGComponent(Component)
? svgMotionConfig
: htmlMotionConfig;
return {
...baseConfig,
preloadedFeatures,
useRender: createUseRender(forwardMotionProps),
createVisualElement,
Component,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/add-dom-event.mjs
function addDomEvent(target, eventName, handler, options = { passive: true }) {
target.addEventListener(eventName, handler, options);
return () => target.removeEventListener(eventName, handler);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/utils/is-primary-pointer.mjs
const isPrimaryPointer = (event) => {
if (event.pointerType === "mouse") {
return typeof event.button !== "number" || event.button <= 0;
}
else {
/**
* isPrimary is true for all mice buttons, whereas every touch point
* is regarded as its own input. So subsequent concurrent touch points
* will be false.
*
* Specifically match against false here as incomplete versions of
* PointerEvents in very old browser might have it set as undefined.
*/
return event.isPrimary !== false;
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/event-info.mjs
function extractEventInfo(event, pointType = "page") {
return {
point: {
x: event[pointType + "X"],
y: event[pointType + "Y"],
},
};
}
const addPointerInfo = (handler) => {
return (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event));
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/add-pointer-event.mjs
function addPointerEvent(target, eventName, handler, options) {
return addDomEvent(target, eventName, addPointerInfo(handler), options);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/pipe.mjs
/**
* Pipe
* Compose other transformers to run linearily
* pipe(min(20), max(40))
* @param {...functions} transformers
* @return {function}
*/
const combineFunctions = (a, b) => (v) => b(a(v));
const pipe = (...transformers) => transformers.reduce(combineFunctions);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/utils/lock.mjs
function createLock(name) {
let lock = null;
return () => {
const openLock = () => {
lock = null;
};
if (lock === null) {
lock = name;
return openLock;
}
return false;
};
}
const globalHorizontalLock = createLock("dragHorizontal");
const globalVerticalLock = createLock("dragVertical");
function getGlobalLock(drag) {
let lock = false;
if (drag === "y") {
lock = globalVerticalLock();
}
else if (drag === "x") {
lock = globalHorizontalLock();
}
else {
const openHorizontal = globalHorizontalLock();
const openVertical = globalVerticalLock();
if (openHorizontal && openVertical) {
lock = () => {
openHorizontal();
openVertical();
};
}
else {
// Release the locks because we don't use them
if (openHorizontal)
openHorizontal();
if (openVertical)
openVertical();
}
}
return lock;
}
function isDragActive() {
// Check the gesture lock - if we get it, it means no drag gesture is active
// and we can safely fire the tap gesture.
const openGestureLock = getGlobalLock(true);
if (!openGestureLock)
return true;
openGestureLock();
return false;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/Feature.mjs
class Feature {
constructor(node) {
this.isMounted = false;
this.node = node;
}
update() { }
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/create-render-step.mjs
function createRenderStep(runNextFrame) {
/**
* We create and reuse two arrays, one to queue jobs for the current frame
* and one for the next. We reuse to avoid triggering GC after x frames.
*/
let toRun = [];
let toRunNextFrame = [];
/**
*
*/
let numToRun = 0;
/**
* Track whether we're currently processing jobs in this step. This way
* we can decide whether to schedule new jobs for this frame or next.
*/
let isProcessing = false;
let flushNextFrame = false;
/**
* A set of processes which were marked keepAlive when scheduled.
*/
const toKeepAlive = new WeakSet();
const step = {
/**
* Schedule a process to run on the next frame.
*/
schedule: (callback, keepAlive = false, immediate = false) => {
const addToCurrentFrame = immediate && isProcessing;
const buffer = addToCurrentFrame ? toRun : toRunNextFrame;
if (keepAlive)
toKeepAlive.add(callback);
// If the buffer doesn't already contain this callback, add it
if (buffer.indexOf(callback) === -1) {
buffer.push(callback);
// If we're adding it to the currently running buffer, update its measured size
if (addToCurrentFrame && isProcessing)
numToRun = toRun.length;
}
return callback;
},
/**
* Cancel the provided callback from running on the next frame.
*/
cancel: (callback) => {
const index = toRunNextFrame.indexOf(callback);
if (index !== -1)
toRunNextFrame.splice(index, 1);
toKeepAlive.delete(callback);
},
/**
* Execute all schedule callbacks.
*/
process: (frameData) => {
/**
* If we're already processing we've probably been triggered by a flushSync
* inside an existing process. Instead of executing, mark flushNextFrame
* as true and ensure we flush the following frame at the end of this one.
*/
if (isProcessing) {
flushNextFrame = true;
return;
}
isProcessing = true;
[toRun, toRunNextFrame] = [toRunNextFrame, toRun];
// Clear the next frame list
toRunNextFrame.length = 0;
// Execute this frame
numToRun = toRun.length;
if (numToRun) {
for (let i = 0; i < numToRun; i++) {
const callback = toRun[i];
callback(frameData);
if (toKeepAlive.has(callback)) {
step.schedule(callback);
runNextFrame();
}
}
}
isProcessing = false;
if (flushNextFrame) {
flushNextFrame = false;
step.process(frameData);
}
},
};
return step;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/data.mjs
const frameData = {
delta: 0,
timestamp: 0,
isProcessing: false,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/index.mjs
const maxElapsed = 40;
let useDefaultElapsed = true;
let runNextFrame = false;
const stepsOrder = [
"read",
"update",
"preRender",
"render",
"postRender",
];
const steps = stepsOrder.reduce((acc, key) => {
acc[key] = createRenderStep(() => (runNextFrame = true));
return acc;
}, {});
const sync = stepsOrder.reduce((acc, key) => {
const step = steps[key];
acc[key] = (process, keepAlive = false, immediate = false) => {
if (!runNextFrame)
startLoop();
return step.schedule(process, keepAlive, immediate);
};
return acc;
}, {});
const cancelSync = stepsOrder.reduce((acc, key) => {
acc[key] = steps[key].cancel;
return acc;
}, {});
const flushSync = stepsOrder.reduce((acc, key) => {
acc[key] = () => steps[key].process(frameData);
return acc;
}, {});
const processStep = (stepId) => steps[stepId].process(frameData);
const processFrame = (timestamp) => {
runNextFrame = false;
frameData.delta = useDefaultElapsed
? 1000 / 60
: Math.max(Math.min(timestamp - frameData.timestamp, maxElapsed), 1);
frameData.timestamp = timestamp;
frameData.isProcessing = true;
stepsOrder.forEach(processStep);
frameData.isProcessing = false;
if (runNextFrame) {
useDefaultElapsed = false;
requestAnimationFrame(processFrame);
}
};
const startLoop = () => {
runNextFrame = true;
useDefaultElapsed = true;
if (!frameData.isProcessing)
requestAnimationFrame(processFrame);
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/hover.mjs
function addHoverEvent(node, isActive) {
const eventName = "pointer" + (isActive ? "enter" : "leave");
const callbackName = "onHover" + (isActive ? "Start" : "End");
const handleEvent = (event, info) => {
if (event.type === "touch" || isDragActive())
return;
const props = node.getProps();
if (node.animationState && props.whileHover) {
node.animationState.setActive("whileHover", isActive);
}
if (props[callbackName]) {
sync.update(() => props[callbackName](event, info));
}
};
return addPointerEvent(node.current, eventName, handleEvent, {
passive: !node.getProps()[callbackName],
});
}
class HoverGesture extends Feature {
mount() {
this.unmount = pipe(addHoverEvent(this.node, true), addHoverEvent(this.node, false));
}
unmount() { }
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/focus.mjs
class FocusGesture extends Feature {
constructor() {
super(...arguments);
this.isActive = false;
}
onFocus() {
let isFocusVisible = false;
/**
* If this element doesn't match focus-visible then don't
* apply whileHover. But, if matches throws that focus-visible
* is not a valid selector then in that browser outline styles will be applied
* to the element by default and we want to match that behaviour with whileFocus.
*/
try {
isFocusVisible = this.node.current.matches(":focus-visible");
}
catch (e) {
isFocusVisible = true;
}
if (!isFocusVisible || !this.node.animationState)
return;
this.node.animationState.setActive("whileFocus", true);
this.isActive = true;
}
onBlur() {
if (!this.isActive || !this.node.animationState)
return;
this.node.animationState.setActive("whileFocus", false);
this.isActive = false;
}
mount() {
this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur()));
}
unmount() { }
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/utils/is-node-or-child.mjs
/**
* Recursively traverse up the tree to check whether the provided child node
* is the parent or a descendant of it.
*
* @param parent - Element to find
* @param child - Element to test against parent
*/
const isNodeOrChild = (parent, child) => {
if (!child) {
return false;
}
else if (parent === child) {
return true;
}
else {
return isNodeOrChild(parent, child.parentElement);
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/noop.mjs
const noop = (any) => any;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/press.mjs
function fireSyntheticPointerEvent(name, handler) {
if (!handler)
return;
const syntheticPointerEvent = new PointerEvent("pointer" + name);
handler(syntheticPointerEvent, extractEventInfo(syntheticPointerEvent));
}
class PressGesture extends Feature {
constructor() {
super(...arguments);
this.removeStartListeners = noop;
this.removeEndListeners = noop;
this.removeAccessibleListeners = noop;
this.startPointerPress = (startEvent, startInfo) => {
this.removeEndListeners();
if (this.isPressing)
return;
const props = this.node.getProps();
const endPointerPress = (endEvent, endInfo) => {
if (!this.checkPressEnd())
return;
const { onTap, onTapCancel } = this.node.getProps();
sync.update(() => {
/**
* We only count this as a tap gesture if the event.target is the same
* as, or a child of, this component's element
*/
!isNodeOrChild(this.node.current, endEvent.target)
? onTapCancel && onTapCancel(endEvent, endInfo)
: onTap && onTap(endEvent, endInfo);
});
};
const removePointerUpListener = addPointerEvent(window, "pointerup", endPointerPress, { passive: !(props.onTap || props["onPointerUp"]) });
const removePointerCancelListener = addPointerEvent(window, "pointercancel", (cancelEvent, cancelInfo) => this.cancelPress(cancelEvent, cancelInfo), { passive: !(props.onTapCancel || props["onPointerCancel"]) });
this.removeEndListeners = pipe(removePointerUpListener, removePointerCancelListener);
this.startPress(startEvent, startInfo);
};
this.startAccessiblePress = () => {
const handleKeydown = (keydownEvent) => {
if (keydownEvent.key !== "Enter" || this.isPressing)
return;
const handleKeyup = (keyupEvent) => {
if (keyupEvent.key !== "Enter" || !this.checkPressEnd())
return;
fireSyntheticPointerEvent("up", (event, info) => {
const { onTap } = this.node.getProps();
if (onTap) {
sync.update(() => onTap(event, info));
}
});
};
this.removeEndListeners();
this.removeEndListeners = addDomEvent(this.node.current, "keyup", handleKeyup);
fireSyntheticPointerEvent("down", (event, info) => {
this.startPress(event, info);
});
};
const removeKeydownListener = addDomEvent(this.node.current, "keydown", handleKeydown);
const handleBlur = () => {
if (!this.isPressing)
return;
fireSyntheticPointerEvent("cancel", (cancelEvent, cancelInfo) => this.cancelPress(cancelEvent, cancelInfo));
};
const removeBlurListener = addDomEvent(this.node.current, "blur", handleBlur);
this.removeAccessibleListeners = pipe(removeKeydownListener, removeBlurListener);
};
}
startPress(event, info) {
this.isPressing = true;
const { onTapStart, whileTap } = this.node.getProps();
/**
* Ensure we trigger animations before firing event callback
*/
if (whileTap && this.node.animationState) {
this.node.animationState.setActive("whileTap", true);
}
if (onTapStart) {
sync.update(() => onTapStart(event, info));
}
}
checkPressEnd() {
this.removeEndListeners();
this.isPressing = false;
const props = this.node.getProps();
if (props.whileTap && this.node.animationState) {
this.node.animationState.setActive("whileTap", false);
}
return !isDragActive();
}
cancelPress(event, info) {
if (!this.checkPressEnd())
return;
const { onTapCancel } = this.node.getProps();
if (onTapCancel) {
sync.update(() => onTapCancel(event, info));
}
}
mount() {
const props = this.node.getProps();
const removePointerListener = addPointerEvent(this.node.current, "pointerdown", this.startPointerPress, { passive: !(props.onTapStart || props["onPointerStart"]) });
const removeFocusListener = addDomEvent(this.node.current, "focus", this.startAccessiblePress);
this.removeStartListeners = pipe(removePointerListener, removeFocusListener);
}
unmount() {
this.removeStartListeners();
this.removeEndListeners();
this.removeAccessibleListeners();
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs
/**
* Map an IntersectionHandler callback to an element. We only ever make one handler for one
* element, so even though these handlers might all be triggered by different
* observers, we can keep them in the same map.
*/
const observerCallbacks = new WeakMap();
/**
* Multiple observers can be created for multiple element/document roots. Each with
* different settings. So here we store dictionaries of observers to each root,
* using serialised settings (threshold/margin) as lookup keys.
*/
const observers = new WeakMap();
const fireObserverCallback = (entry) => {
const callback = observerCallbacks.get(entry.target);
callback && callback(entry);
};
const fireAllObserverCallbacks = (entries) => {
entries.forEach(fireObserverCallback);
};
function initIntersectionObserver({ root, ...options }) {
const lookupRoot = root || document;
/**
* If we don't have an observer lookup map for this root, create one.
*/
if (!observers.has(lookupRoot)) {
observers.set(lookupRoot, {});
}
const rootObservers = observers.get(lookupRoot);
const key = JSON.stringify(options);
/**
* If we don't have an observer for this combination of root and settings,
* create one.
*/
if (!rootObservers[key]) {
rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options });
}
return rootObservers[key];
}
function observeIntersection(element, options, callback) {
const rootInteresectionObserver = initIntersectionObserver(options);
observerCallbacks.set(element, callback);
rootInteresectionObserver.observe(element);
return () => {
observerCallbacks.delete(element);
rootInteresectionObserver.unobserve(element);
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs
const thresholdNames = {
some: 0,
all: 1,
};
class InViewFeature extends Feature {
constructor() {
super(...arguments);
this.hasEnteredView = false;
this.isInView = false;
}
startObserver() {
this.unmount();
const { viewport = {} } = this.node.getProps();
const { root, margin: rootMargin, amount = "some", once } = viewport;
const options = {
root: root ? root.current : undefined,
rootMargin,
threshold: typeof amount === "number" ? amount : thresholdNames[amount],
};
const onIntersectionUpdate = (entry) => {
const { isIntersecting } = entry;
/**
* If there's been no change in the viewport state, early return.
*/
if (this.isInView === isIntersecting)
return;
this.isInView = isIntersecting;
/**
* Handle hasEnteredView. If this is only meant to run once, and
* element isn't visible, early return. Otherwise set hasEnteredView to true.
*/
if (once && !isIntersecting && this.hasEnteredView) {
return;
}
else if (isIntersecting) {
this.hasEnteredView = true;
}
if (this.node.animationState) {
this.node.animationState.setActive("whileInView", isIntersecting);
}
/**
* Use the latest committed props rather than the ones in scope
* when this observer is created
*/
const { onViewportEnter, onViewportLeave } = this.node.getProps();
const callback = isIntersecting ? onViewportEnter : onViewportLeave;
callback && callback(entry);
};
return observeIntersection(this.node.current, options, onIntersectionUpdate);
}
mount() {
this.startObserver();
}
update() {
if (typeof IntersectionObserver === "undefined")
return;
const { props, prevProps } = this.node;
const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps));
if (hasOptionsChanged) {
this.startObserver();
}
}
unmount() { }
}
function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) {
return (name) => viewport[name] !== prevViewport[name];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/gestures.mjs
const gestureAnimations = {
inView: {
Feature: InViewFeature,
},
tap: {
Feature: PressGesture,
},
focus: {
Feature: FocusGesture,
},
hover: {
Feature: HoverGesture,
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/shallow-compare.mjs
function shallowCompare(next, prev) {
if (!Array.isArray(prev))
return false;
const prevLength = prev.length;
if (prevLength !== next.length)
return false;
for (let i = 0; i < prevLength; i++) {
if (prev[i] !== next[i])
return false;
}
return true;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs
/**
* Creates an object containing the latest state of every MotionValue on a VisualElement
*/
function getCurrent(visualElement) {
const current = {};
visualElement.values.forEach((value, key) => (current[key] = value.get()));
return current;
}
/**
* Creates an object containing the latest velocity of every MotionValue on a VisualElement
*/
function getVelocity(visualElement) {
const velocity = {};
visualElement.values.forEach((value, key) => (velocity[key] = value.getVelocity()));
return velocity;
}
function resolveVariant(visualElement, definition, custom) {
const props = visualElement.getProps();
return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, getCurrent(visualElement), getVelocity(visualElement));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs
const optimizedAppearDataId = "framerAppearId";
const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/errors.mjs
let warning = noop;
let invariant = noop;
if (false) {}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/time-conversion.mjs
/**
* Converts seconds to milliseconds
*
* @param seconds - Time in seconds.
* @return milliseconds - Converted time in milliseconds.
*/
const secondsToMilliseconds = (seconds) => seconds * 1000;
const millisecondsToSeconds = (milliseconds) => milliseconds / 1000;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-instant-transition-state.mjs
const instantAnimationState = {
current: false,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/utils/is-bezier-definition.mjs
const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number";
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/waapi/easing.mjs
function isWaapiSupportedEasing(easing) {
return Boolean(!easing ||
(typeof easing === "string" && supportedWaapiEasing[easing]) ||
isBezierDefinition(easing) ||
(Array.isArray(easing) && easing.every(isWaapiSupportedEasing)));
}
const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
const supportedWaapiEasing = {
linear: "linear",
ease: "ease",
easeIn: "ease-in",
easeOut: "ease-out",
easeInOut: "ease-in-out",
circIn: cubicBezierAsString([0, 0.65, 0.55, 1]),
circOut: cubicBezierAsString([0.55, 0, 1, 0.45]),
backIn: cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),
backOut: cubicBezierAsString([0.33, 1.53, 0.69, 0.99]),
};
function mapEasingToNativeEasing(easing) {
if (!easing)
return undefined;
return isBezierDefinition(easing)
? cubicBezierAsString(easing)
: Array.isArray(easing)
? easing.map(mapEasingToNativeEasing)
: supportedWaapiEasing[easing];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/waapi/index.mjs
function animateStyle(element, valueName, keyframes, { delay = 0, duration, repeat = 0, repeatType = "loop", ease, times, } = {}) {
const keyframeOptions = { [valueName]: keyframes };
if (times)
keyframeOptions.offset = times;
const easing = mapEasingToNativeEasing(ease);
/**
* If this is an easing array, apply to keyframes, not animation as a whole
*/
if (Array.isArray(easing))
keyframeOptions.easing = easing;
return element.animate(keyframeOptions, {
delay,
duration,
easing: !Array.isArray(easing) ? easing : "linear",
fill: "both",
iterations: repeat + 1,
direction: repeatType === "reverse" ? "alternate" : "normal",
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/waapi/supports.mjs
const featureTests = {
waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"),
};
const results = {};
const supports = {};
/**
* Generate features tests that cache their results.
*/
for (const key in featureTests) {
supports[key] = () => {
if (results[key] === undefined)
results[key] = featureTests[key]();
return results[key];
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/waapi/utils/get-final-keyframe.mjs
function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }) {
const index = repeat && repeatType !== "loop" && repeat % 2 === 1
? 0
: keyframes.length - 1;
return keyframes[index];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/cubic-bezier.mjs
/*
Bezier function generator
This has been modified from Gaëtan Renaudeau's BezierEasing
https://github.com/gre/bezier-easing/blob/master/src/index.js
https://github.com/gre/bezier-easing/blob/master/LICENSE
I've removed the newtonRaphsonIterate algo because in benchmarking it
wasn't noticiably faster than binarySubdivision, indeed removing it
usually improved times, depending on the curve.
I also removed the lookup table, as for the added bundle size and loop we're
only cutting ~4 or so subdivision iterations. I bumped the max iterations up
to 12 to compensate and this still tended to be faster for no perceivable
loss in accuracy.
Usage
const easeOut = cubicBezier(.17,.67,.83,.67);
const x = easeOut(0.5); // returns 0.627...
*/
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) *
t;
const subdivisionPrecision = 0.0000001;
const subdivisionMaxIterations = 12;
function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
let currentX;
let currentT;
let i = 0;
do {
currentT = lowerBound + (upperBound - lowerBound) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - x;
if (currentX > 0.0) {
upperBound = currentT;
}
else {
lowerBound = currentT;
}
} while (Math.abs(currentX) > subdivisionPrecision &&
++i < subdivisionMaxIterations);
return currentT;
}
function cubicBezier(mX1, mY1, mX2, mY2) {
// If this is a linear gradient, return linear easing
if (mX1 === mY1 && mX2 === mY2)
return noop;
const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
// If animation is at start/end, return t without easing
return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/ease.mjs
const easeIn = cubicBezier(0.42, 0, 1, 1);
const easeOut = cubicBezier(0, 0, 0.58, 1);
const easeInOut = cubicBezier(0.42, 0, 0.58, 1);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/utils/is-easing-array.mjs
const isEasingArray = (ease) => {
return Array.isArray(ease) && typeof ease[0] !== "number";
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/modifiers/mirror.mjs
// Accepts an easing function and returns a new one that outputs mirrored values for
// the second half of the animation. Turns easeIn into easeInOut.
const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/modifiers/reverse.mjs
// Accepts an easing function and returns a new one that outputs reversed values.
// Turns easeIn into easeOut.
const reverseEasing = (easing) => (p) => 1 - easing(1 - p);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/circ.mjs
const circIn = (p) => 1 - Math.sin(Math.acos(p));
const circOut = reverseEasing(circIn);
const circInOut = mirrorEasing(circOut);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/back.mjs
const backOut = cubicBezier(0.33, 1.53, 0.69, 0.99);
const backIn = reverseEasing(backOut);
const backInOut = mirrorEasing(backIn);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/anticipate.mjs
const anticipate = (p) => (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/utils/map.mjs
const easingLookup = {
linear: noop,
easeIn: easeIn,
easeInOut: easeInOut,
easeOut: easeOut,
circIn: circIn,
circInOut: circInOut,
circOut: circOut,
backIn: backIn,
backInOut: backInOut,
backOut: backOut,
anticipate: anticipate,
};
const easingDefinitionToFunction = (definition) => {
if (Array.isArray(definition)) {
// If cubic bezier definition, create bezier curve
invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`);
const [x1, y1, x2, y2] = definition;
return cubicBezier(x1, y1, x2, y2);
}
else if (typeof definition === "string") {
// Else lookup from table
invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`);
return easingLookup[definition];
}
return definition;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/utils.mjs
/**
* Returns true if the provided string is a color, ie rgba(0,0,0,0) or #000,
* but false if a number or multiple colors
*/
const isColorString = (type, testProp) => (v) => {
return Boolean((isString(v) && singleColorRegex.test(v) && v.startsWith(type)) ||
(testProp && Object.prototype.hasOwnProperty.call(v, testProp)));
};
const splitColor = (aName, bName, cName) => (v) => {
if (!isString(v))
return v;
const [a, b, c, alpha] = v.match(floatRegex);
return {
[aName]: parseFloat(a),
[bName]: parseFloat(b),
[cName]: parseFloat(c),
alpha: alpha !== undefined ? parseFloat(alpha) : 1,
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/rgba.mjs
const clampRgbUnit = (v) => clamp(0, 255, v);
const rgbUnit = {
...number,
transform: (v) => Math.round(clampRgbUnit(v)),
};
const rgba = {
test: isColorString("rgb", "red"),
parse: splitColor("red", "green", "blue"),
transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" +
rgbUnit.transform(red) +
", " +
rgbUnit.transform(green) +
", " +
rgbUnit.transform(blue) +
", " +
sanitize(alpha.transform(alpha$1)) +
")",
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/hex.mjs
function parseHex(v) {
let r = "";
let g = "";
let b = "";
let a = "";
// If we have 6 characters, ie #FF0000
if (v.length > 5) {
r = v.substring(1, 3);
g = v.substring(3, 5);
b = v.substring(5, 7);
a = v.substring(7, 9);
// Or we have 3 characters, ie #F00
}
else {
r = v.substring(1, 2);
g = v.substring(2, 3);
b = v.substring(3, 4);
a = v.substring(4, 5);
r += r;
g += g;
b += b;
a += a;
}
return {
red: parseInt(r, 16),
green: parseInt(g, 16),
blue: parseInt(b, 16),
alpha: a ? parseInt(a, 16) / 255 : 1,
};
}
const hex = {
test: isColorString("#"),
parse: parseHex,
transform: rgba.transform,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/hsla.mjs
const hsla = {
test: isColorString("hsl", "hue"),
parse: splitColor("hue", "saturation", "lightness"),
transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
return ("hsla(" +
Math.round(hue) +
", " +
percent.transform(sanitize(saturation)) +
", " +
percent.transform(sanitize(lightness)) +
", " +
sanitize(alpha.transform(alpha$1)) +
")");
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/index.mjs
const color = {
test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
parse: (v) => {
if (rgba.test(v)) {
return rgba.parse(v);
}
else if (hsla.test(v)) {
return hsla.parse(v);
}
else {
return hex.parse(v);
}
},
transform: (v) => {
return isString(v)
? v
: v.hasOwnProperty("red")
? rgba.transform(v)
: hsla.transform(v);
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix.mjs
/*
Value in range from progress
Given a lower limit and an upper limit, we return the value within
that range as expressed by progress (usually a number from 0 to 1)
So progress = 0.5 would change
from -------- to
to
from ---- to
E.g. from = 10, to = 20, progress = 0.5 => 15
@param [number]: Lower limit of range
@param [number]: Upper limit of range
@param [number]: The progress between lower and upper limits expressed 0-1
@return [number]: Value as calculated from progress within range (not limited within range)
*/
const mix = (from, to, progress) => -progress * from + progress * to + from;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/hsla-to-rgba.mjs
// Adapted from https://gist.github.com/mjackson/5311256
function hueToRgb(p, q, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p + (q - p) * 6 * t;
if (t < 1 / 2)
return q;
if (t < 2 / 3)
return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslaToRgba({ hue, saturation, lightness, alpha }) {
hue /= 360;
saturation /= 100;
lightness /= 100;
let red = 0;
let green = 0;
let blue = 0;
if (!saturation) {
red = green = blue = lightness;
}
else {
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
red = hueToRgb(p, q, hue + 1 / 3);
green = hueToRgb(p, q, hue);
blue = hueToRgb(p, q, hue - 1 / 3);
}
return {
red: Math.round(red * 255),
green: Math.round(green * 255),
blue: Math.round(blue * 255),
alpha,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix-color.mjs
// Linear color space blending
// Explained https://www.youtube.com/watch?v=LKnqECcg6Gw
// Demonstrated http://codepen.io/osublake/pen/xGVVaN
const mixLinearColor = (from, to, v) => {
const fromExpo = from * from;
return Math.sqrt(Math.max(0, v * (to * to - fromExpo) + fromExpo));
};
const colorTypes = [hex, rgba, hsla];
const getColorType = (v) => colorTypes.find((type) => type.test(v));
function asRGBA(color) {
const type = getColorType(color);
invariant(Boolean(type), `'${color}' is not an animatable color. Use the equivalent color code instead.`);
let model = type.parse(color);
if (type === hsla) {
// TODO Remove this cast - needed since Framer Motion's stricter typing
model = hslaToRgba(model);
}
return model;
}
const mixColor = (from, to) => {
const fromRGBA = asRGBA(from);
const toRGBA = asRGBA(to);
const blended = { ...fromRGBA };
return (v) => {
blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v);
blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v);
blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v);
blended.alpha = mix(fromRGBA.alpha, toRGBA.alpha, v);
return rgba.transform(blended);
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/complex/index.mjs
const colorToken = "${c}";
const numberToken = "${n}";
function test(v) {
var _a, _b;
return (isNaN(v) &&
isString(v) &&
(((_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) || 0) +
(((_b = v.match(colorRegex)) === null || _b === void 0 ? void 0 : _b.length) || 0) >
0);
}
function analyseComplexValue(v) {
if (typeof v === "number")
v = `${v}`;
const values = [];
let numColors = 0;
let numNumbers = 0;
const colors = v.match(colorRegex);
if (colors) {
numColors = colors.length;
// Strip colors from input so they're not picked up by number regex.
// There's a better way to combine these regex searches, but its beyond my regex skills
v = v.replace(colorRegex, colorToken);
values.push(...colors.map(color.parse));
}
const numbers = v.match(floatRegex);
if (numbers) {
numNumbers = numbers.length;
v = v.replace(floatRegex, numberToken);
values.push(...numbers.map(number.parse));
}
return { values, numColors, numNumbers, tokenised: v };
}
function parse(v) {
return analyseComplexValue(v).values;
}
function createTransformer(source) {
const { values, numColors, tokenised } = analyseComplexValue(source);
const numValues = values.length;
return (v) => {
let output = tokenised;
for (let i = 0; i < numValues; i++) {
output = output.replace(i < numColors ? colorToken : numberToken, i < numColors
? color.transform(v[i])
: sanitize(v[i]));
}
return output;
};
}
const convertNumbersToZero = (v) => typeof v === "number" ? 0 : v;
function getAnimatableNone(v) {
const parsed = parse(v);
const transformer = createTransformer(v);
return transformer(parsed.map(convertNumbersToZero));
}
const complex = { test, parse, createTransformer, getAnimatableNone };
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix-complex.mjs
function getMixer(origin, target) {
if (typeof origin === "number") {
return (v) => mix(origin, target, v);
}
else if (color.test(origin)) {
return mixColor(origin, target);
}
else {
return mixComplex(origin, target);
}
}
const mixArray = (from, to) => {
const output = [...from];
const numValues = output.length;
const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i]));
return (v) => {
for (let i = 0; i < numValues; i++) {
output[i] = blendValue[i](v);
}
return output;
};
};
const mixObject = (origin, target) => {
const output = { ...origin, ...target };
const blendValue = {};
for (const key in output) {
if (origin[key] !== undefined && target[key] !== undefined) {
blendValue[key] = getMixer(origin[key], target[key]);
}
}
return (v) => {
for (const key in blendValue) {
output[key] = blendValue[key](v);
}
return output;
};
};
const mixComplex = (origin, target) => {
const template = complex.createTransformer(target);
const originStats = analyseComplexValue(origin);
const targetStats = analyseComplexValue(target);
const canInterpolate = originStats.numColors === targetStats.numColors &&
originStats.numNumbers >= targetStats.numNumbers;
if (canInterpolate) {
return pipe(mixArray(originStats.values, targetStats.values), template);
}
else {
warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`);
return (p) => `${p > 0 ? target : origin}`;
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/progress.mjs
/*
Progress within given range
Given a lower limit and an upper limit, we return the progress
(expressed as a number 0-1) represented by the given value, and
limit that progress to within 0-1.
@param [number]: Lower limit
@param [number]: Upper limit
@param [number]: Value to find progress within given range
@return [number]: Progress of value within range as expressed 0-1
*/
const progress = (from, to, value) => {
const toFromDifference = to - from;
return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/interpolate.mjs
const mixNumber = (from, to) => (p) => mix(from, to, p);
function detectMixerFactory(v) {
if (typeof v === "number") {
return mixNumber;
}
else if (typeof v === "string") {
if (color.test(v)) {
return mixColor;
}
else {
return mixComplex;
}
}
else if (Array.isArray(v)) {
return mixArray;
}
else if (typeof v === "object") {
return mixObject;
}
return mixNumber;
}
function createMixers(output, ease, customMixer) {
const mixers = [];
const mixerFactory = customMixer || detectMixerFactory(output[0]);
const numMixers = output.length - 1;
for (let i = 0; i < numMixers; i++) {
let mixer = mixerFactory(output[i], output[i + 1]);
if (ease) {
const easingFunction = Array.isArray(ease) ? ease[i] || noop : ease;
mixer = pipe(easingFunction, mixer);
}
mixers.push(mixer);
}
return mixers;
}
/**
* Create a function that maps from a numerical input array to a generic output array.
*
* Accepts:
* - Numbers
* - Colors (hex, hsl, hsla, rgb, rgba)
* - Complex (combinations of one or more numbers or strings)
*
* ```jsx
* const mixColor = interpolate([0, 1], ['#fff', '#000'])
*
* mixColor(0.5) // 'rgba(128, 128, 128, 1)'
* ```
*
* TODO Revist this approach once we've moved to data models for values,
* probably not needed to pregenerate mixer functions.
*
* @public
*/
function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {
const inputLength = input.length;
invariant(inputLength === output.length, "Both input and output ranges must be the same length");
/**
* If we're only provided a single input, we can just make a function
* that returns the output.
*/
if (inputLength === 1)
return () => output[0];
// If input runs highest -> lowest, reverse both arrays
if (input[0] > input[inputLength - 1]) {
input = [...input].reverse();
output = [...output].reverse();
}
const mixers = createMixers(output, ease, mixer);
const numMixers = mixers.length;
const interpolator = (v) => {
let i = 0;
if (numMixers > 1) {
for (; i < input.length - 2; i++) {
if (v < input[i + 1])
break;
}
}
const progressInRange = progress(input[i], input[i + 1], v);
return mixers[i](progressInRange);
};
return isClamp
? (v) => interpolator(clamp(input[0], input[inputLength - 1], v))
: interpolator;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/offsets/fill.mjs
function fillOffset(offset, remaining) {
const min = offset[offset.length - 1];
for (let i = 1; i <= remaining; i++) {
const offsetProgress = progress(0, remaining, i);
offset.push(mix(min, 1, offsetProgress));
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/offsets/default.mjs
function defaultOffset(arr) {
const offset = [0];
fillOffset(offset, arr.length - 1);
return offset;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/offsets/time.mjs
function convertOffsetToTimes(offset, duration) {
return offset.map((o) => o * duration);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/generators/keyframes.mjs
function defaultEasing(values, easing) {
return values.map(() => easing || easeInOut).splice(0, values.length - 1);
}
function keyframes({ duration = 300, keyframes: keyframeValues, times, ease = "easeInOut", }) {
/**
* Easing functions can be externally defined as strings. Here we convert them
* into actual functions.
*/
const easingFunctions = isEasingArray(ease)
? ease.map(easingDefinitionToFunction)
: easingDefinitionToFunction(ease);
/**
* This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
* to reduce GC during animation.
*/
const state = {
done: false,
value: keyframeValues[0],
};
/**
* Create a times array based on the provided 0-1 offsets
*/
const absoluteTimes = convertOffsetToTimes(
// Only use the provided offsets if they're the correct length
// TODO Maybe we should warn here if there's a length mismatch
times && times.length === keyframeValues.length
? times
: defaultOffset(keyframeValues), duration);
const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {
ease: Array.isArray(easingFunctions)
? easingFunctions
: defaultEasing(keyframeValues, easingFunctions),
});
return {
calculatedDuration: duration,
next: (t) => {
state.value = mapTimeToKeyframe(t);
state.done = t >= duration;
return state;
},
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/velocity-per-second.mjs
/*
Convert velocity into velocity per second
@param [number]: Unit per frame
@param [number]: Frame duration in ms
*/
function velocityPerSecond(velocity, frameDuration) {
return frameDuration ? velocity * (1000 / frameDuration) : 0;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/generators/utils/velocity.mjs
const velocitySampleDuration = 5; // ms
function calcGeneratorVelocity(resolveValue, t, current) {
const prevT = Math.max(t - velocitySampleDuration, 0);
return velocityPerSecond(current - resolveValue(prevT), t - prevT);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/generators/spring/find.mjs
const safeMin = 0.001;
const minDuration = 0.01;
const maxDuration = 10.0;
const minDamping = 0.05;
const maxDamping = 1;
function findSpring({ duration = 800, bounce = 0.25, velocity = 0, mass = 1, }) {
let envelope;
let derivative;
warning(duration <= secondsToMilliseconds(maxDuration), "Spring duration must be 10 seconds or less");
let dampingRatio = 1 - bounce;
/**
* Restrict dampingRatio and duration to within acceptable ranges.
*/
dampingRatio = clamp(minDamping, maxDamping, dampingRatio);
duration = clamp(minDuration, maxDuration, millisecondsToSeconds(duration));
if (dampingRatio < 1) {
/**
* Underdamped spring
*/
envelope = (undampedFreq) => {
const exponentialDecay = undampedFreq * dampingRatio;
const delta = exponentialDecay * duration;
const a = exponentialDecay - velocity;
const b = calcAngularFreq(undampedFreq, dampingRatio);
const c = Math.exp(-delta);
return safeMin - (a / b) * c;
};
derivative = (undampedFreq) => {
const exponentialDecay = undampedFreq * dampingRatio;
const delta = exponentialDecay * duration;
const d = delta * velocity + velocity;
const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;
const f = Math.exp(-delta);
const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);
const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;
return (factor * ((d - e) * f)) / g;
};
}
else {
/**
* Critically-damped spring
*/
envelope = (undampedFreq) => {
const a = Math.exp(-undampedFreq * duration);
const b = (undampedFreq - velocity) * duration + 1;
return -safeMin + a * b;
};
derivative = (undampedFreq) => {
const a = Math.exp(-undampedFreq * duration);
const b = (velocity - undampedFreq) * (duration * duration);
return a * b;
};
}
const initialGuess = 5 / duration;
const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
duration = secondsToMilliseconds(duration);
if (isNaN(undampedFreq)) {
return {
stiffness: 100,
damping: 10,
duration,
};
}
else {
const stiffness = Math.pow(undampedFreq, 2) * mass;
return {
stiffness,
damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
duration,
};
}
}
const rootIterations = 12;
function approximateRoot(envelope, derivative, initialGuess) {
let result = initialGuess;
for (let i = 1; i < rootIterations; i++) {
result = result - envelope(result) / derivative(result);
}
return result;
}
function calcAngularFreq(undampedFreq, dampingRatio) {
return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/generators/spring/index.mjs
const durationKeys = ["duration", "bounce"];
const physicsKeys = ["stiffness", "damping", "mass"];
function isSpringType(options, keys) {
return keys.some((key) => options[key] !== undefined);
}
function getSpringOptions(options) {
let springOptions = {
velocity: 0.0,
stiffness: 100,
damping: 10,
mass: 1.0,
isResolvedFromDuration: false,
...options,
};
// stiffness/damping/mass overrides duration/bounce
if (!isSpringType(options, physicsKeys) &&
isSpringType(options, durationKeys)) {
const derived = findSpring(options);
springOptions = {
...springOptions,
...derived,
velocity: 0.0,
mass: 1.0,
};
springOptions.isResolvedFromDuration = true;
}
return springOptions;
}
function spring({ keyframes, restDelta, restSpeed, ...options }) {
const origin = keyframes[0];
const target = keyframes[keyframes.length - 1];
/**
* This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
* to reduce GC during animation.
*/
const state = { done: false, value: origin };
const { stiffness, damping, mass, velocity, duration, isResolvedFromDuration, } = getSpringOptions(options);
const initialVelocity = velocity ? -millisecondsToSeconds(velocity) : 0.0;
const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
const initialDelta = target - origin;
const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass));
/**
* If we're working on a granular scale, use smaller defaults for determining
* when the spring is finished.
*
* These defaults have been selected emprically based on what strikes a good
* ratio between feeling good and finishing as soon as changes are imperceptible.
*/
const isGranularScale = Math.abs(initialDelta) < 5;
restSpeed || (restSpeed = isGranularScale ? 0.01 : 2);
restDelta || (restDelta = isGranularScale ? 0.005 : 0.5);
let resolveSpring;
if (dampingRatio < 1) {
const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
// Underdamped spring
resolveSpring = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
return (target -
envelope *
(((initialVelocity +
dampingRatio * undampedAngularFreq * initialDelta) /
angularFreq) *
Math.sin(angularFreq * t) +
initialDelta * Math.cos(angularFreq * t)));
};
}
else if (dampingRatio === 1) {
// Critically damped spring
resolveSpring = (t) => target -
Math.exp(-undampedAngularFreq * t) *
(initialDelta +
(initialVelocity + undampedAngularFreq * initialDelta) * t);
}
else {
// Overdamped spring
const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
resolveSpring = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
// When performing sinh or cosh values can hit Infinity so we cap them here
const freqForT = Math.min(dampedAngularFreq * t, 300);
return (target -
(envelope *
((initialVelocity +
dampingRatio * undampedAngularFreq * initialDelta) *
Math.sinh(freqForT) +
dampedAngularFreq *
initialDelta *
Math.cosh(freqForT))) /
dampedAngularFreq);
};
}
return {
calculatedDuration: isResolvedFromDuration ? duration || null : null,
next: (t) => {
const current = resolveSpring(t);
if (!isResolvedFromDuration) {
let currentVelocity = initialVelocity;
if (t !== 0) {
/**
* We only need to calculate velocity for under-damped springs
* as over- and critically-damped springs can't overshoot, so
* checking only for displacement is enough.
*/
if (dampingRatio < 1) {
currentVelocity = calcGeneratorVelocity(resolveSpring, t, current);
}
else {
currentVelocity = 0;
}
}
const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;
const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta;
state.done =
isBelowVelocityThreshold && isBelowDisplacementThreshold;
}
else {
state.done = t >= duration;
}
state.value = state.done ? target : current;
return state;
},
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/generators/inertia.mjs
function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {
const origin = keyframes[0];
const state = {
done: false,
value: origin,
};
const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);
const nearestBoundary = (v) => {
if (min === undefined)
return max;
if (max === undefined)
return min;
return Math.abs(min - v) < Math.abs(max - v) ? min : max;
};
let amplitude = power * velocity;
const ideal = origin + amplitude;
const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
/**
* If the target has changed we need to re-calculate the amplitude, otherwise
* the animation will start from the wrong position.
*/
if (target !== ideal)
amplitude = target - origin;
const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);
const calcLatest = (t) => target + calcDelta(t);
const applyFriction = (t) => {
const delta = calcDelta(t);
const latest = calcLatest(t);
state.done = Math.abs(delta) <= restDelta;
state.value = state.done ? target : latest;
};
/**
* Ideally this would resolve for t in a stateless way, we could
* do that by always precalculating the animation but as we know
* this will be done anyway we can assume that spring will
* be discovered during that.
*/
let timeReachedBoundary;
let spring$1;
const checkCatchBoundary = (t) => {
if (!isOutOfBounds(state.value))
return;
timeReachedBoundary = t;
spring$1 = spring({
keyframes: [state.value, nearestBoundary(state.value)],
velocity: calcGeneratorVelocity(calcLatest, t, state.value),
damping: bounceDamping,
stiffness: bounceStiffness,
restDelta,
restSpeed,
});
};
checkCatchBoundary(0);
return {
calculatedDuration: null,
next: (t) => {
/**
* We need to resolve the friction to figure out if we need a
* spring but we don't want to do this twice per frame. So here
* we flag if we updated for this frame and later if we did
* we can skip doing it again.
*/
let hasUpdatedFrame = false;
if (!spring$1 && timeReachedBoundary === undefined) {
hasUpdatedFrame = true;
applyFriction(t);
checkCatchBoundary(t);
}
/**
* If we have a spring and the provided t is beyond the moment the friction
* animation crossed the min/max boundary, use the spring.
*/
if (timeReachedBoundary !== undefined && t > timeReachedBoundary) {
return spring$1.next(t - timeReachedBoundary);
}
else {
!hasUpdatedFrame && applyFriction(t);
return state;
}
},
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/js/driver-frameloop.mjs
const frameloopDriver = (update) => {
const passTimestamp = ({ timestamp }) => update(timestamp);
return {
start: () => sync.update(passTimestamp, true),
stop: () => cancelSync.update(passTimestamp),
/**
* If we're processing this frame we can use the
* framelocked timestamp to keep things in sync.
*/
now: () => frameData.isProcessing ? frameData.timestamp : performance.now(),
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/generators/utils/calc-duration.mjs
/**
* Implement a practical max duration for keyframe generation
* to prevent infinite loops
*/
const maxGeneratorDuration = 20000;
function calcGeneratorDuration(generator) {
let duration = 0;
const timeStep = 50;
let state = generator.next(duration);
while (!state.done && duration < maxGeneratorDuration) {
duration += timeStep;
state = generator.next(duration);
}
return duration >= maxGeneratorDuration ? Infinity : duration;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/js/index.mjs
const types = {
decay: inertia,
inertia: inertia,
tween: keyframes,
keyframes: keyframes,
spring: spring,
};
/**
* Animate a single value on the main thread.
*
* This function is written, where functionality overlaps,
* to be largely spec-compliant with WAAPI to allow fungibility
* between the two.
*/
function animateValue({ autoplay = true, delay = 0, driver = frameloopDriver, keyframes: keyframes$1, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", onPlay, onStop, onComplete, onUpdate, ...options }) {
let speed = 1;
let hasStopped = false;
let resolveFinishedPromise;
let currentFinishedPromise;
/**
* Create a new finished Promise every time we enter the
* finished state and resolve the old Promise. This is
* WAAPI-compatible behaviour.
*/
const updateFinishedPromise = () => {
resolveFinishedPromise && resolveFinishedPromise();
currentFinishedPromise = new Promise((resolve) => {
resolveFinishedPromise = resolve;
});
};
// Create the first finished promise
updateFinishedPromise();
let animationDriver;
const generatorFactory = types[type] || keyframes;
/**
* If this isn't the keyframes generator and we've been provided
* strings as keyframes, we need to interpolate these.
* TODO: Support velocity for units and complex value types/
*/
let mapNumbersToKeyframes;
if (generatorFactory !== keyframes &&
typeof keyframes$1[0] !== "number") {
mapNumbersToKeyframes = interpolate([0, 100], keyframes$1, {
clamp: false,
});
keyframes$1 = [0, 100];
}
const generator = generatorFactory({ ...options, keyframes: keyframes$1 });
let mirroredGenerator;
if (repeatType === "mirror") {
mirroredGenerator = generatorFactory({
...options,
keyframes: [...keyframes$1].reverse(),
velocity: -(options.velocity || 0),
});
}
let playState = "idle";
let holdTime = null;
let startTime = null;
let cancelTime = null;
/**
* If duration is undefined and we have repeat options,
* we need to calculate a duration from the generator.
*
* We set it to the generator itself to cache the duration.
* Any timeline resolver will need to have already precalculated
* the duration by this step.
*/
if (generator.calculatedDuration === null && repeat) {
generator.calculatedDuration = calcGeneratorDuration(generator);
}
const { calculatedDuration } = generator;
let resolvedDuration = Infinity;
let totalDuration = Infinity;
if (calculatedDuration !== null) {
resolvedDuration = calculatedDuration + repeatDelay;
totalDuration = resolvedDuration * (repeat + 1) - repeatDelay;
}
let currentTime = 0;
const tick = (timestamp) => {
if (startTime === null)
return;
/**
* requestAnimationFrame timestamps can come through as lower than
* the startTime as set by performance.now(). Here we prevent this,
* though in the future it could be possible to make setting startTime
* a pending operation that gets resolved here.
*/
if (speed > 0)
startTime = Math.min(startTime, timestamp);
if (holdTime !== null) {
currentTime = holdTime;
}
else {
currentTime = (timestamp - startTime) * speed;
}
// Rebase on delay
const timeWithoutDelay = currentTime - delay;
const isInDelayPhase = timeWithoutDelay < 0;
currentTime = Math.max(timeWithoutDelay, 0);
/**
* If this animation has finished, set the current time
* to the total duration.
*/
if (playState === "finished" && holdTime === null) {
currentTime = totalDuration;
}
let elapsed = currentTime;
let frameGenerator = generator;
if (repeat) {
/**
* Get the current progress (0-1) of the animation. If t is >
* than duration we'll get values like 2.5 (midway through the
* third iteration)
*/
const progress = currentTime / resolvedDuration;
/**
* Get the current iteration (0 indexed). For instance the floor of
* 2.5 is 2.
*/
let currentIteration = Math.floor(progress);
/**
* Get the current progress of the iteration by taking the remainder
* so 2.5 is 0.5 through iteration 2
*/
let iterationProgress = progress % 1.0;
/**
* If iteration progress is 1 we count that as the end
* of the previous iteration.
*/
if (!iterationProgress && progress >= 1) {
iterationProgress = 1;
}
iterationProgress === 1 && currentIteration--;
currentIteration = Math.min(currentIteration, repeat + 1);
/**
* Reverse progress if we're not running in "normal" direction
*/
const iterationIsOdd = Boolean(currentIteration % 2);
if (iterationIsOdd) {
if (repeatType === "reverse") {
iterationProgress = 1 - iterationProgress;
if (repeatDelay) {
iterationProgress -= repeatDelay / resolvedDuration;
}
}
else if (repeatType === "mirror") {
frameGenerator = mirroredGenerator;
}
}
let p = clamp(0, 1, iterationProgress);
if (currentTime > totalDuration) {
p = repeatType === "reverse" && iterationIsOdd ? 1 : 0;
}
elapsed = p * resolvedDuration;
}
/**
* If we're in negative time, set state as the initial keyframe.
* This prevents delay: x, duration: 0 animations from finishing
* instantly.
*/
const state = isInDelayPhase
? { done: false, value: keyframes$1[0] }
: frameGenerator.next(elapsed);
if (mapNumbersToKeyframes) {
state.value = mapNumbersToKeyframes(state.value);
}
let { done } = state;
if (!isInDelayPhase && calculatedDuration !== null) {
done = currentTime >= totalDuration;
}
const isAnimationFinished = holdTime === null &&
(playState === "finished" ||
(playState === "running" && done) ||
(speed < 0 && currentTime <= 0));
if (onUpdate) {
onUpdate(state.value);
}
if (isAnimationFinished) {
finish();
}
return state;
};
const stopAnimationDriver = () => {
animationDriver && animationDriver.stop();
animationDriver = undefined;
};
const cancel = () => {
playState = "idle";
stopAnimationDriver();
updateFinishedPromise();
startTime = cancelTime = null;
};
const finish = () => {
playState = "finished";
onComplete && onComplete();
stopAnimationDriver();
updateFinishedPromise();
};
const play = () => {
if (hasStopped)
return;
if (!animationDriver)
animationDriver = driver(tick);
const now = animationDriver.now();
onPlay && onPlay();
if (holdTime !== null) {
startTime = now - holdTime;
}
else if (!startTime || playState === "finished") {
startTime = now;
}
cancelTime = startTime;
holdTime = null;
/**
* Set playState to running only after we've used it in
* the previous logic.
*/
playState = "running";
animationDriver.start();
};
if (autoplay) {
play();
}
const controls = {
then(resolve, reject) {
return currentFinishedPromise.then(resolve, reject);
},
get time() {
return millisecondsToSeconds(currentTime);
},
set time(newTime) {
newTime = secondsToMilliseconds(newTime);
currentTime = newTime;
if (holdTime !== null || !animationDriver || speed === 0) {
holdTime = newTime;
}
else {
startTime = animationDriver.now() - newTime / speed;
}
},
get duration() {
const duration = generator.calculatedDuration === null
? calcGeneratorDuration(generator)
: generator.calculatedDuration;
return millisecondsToSeconds(duration);
},
get speed() {
return speed;
},
set speed(newSpeed) {
if (newSpeed === speed || !animationDriver)
return;
speed = newSpeed;
controls.time = millisecondsToSeconds(currentTime);
},
get state() {
return playState;
},
play,
pause: () => {
playState = "paused";
holdTime = currentTime;
},
stop: () => {
hasStopped = true;
if (playState === "idle")
return;
playState = "idle";
onStop && onStop();
cancel();
},
cancel: () => {
if (cancelTime !== null)
tick(cancelTime);
cancel();
},
complete: () => {
playState = "finished";
},
sample: (elapsed) => {
startTime = 0;
return tick(elapsed);
},
};
return controls;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/waapi/create-accelerated-animation.mjs
/**
* A list of values that can be hardware-accelerated.
*/
const acceleratedValues = new Set([
"opacity",
"clipPath",
"filter",
"transform",
"backgroundColor",
]);
/**
* 10ms is chosen here as it strikes a balance between smooth
* results (more than one keyframe per frame at 60fps) and
* keyframe quantity.
*/
const sampleDelta = 10; //ms
/**
* Implement a practical max duration for keyframe generation
* to prevent infinite loops
*/
const create_accelerated_animation_maxDuration = 20000;
const requiresPregeneratedKeyframes = (valueName, options) => options.type === "spring" ||
valueName === "backgroundColor" ||
!isWaapiSupportedEasing(options.ease);
function createAcceleratedAnimation(value, valueName, { onUpdate, onComplete, ...options }) {
const canAccelerateAnimation = supports.waapi() &&
acceleratedValues.has(valueName) &&
!options.repeatDelay &&
options.repeatType !== "mirror" &&
options.damping !== 0 &&
options.type !== "inertia";
if (!canAccelerateAnimation)
return false;
/**
* TODO: Unify with js/index
*/
let hasStopped = false;
let resolveFinishedPromise;
let currentFinishedPromise;
/**
* Create a new finished Promise every time we enter the
* finished state and resolve the old Promise. This is
* WAAPI-compatible behaviour.
*/
const updateFinishedPromise = () => {
currentFinishedPromise = new Promise((resolve) => {
resolveFinishedPromise = resolve;
});
};
// Create the first finished promise
updateFinishedPromise();
let { keyframes, duration = 300, ease, times } = options;
/**
* If this animation needs pre-generated keyframes then generate.
*/
if (requiresPregeneratedKeyframes(valueName, options)) {
const sampleAnimation = animateValue({
...options,
repeat: 0,
delay: 0,
});
let state = { done: false, value: keyframes[0] };
const pregeneratedKeyframes = [];
/**
* Bail after 20 seconds of pre-generated keyframes as it's likely
* we're heading for an infinite loop.
*/
let t = 0;
while (!state.done && t < create_accelerated_animation_maxDuration) {
state = sampleAnimation.sample(t);
pregeneratedKeyframes.push(state.value);
t += sampleDelta;
}
times = undefined;
keyframes = pregeneratedKeyframes;
duration = t - sampleDelta;
ease = "linear";
}
const animation = animateStyle(value.owner.current, valueName, keyframes, {
...options,
duration,
/**
* This function is currently not called if ease is provided
* as a function so the cast is safe.
*
* However it would be possible for a future refinement to port
* in easing pregeneration from Motion One for browsers that
* support the upcoming `linear()` easing function.
*/
ease: ease,
times,
});
const cancelAnimation = () => animation.cancel();
const safeCancel = () => {
sync.update(cancelAnimation);
resolveFinishedPromise();
updateFinishedPromise();
};
/**
* Prefer the `onfinish` prop as it's more widely supported than
* the `finished` promise.
*
* Here, we synchronously set the provided MotionValue to the end
* keyframe. If we didn't, when the WAAPI animation is finished it would
* be removed from the element which would then revert to its old styles.
*/
animation.onfinish = () => {
value.set(getFinalKeyframe(keyframes, options));
onComplete && onComplete();
safeCancel();
};
/**
* Animation interrupt callback.
*/
return {
then(resolve, reject) {
return currentFinishedPromise.then(resolve, reject);
},
get time() {
return millisecondsToSeconds(animation.currentTime || 0);
},
set time(newTime) {
animation.currentTime = secondsToMilliseconds(newTime);
},
get speed() {
return animation.playbackRate;
},
set speed(newSpeed) {
animation.playbackRate = newSpeed;
},
get duration() {
return millisecondsToSeconds(duration);
},
play: () => {
if (hasStopped)
return;
animation.play();
/**
* Cancel any pending cancel tasks
*/
cancelSync.update(cancelAnimation);
},
pause: () => animation.pause(),
stop: () => {
hasStopped = true;
if (animation.playState === "idle")
return;
/**
* WAAPI doesn't natively have any interruption capabilities.
*
* Rather than read commited styles back out of the DOM, we can
* create a renderless JS animation and sample it twice to calculate
* its current value, "previous" value, and therefore allow
* Motion to calculate velocity for any subsequent animation.
*/
const { currentTime } = animation;
if (currentTime) {
const sampleAnimation = animateValue({
...options,
autoplay: false,
});
value.setWithVelocity(sampleAnimation.sample(currentTime - sampleDelta).value, sampleAnimation.sample(currentTime).value, sampleDelta);
}
safeCancel();
},
complete: () => animation.finish(),
cancel: safeCancel,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/instant.mjs
function createInstantAnimation({ keyframes, delay, onUpdate, onComplete, }) {
const setValue = () => {
onUpdate && onUpdate(keyframes[keyframes.length - 1]);
onComplete && onComplete();
/**
* TODO: As this API grows it could make sense to always return
* animateValue. This will be a bigger project as animateValue
* is frame-locked whereas this function resolves instantly.
* This is a behavioural change and also has ramifications regarding
* assumptions within tests.
*/
return {
time: 0,
speed: 1,
duration: 0,
play: (noop),
pause: (noop),
stop: (noop),
then: (resolve) => {
resolve();
return Promise.resolve();
},
cancel: (noop),
complete: (noop),
};
};
return delay
? animateValue({
keyframes: [0, 1],
duration: 0,
delay,
onComplete: setValue,
})
: setValue();
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs
const underDampedSpring = {
type: "spring",
stiffness: 500,
damping: 25,
restSpeed: 10,
};
const criticallyDampedSpring = (target) => ({
type: "spring",
stiffness: 550,
damping: target === 0 ? 2 * Math.sqrt(550) : 30,
restSpeed: 10,
});
const keyframesTransition = {
type: "keyframes",
duration: 0.8,
};
/**
* Default easing curve is a slightly shallower version of
* the default browser easing curve.
*/
const ease = {
type: "keyframes",
ease: [0.25, 0.1, 0.35, 1],
duration: 0.3,
};
const getDefaultTransition = (valueKey, { keyframes }) => {
if (keyframes.length > 2) {
return keyframesTransition;
}
else if (transformProps.has(valueKey)) {
return valueKey.startsWith("scale")
? criticallyDampedSpring(keyframes[1])
: underDampedSpring;
}
return ease;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-animatable.mjs
/**
* Check if a value is animatable. Examples:
*
* ✅: 100, "100px", "#fff"
* ❌: "block", "url(2.jpg)"
* @param value
*
* @internal
*/
const isAnimatable = (key, value) => {
// If the list of keys tat might be non-animatable grows, replace with Set
if (key === "zIndex")
return false;
// If it's a number or a keyframes array, we can animate it. We might at some point
// need to do a deep isAnimatable check of keyframes, or let Popmotion handle this,
// but for now lets leave it like this for performance reasons
if (typeof value === "number" || Array.isArray(value))
return true;
if (typeof value === "string" && // It's animatable if we have a string
complex.test(value) && // And it contains numbers and/or colors
!value.startsWith("url(") // Unless it starts with "url("
) {
return true;
}
return false;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/complex/filter.mjs
/**
* Properties that should default to 1 or 100%
*/
const maxDefaults = new Set(["brightness", "contrast", "saturate", "opacity"]);
function applyDefaultFilter(v) {
const [name, value] = v.slice(0, -1).split("(");
if (name === "drop-shadow")
return v;
const [number] = value.match(floatRegex) || [];
if (!number)
return v;
const unit = value.replace(number, "");
let defaultValue = maxDefaults.has(name) ? 1 : 0;
if (number !== value)
defaultValue *= 100;
return name + "(" + defaultValue + unit + ")";
}
const functionRegex = /([a-z-]*)\(.*?\)/g;
const filter = {
...complex,
getAnimatableNone: (v) => {
const functions = v.match(functionRegex);
return functions ? functions.map(applyDefaultFilter).join(" ") : v;
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/defaults.mjs
/**
* A map of default value types for common values
*/
const defaultValueTypes = {
...numberValueTypes,
// Color props
color: color,
backgroundColor: color,
outlineColor: color,
fill: color,
stroke: color,
// Border props
borderColor: color,
borderTopColor: color,
borderRightColor: color,
borderBottomColor: color,
borderLeftColor: color,
filter: filter,
WebkitFilter: filter,
};
/**
* Gets the default ValueType for the provided value key
*/
const getDefaultValueType = (key) => defaultValueTypes[key];
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/animatable-none.mjs
function animatable_none_getAnimatableNone(key, value) {
let defaultValueType = getDefaultValueType(key);
if (defaultValueType !== filter)
defaultValueType = complex;
// If value is not recognised as animatable, ie "none", create an animatable version origin based on the target
return defaultValueType.getAnimatableNone
? defaultValueType.getAnimatableNone(value)
: undefined;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/transitions.mjs
/**
* Decide whether a transition is defined on a given Transition.
* This filters out orchestration options and returns true
* if any options are left.
*/
function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) {
return !!Object.keys(transition).length;
}
function isZero(value) {
return (value === 0 ||
(typeof value === "string" &&
parseFloat(value) === 0 &&
value.indexOf(" ") === -1));
}
function getZeroUnit(potentialUnitType) {
return typeof potentialUnitType === "number"
? 0
: animatable_none_getAnimatableNone("", potentialUnitType);
}
function getValueTransition(transition, key) {
return transition[key] || transition["default"] || transition;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/wildcards.mjs
function fillWildcardKeyframes(origin, [...keyframes]) {
/**
* Ensure an wildcard keyframes are hydrated by the origin.
*/
for (let i = 0; i < keyframes.length; i++) {
if (keyframes[i] === null) {
keyframes[i] = i === 0 ? origin : keyframes[i - 1];
}
}
return keyframes;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/keyframes.mjs
function getKeyframes(value, valueName, target, transition) {
const isTargetAnimatable = isAnimatable(valueName, target);
let origin = transition.from !== undefined ? transition.from : value.get();
if (origin === "none" && isTargetAnimatable && typeof target === "string") {
/**
* If we're trying to animate from "none", try and get an animatable version
* of the target. This could be improved to work both ways.
*/
origin = animatable_none_getAnimatableNone(valueName, target);
}
else if (isZero(origin) && typeof target === "string") {
origin = getZeroUnit(target);
}
else if (!Array.isArray(target) &&
isZero(target) &&
typeof origin === "string") {
target = getZeroUnit(origin);
}
/**
* If the target has been defined as a series of keyframes
*/
if (Array.isArray(target)) {
return fillWildcardKeyframes(origin, target);
}
else {
return [origin, target];
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs
const animateMotionValue = (valueName, value, target, transition = {}) => {
return (onComplete) => {
const valueTransition = getValueTransition(transition, valueName) || {};
/**
* Most transition values are currently completely overwritten by value-specific
* transitions. In the future it'd be nicer to blend these transitions. But for now
* delay actually does inherit from the root transition if not value-specific.
*/
const delay = valueTransition.delay || transition.delay || 0;
/**
* Elapsed isn't a public transition option but can be passed through from
* optimized appear effects in milliseconds.
*/
let { elapsed = 0 } = transition;
elapsed = elapsed - secondsToMilliseconds(delay);
const keyframes = getKeyframes(value, valueName, target, valueTransition);
/**
* Check if we're able to animate between the start and end keyframes,
* and throw a warning if we're attempting to animate between one that's
* animatable and another that isn't.
*/
const originKeyframe = keyframes[0];
const targetKeyframe = keyframes[keyframes.length - 1];
const isOriginAnimatable = isAnimatable(valueName, originKeyframe);
const isTargetAnimatable = isAnimatable(valueName, targetKeyframe);
warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${valueName} from "${originKeyframe}" to "${targetKeyframe}". ${originKeyframe} is not an animatable value - to enable this animation set ${originKeyframe} to a value animatable to ${targetKeyframe} via the \`style\` property.`);
let options = {
keyframes,
velocity: value.getVelocity(),
ease: "easeOut",
...valueTransition,
delay: -elapsed,
onUpdate: (v) => {
value.set(v);
valueTransition.onUpdate && valueTransition.onUpdate(v);
},
onComplete: () => {
onComplete();
valueTransition.onComplete && valueTransition.onComplete();
},
};
/**
* If there's no transition defined for this value, we can generate
* unqiue transition settings for this value.
*/
if (!isTransitionDefined(valueTransition)) {
options = {
...options,
...getDefaultTransition(valueName, options),
};
}
/**
* Both WAAPI and our internal animation functions use durations
* as defined by milliseconds, while our external API defines them
* as seconds.
*/
if (options.duration) {
options.duration = secondsToMilliseconds(options.duration);
}
if (options.repeatDelay) {
options.repeatDelay = secondsToMilliseconds(options.repeatDelay);
}
if (!isOriginAnimatable ||
!isTargetAnimatable ||
instantAnimationState.current ||
valueTransition.type === false) {
/**
* If we can't animate this value, or the global instant animation flag is set,
* or this is simply defined as an instant transition, return an instant transition.
*/
return createInstantAnimation(options);
}
/**
* Animate via WAAPI if possible.
*/
if (value.owner &&
value.owner.current instanceof HTMLElement &&
!value.owner.getProps().onUpdate) {
const acceleratedAnimation = createAcceleratedAnimation(value, valueName, options);
if (acceleratedAnimation)
return acceleratedAnimation;
}
/**
* If we didn't create an accelerated animation, create a JS animation
*/
return animateValue(options);
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/use-will-change/is.mjs
function isWillChangeMotionValue(value) {
return Boolean(isMotionValue(value) && value.add);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-numerical-string.mjs
/**
* Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1"
*/
const isNumericalString = (v) => /^\-?\d*\.?\d+$/.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-zero-value-string.mjs
/**
* Check if the value is a zero value string like "0px" or "0%"
*/
const isZeroValueString = (v) => /^0[^.\s]+$/.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/array.mjs
function addUniqueItem(arr, item) {
if (arr.indexOf(item) === -1)
arr.push(item);
}
function removeItem(arr, item) {
const index = arr.indexOf(item);
if (index > -1)
arr.splice(index, 1);
}
// Adapted from array-move
function moveItem([...arr], fromIndex, toIndex) {
const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex;
if (startIndex >= 0 && startIndex < arr.length) {
const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex;
const [item] = arr.splice(fromIndex, 1);
arr.splice(endIndex, 0, item);
}
return arr;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/subscription-manager.mjs
class SubscriptionManager {
constructor() {
this.subscriptions = [];
}
add(handler) {
addUniqueItem(this.subscriptions, handler);
return () => removeItem(this.subscriptions, handler);
}
notify(a, b, c) {
const numSubscriptions = this.subscriptions.length;
if (!numSubscriptions)
return;
if (numSubscriptions === 1) {
/**
* If there's only a single handler we can just call it without invoking a loop.
*/
this.subscriptions[0](a, b, c);
}
else {
for (let i = 0; i < numSubscriptions; i++) {
/**
* Check whether the handler exists before firing as it's possible
* the subscriptions were modified during this loop running.
*/
const handler = this.subscriptions[i];
handler && handler(a, b, c);
}
}
}
getSize() {
return this.subscriptions.length;
}
clear() {
this.subscriptions.length = 0;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/index.mjs
const isFloat = (value) => {
return !isNaN(parseFloat(value));
};
/**
* `MotionValue` is used to track the state and velocity of motion values.
*
* @public
*/
class MotionValue {
/**
* @param init - The initiating value
* @param config - Optional configuration options
*
* - `transformer`: A function to transform incoming values with.
*
* @internal
*/
constructor(init, options = {}) {
/**
* This will be replaced by the build step with the latest version number.
* When MotionValues are provided to motion components, warn if versions are mixed.
*/
this.version = "10.11.6";
/**
* Duration, in milliseconds, since last updating frame.
*
* @internal
*/
this.timeDelta = 0;
/**
* Timestamp of the last time this `MotionValue` was updated.
*
* @internal
*/
this.lastUpdated = 0;
/**
* Tracks whether this value can output a velocity. Currently this is only true
* if the value is numerical, but we might be able to widen the scope here and support
* other value types.
*
* @internal
*/
this.canTrackVelocity = false;
/**
* An object containing a SubscriptionManager for each active event.
*/
this.events = {};
this.updateAndNotify = (v, render = true) => {
this.prev = this.current;
this.current = v;
// Update timestamp
const { delta, timestamp } = frameData;
if (this.lastUpdated !== timestamp) {
this.timeDelta = delta;
this.lastUpdated = timestamp;
sync.postRender(this.scheduleVelocityCheck);
}
// Update update subscribers
if (this.prev !== this.current && this.events.change) {
this.events.change.notify(this.current);
}
// Update velocity subscribers
if (this.events.velocityChange) {
this.events.velocityChange.notify(this.getVelocity());
}
// Update render subscribers
if (render && this.events.renderRequest) {
this.events.renderRequest.notify(this.current);
}
};
/**
* Schedule a velocity check for the next frame.
*
* This is an instanced and bound function to prevent generating a new
* function once per frame.
*
* @internal
*/
this.scheduleVelocityCheck = () => sync.postRender(this.velocityCheck);
/**
* Updates `prev` with `current` if the value hasn't been updated this frame.
* This ensures velocity calculations return `0`.
*
* This is an instanced and bound function to prevent generating a new
* function once per frame.
*
* @internal
*/
this.velocityCheck = ({ timestamp }) => {
if (timestamp !== this.lastUpdated) {
this.prev = this.current;
if (this.events.velocityChange) {
this.events.velocityChange.notify(this.getVelocity());
}
}
};
this.hasAnimated = false;
this.prev = this.current = init;
this.canTrackVelocity = isFloat(this.current);
this.owner = options.owner;
}
/**
* Adds a function that will be notified when the `MotionValue` is updated.
*
* It returns a function that, when called, will cancel the subscription.
*
* When calling `onChange` inside a React component, it should be wrapped with the
* `useEffect` hook. As it returns an unsubscribe function, this should be returned
* from the `useEffect` function to ensure you don't add duplicate subscribers..
*
* ```jsx
* export const MyComponent = () => {
* const x = useMotionValue(0)
* const y = useMotionValue(0)
* const opacity = useMotionValue(1)
*
* useEffect(() => {
* function updateOpacity() {
* const maxXY = Math.max(x.get(), y.get())
* const newOpacity = transform(maxXY, [0, 100], [1, 0])
* opacity.set(newOpacity)
* }
*
* const unsubscribeX = x.on("change", updateOpacity)
* const unsubscribeY = y.on("change", updateOpacity)
*
* return () => {
* unsubscribeX()
* unsubscribeY()
* }
* }, [])
*
* return <motion.div style={{ x }} />
* }
* ```
*
* @param subscriber - A function that receives the latest value.
* @returns A function that, when called, will cancel this subscription.
*
* @deprecated
*/
onChange(subscription) {
if (false) {}
return this.on("change", subscription);
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = new SubscriptionManager();
}
const unsubscribe = this.events[eventName].add(callback);
if (eventName === "change") {
return () => {
unsubscribe();
/**
* If we have no more change listeners by the start
* of the next frame, stop active animations.
*/
sync.read(() => {
if (!this.events.change.getSize()) {
this.stop();
}
});
};
}
return unsubscribe;
}
clearListeners() {
for (const eventManagers in this.events) {
this.events[eventManagers].clear();
}
}
/**
* Attaches a passive effect to the `MotionValue`.
*
* @internal
*/
attach(passiveEffect, stopPassiveEffect) {
this.passiveEffect = passiveEffect;
this.stopPassiveEffect = stopPassiveEffect;
}
/**
* Sets the state of the `MotionValue`.
*
* @remarks
*
* ```jsx
* const x = useMotionValue(0)
* x.set(10)
* ```
*
* @param latest - Latest value to set.
* @param render - Whether to notify render subscribers. Defaults to `true`
*
* @public
*/
set(v, render = true) {
if (!render || !this.passiveEffect) {
this.updateAndNotify(v, render);
}
else {
this.passiveEffect(v, this.updateAndNotify);
}
}
setWithVelocity(prev, current, delta) {
this.set(current);
this.prev = prev;
this.timeDelta = delta;
}
/**
* Set the state of the `MotionValue`, stopping any active animations,
* effects, and resets velocity to `0`.
*/
jump(v) {
this.updateAndNotify(v);
this.prev = v;
this.stop();
if (this.stopPassiveEffect)
this.stopPassiveEffect();
}
/**
* Returns the latest state of `MotionValue`
*
* @returns - The latest state of `MotionValue`
*
* @public
*/
get() {
return this.current;
}
/**
* @public
*/
getPrevious() {
return this.prev;
}
/**
* Returns the latest velocity of `MotionValue`
*
* @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
*
* @public
*/
getVelocity() {
// This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful
return this.canTrackVelocity
? // These casts could be avoided if parseFloat would be typed better
velocityPerSecond(parseFloat(this.current) -
parseFloat(this.prev), this.timeDelta)
: 0;
}
/**
* Registers a new animation to control this `MotionValue`. Only one
* animation can drive a `MotionValue` at one time.
*
* ```jsx
* value.start()
* ```
*
* @param animation - A function that starts the provided animation
*
* @internal
*/
start(startAnimation) {
this.stop();
return new Promise((resolve) => {
this.hasAnimated = true;
this.animation = startAnimation(resolve);
if (this.events.animationStart) {
this.events.animationStart.notify();
}
}).then(() => {
if (this.events.animationComplete) {
this.events.animationComplete.notify();
}
this.clearAnimation();
});
}
/**
* Stop the currently active animation.
*
* @public
*/
stop() {
if (this.animation) {
this.animation.stop();
if (this.events.animationCancel) {
this.events.animationCancel.notify();
}
}
this.clearAnimation();
}
/**
* Returns `true` if this value is currently animating.
*
* @public
*/
isAnimating() {
return !!this.animation;
}
clearAnimation() {
delete this.animation;
}
/**
* Destroy and clean up subscribers to this `MotionValue`.
*
* The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
* handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
* created a `MotionValue` via the `motionValue` function.
*
* @public
*/
destroy() {
this.clearListeners();
this.stop();
if (this.stopPassiveEffect) {
this.stopPassiveEffect();
}
}
}
function motionValue(init, options) {
return new MotionValue(init, options);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/test.mjs
/**
* Tests a provided value against a ValueType
*/
const testValueType = (v) => (type) => type.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/type-auto.mjs
/**
* ValueType for "auto"
*/
const auto = {
test: (v) => v === "auto",
parse: (v) => v,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/dimensions.mjs
/**
* A list of value types commonly used for dimensions
*/
const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];
/**
* Tests a dimensional value against the list of dimension ValueTypes
*/
const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/find.mjs
/**
* A list of all ValueTypes
*/
const valueTypes = [...dimensionValueTypes, color, complex];
/**
* Tests a value against the list of ValueTypes
*/
const findValueType = (v) => valueTypes.find(testValueType(v));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/setters.mjs
/**
* Set VisualElement's MotionValue, creating a new MotionValue for it if
* it doesn't exist.
*/
function setMotionValue(visualElement, key, value) {
if (visualElement.hasValue(key)) {
visualElement.getValue(key).set(value);
}
else {
visualElement.addValue(key, motionValue(value));
}
}
function setTarget(visualElement, definition) {
const resolved = resolveVariant(visualElement, definition);
let { transitionEnd = {}, transition = {}, ...target } = resolved ? visualElement.makeTargetAnimatable(resolved, false) : {};
target = { ...target, ...transitionEnd };
for (const key in target) {
const value = resolveFinalValueInKeyframes(target[key]);
setMotionValue(visualElement, key, value);
}
}
function setVariants(visualElement, variantLabels) {
const reversedLabels = [...variantLabels].reverse();
reversedLabels.forEach((key) => {
const variant = visualElement.getVariant(key);
variant && setTarget(visualElement, variant);
if (visualElement.variantChildren) {
visualElement.variantChildren.forEach((child) => {
setVariants(child, variantLabels);
});
}
});
}
function setValues(visualElement, definition) {
if (Array.isArray(definition)) {
return setVariants(visualElement, definition);
}
else if (typeof definition === "string") {
return setVariants(visualElement, [definition]);
}
else {
setTarget(visualElement, definition);
}
}
function checkTargetForNewValues(visualElement, target, origin) {
var _a, _b;
const newValueKeys = Object.keys(target).filter((key) => !visualElement.hasValue(key));
const numNewValues = newValueKeys.length;
if (!numNewValues)
return;
for (let i = 0; i < numNewValues; i++) {
const key = newValueKeys[i];
const targetValue = target[key];
let value = null;
/**
* If the target is a series of keyframes, we can use the first value
* in the array. If this first value is null, we'll still need to read from the DOM.
*/
if (Array.isArray(targetValue)) {
value = targetValue[0];
}
/**
* If the target isn't keyframes, or the first keyframe was null, we need to
* first check if an origin value was explicitly defined in the transition as "from",
* if not read the value from the DOM. As an absolute fallback, take the defined target value.
*/
if (value === null) {
value = (_b = (_a = origin[key]) !== null && _a !== void 0 ? _a : visualElement.readValue(key)) !== null && _b !== void 0 ? _b : target[key];
}
/**
* If value is still undefined or null, ignore it. Preferably this would throw,
* but this was causing issues in Framer.
*/
if (value === undefined || value === null)
continue;
if (typeof value === "string" &&
(isNumericalString(value) || isZeroValueString(value))) {
// If this is a number read as a string, ie "0" or "200", convert it to a number
value = parseFloat(value);
}
else if (!findValueType(value) && complex.test(targetValue)) {
value = animatable_none_getAnimatableNone(key, targetValue);
}
visualElement.addValue(key, motionValue(value, { owner: visualElement }));
if (origin[key] === undefined) {
origin[key] = value;
}
if (value !== null)
visualElement.setBaseTarget(key, value);
}
}
function getOriginFromTransition(key, transition) {
if (!transition)
return;
const valueTransition = transition[key] || transition["default"] || transition;
return valueTransition.from;
}
function getOrigin(target, transition, visualElement) {
const origin = {};
for (const key in target) {
const transitionOrigin = getOriginFromTransition(key, transition);
if (transitionOrigin !== undefined) {
origin[key] = transitionOrigin;
}
else {
const value = visualElement.getValue(key);
if (value) {
origin[key] = value.get();
}
}
}
return origin;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/interfaces/visual-element-target.mjs
/**
* Decide whether we should block this animation. Previously, we achieved this
* just by checking whether the key was listed in protectedKeys, but this
* posed problems if an animation was triggered by afterChildren and protectedKeys
* had been set to true in the meantime.
*/
function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
needsAnimating[key] = false;
return shouldBlock;
}
function animateTarget(visualElement, definition, { delay = 0, transitionOverride, type } = {}) {
let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = visualElement.makeTargetAnimatable(definition);
const willChange = visualElement.getValue("willChange");
if (transitionOverride)
transition = transitionOverride;
const animations = [];
const animationTypeState = type &&
visualElement.animationState &&
visualElement.animationState.getState()[type];
for (const key in target) {
const value = visualElement.getValue(key);
const valueTarget = target[key];
if (!value ||
valueTarget === undefined ||
(animationTypeState &&
shouldBlockAnimation(animationTypeState, key))) {
continue;
}
const valueTransition = { delay, elapsed: 0, ...transition };
/**
* If this is the first time a value is being animated, check
* to see if we're handling off from an existing animation.
*/
if (window.HandoffAppearAnimations && !value.hasAnimated) {
const appearId = visualElement.getProps()[optimizedAppearDataAttribute];
if (appearId) {
valueTransition.elapsed = window.HandoffAppearAnimations(appearId, key, value, sync);
}
}
value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && transformProps.has(key)
? { type: false }
: valueTransition));
const animation = value.animation;
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
animation.then(() => willChange.remove(key));
}
animations.push(animation);
}
if (transitionEnd) {
Promise.all(animations).then(() => {
transitionEnd && setTarget(visualElement, transitionEnd);
});
}
return animations;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/interfaces/visual-element-variant.mjs
function animateVariant(visualElement, variant, options = {}) {
const resolved = resolveVariant(visualElement, variant, options.custom);
let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};
if (options.transitionOverride) {
transition = options.transitionOverride;
}
/**
* If we have a variant, create a callback that runs it as an animation.
* Otherwise, we resolve a Promise immediately for a composable no-op.
*/
const getAnimation = resolved
? () => Promise.all(animateTarget(visualElement, resolved, options))
: () => Promise.resolve();
/**
* If we have children, create a callback that runs all their animations.
* Otherwise, we resolve a Promise immediately for a composable no-op.
*/
const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size
? (forwardDelay = 0) => {
const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
return animateChildren(visualElement, variant, delayChildren + forwardDelay, staggerChildren, staggerDirection, options);
}
: () => Promise.resolve();
/**
* If the transition explicitly defines a "when" option, we need to resolve either
* this animation or all children animations before playing the other.
*/
const { when } = transition;
if (when) {
const [first, last] = when === "beforeChildren"
? [getAnimation, getChildAnimations]
: [getChildAnimations, getAnimation];
return first().then(() => last());
}
else {
return Promise.all([getAnimation(), getChildAnimations(options.delay)]);
}
}
function animateChildren(visualElement, variant, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {
const animations = [];
const maxStaggerDuration = (visualElement.variantChildren.size - 1) * staggerChildren;
const generateStaggerDuration = staggerDirection === 1
? (i = 0) => i * staggerChildren
: (i = 0) => maxStaggerDuration - i * staggerChildren;
Array.from(visualElement.variantChildren)
.sort(sortByTreeOrder)
.forEach((child, i) => {
child.notify("AnimationStart", variant);
animations.push(animateVariant(child, variant, {
...options,
delay: delayChildren + generateStaggerDuration(i),
}).then(() => child.notify("AnimationComplete", variant)));
});
return Promise.all(animations);
}
function sortByTreeOrder(a, b) {
return a.sortNodePosition(b);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/interfaces/visual-element.mjs
function animateVisualElement(visualElement, definition, options = {}) {
visualElement.notify("AnimationStart", definition);
let animation;
if (Array.isArray(definition)) {
const animations = definition.map((variant) => animateVariant(visualElement, variant, options));
animation = Promise.all(animations);
}
else if (typeof definition === "string") {
animation = animateVariant(visualElement, definition, options);
}
else {
const resolvedDefinition = typeof definition === "function"
? resolveVariant(visualElement, definition, options.custom)
: definition;
animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));
}
return animation.then(() => visualElement.notify("AnimationComplete", definition));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/animation-state.mjs
const reversePriorityOrder = [...variantPriorityOrder].reverse();
const numAnimationTypes = variantPriorityOrder.length;
function animateList(visualElement) {
return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
}
function createAnimationState(visualElement) {
let animate = animateList(visualElement);
const state = createState();
let isInitialRender = true;
/**
* This function will be used to reduce the animation definitions for
* each active animation type into an object of resolved values for it.
*/
const buildResolvedTypeValues = (acc, definition) => {
const resolved = resolveVariant(visualElement, definition);
if (resolved) {
const { transition, transitionEnd, ...target } = resolved;
acc = { ...acc, ...target, ...transitionEnd };
}
return acc;
};
/**
* This just allows us to inject mocked animation functions
* @internal
*/
function setAnimateFunction(makeAnimator) {
animate = makeAnimator(visualElement);
}
/**
* When we receive new props, we need to:
* 1. Create a list of protected keys for each type. This is a directory of
* value keys that are currently being "handled" by types of a higher priority
* so that whenever an animation is played of a given type, these values are
* protected from being animated.
* 2. Determine if an animation type needs animating.
* 3. Determine if any values have been removed from a type and figure out
* what to animate those to.
*/
function animateChanges(options, changedActiveType) {
const props = visualElement.getProps();
const context = visualElement.getVariantContext(true) || {};
/**
* A list of animations that we'll build into as we iterate through the animation
* types. This will get executed at the end of the function.
*/
const animations = [];
/**
* Keep track of which values have been removed. Then, as we hit lower priority
* animation types, we can check if they contain removed values and animate to that.
*/
const removedKeys = new Set();
/**
* A dictionary of all encountered keys. This is an object to let us build into and
* copy it without iteration. Each time we hit an animation type we set its protected
* keys - the keys its not allowed to animate - to the latest version of this object.
*/
let encounteredKeys = {};
/**
* If a variant has been removed at a given index, and this component is controlling
* variant animations, we want to ensure lower-priority variants are forced to animate.
*/
let removedVariantIndex = Infinity;
/**
* Iterate through all animation types in reverse priority order. For each, we want to
* detect which values it's handling and whether or not they've changed (and therefore
* need to be animated). If any values have been removed, we want to detect those in
* lower priority props and flag for animation.
*/
for (let i = 0; i < numAnimationTypes; i++) {
const type = reversePriorityOrder[i];
const typeState = state[type];
const prop = props[type] !== undefined ? props[type] : context[type];
const propIsVariant = isVariantLabel(prop);
/**
* If this type has *just* changed isActive status, set activeDelta
* to that status. Otherwise set to null.
*/
const activeDelta = type === changedActiveType ? typeState.isActive : null;
if (activeDelta === false)
removedVariantIndex = i;
/**
* If this prop is an inherited variant, rather than been set directly on the
* component itself, we want to make sure we allow the parent to trigger animations.
*
* TODO: Can probably change this to a !isControllingVariants check
*/
let isInherited = prop === context[type] && prop !== props[type] && propIsVariant;
/**
*
*/
if (isInherited &&
isInitialRender &&
visualElement.manuallyAnimateOnMount) {
isInherited = false;
}
/**
* Set all encountered keys so far as the protected keys for this type. This will
* be any key that has been animated or otherwise handled by active, higher-priortiy types.
*/
typeState.protectedKeys = { ...encounteredKeys };
// Check if we can skip analysing this prop early
if (
// If it isn't active and hasn't *just* been set as inactive
(!typeState.isActive && activeDelta === null) ||
// If we didn't and don't have any defined prop for this animation type
(!prop && !typeState.prevProp) ||
// Or if the prop doesn't define an animation
isAnimationControls(prop) ||
typeof prop === "boolean") {
continue;
}
/**
* As we go look through the values defined on this type, if we detect
* a changed value or a value that was removed in a higher priority, we set
* this to true and add this prop to the animation list.
*/
const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);
let shouldAnimateType = variantDidChange ||
// If we're making this variant active, we want to always make it active
(type === changedActiveType &&
typeState.isActive &&
!isInherited &&
propIsVariant) ||
// If we removed a higher-priority variant (i is in reverse order)
(i > removedVariantIndex && propIsVariant);
/**
* As animations can be set as variant lists, variants or target objects, we
* coerce everything to an array if it isn't one already
*/
const definitionList = Array.isArray(prop) ? prop : [prop];
/**
* Build an object of all the resolved values. We'll use this in the subsequent
* animateChanges calls to determine whether a value has changed.
*/
let resolvedValues = definitionList.reduce(buildResolvedTypeValues, {});
if (activeDelta === false)
resolvedValues = {};
/**
* Now we need to loop through all the keys in the prev prop and this prop,
* and decide:
* 1. If the value has changed, and needs animating
* 2. If it has been removed, and needs adding to the removedKeys set
* 3. If it has been removed in a higher priority type and needs animating
* 4. If it hasn't been removed in a higher priority but hasn't changed, and
* needs adding to the type's protectedKeys list.
*/
const { prevResolvedValues = {} } = typeState;
const allKeys = {
...prevResolvedValues,
...resolvedValues,
};
const markToAnimate = (key) => {
shouldAnimateType = true;
removedKeys.delete(key);
typeState.needsAnimating[key] = true;
};
for (const key in allKeys) {
const next = resolvedValues[key];
const prev = prevResolvedValues[key];
// If we've already handled this we can just skip ahead
if (encounteredKeys.hasOwnProperty(key))
continue;
/**
* If the value has changed, we probably want to animate it.
*/
if (next !== prev) {
/**
* If both values are keyframes, we need to shallow compare them to
* detect whether any value has changed. If it has, we animate it.
*/
if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
if (!shallowCompare(next, prev) || variantDidChange) {
markToAnimate(key);
}
else {
/**
* If it hasn't changed, we want to ensure it doesn't animate by
* adding it to the list of protected keys.
*/
typeState.protectedKeys[key] = true;
}
}
else if (next !== undefined) {
// If next is defined and doesn't equal prev, it needs animating
markToAnimate(key);
}
else {
// If it's undefined, it's been removed.
removedKeys.add(key);
}
}
else if (next !== undefined && removedKeys.has(key)) {
/**
* If next hasn't changed and it isn't undefined, we want to check if it's
* been removed by a higher priority
*/
markToAnimate(key);
}
else {
/**
* If it hasn't changed, we add it to the list of protected values
* to ensure it doesn't get animated.
*/
typeState.protectedKeys[key] = true;
}
}
/**
* Update the typeState so next time animateChanges is called we can compare the
* latest prop and resolvedValues to these.
*/
typeState.prevProp = prop;
typeState.prevResolvedValues = resolvedValues;
/**
*
*/
if (typeState.isActive) {
encounteredKeys = { ...encounteredKeys, ...resolvedValues };
}
if (isInitialRender && visualElement.blockInitialAnimation) {
shouldAnimateType = false;
}
/**
* If this is an inherited prop we want to hard-block animations
* TODO: Test as this should probably still handle animations triggered
* by removed values?
*/
if (shouldAnimateType && !isInherited) {
animations.push(...definitionList.map((animation) => ({
animation: animation,
options: { type, ...options },
})));
}
}
/**
* If there are some removed value that haven't been dealt with,
* we need to create a new animation that falls back either to the value
* defined in the style prop, or the last read value.
*/
if (removedKeys.size) {
const fallbackAnimation = {};
removedKeys.forEach((key) => {
const fallbackTarget = visualElement.getBaseTarget(key);
if (fallbackTarget !== undefined) {
fallbackAnimation[key] = fallbackTarget;
}
});
animations.push({ animation: fallbackAnimation });
}
let shouldAnimate = Boolean(animations.length);
if (isInitialRender &&
props.initial === false &&
!visualElement.manuallyAnimateOnMount) {
shouldAnimate = false;
}
isInitialRender = false;
return shouldAnimate ? animate(animations) : Promise.resolve();
}
/**
* Change whether a certain animation type is active.
*/
function setActive(type, isActive, options) {
var _a;
// If the active state hasn't changed, we can safely do nothing here
if (state[type].isActive === isActive)
return Promise.resolve();
// Propagate active change to children
(_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach((child) => { var _a; return (_a = child.animationState) === null || _a === void 0 ? void 0 : _a.setActive(type, isActive); });
state[type].isActive = isActive;
const animations = animateChanges(options, type);
for (const key in state) {
state[key].protectedKeys = {};
}
return animations;
}
return {
animateChanges,
setActive,
setAnimateFunction,
getState: () => state,
};
}
function checkVariantsDidChange(prev, next) {
if (typeof next === "string") {
return next !== prev;
}
else if (Array.isArray(next)) {
return !shallowCompare(next, prev);
}
return false;
}
function createTypeState(isActive = false) {
return {
isActive,
protectedKeys: {},
needsAnimating: {},
prevResolvedValues: {},
};
}
function createState() {
return {
animate: createTypeState(true),
whileInView: createTypeState(),
whileHover: createTypeState(),
whileTap: createTypeState(),
whileDrag: createTypeState(),
whileFocus: createTypeState(),
exit: createTypeState(),
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/animation/index.mjs
class AnimationFeature extends Feature {
/**
* We dynamically generate the AnimationState manager as it contains a reference
* to the underlying animation library. We only want to load that if we load this,
* so people can optionally code split it out using the `m` component.
*/
constructor(node) {
super(node);
node.animationState || (node.animationState = createAnimationState(node));
}
updateAnimationControlsSubscription() {
const { animate } = this.node.getProps();
this.unmount();
if (isAnimationControls(animate)) {
this.unmount = animate.subscribe(this.node);
}
}
/**
* Subscribe any provided AnimationControls to the component's VisualElement
*/
mount() {
this.updateAnimationControlsSubscription();
}
update() {
const { animate } = this.node.getProps();
const { animate: prevAnimate } = this.node.prevProps || {};
if (animate !== prevAnimate) {
this.updateAnimationControlsSubscription();
}
}
unmount() { }
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs
let exit_id = 0;
class ExitAnimationFeature extends Feature {
constructor() {
super(...arguments);
this.id = exit_id++;
}
update() {
if (!this.node.presenceContext)
return;
const { isPresent, onExitComplete, custom } = this.node.presenceContext;
const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};
if (!this.node.animationState || isPresent === prevIsPresent) {
return;
}
const exitAnimation = this.node.animationState.setActive("exit", !isPresent, { custom: custom !== null && custom !== void 0 ? custom : this.node.getProps().custom });
if (onExitComplete && !isPresent) {
exitAnimation.then(() => onExitComplete(this.id));
}
}
mount() {
const { register } = this.node.presenceContext || {};
if (register) {
this.unmount = register(this.id);
}
}
unmount() { }
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/animations.mjs
const animations = {
animation: {
Feature: AnimationFeature,
},
exit: {
Feature: ExitAnimationFeature,
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/distance.mjs
const distance = (a, b) => Math.abs(a - b);
function distance2D(a, b) {
// Multi-dimensional
const xDelta = distance(a.x, b.x);
const yDelta = distance(a.y, b.y);
return Math.sqrt(xDelta ** 2 + yDelta ** 2);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs
/**
* @internal
*/
class PanSession {
constructor(event, handlers, { transformPagePoint } = {}) {
/**
* @internal
*/
this.startEvent = null;
/**
* @internal
*/
this.lastMoveEvent = null;
/**
* @internal
*/
this.lastMoveEventInfo = null;
/**
* @internal
*/
this.handlers = {};
this.updatePoint = () => {
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
return;
const info = getPanInfo(this.lastMoveEventInfo, this.history);
const isPanStarted = this.startEvent !== null;
// Only start panning if the offset is larger than 3 pixels. If we make it
// any larger than this we'll want to reset the pointer history
// on the first update to avoid visual snapping to the cursoe.
const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= 3;
if (!isPanStarted && !isDistancePastThreshold)
return;
const { point } = info;
const { timestamp } = frameData;
this.history.push({ ...point, timestamp });
const { onStart, onMove } = this.handlers;
if (!isPanStarted) {
onStart && onStart(this.lastMoveEvent, info);
this.startEvent = this.lastMoveEvent;
}
onMove && onMove(this.lastMoveEvent, info);
};
this.handlePointerMove = (event, info) => {
this.lastMoveEvent = event;
this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint);
// Throttle mouse move event to once per frame
sync.update(this.updatePoint, true);
};
this.handlePointerUp = (event, info) => {
this.end();
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
return;
const { onEnd, onSessionEnd } = this.handlers;
const panInfo = getPanInfo(event.type === "pointercancel"
? this.lastMoveEventInfo
: transformPoint(info, this.transformPagePoint), this.history);
if (this.startEvent && onEnd) {
onEnd(event, panInfo);
}
onSessionEnd && onSessionEnd(event, panInfo);
};
// If we have more than one touch, don't start detecting this gesture
if (!isPrimaryPointer(event))
return;
this.handlers = handlers;
this.transformPagePoint = transformPagePoint;
const info = extractEventInfo(event);
const initialInfo = transformPoint(info, this.transformPagePoint);
const { point } = initialInfo;
const { timestamp } = frameData;
this.history = [{ ...point, timestamp }];
const { onSessionStart } = handlers;
onSessionStart &&
onSessionStart(event, getPanInfo(initialInfo, this.history));
this.removeListeners = pipe(addPointerEvent(window, "pointermove", this.handlePointerMove), addPointerEvent(window, "pointerup", this.handlePointerUp), addPointerEvent(window, "pointercancel", this.handlePointerUp));
}
updateHandlers(handlers) {
this.handlers = handlers;
}
end() {
this.removeListeners && this.removeListeners();
cancelSync.update(this.updatePoint);
}
}
function transformPoint(info, transformPagePoint) {
return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
}
function subtractPoint(a, b) {
return { x: a.x - b.x, y: a.y - b.y };
}
function getPanInfo({ point }, history) {
return {
point,
delta: subtractPoint(point, lastDevicePoint(history)),
offset: subtractPoint(point, startDevicePoint(history)),
velocity: PanSession_getVelocity(history, 0.1),
};
}
function startDevicePoint(history) {
return history[0];
}
function lastDevicePoint(history) {
return history[history.length - 1];
}
function PanSession_getVelocity(history, timeDelta) {
if (history.length < 2) {
return { x: 0, y: 0 };
}
let i = history.length - 1;
let timestampedPoint = null;
const lastPoint = lastDevicePoint(history);
while (i >= 0) {
timestampedPoint = history[i];
if (lastPoint.timestamp - timestampedPoint.timestamp >
secondsToMilliseconds(timeDelta)) {
break;
}
i--;
}
if (!timestampedPoint) {
return { x: 0, y: 0 };
}
const time = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp);
if (time === 0) {
return { x: 0, y: 0 };
}
const currentVelocity = {
x: (lastPoint.x - timestampedPoint.x) / time,
y: (lastPoint.y - timestampedPoint.y) / time,
};
if (currentVelocity.x === Infinity) {
currentVelocity.x = 0;
}
if (currentVelocity.y === Infinity) {
currentVelocity.y = 0;
}
return currentVelocity;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs
function calcLength(axis) {
return axis.max - axis.min;
}
function isNear(value, target = 0, maxDistance = 0.01) {
return Math.abs(value - target) <= maxDistance;
}
function calcAxisDelta(delta, source, target, origin = 0.5) {
delta.origin = origin;
delta.originPoint = mix(source.min, source.max, delta.origin);
delta.scale = calcLength(target) / calcLength(source);
if (isNear(delta.scale, 1, 0.0001) || isNaN(delta.scale))
delta.scale = 1;
delta.translate =
mix(target.min, target.max, delta.origin) - delta.originPoint;
if (isNear(delta.translate) || isNaN(delta.translate))
delta.translate = 0;
}
function calcBoxDelta(delta, source, target, origin) {
calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);
calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);
}
function calcRelativeAxis(target, relative, parent) {
target.min = parent.min + relative.min;
target.max = target.min + calcLength(relative);
}
function calcRelativeBox(target, relative, parent) {
calcRelativeAxis(target.x, relative.x, parent.x);
calcRelativeAxis(target.y, relative.y, parent.y);
}
function calcRelativeAxisPosition(target, layout, parent) {
target.min = layout.min - parent.min;
target.max = target.min + calcLength(layout);
}
function calcRelativePosition(target, layout, parent) {
calcRelativeAxisPosition(target.x, layout.x, parent.x);
calcRelativeAxisPosition(target.y, layout.y, parent.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs
/**
* Apply constraints to a point. These constraints are both physical along an
* axis, and an elastic factor that determines how much to constrain the point
* by if it does lie outside the defined parameters.
*/
function applyConstraints(point, { min, max }, elastic) {
if (min !== undefined && point < min) {
// If we have a min point defined, and this is outside of that, constrain
point = elastic ? mix(min, point, elastic.min) : Math.max(point, min);
}
else if (max !== undefined && point > max) {
// If we have a max point defined, and this is outside of that, constrain
point = elastic ? mix(max, point, elastic.max) : Math.min(point, max);
}
return point;
}
/**
* Calculate constraints in terms of the viewport when defined relatively to the
* measured axis. This is measured from the nearest edge, so a max constraint of 200
* on an axis with a max value of 300 would return a constraint of 500 - axis length
*/
function calcRelativeAxisConstraints(axis, min, max) {
return {
min: min !== undefined ? axis.min + min : undefined,
max: max !== undefined
? axis.max + max - (axis.max - axis.min)
: undefined,
};
}
/**
* Calculate constraints in terms of the viewport when
* defined relatively to the measured bounding box.
*/
function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {
return {
x: calcRelativeAxisConstraints(layoutBox.x, left, right),
y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),
};
}
/**
* Calculate viewport constraints when defined as another viewport-relative axis
*/
function calcViewportAxisConstraints(layoutAxis, constraintsAxis) {
let min = constraintsAxis.min - layoutAxis.min;
let max = constraintsAxis.max - layoutAxis.max;
// If the constraints axis is actually smaller than the layout axis then we can
// flip the constraints
if (constraintsAxis.max - constraintsAxis.min <
layoutAxis.max - layoutAxis.min) {
[min, max] = [max, min];
}
return { min, max };
}
/**
* Calculate viewport constraints when defined as another viewport-relative box
*/
function calcViewportConstraints(layoutBox, constraintsBox) {
return {
x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),
y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),
};
}
/**
* Calculate a transform origin relative to the source axis, between 0-1, that results
* in an asthetically pleasing scale/transform needed to project from source to target.
*/
function constraints_calcOrigin(source, target) {
let origin = 0.5;
const sourceLength = calcLength(source);
const targetLength = calcLength(target);
if (targetLength > sourceLength) {
origin = progress(target.min, target.max - sourceLength, source.min);
}
else if (sourceLength > targetLength) {
origin = progress(source.min, source.max - targetLength, target.min);
}
return clamp(0, 1, origin);
}
/**
* Rebase the calculated viewport constraints relative to the layout.min point.
*/
function rebaseAxisConstraints(layout, constraints) {
const relativeConstraints = {};
if (constraints.min !== undefined) {
relativeConstraints.min = constraints.min - layout.min;
}
if (constraints.max !== undefined) {
relativeConstraints.max = constraints.max - layout.min;
}
return relativeConstraints;
}
const defaultElastic = 0.35;
/**
* Accepts a dragElastic prop and returns resolved elastic values for each axis.
*/
function resolveDragElastic(dragElastic = defaultElastic) {
if (dragElastic === false) {
dragElastic = 0;
}
else if (dragElastic === true) {
dragElastic = defaultElastic;
}
return {
x: resolveAxisElastic(dragElastic, "left", "right"),
y: resolveAxisElastic(dragElastic, "top", "bottom"),
};
}
function resolveAxisElastic(dragElastic, minLabel, maxLabel) {
return {
min: resolvePointElastic(dragElastic, minLabel),
max: resolvePointElastic(dragElastic, maxLabel),
};
}
function resolvePointElastic(dragElastic, label) {
return typeof dragElastic === "number"
? dragElastic
: dragElastic[label] || 0;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/models.mjs
const createAxisDelta = () => ({
translate: 0,
scale: 1,
origin: 0,
originPoint: 0,
});
const createDelta = () => ({
x: createAxisDelta(),
y: createAxisDelta(),
});
const createAxis = () => ({ min: 0, max: 0 });
const createBox = () => ({
x: createAxis(),
y: createAxis(),
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs
function eachAxis(callback) {
return [callback("x"), callback("y")];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs
/**
* Bounding boxes tend to be defined as top, left, right, bottom. For various operations
* it's easier to consider each axis individually. This function returns a bounding box
* as a map of single-axis min/max values.
*/
function convertBoundingBoxToBox({ top, left, right, bottom, }) {
return {
x: { min: left, max: right },
y: { min: top, max: bottom },
};
}
function convertBoxToBoundingBox({ x, y }) {
return { top: y.min, right: x.max, bottom: y.max, left: x.min };
}
/**
* Applies a TransformPoint function to a bounding box. TransformPoint is usually a function
* provided by Framer to allow measured points to be corrected for device scaling. This is used
* when measuring DOM elements and DOM event points.
*/
function transformBoxPoints(point, transformPoint) {
if (!transformPoint)
return point;
const topLeft = transformPoint({ x: point.left, y: point.top });
const bottomRight = transformPoint({ x: point.right, y: point.bottom });
return {
top: topLeft.y,
left: topLeft.x,
bottom: bottomRight.y,
right: bottomRight.x,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs
function isIdentityScale(scale) {
return scale === undefined || scale === 1;
}
function hasScale({ scale, scaleX, scaleY }) {
return (!isIdentityScale(scale) ||
!isIdentityScale(scaleX) ||
!isIdentityScale(scaleY));
}
function hasTransform(values) {
return (hasScale(values) ||
has2DTranslate(values) ||
values.z ||
values.rotate ||
values.rotateX ||
values.rotateY);
}
function has2DTranslate(values) {
return is2DTranslate(values.x) || is2DTranslate(values.y);
}
function is2DTranslate(value) {
return value && value !== "0%";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs
/**
* Scales a point based on a factor and an originPoint
*/
function scalePoint(point, scale, originPoint) {
const distanceFromOrigin = point - originPoint;
const scaled = scale * distanceFromOrigin;
return originPoint + scaled;
}
/**
* Applies a translate/scale delta to a point
*/
function applyPointDelta(point, translate, scale, originPoint, boxScale) {
if (boxScale !== undefined) {
point = scalePoint(point, boxScale, originPoint);
}
return scalePoint(point, scale, originPoint) + translate;
}
/**
* Applies a translate/scale delta to an axis
*/
function applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) {
axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale);
axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale);
}
/**
* Applies a translate/scale delta to a box
*/
function applyBoxDelta(box, { x, y }) {
applyAxisDelta(box.x, x.translate, x.scale, x.originPoint);
applyAxisDelta(box.y, y.translate, y.scale, y.originPoint);
}
/**
* Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms
* in a tree upon our box before then calculating how to project it into our desired viewport-relative box
*
* This is the final nested loop within updateLayoutDelta for future refactoring
*/
function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
const treeLength = treePath.length;
if (!treeLength)
return;
// Reset the treeScale
treeScale.x = treeScale.y = 1;
let node;
let delta;
for (let i = 0; i < treeLength; i++) {
node = treePath[i];
delta = node.projectionDelta;
/**
* TODO: Prefer to remove this, but currently we have motion components with
* display: contents in Framer.
*/
const instance = node.instance;
if (instance &&
instance.style &&
instance.style.display === "contents") {
continue;
}
if (isSharedTransition &&
node.options.layoutScroll &&
node.scroll &&
node !== node.root) {
transformBox(box, {
x: -node.scroll.offset.x,
y: -node.scroll.offset.y,
});
}
if (delta) {
// Incoporate each ancestor's scale into a culmulative treeScale for this component
treeScale.x *= delta.x.scale;
treeScale.y *= delta.y.scale;
// Apply each ancestor's calculated delta into this component's recorded layout box
applyBoxDelta(box, delta);
}
if (isSharedTransition && hasTransform(node.latestValues)) {
transformBox(box, node.latestValues);
}
}
/**
* Snap tree scale back to 1 if it's within a non-perceivable threshold.
* This will help reduce useless scales getting rendered.
*/
treeScale.x = snapToDefault(treeScale.x);
treeScale.y = snapToDefault(treeScale.y);
}
function snapToDefault(scale) {
if (Number.isInteger(scale))
return scale;
return scale > 1.0000000000001 || scale < 0.999999999999 ? scale : 1;
}
function translateAxis(axis, distance) {
axis.min = axis.min + distance;
axis.max = axis.max + distance;
}
/**
* Apply a transform to an axis from the latest resolved motion values.
* This function basically acts as a bridge between a flat motion value map
* and applyAxisDelta
*/
function transformAxis(axis, transforms, [key, scaleKey, originKey]) {
const axisOrigin = transforms[originKey] !== undefined ? transforms[originKey] : 0.5;
const originPoint = mix(axis.min, axis.max, axisOrigin);
// Apply the axis delta to the final axis
applyAxisDelta(axis, transforms[key], transforms[scaleKey], originPoint, transforms.scale);
}
/**
* The names of the motion values we want to apply as translation, scale and origin.
*/
const xKeys = ["x", "scaleX", "originX"];
const yKeys = ["y", "scaleY", "originY"];
/**
* Apply a transform to a box from the latest resolved motion values.
*/
function transformBox(box, transform) {
transformAxis(box.x, transform, xKeys);
transformAxis(box.y, transform, yKeys);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/utils/measure.mjs
function measureViewportBox(instance, transformPoint) {
return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));
}
function measurePageBox(element, rootProjectionNode, transformPagePoint) {
const viewportBox = measureViewportBox(element, transformPagePoint);
const { scroll } = rootProjectionNode;
if (scroll) {
translateAxis(viewportBox.x, scroll.offset.x);
translateAxis(viewportBox.y, scroll.offset.y);
}
return viewportBox;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs
const elementDragControls = new WeakMap();
/**
*
*/
// let latestPointerEvent: PointerEvent
class VisualElementDragControls {
constructor(visualElement) {
// This is a reference to the global drag gesture lock, ensuring only one component
// can "capture" the drag of one or both axes.
// TODO: Look into moving this into pansession?
this.openGlobalLock = null;
this.isDragging = false;
this.currentDirection = null;
this.originPoint = { x: 0, y: 0 };
/**
* The permitted boundaries of travel, in pixels.
*/
this.constraints = false;
this.hasMutatedConstraints = false;
/**
* The per-axis resolved elastic values.
*/
this.elastic = createBox();
this.visualElement = visualElement;
}
start(originEvent, { snapToCursor = false } = {}) {
/**
* Don't start dragging if this component is exiting
*/
const { presenceContext } = this.visualElement;
if (presenceContext && presenceContext.isPresent === false)
return;
const onSessionStart = (event) => {
// Stop any animations on both axis values immediately. This allows the user to throw and catch
// the component.
this.stopAnimation();
if (snapToCursor) {
this.snapToCursor(extractEventInfo(event, "page").point);
}
};
const onStart = (event, info) => {
// Attempt to grab the global drag gesture lock - maybe make this part of PanSession
const { drag, dragPropagation, onDragStart } = this.getProps();
if (drag && !dragPropagation) {
if (this.openGlobalLock)
this.openGlobalLock();
this.openGlobalLock = getGlobalLock(drag);
// If we don 't have the lock, don't start dragging
if (!this.openGlobalLock)
return;
}
this.isDragging = true;
this.currentDirection = null;
this.resolveConstraints();
if (this.visualElement.projection) {
this.visualElement.projection.isAnimationBlocked = true;
this.visualElement.projection.target = undefined;
}
/**
* Record gesture origin
*/
eachAxis((axis) => {
let current = this.getAxisMotionValue(axis).get() || 0;
/**
* If the MotionValue is a percentage value convert to px
*/
if (percent.test(current)) {
const { projection } = this.visualElement;
if (projection && projection.layout) {
const measuredAxis = projection.layout.layoutBox[axis];
if (measuredAxis) {
const length = calcLength(measuredAxis);
current = length * (parseFloat(current) / 100);
}
}
}
this.originPoint[axis] = current;
});
// Fire onDragStart event
if (onDragStart) {
sync.update(() => onDragStart(event, info));
}
const { animationState } = this.visualElement;
animationState && animationState.setActive("whileDrag", true);
};
const onMove = (event, info) => {
// latestPointerEvent = event
const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps();
// If we didn't successfully receive the gesture lock, early return.
if (!dragPropagation && !this.openGlobalLock)
return;
const { offset } = info;
// Attempt to detect drag direction if directionLock is true
if (dragDirectionLock && this.currentDirection === null) {
this.currentDirection = getCurrentDirection(offset);
// If we've successfully set a direction, notify listener
if (this.currentDirection !== null) {
onDirectionLock && onDirectionLock(this.currentDirection);
}
return;
}
// Update each point with the latest position
this.updateAxis("x", info.point, offset);
this.updateAxis("y", info.point, offset);
/**
* Ideally we would leave the renderer to fire naturally at the end of
* this frame but if the element is about to change layout as the result
* of a re-render we want to ensure the browser can read the latest
* bounding box to ensure the pointer and element don't fall out of sync.
*/
this.visualElement.render();
/**
* This must fire after the render call as it might trigger a state
* change which itself might trigger a layout update.
*/
onDrag && onDrag(event, info);
};
const onSessionEnd = (event, info) => this.stop(event, info);
this.panSession = new PanSession(originEvent, {
onSessionStart,
onStart,
onMove,
onSessionEnd,
}, { transformPagePoint: this.visualElement.getTransformPagePoint() });
}
stop(event, info) {
const isDragging = this.isDragging;
this.cancel();
if (!isDragging)
return;
const { velocity } = info;
this.startAnimation(velocity);
const { onDragEnd } = this.getProps();
if (onDragEnd) {
sync.update(() => onDragEnd(event, info));
}
}
cancel() {
this.isDragging = false;
const { projection, animationState } = this.visualElement;
if (projection) {
projection.isAnimationBlocked = false;
}
this.panSession && this.panSession.end();
this.panSession = undefined;
const { dragPropagation } = this.getProps();
if (!dragPropagation && this.openGlobalLock) {
this.openGlobalLock();
this.openGlobalLock = null;
}
animationState && animationState.setActive("whileDrag", false);
}
updateAxis(axis, _point, offset) {
const { drag } = this.getProps();
// If we're not dragging this axis, do an early return.
if (!offset || !shouldDrag(axis, drag, this.currentDirection))
return;
const axisValue = this.getAxisMotionValue(axis);
let next = this.originPoint[axis] + offset[axis];
// Apply constraints
if (this.constraints && this.constraints[axis]) {
next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
}
axisValue.set(next);
}
resolveConstraints() {
const { dragConstraints, dragElastic } = this.getProps();
const { layout } = this.visualElement.projection || {};
const prevConstraints = this.constraints;
if (dragConstraints && is_ref_object_isRefObject(dragConstraints)) {
if (!this.constraints) {
this.constraints = this.resolveRefConstraints();
}
}
else {
if (dragConstraints && layout) {
this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints);
}
else {
this.constraints = false;
}
}
this.elastic = resolveDragElastic(dragElastic);
/**
* If we're outputting to external MotionValues, we want to rebase the measured constraints
* from viewport-relative to component-relative.
*/
if (prevConstraints !== this.constraints &&
layout &&
this.constraints &&
!this.hasMutatedConstraints) {
eachAxis((axis) => {
if (this.getAxisMotionValue(axis)) {
this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]);
}
});
}
}
resolveRefConstraints() {
const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();
if (!constraints || !is_ref_object_isRefObject(constraints))
return false;
const constraintsElement = constraints.current;
invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");
const { projection } = this.visualElement;
// TODO
if (!projection || !projection.layout)
return false;
const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
/**
* If there's an onMeasureDragConstraints listener we call it and
* if different constraints are returned, set constraints to that
*/
if (onMeasureDragConstraints) {
const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints));
this.hasMutatedConstraints = !!userConstraints;
if (userConstraints) {
measuredConstraints = convertBoundingBoxToBox(userConstraints);
}
}
return measuredConstraints;
}
startAnimation(velocity) {
const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps();
const constraints = this.constraints || {};
const momentumAnimations = eachAxis((axis) => {
if (!shouldDrag(axis, drag, this.currentDirection)) {
return;
}
let transition = (constraints && constraints[axis]) || {};
if (dragSnapToOrigin)
transition = { min: 0, max: 0 };
/**
* Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame
* of spring animations so we should look into adding a disable spring option to `inertia`.
* We could do something here where we affect the `bounceStiffness` and `bounceDamping`
* using the value of `dragElastic`.
*/
const bounceStiffness = dragElastic ? 200 : 1000000;
const bounceDamping = dragElastic ? 40 : 10000000;
const inertia = {
type: "inertia",
velocity: dragMomentum ? velocity[axis] : 0,
bounceStiffness,
bounceDamping,
timeConstant: 750,
restDelta: 1,
restSpeed: 10,
...dragTransition,
...transition,
};
// If we're not animating on an externally-provided `MotionValue` we can use the
// component's animation controls which will handle interactions with whileHover (etc),
// otherwise we just have to animate the `MotionValue` itself.
return this.startAxisValueAnimation(axis, inertia);
});
// Run all animations and then resolve the new drag constraints.
return Promise.all(momentumAnimations).then(onDragTransitionEnd);
}
startAxisValueAnimation(axis, transition) {
const axisValue = this.getAxisMotionValue(axis);
return axisValue.start(animateMotionValue(axis, axisValue, 0, transition));
}
stopAnimation() {
eachAxis((axis) => this.getAxisMotionValue(axis).stop());
}
/**
* Drag works differently depending on which props are provided.
*
* - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.
* - Otherwise, we apply the delta to the x/y motion values.
*/
getAxisMotionValue(axis) {
const dragKey = "_drag" + axis.toUpperCase();
const props = this.visualElement.getProps();
const externalMotionValue = props[dragKey];
return externalMotionValue
? externalMotionValue
: this.visualElement.getValue(axis, (props.initial ? props.initial[axis] : undefined) || 0);
}
snapToCursor(point) {
eachAxis((axis) => {
const { drag } = this.getProps();
// If we're not dragging this axis, do an early return.
if (!shouldDrag(axis, drag, this.currentDirection))
return;
const { projection } = this.visualElement;
const axisValue = this.getAxisMotionValue(axis);
if (projection && projection.layout) {
const { min, max } = projection.layout.layoutBox[axis];
axisValue.set(point[axis] - mix(min, max, 0.5));
}
});
}
/**
* When the viewport resizes we want to check if the measured constraints
* have changed and, if so, reposition the element within those new constraints
* relative to where it was before the resize.
*/
scalePositionWithinConstraints() {
if (!this.visualElement.current)
return;
const { drag, dragConstraints } = this.getProps();
const { projection } = this.visualElement;
if (!is_ref_object_isRefObject(dragConstraints) || !projection || !this.constraints)
return;
/**
* Stop current animations as there can be visual glitching if we try to do
* this mid-animation
*/
this.stopAnimation();
/**
* Record the relative position of the dragged element relative to the
* constraints box and save as a progress value.
*/
const boxProgress = { x: 0, y: 0 };
eachAxis((axis) => {
const axisValue = this.getAxisMotionValue(axis);
if (axisValue) {
const latest = axisValue.get();
boxProgress[axis] = constraints_calcOrigin({ min: latest, max: latest }, this.constraints[axis]);
}
});
/**
* Update the layout of this element and resolve the latest drag constraints
*/
const { transformTemplate } = this.visualElement.getProps();
this.visualElement.current.style.transform = transformTemplate
? transformTemplate({}, "")
: "none";
projection.root && projection.root.updateScroll();
projection.updateLayout();
this.resolveConstraints();
/**
* For each axis, calculate the current progress of the layout axis
* within the new constraints.
*/
eachAxis((axis) => {
if (!shouldDrag(axis, drag, null))
return;
/**
* Calculate a new transform based on the previous box progress
*/
const axisValue = this.getAxisMotionValue(axis);
const { min, max } = this.constraints[axis];
axisValue.set(mix(min, max, boxProgress[axis]));
});
}
addListeners() {
if (!this.visualElement.current)
return;
elementDragControls.set(this.visualElement, this);
const element = this.visualElement.current;
/**
* Attach a pointerdown event listener on this DOM element to initiate drag tracking.
*/
const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => {
const { drag, dragListener = true } = this.getProps();
drag && dragListener && this.start(event);
});
const measureDragConstraints = () => {
const { dragConstraints } = this.getProps();
if (is_ref_object_isRefObject(dragConstraints)) {
this.constraints = this.resolveRefConstraints();
}
};
const { projection } = this.visualElement;
const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
if (projection && !projection.layout) {
projection.root && projection.root.updateScroll();
projection.updateLayout();
}
measureDragConstraints();
/**
* Attach a window resize listener to scale the draggable target within its defined
* constraints as the window resizes.
*/
const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints());
/**
* If the element's layout changes, calculate the delta and apply that to
* the drag gesture's origin point.
*/
const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => {
if (this.isDragging && hasLayoutChanged) {
eachAxis((axis) => {
const motionValue = this.getAxisMotionValue(axis);
if (!motionValue)
return;
this.originPoint[axis] += delta[axis].translate;
motionValue.set(motionValue.get() + delta[axis].translate);
});
this.visualElement.render();
}
}));
return () => {
stopResizeListener();
stopPointerListener();
stopMeasureLayoutListener();
stopLayoutUpdateListener && stopLayoutUpdateListener();
};
}
getProps() {
const props = this.visualElement.getProps();
const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;
return {
...props,
drag,
dragDirectionLock,
dragPropagation,
dragConstraints,
dragElastic,
dragMomentum,
};
}
}
function shouldDrag(direction, drag, currentDirection) {
return ((drag === true || drag === direction) &&
(currentDirection === null || currentDirection === direction));
}
/**
* Based on an x/y offset determine the current drag direction. If both axis' offsets are lower
* than the provided threshold, return `null`.
*
* @param offset - The x/y offset from origin.
* @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.
*/
function getCurrentDirection(offset, lockThreshold = 10) {
let direction = null;
if (Math.abs(offset.y) > lockThreshold) {
direction = "y";
}
else if (Math.abs(offset.x) > lockThreshold) {
direction = "x";
}
return direction;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/index.mjs
class DragGesture extends Feature {
constructor(node) {
super(node);
this.removeGroupControls = noop;
this.removeListeners = noop;
this.controls = new VisualElementDragControls(node);
}
mount() {
// If we've been provided a DragControls for manual control over the drag gesture,
// subscribe this component to it on mount.
const { dragControls } = this.node.getProps();
if (dragControls) {
this.removeGroupControls = dragControls.subscribe(this.controls);
}
this.removeListeners = this.controls.addListeners() || noop;
}
unmount() {
this.removeGroupControls();
this.removeListeners();
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/pan/index.mjs
const asyncHandler = (handler) => (event, info) => {
if (handler) {
sync.update(() => handler(event, info));
}
};
class PanGesture extends Feature {
constructor() {
super(...arguments);
this.removePointerDownListener = noop;
}
onPointerDown(pointerDownEvent) {
this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), { transformPagePoint: this.node.getTransformPagePoint() });
}
createPanHandlers() {
const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps();
return {
onSessionStart: asyncHandler(onPanSessionStart),
onStart: asyncHandler(onPanStart),
onMove: onPan,
onEnd: (event, info) => {
delete this.session;
if (onPanEnd) {
sync.update(() => onPanEnd(event, info));
}
},
};
}
mount() {
this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event));
}
update() {
this.session && this.session.updateHandlers(this.createPanHandlers());
}
unmount() {
this.removePointerDownListener();
this.session && this.session.end();
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs
/**
* When a component is the child of `AnimatePresence`, it can use `usePresence`
* to access information about whether it's still present in the React tree.
*
* ```jsx
* import { usePresence } from "framer-motion"
*
* export const Component = () => {
* const [isPresent, safeToRemove] = usePresence()
*
* useEffect(() => {
* !isPresent && setTimeout(safeToRemove, 1000)
* }, [isPresent])
*
* return <div />
* }
* ```
*
* If `isPresent` is `false`, it means that a component has been removed the tree, but
* `AnimatePresence` won't really remove it until `safeToRemove` has been called.
*
* @public
*/
function usePresence() {
const context = (0,external_React_.useContext)(PresenceContext_PresenceContext);
if (context === null)
return [true, null];
const { isPresent, onExitComplete, register } = context;
// It's safe to call the following hooks conditionally (after an early return) because the context will always
// either be null or non-null for the lifespan of the component.
const id = (0,external_React_.useId)();
(0,external_React_.useEffect)(() => register(id), []);
const safeToRemove = () => onExitComplete && onExitComplete(id);
return !isPresent && onExitComplete ? [false, safeToRemove] : [true];
}
/**
* Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present.
* There is no `safeToRemove` function.
*
* ```jsx
* import { useIsPresent } from "framer-motion"
*
* export const Component = () => {
* const isPresent = useIsPresent()
*
* useEffect(() => {
* !isPresent && console.log("I've been removed!")
* }, [isPresent])
*
* return <div />
* }
* ```
*
* @public
*/
function useIsPresent() {
return isPresent(useContext(PresenceContext));
}
function isPresent(context) {
return context === null ? true : context.isPresent;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs
function pixelsToPercent(pixels, axis) {
if (axis.max === axis.min)
return 0;
return (pixels / (axis.max - axis.min)) * 100;
}
/**
* We always correct borderRadius as a percentage rather than pixels to reduce paints.
* For example, if you are projecting a box that is 100px wide with a 10px borderRadius
* into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
* borderRadius in both states. If we animate between the two in pixels that will trigger
* a paint each time. If we animate between the two in percentage we'll avoid a paint.
*/
const correctBorderRadius = {
correct: (latest, node) => {
if (!node.target)
return latest;
/**
* If latest is a string, if it's a percentage we can return immediately as it's
* going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
*/
if (typeof latest === "string") {
if (px.test(latest)) {
latest = parseFloat(latest);
}
else {
return latest;
}
}
/**
* If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
* pixel value as a percentage of each axis
*/
const x = pixelsToPercent(latest, node.target.x);
const y = pixelsToPercent(latest, node.target.y);
return `${x}% ${y}%`;
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/css-variables-conversion.mjs
/**
* Parse Framer's special CSS variable format into a CSS token and a fallback.
*
* ```
* `var(--foo, #fff)` => [`--foo`, '#fff']
* ```
*
* @param current
*/
const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
function parseCSSVariable(current) {
const match = cssVariableRegex.exec(current);
if (!match)
return [,];
const [, token, fallback] = match;
return [token, fallback];
}
const maxDepth = 4;
function getVariableValue(current, element, depth = 1) {
invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`);
const [token, fallback] = parseCSSVariable(current);
// No CSS variable detected
if (!token)
return;
// Attempt to read this CSS variable off the element
const resolved = window.getComputedStyle(element).getPropertyValue(token);
if (resolved) {
return resolved.trim();
}
else if (isCSSVariableToken(fallback)) {
// The fallback might itself be a CSS variable, in which case we attempt to resolve it too.
return getVariableValue(fallback, element, depth + 1);
}
else {
return fallback;
}
}
/**
* Resolve CSS variables from
*
* @internal
*/
function resolveCSSVariables(visualElement, { ...target }, transitionEnd) {
const element = visualElement.current;
if (!(element instanceof Element))
return { target, transitionEnd };
// If `transitionEnd` isn't `undefined`, clone it. We could clone `target` and `transitionEnd`
// only if they change but I think this reads clearer and this isn't a performance-critical path.
if (transitionEnd) {
transitionEnd = { ...transitionEnd };
}
// Go through existing `MotionValue`s and ensure any existing CSS variables are resolved
visualElement.values.forEach((value) => {
const current = value.get();
if (!isCSSVariableToken(current))
return;
const resolved = getVariableValue(current, element);
if (resolved)
value.set(resolved);
});
// Cycle through every target property and resolve CSS variables. Currently
// we only read single-var properties like `var(--foo)`, not `calc(var(--foo) + 20px)`
for (const key in target) {
const current = target[key];
if (!isCSSVariableToken(current))
continue;
const resolved = getVariableValue(current, element);
if (!resolved)
continue;
// Clone target if it hasn't already been
target[key] = resolved;
if (!transitionEnd)
transitionEnd = {};
// If the user hasn't already set this key on `transitionEnd`, set it to the unresolved
// CSS variable. This will ensure that after the animation the component will reflect
// changes in the value of the CSS variable.
if (transitionEnd[key] === undefined) {
transitionEnd[key] = current;
}
}
return { target, transitionEnd };
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs
const varToken = "_$css";
const correctBoxShadow = {
correct: (latest, { treeScale, projectionDelta }) => {
const original = latest;
/**
* We need to first strip and store CSS variables from the string.
*/
const containsCSSVariables = latest.includes("var(");
const cssVariables = [];
if (containsCSSVariables) {
latest = latest.replace(cssVariableRegex, (match) => {
cssVariables.push(match);
return varToken;
});
}
const shadow = complex.parse(latest);
// TODO: Doesn't support multiple shadows
if (shadow.length > 5)
return original;
const template = complex.createTransformer(latest);
const offset = typeof shadow[0] !== "number" ? 1 : 0;
// Calculate the overall context scale
const xScale = projectionDelta.x.scale * treeScale.x;
const yScale = projectionDelta.y.scale * treeScale.y;
shadow[0 + offset] /= xScale;
shadow[1 + offset] /= yScale;
/**
* Ideally we'd correct x and y scales individually, but because blur and
* spread apply to both we have to take a scale average and apply that instead.
* We could potentially improve the outcome of this by incorporating the ratio between
* the two scales.
*/
const averageScale = mix(xScale, yScale, 0.5);
// Blur
if (typeof shadow[2 + offset] === "number")
shadow[2 + offset] /= averageScale;
// Spread
if (typeof shadow[3 + offset] === "number")
shadow[3 + offset] /= averageScale;
let output = template(shadow);
if (containsCSSVariables) {
let i = 0;
output = output.replace(varToken, () => {
const cssVariable = cssVariables[i];
i++;
return cssVariable;
});
}
return output;
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs
class MeasureLayoutWithContext extends external_React_.Component {
/**
* This only mounts projection nodes for components that
* need measuring, we might want to do it for all components
* in order to incorporate transforms
*/
componentDidMount() {
const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props;
const { projection } = visualElement;
addScaleCorrector(defaultScaleCorrectors);
if (projection) {
if (layoutGroup.group)
layoutGroup.group.add(projection);
if (switchLayoutGroup && switchLayoutGroup.register && layoutId) {
switchLayoutGroup.register(projection);
}
projection.root.didUpdate();
projection.addEventListener("animationComplete", () => {
this.safeToRemove();
});
projection.setOptions({
...projection.options,
onExitComplete: () => this.safeToRemove(),
});
}
globalProjectionState.hasEverUpdated = true;
}
getSnapshotBeforeUpdate(prevProps) {
const { layoutDependency, visualElement, drag, isPresent } = this.props;
const projection = visualElement.projection;
if (!projection)
return null;
/**
* TODO: We use this data in relegate to determine whether to
* promote a previous element. There's no guarantee its presence data
* will have updated by this point - if a bug like this arises it will
* have to be that we markForRelegation and then find a new lead some other way,
* perhaps in didUpdate
*/
projection.isPresent = isPresent;
if (drag ||
prevProps.layoutDependency !== layoutDependency ||
layoutDependency === undefined) {
projection.willUpdate();
}
else {
this.safeToRemove();
}
if (prevProps.isPresent !== isPresent) {
if (isPresent) {
projection.promote();
}
else if (!projection.relegate()) {
/**
* If there's another stack member taking over from this one,
* it's in charge of the exit animation and therefore should
* be in charge of the safe to remove. Otherwise we call it here.
*/
sync.postRender(() => {
const stack = projection.getStack();
if (!stack || !stack.members.length) {
this.safeToRemove();
}
});
}
}
return null;
}
componentDidUpdate() {
const { projection } = this.props.visualElement;
if (projection) {
projection.root.didUpdate();
if (!projection.currentAnimation && projection.isLead()) {
this.safeToRemove();
}
}
}
componentWillUnmount() {
const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props;
const { projection } = visualElement;
if (projection) {
projection.scheduleCheckAfterUnmount();
if (layoutGroup && layoutGroup.group)
layoutGroup.group.remove(projection);
if (promoteContext && promoteContext.deregister)
promoteContext.deregister(projection);
}
}
safeToRemove() {
const { safeToRemove } = this.props;
safeToRemove && safeToRemove();
}
render() {
return null;
}
}
function MeasureLayout(props) {
const [isPresent, safeToRemove] = usePresence();
const layoutGroup = (0,external_React_.useContext)(LayoutGroupContext);
return (external_React_.createElement(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: (0,external_React_.useContext)(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove }));
}
const defaultScaleCorrectors = {
borderRadius: {
...correctBorderRadius,
applyTo: [
"borderTopLeftRadius",
"borderTopRightRadius",
"borderBottomLeftRadius",
"borderBottomRightRadius",
],
},
borderTopLeftRadius: correctBorderRadius,
borderTopRightRadius: correctBorderRadius,
borderBottomLeftRadius: correctBorderRadius,
borderBottomRightRadius: correctBorderRadius,
boxShadow: correctBoxShadow,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs
const borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"];
const numBorders = borders.length;
const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
const isPx = (value) => typeof value === "number" || px.test(value);
function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
if (shouldCrossfadeOpacity) {
target.opacity = mix(0,
// TODO Reinstate this if only child
lead.opacity !== undefined ? lead.opacity : 1, easeCrossfadeIn(progress));
target.opacityExit = mix(follow.opacity !== undefined ? follow.opacity : 1, 0, easeCrossfadeOut(progress));
}
else if (isOnlyMember) {
target.opacity = mix(follow.opacity !== undefined ? follow.opacity : 1, lead.opacity !== undefined ? lead.opacity : 1, progress);
}
/**
* Mix border radius
*/
for (let i = 0; i < numBorders; i++) {
const borderLabel = `border${borders[i]}Radius`;
let followRadius = getRadius(follow, borderLabel);
let leadRadius = getRadius(lead, borderLabel);
if (followRadius === undefined && leadRadius === undefined)
continue;
followRadius || (followRadius = 0);
leadRadius || (leadRadius = 0);
const canMix = followRadius === 0 ||
leadRadius === 0 ||
isPx(followRadius) === isPx(leadRadius);
if (canMix) {
target[borderLabel] = Math.max(mix(asNumber(followRadius), asNumber(leadRadius), progress), 0);
if (percent.test(leadRadius) || percent.test(followRadius)) {
target[borderLabel] += "%";
}
}
else {
target[borderLabel] = leadRadius;
}
}
/**
* Mix rotation
*/
if (follow.rotate || lead.rotate) {
target.rotate = mix(follow.rotate || 0, lead.rotate || 0, progress);
}
}
function getRadius(values, radiusName) {
return values[radiusName] !== undefined
? values[radiusName]
: values.borderRadius;
}
// /**
// * We only want to mix the background color if there's a follow element
// * that we're not crossfading opacity between. For instance with switch
// * AnimateSharedLayout animations, this helps the illusion of a continuous
// * element being animated but also cuts down on the number of paints triggered
// * for elements where opacity is doing that work for us.
// */
// if (
// !hasFollowElement &&
// latestLeadValues.backgroundColor &&
// latestFollowValues.backgroundColor
// ) {
// /**
// * This isn't ideal performance-wise as mixColor is creating a new function every frame.
// * We could probably create a mixer that runs at the start of the animation but
// * the idea behind the crossfader is that it runs dynamically between two potentially
// * changing targets (ie opacity or borderRadius may be animating independently via variants)
// */
// leadState.backgroundColor = followState.backgroundColor = mixColor(
// latestFollowValues.backgroundColor as string,
// latestLeadValues.backgroundColor as string
// )(p)
// }
const easeCrossfadeIn = compress(0, 0.5, circOut);
const easeCrossfadeOut = compress(0.5, 0.95, noop);
function compress(min, max, easing) {
return (p) => {
// Could replace ifs with clamp
if (p < min)
return 0;
if (p > max)
return 1;
return easing(progress(min, max, p));
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/copy.mjs
/**
* Reset an axis to the provided origin box.
*
* This is a mutative operation.
*/
function copyAxisInto(axis, originAxis) {
axis.min = originAxis.min;
axis.max = originAxis.max;
}
/**
* Reset a box to the provided origin box.
*
* This is a mutative operation.
*/
function copyBoxInto(box, originBox) {
copyAxisInto(box.x, originBox.x);
copyAxisInto(box.y, originBox.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs
/**
* Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse
*/
function removePointDelta(point, translate, scale, originPoint, boxScale) {
point -= translate;
point = scalePoint(point, 1 / scale, originPoint);
if (boxScale !== undefined) {
point = scalePoint(point, 1 / boxScale, originPoint);
}
return point;
}
/**
* Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse
*/
function removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) {
if (percent.test(translate)) {
translate = parseFloat(translate);
const relativeProgress = mix(sourceAxis.min, sourceAxis.max, translate / 100);
translate = relativeProgress - sourceAxis.min;
}
if (typeof translate !== "number")
return;
let originPoint = mix(originAxis.min, originAxis.max, origin);
if (axis === originAxis)
originPoint -= translate;
axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale);
axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale);
}
/**
* Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse
* and acts as a bridge between motion values and removeAxisDelta
*/
function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) {
removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis);
}
/**
* The names of the motion values we want to apply as translation, scale and origin.
*/
const delta_remove_xKeys = ["x", "scaleX", "originX"];
const delta_remove_yKeys = ["y", "scaleY", "originY"];
/**
* Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse
* and acts as a bridge between motion values and removeAxisDelta
*/
function removeBoxTransforms(box, transforms, originBox, sourceBox) {
removeAxisTransforms(box.x, transforms, delta_remove_xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);
removeAxisTransforms(box.y, transforms, delta_remove_yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/utils.mjs
function isAxisDeltaZero(delta) {
return delta.translate === 0 && delta.scale === 1;
}
function isDeltaZero(delta) {
return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y);
}
function boxEquals(a, b) {
return (a.x.min === b.x.min &&
a.x.max === b.x.max &&
a.y.min === b.y.min &&
a.y.max === b.y.max);
}
function aspectRatio(box) {
return calcLength(box.x) / calcLength(box.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/shared/stack.mjs
class NodeStack {
constructor() {
this.members = [];
}
add(node) {
addUniqueItem(this.members, node);
node.scheduleRender();
}
remove(node) {
removeItem(this.members, node);
if (node === this.prevLead) {
this.prevLead = undefined;
}
if (node === this.lead) {
const prevLead = this.members[this.members.length - 1];
if (prevLead) {
this.promote(prevLead);
}
}
}
relegate(node) {
const indexOfNode = this.members.findIndex((member) => node === member);
if (indexOfNode === 0)
return false;
/**
* Find the next projection node that is present
*/
let prevLead;
for (let i = indexOfNode; i >= 0; i--) {
const member = this.members[i];
if (member.isPresent !== false) {
prevLead = member;
break;
}
}
if (prevLead) {
this.promote(prevLead);
return true;
}
else {
return false;
}
}
promote(node, preserveFollowOpacity) {
const prevLead = this.lead;
if (node === prevLead)
return;
this.prevLead = prevLead;
this.lead = node;
node.show();
if (prevLead) {
prevLead.instance && prevLead.scheduleRender();
node.scheduleRender();
node.resumeFrom = prevLead;
if (preserveFollowOpacity) {
node.resumeFrom.preserveOpacity = true;
}
if (prevLead.snapshot) {
node.snapshot = prevLead.snapshot;
node.snapshot.latestValues =
prevLead.animationValues || prevLead.latestValues;
}
if (node.root && node.root.isUpdating) {
node.isLayoutDirty = true;
}
const { crossfade } = node.options;
if (crossfade === false) {
prevLead.hide();
}
/**
* TODO:
* - Test border radius when previous node was deleted
* - boxShadow mixing
* - Shared between element A in scrolled container and element B (scroll stays the same or changes)
* - Shared between element A in transformed container and element B (transform stays the same or changes)
* - Shared between element A in scrolled page and element B (scroll stays the same or changes)
* ---
* - Crossfade opacity of root nodes
* - layoutId changes after animation
* - layoutId changes mid animation
*/
}
}
exitAnimationComplete() {
this.members.forEach((node) => {
const { options, resumingFrom } = node;
options.onExitComplete && options.onExitComplete();
if (resumingFrom) {
resumingFrom.options.onExitComplete &&
resumingFrom.options.onExitComplete();
}
});
}
scheduleRender() {
this.members.forEach((node) => {
node.instance && node.scheduleRender(false);
});
}
/**
* Clear any leads that have been removed this render to prevent them from being
* used in future animations and to prevent memory leaks
*/
removeLeadSnapshot() {
if (this.lead && this.lead.snapshot) {
this.lead.snapshot = undefined;
}
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/transform.mjs
function buildProjectionTransform(delta, treeScale, latestTransform) {
let transform = "";
/**
* The translations we use to calculate are always relative to the viewport coordinate space.
* But when we apply scales, we also scale the coordinate space of an element and its children.
* For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need
* to move an element 100 pixels, we actually need to move it 200 in within that scaled space.
*/
const xTranslate = delta.x.translate / treeScale.x;
const yTranslate = delta.y.translate / treeScale.y;
if (xTranslate || yTranslate) {
transform = `translate3d(${xTranslate}px, ${yTranslate}px, 0) `;
}
/**
* Apply scale correction for the tree transform.
* This will apply scale to the screen-orientated axes.
*/
if (treeScale.x !== 1 || treeScale.y !== 1) {
transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
}
if (latestTransform) {
const { rotate, rotateX, rotateY } = latestTransform;
if (rotate)
transform += `rotate(${rotate}deg) `;
if (rotateX)
transform += `rotateX(${rotateX}deg) `;
if (rotateY)
transform += `rotateY(${rotateY}deg) `;
}
/**
* Apply scale to match the size of the element to the size we want it.
* This will apply scale to the element-orientated axes.
*/
const elementScaleX = delta.x.scale * treeScale.x;
const elementScaleY = delta.y.scale * treeScale.y;
if (elementScaleX !== 1 || elementScaleY !== 1) {
transform += `scale(${elementScaleX}, ${elementScaleY})`;
}
return transform || "none";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs
const compareByDepth = (a, b) => a.depth - b.depth;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs
class FlatTree {
constructor() {
this.children = [];
this.isDirty = false;
}
add(child) {
addUniqueItem(this.children, child);
this.isDirty = true;
}
remove(child) {
removeItem(this.children, child);
this.isDirty = true;
}
forEach(callback) {
this.isDirty && this.children.sort(compareByDepth);
this.isDirty = false;
this.children.forEach(callback);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/delay.mjs
/**
* Timeout defined in ms
*/
function delay(callback, timeout) {
const start = performance.now();
const checkElapsed = ({ timestamp }) => {
const elapsed = timestamp - start;
if (elapsed >= timeout) {
cancelSync.read(checkElapsed);
callback(elapsed - timeout);
}
};
sync.read(checkElapsed, true);
return () => cancelSync.read(checkElapsed);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/debug/record.mjs
function record(data) {
if (window.MotionDebug) {
window.MotionDebug.record(data);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/is-svg-element.mjs
function isSVGElement(element) {
return element instanceof SVGElement && element.tagName !== "svg";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/interfaces/single-value.mjs
function animateSingleValue(value, keyframes, options) {
const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options));
return motionValue$1.animation;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs
const transformAxes = ["", "X", "Y", "Z"];
/**
* We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1
* which has a noticeable difference in spring animations
*/
const animationTarget = 1000;
let create_projection_node_id = 0;
/**
* Use a mutable data object for debug data so as to not create a new
* object every frame.
*/
const projectionFrameData = {
type: "projectionFrame",
totalNodes: 0,
resolvedTargetDeltas: 0,
recalculatedProjection: 0,
};
function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
return class ProjectionNode {
constructor(elementId, latestValues = {}, parent = defaultParent === null || defaultParent === void 0 ? void 0 : defaultParent()) {
/**
* A unique ID generated for every projection node.
*/
this.id = create_projection_node_id++;
/**
* An id that represents a unique session instigated by startUpdate.
*/
this.animationId = 0;
/**
* A Set containing all this component's children. This is used to iterate
* through the children.
*
* TODO: This could be faster to iterate as a flat array stored on the root node.
*/
this.children = new Set();
/**
* Options for the node. We use this to configure what kind of layout animations
* we should perform (if any).
*/
this.options = {};
/**
* We use this to detect when its safe to shut down part of a projection tree.
* We have to keep projecting children for scale correction and relative projection
* until all their parents stop performing layout animations.
*/
this.isTreeAnimating = false;
this.isAnimationBlocked = false;
/**
* Flag to true if we think this layout has been changed. We can't always know this,
* currently we set it to true every time a component renders, or if it has a layoutDependency
* if that has changed between renders. Additionally, components can be grouped by LayoutGroup
* and if one node is dirtied, they all are.
*/
this.isLayoutDirty = false;
/**
* Flag to true if we think the projection calculations for this node needs
* recalculating as a result of an updated transform or layout animation.
*/
this.isProjectionDirty = false;
/**
* Flag to true if the layout *or* transform has changed. This then gets propagated
* throughout the projection tree, forcing any element below to recalculate on the next frame.
*/
this.isSharedProjectionDirty = false;
/**
* Flag transform dirty. This gets propagated throughout the whole tree but is only
* respected by shared nodes.
*/
this.isTransformDirty = false;
/**
* Block layout updates for instant layout transitions throughout the tree.
*/
this.updateManuallyBlocked = false;
this.updateBlockedByResize = false;
/**
* Set to true between the start of the first `willUpdate` call and the end of the `didUpdate`
* call.
*/
this.isUpdating = false;
/**
* If this is an SVG element we currently disable projection transforms
*/
this.isSVG = false;
/**
* Flag to true (during promotion) if a node doing an instant layout transition needs to reset
* its projection styles.
*/
this.needsReset = false;
/**
* Flags whether this node should have its transform reset prior to measuring.
*/
this.shouldResetTransform = false;
/**
* An object representing the calculated contextual/accumulated/tree scale.
* This will be used to scale calculcated projection transforms, as these are
* calculated in screen-space but need to be scaled for elements to layoutly
* make it to their calculated destinations.
*
* TODO: Lazy-init
*/
this.treeScale = { x: 1, y: 1 };
/**
*
*/
this.eventHandlers = new Map();
// Note: Currently only running on root node
this.potentialNodes = new Map();
this.checkUpdateFailed = () => {
if (this.isUpdating) {
this.isUpdating = false;
this.clearAllSnapshots();
}
};
/**
* This is a multi-step process as shared nodes might be of different depths. Nodes
* are sorted by depth order, so we need to resolve the entire tree before moving to
* the next step.
*/
this.updateProjection = () => {
/**
* Reset debug counts. Manually resetting rather than creating a new
* object each frame.
*/
projectionFrameData.totalNodes =
projectionFrameData.resolvedTargetDeltas =
projectionFrameData.recalculatedProjection =
0;
this.nodes.forEach(propagateDirtyNodes);
this.nodes.forEach(resolveTargetDelta);
this.nodes.forEach(calcProjection);
this.nodes.forEach(cleanDirtyNodes);
record(projectionFrameData);
};
this.hasProjected = false;
this.isVisible = true;
this.animationProgress = 0;
/**
* Shared layout
*/
// TODO Only running on root node
this.sharedNodes = new Map();
this.elementId = elementId;
this.latestValues = latestValues;
this.root = parent ? parent.root || parent : this;
this.path = parent ? [...parent.path, parent] : [];
this.parent = parent;
this.depth = parent ? parent.depth + 1 : 0;
elementId && this.root.registerPotentialNode(elementId, this);
for (let i = 0; i < this.path.length; i++) {
this.path[i].shouldResetTransform = true;
}
if (this.root === this)
this.nodes = new FlatTree();
}
addEventListener(name, handler) {
if (!this.eventHandlers.has(name)) {
this.eventHandlers.set(name, new SubscriptionManager());
}
return this.eventHandlers.get(name).add(handler);
}
notifyListeners(name, ...args) {
const subscriptionManager = this.eventHandlers.get(name);
subscriptionManager && subscriptionManager.notify(...args);
}
hasListeners(name) {
return this.eventHandlers.has(name);
}
registerPotentialNode(elementId, node) {
this.potentialNodes.set(elementId, node);
}
/**
* Lifecycles
*/
mount(instance, isLayoutDirty = false) {
if (this.instance)
return;
this.isSVG = isSVGElement(instance);
this.instance = instance;
const { layoutId, layout, visualElement } = this.options;
if (visualElement && !visualElement.current) {
visualElement.mount(instance);
}
this.root.nodes.add(this);
this.parent && this.parent.children.add(this);
this.elementId && this.root.potentialNodes.delete(this.elementId);
if (isLayoutDirty && (layout || layoutId)) {
this.isLayoutDirty = true;
}
if (attachResizeListener) {
let cancelDelay;
const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false);
attachResizeListener(instance, () => {
this.root.updateBlockedByResize = true;
cancelDelay && cancelDelay();
cancelDelay = delay(resizeUnblockUpdate, 250);
if (globalProjectionState.hasAnimatedSinceResize) {
globalProjectionState.hasAnimatedSinceResize = false;
this.nodes.forEach(finishAnimation);
}
});
}
if (layoutId) {
this.root.registerSharedNode(layoutId, this);
}
// Only register the handler if it requires layout animation
if (this.options.animate !== false &&
visualElement &&
(layoutId || layout)) {
this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeTargetChanged, layout: newLayout, }) => {
if (this.isTreeAnimationBlocked()) {
this.target = undefined;
this.relativeTarget = undefined;
return;
}
// TODO: Check here if an animation exists
const layoutTransition = this.options.transition ||
visualElement.getDefaultTransition() ||
defaultLayoutTransition;
const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps();
/**
* The target layout of the element might stay the same,
* but its position relative to its parent has changed.
*/
const targetChanged = !this.targetLayout ||
!boxEquals(this.targetLayout, newLayout) ||
hasRelativeTargetChanged;
/**
* If the layout hasn't seemed to have changed, it might be that the
* element is visually in the same place in the document but its position
* relative to its parent has indeed changed. So here we check for that.
*/
const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeTargetChanged;
if (this.options.layoutRoot ||
(this.resumeFrom && this.resumeFrom.instance) ||
hasOnlyRelativeTargetChanged ||
(hasLayoutChanged &&
(targetChanged || !this.currentAnimation))) {
if (this.resumeFrom) {
this.resumingFrom = this.resumeFrom;
this.resumingFrom.resumingFrom = undefined;
}
this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);
const animationOptions = {
...getValueTransition(layoutTransition, "layout"),
onPlay: onLayoutAnimationStart,
onComplete: onLayoutAnimationComplete,
};
if (visualElement.shouldReduceMotion ||
this.options.layoutRoot) {
animationOptions.delay = 0;
animationOptions.type = false;
}
this.startAnimation(animationOptions);
}
else {
/**
* If the layout hasn't changed and we have an animation that hasn't started yet,
* finish it immediately. Otherwise it will be animating from a location
* that was probably never commited to screen and look like a jumpy box.
*/
if (!hasLayoutChanged &&
this.animationProgress === 0) {
finishAnimation(this);
}
if (this.isLead() && this.options.onExitComplete) {
this.options.onExitComplete();
}
}
this.targetLayout = newLayout;
});
}
}
unmount() {
this.options.layoutId && this.willUpdate();
this.root.nodes.remove(this);
const stack = this.getStack();
stack && stack.remove(this);
this.parent && this.parent.children.delete(this);
this.instance = undefined;
cancelSync.preRender(this.updateProjection);
}
// only on the root
blockUpdate() {
this.updateManuallyBlocked = true;
}
unblockUpdate() {
this.updateManuallyBlocked = false;
}
isUpdateBlocked() {
return this.updateManuallyBlocked || this.updateBlockedByResize;
}
isTreeAnimationBlocked() {
return (this.isAnimationBlocked ||
(this.parent && this.parent.isTreeAnimationBlocked()) ||
false);
}
// Note: currently only running on root node
startUpdate() {
if (this.isUpdateBlocked())
return;
this.isUpdating = true;
this.nodes && this.nodes.forEach(resetRotation);
this.animationId++;
}
getTransformTemplate() {
const { visualElement } = this.options;
return visualElement && visualElement.getProps().transformTemplate;
}
willUpdate(shouldNotifyListeners = true) {
if (this.root.isUpdateBlocked()) {
this.options.onExitComplete && this.options.onExitComplete();
return;
}
!this.root.isUpdating && this.root.startUpdate();
if (this.isLayoutDirty)
return;
this.isLayoutDirty = true;
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
node.shouldResetTransform = true;
node.updateScroll("snapshot");
if (node.options.layoutRoot) {
node.willUpdate(false);
}
}
const { layoutId, layout } = this.options;
if (layoutId === undefined && !layout)
return;
const transformTemplate = this.getTransformTemplate();
this.prevTransformTemplateValue = transformTemplate
? transformTemplate(this.latestValues, "")
: undefined;
this.updateSnapshot();
shouldNotifyListeners && this.notifyListeners("willUpdate");
}
// Note: Currently only running on root node
didUpdate() {
const updateWasBlocked = this.isUpdateBlocked();
// When doing an instant transition, we skip the layout update,
// but should still clean up the measurements so that the next
// snapshot could be taken correctly.
if (updateWasBlocked) {
this.unblockUpdate();
this.clearAllSnapshots();
this.nodes.forEach(clearMeasurements);
return;
}
if (!this.isUpdating)
return;
this.isUpdating = false;
/**
* Search for and mount newly-added projection elements.
*
* TODO: Every time a new component is rendered we could search up the tree for
* the closest mounted node and query from there rather than document.
*/
if (this.potentialNodes.size) {
this.potentialNodes.forEach(mountNodeEarly);
this.potentialNodes.clear();
}
/**
* Write
*/
this.nodes.forEach(resetTransformStyle);
/**
* Read ==================
*/
// Update layout measurements of updated children
this.nodes.forEach(updateLayout);
/**
* Write
*/
// Notify listeners that the layout is updated
this.nodes.forEach(notifyLayoutUpdate);
this.clearAllSnapshots();
// Flush any scheduled updates
flushSync.update();
flushSync.preRender();
flushSync.render();
}
clearAllSnapshots() {
this.nodes.forEach(clearSnapshot);
this.sharedNodes.forEach(removeLeadSnapshots);
}
scheduleUpdateProjection() {
sync.preRender(this.updateProjection, false, true);
}
scheduleCheckAfterUnmount() {
/**
* If the unmounting node is in a layoutGroup and did trigger a willUpdate,
* we manually call didUpdate to give a chance to the siblings to animate.
* Otherwise, cleanup all snapshots to prevents future nodes from reusing them.
*/
sync.postRender(() => {
if (this.isLayoutDirty) {
this.root.didUpdate();
}
else {
this.root.checkUpdateFailed();
}
});
}
/**
* Update measurements
*/
updateSnapshot() {
if (this.snapshot || !this.instance)
return;
this.snapshot = this.measure();
}
updateLayout() {
if (!this.instance)
return;
// TODO: Incorporate into a forwarded scroll offset
this.updateScroll();
if (!(this.options.alwaysMeasureLayout && this.isLead()) &&
!this.isLayoutDirty) {
return;
}
/**
* When a node is mounted, it simply resumes from the prevLead's
* snapshot instead of taking a new one, but the ancestors scroll
* might have updated while the prevLead is unmounted. We need to
* update the scroll again to make sure the layout we measure is
* up to date.
*/
if (this.resumeFrom && !this.resumeFrom.instance) {
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
node.updateScroll();
}
}
const prevLayout = this.layout;
this.layout = this.measure(false);
this.layoutCorrected = createBox();
this.isLayoutDirty = false;
this.projectionDelta = undefined;
this.notifyListeners("measure", this.layout.layoutBox);
const { visualElement } = this.options;
visualElement &&
visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined);
}
updateScroll(phase = "measure") {
let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);
if (this.scroll &&
this.scroll.animationId === this.root.animationId &&
this.scroll.phase === phase) {
needsMeasurement = false;
}
if (needsMeasurement) {
this.scroll = {
animationId: this.root.animationId,
phase,
isRoot: checkIsScrollRoot(this.instance),
offset: measureScroll(this.instance),
};
}
}
resetTransform() {
if (!resetTransform)
return;
const isResetRequested = this.isLayoutDirty || this.shouldResetTransform;
const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);
const transformTemplate = this.getTransformTemplate();
const transformTemplateValue = transformTemplate
? transformTemplate(this.latestValues, "")
: undefined;
const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue;
if (isResetRequested &&
(hasProjection ||
hasTransform(this.latestValues) ||
transformTemplateHasChanged)) {
resetTransform(this.instance, transformTemplateValue);
this.shouldResetTransform = false;
this.scheduleRender();
}
}
measure(removeTransform = true) {
const pageBox = this.measurePageBox();
let layoutBox = this.removeElementScroll(pageBox);
/**
* Measurements taken during the pre-render stage
* still have transforms applied so we remove them
* via calculation.
*/
if (removeTransform) {
layoutBox = this.removeTransform(layoutBox);
}
roundBox(layoutBox);
return {
animationId: this.root.animationId,
measuredBox: pageBox,
layoutBox,
latestValues: {},
source: this.id,
};
}
measurePageBox() {
const { visualElement } = this.options;
if (!visualElement)
return createBox();
const box = visualElement.measureViewportBox();
// Remove viewport scroll to give page-relative coordinates
const { scroll } = this.root;
if (scroll) {
translateAxis(box.x, scroll.offset.x);
translateAxis(box.y, scroll.offset.y);
}
return box;
}
removeElementScroll(box) {
const boxWithoutScroll = createBox();
copyBoxInto(boxWithoutScroll, box);
/**
* Performance TODO: Keep a cumulative scroll offset down the tree
* rather than loop back up the path.
*/
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
const { scroll, options } = node;
if (node !== this.root && scroll && options.layoutScroll) {
/**
* If this is a new scroll root, we want to remove all previous scrolls
* from the viewport box.
*/
if (scroll.isRoot) {
copyBoxInto(boxWithoutScroll, box);
const { scroll: rootScroll } = this.root;
/**
* Undo the application of page scroll that was originally added
* to the measured bounding box.
*/
if (rootScroll) {
translateAxis(boxWithoutScroll.x, -rootScroll.offset.x);
translateAxis(boxWithoutScroll.y, -rootScroll.offset.y);
}
}
translateAxis(boxWithoutScroll.x, scroll.offset.x);
translateAxis(boxWithoutScroll.y, scroll.offset.y);
}
}
return boxWithoutScroll;
}
applyTransform(box, transformOnly = false) {
const withTransforms = createBox();
copyBoxInto(withTransforms, box);
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
if (!transformOnly &&
node.options.layoutScroll &&
node.scroll &&
node !== node.root) {
transformBox(withTransforms, {
x: -node.scroll.offset.x,
y: -node.scroll.offset.y,
});
}
if (!hasTransform(node.latestValues))
continue;
transformBox(withTransforms, node.latestValues);
}
if (hasTransform(this.latestValues)) {
transformBox(withTransforms, this.latestValues);
}
return withTransforms;
}
removeTransform(box) {
const boxWithoutTransform = createBox();
copyBoxInto(boxWithoutTransform, box);
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
if (!node.instance)
continue;
if (!hasTransform(node.latestValues))
continue;
hasScale(node.latestValues) && node.updateSnapshot();
const sourceBox = createBox();
const nodeBox = node.measurePageBox();
copyBoxInto(sourceBox, nodeBox);
removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot ? node.snapshot.layoutBox : undefined, sourceBox);
}
if (hasTransform(this.latestValues)) {
removeBoxTransforms(boxWithoutTransform, this.latestValues);
}
return boxWithoutTransform;
}
setTargetDelta(delta) {
this.targetDelta = delta;
this.root.scheduleUpdateProjection();
this.isProjectionDirty = true;
}
setOptions(options) {
this.options = {
...this.options,
...options,
crossfade: options.crossfade !== undefined ? options.crossfade : true,
};
}
clearMeasurements() {
this.scroll = undefined;
this.layout = undefined;
this.snapshot = undefined;
this.prevTransformTemplateValue = undefined;
this.targetDelta = undefined;
this.target = undefined;
this.isLayoutDirty = false;
}
forceRelativeParentToResolveTarget() {
if (!this.relativeParent)
return;
/**
* If the parent target isn't up-to-date, force it to update.
* This is an unfortunate de-optimisation as it means any updating relative
* projection will cause all the relative parents to recalculate back
* up the tree.
*/
if (this.relativeParent.resolvedRelativeTargetAt !==
frameData.timestamp) {
this.relativeParent.resolveTargetDelta(true);
}
}
resolveTargetDelta(forceRecalculation = false) {
var _a;
/**
* Once the dirty status of nodes has been spread through the tree, we also
* need to check if we have a shared node of a different depth that has itself
* been dirtied.
*/
const lead = this.getLead();
this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty);
this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty);
this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty);
const isShared = Boolean(this.resumingFrom) || this !== lead;
/**
* We don't use transform for this step of processing so we don't
* need to check whether any nodes have changed transform.
*/
const canSkip = !(forceRecalculation ||
(isShared && this.isSharedProjectionDirty) ||
this.isProjectionDirty ||
((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isProjectionDirty) ||
this.attemptToResolveRelativeTarget);
if (canSkip)
return;
const { layout, layoutId } = this.options;
/**
* If we have no layout, we can't perform projection, so early return
*/
if (!this.layout || !(layout || layoutId))
return;
this.resolvedRelativeTargetAt = frameData.timestamp;
/**
* If we don't have a targetDelta but do have a layout, we can attempt to resolve
* a relativeParent. This will allow a component to perform scale correction
* even if no animation has started.
*/
// TODO If this is unsuccessful this currently happens every frame
if (!this.targetDelta && !this.relativeTarget) {
// TODO: This is a semi-repetition of further down this function, make DRY
const relativeParent = this.getClosestProjectingParent();
if (relativeParent && relativeParent.layout) {
this.relativeParent = relativeParent;
this.forceRelativeParentToResolveTarget();
this.relativeTarget = createBox();
this.relativeTargetOrigin = createBox();
calcRelativePosition(this.relativeTargetOrigin, this.layout.layoutBox, relativeParent.layout.layoutBox);
copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);
}
else {
this.relativeParent = this.relativeTarget = undefined;
}
}
/**
* If we have no relative target or no target delta our target isn't valid
* for this frame.
*/
if (!this.relativeTarget && !this.targetDelta)
return;
/**
* Lazy-init target data structure
*/
if (!this.target) {
this.target = createBox();
this.targetWithTransforms = createBox();
}
/**
* If we've got a relative box for this component, resolve it into a target relative to the parent.
*/
if (this.relativeTarget &&
this.relativeTargetOrigin &&
this.relativeParent &&
this.relativeParent.target) {
this.forceRelativeParentToResolveTarget();
calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target);
/**
* If we've only got a targetDelta, resolve it into a target
*/
}
else if (this.targetDelta) {
if (Boolean(this.resumingFrom)) {
// TODO: This is creating a new object every frame
this.target = this.applyTransform(this.layout.layoutBox);
}
else {
copyBoxInto(this.target, this.layout.layoutBox);
}
applyBoxDelta(this.target, this.targetDelta);
}
else {
/**
* If no target, use own layout as target
*/
copyBoxInto(this.target, this.layout.layoutBox);
}
/**
* If we've been told to attempt to resolve a relative target, do so.
*/
if (this.attemptToResolveRelativeTarget) {
this.attemptToResolveRelativeTarget = false;
const relativeParent = this.getClosestProjectingParent();
if (relativeParent &&
Boolean(relativeParent.resumingFrom) ===
Boolean(this.resumingFrom) &&
!relativeParent.options.layoutScroll &&
relativeParent.target) {
this.relativeParent = relativeParent;
this.forceRelativeParentToResolveTarget();
this.relativeTarget = createBox();
this.relativeTargetOrigin = createBox();
calcRelativePosition(this.relativeTargetOrigin, this.target, relativeParent.target);
copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);
}
else {
this.relativeParent = this.relativeTarget = undefined;
}
}
/**
* Increase debug counter for resolved target deltas
*/
projectionFrameData.resolvedTargetDeltas++;
}
getClosestProjectingParent() {
if (!this.parent ||
hasScale(this.parent.latestValues) ||
has2DTranslate(this.parent.latestValues)) {
return undefined;
}
if (this.parent.isProjecting()) {
return this.parent;
}
else {
return this.parent.getClosestProjectingParent();
}
}
isProjecting() {
return Boolean((this.relativeTarget ||
this.targetDelta ||
this.options.layoutRoot) &&
this.layout);
}
calcProjection() {
var _a;
const lead = this.getLead();
const isShared = Boolean(this.resumingFrom) || this !== lead;
let canSkip = true;
/**
* If this is a normal layout animation and neither this node nor its nearest projecting
* is dirty then we can't skip.
*/
if (this.isProjectionDirty || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isProjectionDirty)) {
canSkip = false;
}
/**
* If this is a shared layout animation and this node's shared projection is dirty then
* we can't skip.
*/
if (isShared &&
(this.isSharedProjectionDirty || this.isTransformDirty)) {
canSkip = false;
}
/**
* If we have resolved the target this frame we must recalculate the
* projection to ensure it visually represents the internal calculations.
*/
if (this.resolvedRelativeTargetAt === frameData.timestamp) {
canSkip = false;
}
if (canSkip)
return;
const { layout, layoutId } = this.options;
/**
* If this section of the tree isn't animating we can
* delete our target sources for the following frame.
*/
this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) ||
this.currentAnimation ||
this.pendingAnimation);
if (!this.isTreeAnimating) {
this.targetDelta = this.relativeTarget = undefined;
}
if (!this.layout || !(layout || layoutId))
return;
/**
* Reset the corrected box with the latest values from box, as we're then going
* to perform mutative operations on it.
*/
copyBoxInto(this.layoutCorrected, this.layout.layoutBox);
/**
* Apply all the parent deltas to this box to produce the corrected box. This
* is the layout box, as it will appear on screen as a result of the transforms of its parents.
*/
applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);
const { target } = lead;
if (!target)
return;
if (!this.projectionDelta) {
this.projectionDelta = createDelta();
this.projectionDeltaWithTransform = createDelta();
}
const prevTreeScaleX = this.treeScale.x;
const prevTreeScaleY = this.treeScale.y;
const prevProjectionTransform = this.projectionTransform;
/**
* Update the delta between the corrected box and the target box before user-set transforms were applied.
* This will allow us to calculate the corrected borderRadius and boxShadow to compensate
* for our layout reprojection, but still allow them to be scaled correctly by the user.
* It might be that to simplify this we may want to accept that user-set scale is also corrected
* and we wouldn't have to keep and calc both deltas, OR we could support a user setting
* to allow people to choose whether these styles are corrected based on just the
* layout reprojection or the final bounding box.
*/
calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues);
this.projectionTransform = buildProjectionTransform(this.projectionDelta, this.treeScale);
if (this.projectionTransform !== prevProjectionTransform ||
this.treeScale.x !== prevTreeScaleX ||
this.treeScale.y !== prevTreeScaleY) {
this.hasProjected = true;
this.scheduleRender();
this.notifyListeners("projectionUpdate", target);
}
/**
* Increase debug counter for recalculated projections
*/
projectionFrameData.recalculatedProjection++;
}
hide() {
this.isVisible = false;
// TODO: Schedule render
}
show() {
this.isVisible = true;
// TODO: Schedule render
}
scheduleRender(notifyAll = true) {
this.options.scheduleRender && this.options.scheduleRender();
if (notifyAll) {
const stack = this.getStack();
stack && stack.scheduleRender();
}
if (this.resumingFrom && !this.resumingFrom.instance) {
this.resumingFrom = undefined;
}
}
setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) {
const snapshot = this.snapshot;
const snapshotLatestValues = snapshot
? snapshot.latestValues
: {};
const mixedValues = { ...this.latestValues };
const targetDelta = createDelta();
if (!this.relativeParent ||
!this.relativeParent.options.layoutRoot) {
this.relativeTarget = this.relativeTargetOrigin = undefined;
}
this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;
const relativeLayout = createBox();
const snapshotSource = snapshot ? snapshot.source : undefined;
const layoutSource = this.layout ? this.layout.source : undefined;
const isSharedLayoutAnimation = snapshotSource !== layoutSource;
const stack = this.getStack();
const isOnlyMember = !stack || stack.members.length <= 1;
const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&
!isOnlyMember &&
this.options.crossfade === true &&
!this.path.some(hasOpacityCrossfade));
this.animationProgress = 0;
let prevRelativeTarget;
this.mixTargetDelta = (latest) => {
const progress = latest / 1000;
mixAxisDelta(targetDelta.x, delta.x, progress);
mixAxisDelta(targetDelta.y, delta.y, progress);
this.setTargetDelta(targetDelta);
if (this.relativeTarget &&
this.relativeTargetOrigin &&
this.layout &&
this.relativeParent &&
this.relativeParent.layout) {
calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox);
mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress);
/**
* If this is an unchanged relative target we can consider the
* projection not dirty.
*/
if (prevRelativeTarget &&
boxEquals(this.relativeTarget, prevRelativeTarget)) {
this.isProjectionDirty = false;
}
if (!prevRelativeTarget)
prevRelativeTarget = createBox();
copyBoxInto(prevRelativeTarget, this.relativeTarget);
}
if (isSharedLayoutAnimation) {
this.animationValues = mixedValues;
mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);
}
this.root.scheduleUpdateProjection();
this.scheduleRender();
this.animationProgress = progress;
};
this.mixTargetDelta(this.options.layoutRoot ? 1000 : 0);
}
startAnimation(options) {
this.notifyListeners("animationStart");
this.currentAnimation && this.currentAnimation.stop();
if (this.resumingFrom && this.resumingFrom.currentAnimation) {
this.resumingFrom.currentAnimation.stop();
}
if (this.pendingAnimation) {
cancelSync.update(this.pendingAnimation);
this.pendingAnimation = undefined;
}
/**
* Start the animation in the next frame to have a frame with progress 0,
* where the target is the same as when the animation started, so we can
* calculate the relative positions correctly for instant transitions.
*/
this.pendingAnimation = sync.update(() => {
globalProjectionState.hasAnimatedSinceResize = true;
this.currentAnimation = animateSingleValue(0, animationTarget, {
...options,
onUpdate: (latest) => {
this.mixTargetDelta(latest);
options.onUpdate && options.onUpdate(latest);
},
onComplete: () => {
options.onComplete && options.onComplete();
this.completeAnimation();
},
});
if (this.resumingFrom) {
this.resumingFrom.currentAnimation = this.currentAnimation;
}
this.pendingAnimation = undefined;
});
}
completeAnimation() {
if (this.resumingFrom) {
this.resumingFrom.currentAnimation = undefined;
this.resumingFrom.preserveOpacity = undefined;
}
const stack = this.getStack();
stack && stack.exitAnimationComplete();
this.resumingFrom =
this.currentAnimation =
this.animationValues =
undefined;
this.notifyListeners("animationComplete");
}
finishAnimation() {
if (this.currentAnimation) {
this.mixTargetDelta && this.mixTargetDelta(animationTarget);
this.currentAnimation.stop();
}
this.completeAnimation();
}
applyTransformsToTarget() {
const lead = this.getLead();
let { targetWithTransforms, target, layout, latestValues } = lead;
if (!targetWithTransforms || !target || !layout)
return;
/**
* If we're only animating position, and this element isn't the lead element,
* then instead of projecting into the lead box we instead want to calculate
* a new target that aligns the two boxes but maintains the layout shape.
*/
if (this !== lead &&
this.layout &&
layout &&
shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {
target = this.target || createBox();
const xLength = calcLength(this.layout.layoutBox.x);
target.x.min = lead.target.x.min;
target.x.max = target.x.min + xLength;
const yLength = calcLength(this.layout.layoutBox.y);
target.y.min = lead.target.y.min;
target.y.max = target.y.min + yLength;
}
copyBoxInto(targetWithTransforms, target);
/**
* Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal.
* This is the final box that we will then project into by calculating a transform delta and
* applying it to the corrected box.
*/
transformBox(targetWithTransforms, latestValues);
/**
* Update the delta between the corrected box and the final target box, after
* user-set transforms are applied to it. This will be used by the renderer to
* create a transform style that will reproject the element from its layout layout
* into the desired bounding box.
*/
calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues);
}
registerSharedNode(layoutId, node) {
if (!this.sharedNodes.has(layoutId)) {
this.sharedNodes.set(layoutId, new NodeStack());
}
const stack = this.sharedNodes.get(layoutId);
stack.add(node);
const config = node.options.initialPromotionConfig;
node.promote({
transition: config ? config.transition : undefined,
preserveFollowOpacity: config && config.shouldPreserveFollowOpacity
? config.shouldPreserveFollowOpacity(node)
: undefined,
});
}
isLead() {
const stack = this.getStack();
return stack ? stack.lead === this : true;
}
getLead() {
var _a;
const { layoutId } = this.options;
return layoutId ? ((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.lead) || this : this;
}
getPrevLead() {
var _a;
const { layoutId } = this.options;
return layoutId ? (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.prevLead : undefined;
}
getStack() {
const { layoutId } = this.options;
if (layoutId)
return this.root.sharedNodes.get(layoutId);
}
promote({ needsReset, transition, preserveFollowOpacity, } = {}) {
const stack = this.getStack();
if (stack)
stack.promote(this, preserveFollowOpacity);
if (needsReset) {
this.projectionDelta = undefined;
this.needsReset = true;
}
if (transition)
this.setOptions({ transition });
}
relegate() {
const stack = this.getStack();
if (stack) {
return stack.relegate(this);
}
else {
return false;
}
}
resetRotation() {
const { visualElement } = this.options;
if (!visualElement)
return;
// If there's no detected rotation values, we can early return without a forced render.
let hasRotate = false;
/**
* An unrolled check for rotation values. Most elements don't have any rotation and
* skipping the nested loop and new object creation is 50% faster.
*/
const { latestValues } = visualElement;
if (latestValues.rotate ||
latestValues.rotateX ||
latestValues.rotateY ||
latestValues.rotateZ) {
hasRotate = true;
}
// If there's no rotation values, we don't need to do any more.
if (!hasRotate)
return;
const resetValues = {};
// Check the rotate value of all axes and reset to 0
for (let i = 0; i < transformAxes.length; i++) {
const key = "rotate" + transformAxes[i];
// Record the rotation and then temporarily set it to 0
if (latestValues[key]) {
resetValues[key] = latestValues[key];
visualElement.setStaticValue(key, 0);
}
}
// Force a render of this element to apply the transform with all rotations
// set to 0.
visualElement.render();
// Put back all the values we reset
for (const key in resetValues) {
visualElement.setStaticValue(key, resetValues[key]);
}
// Schedule a render for the next frame. This ensures we won't visually
// see the element with the reset rotate value applied.
visualElement.scheduleRender();
}
getProjectionStyles(styleProp = {}) {
var _a, _b;
// TODO: Return lifecycle-persistent object
const styles = {};
if (!this.instance || this.isSVG)
return styles;
if (!this.isVisible) {
return { visibility: "hidden" };
}
else {
styles.visibility = "";
}
const transformTemplate = this.getTransformTemplate();
if (this.needsReset) {
this.needsReset = false;
styles.opacity = "";
styles.pointerEvents =
resolveMotionValue(styleProp.pointerEvents) || "";
styles.transform = transformTemplate
? transformTemplate(this.latestValues, "")
: "none";
return styles;
}
const lead = this.getLead();
if (!this.projectionDelta || !this.layout || !lead.target) {
const emptyStyles = {};
if (this.options.layoutId) {
emptyStyles.opacity =
this.latestValues.opacity !== undefined
? this.latestValues.opacity
: 1;
emptyStyles.pointerEvents =
resolveMotionValue(styleProp.pointerEvents) || "";
}
if (this.hasProjected && !hasTransform(this.latestValues)) {
emptyStyles.transform = transformTemplate
? transformTemplate({}, "")
: "none";
this.hasProjected = false;
}
return emptyStyles;
}
const valuesToRender = lead.animationValues || lead.latestValues;
this.applyTransformsToTarget();
styles.transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender);
if (transformTemplate) {
styles.transform = transformTemplate(valuesToRender, styles.transform);
}
const { x, y } = this.projectionDelta;
styles.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`;
if (lead.animationValues) {
/**
* If the lead component is animating, assign this either the entering/leaving
* opacity
*/
styles.opacity =
lead === this
? (_b = (_a = valuesToRender.opacity) !== null && _a !== void 0 ? _a : this.latestValues.opacity) !== null && _b !== void 0 ? _b : 1
: this.preserveOpacity
? this.latestValues.opacity
: valuesToRender.opacityExit;
}
else {
/**
* Or we're not animating at all, set the lead component to its layout
* opacity and other components to hidden.
*/
styles.opacity =
lead === this
? valuesToRender.opacity !== undefined
? valuesToRender.opacity
: ""
: valuesToRender.opacityExit !== undefined
? valuesToRender.opacityExit
: 0;
}
/**
* Apply scale correction
*/
for (const key in scaleCorrectors) {
if (valuesToRender[key] === undefined)
continue;
const { correct, applyTo } = scaleCorrectors[key];
/**
* Only apply scale correction to the value if we have an
* active projection transform. Otherwise these values become
* vulnerable to distortion if the element changes size without
* a corresponding layout animation.
*/
const corrected = styles.transform === "none"
? valuesToRender[key]
: correct(valuesToRender[key], lead);
if (applyTo) {
const num = applyTo.length;
for (let i = 0; i < num; i++) {
styles[applyTo[i]] = corrected;
}
}
else {
styles[key] = corrected;
}
}
/**
* Disable pointer events on follow components. This is to ensure
* that if a follow component covers a lead component it doesn't block
* pointer events on the lead.
*/
if (this.options.layoutId) {
styles.pointerEvents =
lead === this
? resolveMotionValue(styleProp.pointerEvents) || ""
: "none";
}
return styles;
}
clearSnapshot() {
this.resumeFrom = this.snapshot = undefined;
}
// Only run on root
resetTree() {
this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });
this.root.nodes.forEach(clearMeasurements);
this.root.sharedNodes.clear();
}
};
}
function updateLayout(node) {
node.updateLayout();
}
function notifyLayoutUpdate(node) {
var _a;
const snapshot = ((_a = node.resumeFrom) === null || _a === void 0 ? void 0 : _a.snapshot) || node.snapshot;
if (node.isLead() &&
node.layout &&
snapshot &&
node.hasListeners("didUpdate")) {
const { layoutBox: layout, measuredBox: measuredLayout } = node.layout;
const { animationType } = node.options;
const isShared = snapshot.source !== node.layout.source;
// TODO Maybe we want to also resize the layout snapshot so we don't trigger
// animations for instance if layout="size" and an element has only changed position
if (animationType === "size") {
eachAxis((axis) => {
const axisSnapshot = isShared
? snapshot.measuredBox[axis]
: snapshot.layoutBox[axis];
const length = calcLength(axisSnapshot);
axisSnapshot.min = layout[axis].min;
axisSnapshot.max = axisSnapshot.min + length;
});
}
else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
eachAxis((axis) => {
const axisSnapshot = isShared
? snapshot.measuredBox[axis]
: snapshot.layoutBox[axis];
const length = calcLength(layout[axis]);
axisSnapshot.max = axisSnapshot.min + length;
/**
* Ensure relative target gets resized and rerendererd
*/
if (node.relativeTarget && !node.currentAnimation) {
node.isProjectionDirty = true;
node.relativeTarget[axis].max =
node.relativeTarget[axis].min + length;
}
});
}
const layoutDelta = createDelta();
calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);
const visualDelta = createDelta();
if (isShared) {
calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);
}
else {
calcBoxDelta(visualDelta, layout, snapshot.layoutBox);
}
const hasLayoutChanged = !isDeltaZero(layoutDelta);
let hasRelativeTargetChanged = false;
if (!node.resumeFrom) {
const relativeParent = node.getClosestProjectingParent();
/**
* If the relativeParent is itself resuming from a different element then
* the relative snapshot is not relavent
*/
if (relativeParent && !relativeParent.resumeFrom) {
const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;
if (parentSnapshot && parentLayout) {
const relativeSnapshot = createBox();
calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox);
const relativeLayout = createBox();
calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox);
if (!boxEquals(relativeSnapshot, relativeLayout)) {
hasRelativeTargetChanged = true;
}
if (relativeParent.options.layoutRoot) {
node.relativeTarget = relativeLayout;
node.relativeTargetOrigin = relativeSnapshot;
node.relativeParent = relativeParent;
}
}
}
}
node.notifyListeners("didUpdate", {
layout,
snapshot,
delta: visualDelta,
layoutDelta,
hasLayoutChanged,
hasRelativeTargetChanged,
});
}
else if (node.isLead()) {
const { onExitComplete } = node.options;
onExitComplete && onExitComplete();
}
/**
* Clearing transition
* TODO: Investigate why this transition is being passed in as {type: false } from Framer
* and why we need it at all
*/
node.options.transition = undefined;
}
function propagateDirtyNodes(node) {
/**
* Increase debug counter for nodes encountered this frame
*/
projectionFrameData.totalNodes++;
if (!node.parent)
return;
/**
* If this node isn't projecting, propagate isProjectionDirty. It will have
* no performance impact but it will allow the next child that *is* projecting
* but *isn't* dirty to just check its parent to see if *any* ancestor needs
* correcting.
*/
if (!node.isProjecting()) {
node.isProjectionDirty = node.parent.isProjectionDirty;
}
/**
* Propagate isSharedProjectionDirty and isTransformDirty
* throughout the whole tree. A future revision can take another look at
* this but for safety we still recalcualte shared nodes.
*/
node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty ||
node.parent.isProjectionDirty ||
node.parent.isSharedProjectionDirty));
node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty);
}
function cleanDirtyNodes(node) {
node.isProjectionDirty =
node.isSharedProjectionDirty =
node.isTransformDirty =
false;
}
function clearSnapshot(node) {
node.clearSnapshot();
}
function clearMeasurements(node) {
node.clearMeasurements();
}
function resetTransformStyle(node) {
const { visualElement } = node.options;
if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {
visualElement.notify("BeforeLayoutMeasure");
}
node.resetTransform();
}
function finishAnimation(node) {
node.finishAnimation();
node.targetDelta = node.relativeTarget = node.target = undefined;
}
function resolveTargetDelta(node) {
node.resolveTargetDelta();
}
function calcProjection(node) {
node.calcProjection();
}
function resetRotation(node) {
node.resetRotation();
}
function removeLeadSnapshots(stack) {
stack.removeLeadSnapshot();
}
function mixAxisDelta(output, delta, p) {
output.translate = mix(delta.translate, 0, p);
output.scale = mix(delta.scale, 1, p);
output.origin = delta.origin;
output.originPoint = delta.originPoint;
}
function mixAxis(output, from, to, p) {
output.min = mix(from.min, to.min, p);
output.max = mix(from.max, to.max, p);
}
function mixBox(output, from, to, p) {
mixAxis(output.x, from.x, to.x, p);
mixAxis(output.y, from.y, to.y, p);
}
function hasOpacityCrossfade(node) {
return (node.animationValues && node.animationValues.opacityExit !== undefined);
}
const defaultLayoutTransition = {
duration: 0.45,
ease: [0.4, 0, 0.1, 1],
};
function mountNodeEarly(node, elementId) {
/**
* Rather than searching the DOM from document we can search the
* path for the deepest mounted ancestor and search from there
*/
let searchNode = node.root;
for (let i = node.path.length - 1; i >= 0; i--) {
if (Boolean(node.path[i].instance)) {
searchNode = node.path[i];
break;
}
}
const searchElement = searchNode && searchNode !== node.root ? searchNode.instance : document;
const element = searchElement.querySelector(`[data-projection-id="${elementId}"]`);
if (element)
node.mount(element, true);
}
function roundAxis(axis) {
axis.min = Math.round(axis.min);
axis.max = Math.round(axis.max);
}
function roundBox(box) {
roundAxis(box.x);
roundAxis(box.y);
}
function shouldAnimatePositionOnly(animationType, snapshot, layout) {
return (animationType === "position" ||
(animationType === "preserve-aspect" &&
!isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2)));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs
const DocumentProjectionNode = createProjectionNode({
attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify),
measureScroll: () => ({
x: document.documentElement.scrollLeft || document.body.scrollLeft,
y: document.documentElement.scrollTop || document.body.scrollTop,
}),
checkIsScrollRoot: () => true,
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs
const rootProjectionNode = {
current: undefined,
};
const HTMLProjectionNode = createProjectionNode({
measureScroll: (instance) => ({
x: instance.scrollLeft,
y: instance.scrollTop,
}),
defaultParent: () => {
if (!rootProjectionNode.current) {
const documentNode = new DocumentProjectionNode(0, {});
documentNode.mount(window);
documentNode.setOptions({ layoutScroll: true });
rootProjectionNode.current = documentNode;
}
return rootProjectionNode.current;
},
resetTransform: (instance, value) => {
instance.style.transform = value !== undefined ? value : "none";
},
checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/drag.mjs
const drag = {
pan: {
Feature: PanGesture,
},
drag: {
Feature: DragGesture,
ProjectionNode: HTMLProjectionNode,
MeasureLayout: MeasureLayout,
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/unit-conversion.mjs
const positionalKeys = new Set([
"width",
"height",
"top",
"left",
"right",
"bottom",
"x",
"y",
]);
const isPositionalKey = (key) => positionalKeys.has(key);
const hasPositionalKey = (target) => {
return Object.keys(target).some(isPositionalKey);
};
const isNumOrPxType = (v) => v === number || v === px;
const getPosFromMatrix = (matrix, pos) => parseFloat(matrix.split(", ")[pos]);
const getTranslateFromMatrix = (pos2, pos3) => (_bbox, { transform }) => {
if (transform === "none" || !transform)
return 0;
const matrix3d = transform.match(/^matrix3d\((.+)\)$/);
if (matrix3d) {
return getPosFromMatrix(matrix3d[1], pos3);
}
else {
const matrix = transform.match(/^matrix\((.+)\)$/);
if (matrix) {
return getPosFromMatrix(matrix[1], pos2);
}
else {
return 0;
}
}
};
const transformKeys = new Set(["x", "y", "z"]);
const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));
function removeNonTranslationalTransform(visualElement) {
const removedTransforms = [];
nonTranslationalTransformKeys.forEach((key) => {
const value = visualElement.getValue(key);
if (value !== undefined) {
removedTransforms.push([key, value.get()]);
value.set(key.startsWith("scale") ? 1 : 0);
}
});
// Apply changes to element before measurement
if (removedTransforms.length)
visualElement.render();
return removedTransforms;
}
const positionalValues = {
// Dimensions
width: ({ x }, { paddingLeft = "0", paddingRight = "0" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),
height: ({ y }, { paddingTop = "0", paddingBottom = "0" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),
top: (_bbox, { top }) => parseFloat(top),
left: (_bbox, { left }) => parseFloat(left),
bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),
right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),
// Transform
x: getTranslateFromMatrix(4, 13),
y: getTranslateFromMatrix(5, 14),
};
const convertChangedValueTypes = (target, visualElement, changedKeys) => {
const originBbox = visualElement.measureViewportBox();
const element = visualElement.current;
const elementComputedStyle = getComputedStyle(element);
const { display } = elementComputedStyle;
const origin = {};
// If the element is currently set to display: "none", make it visible before
// measuring the target bounding box
if (display === "none") {
visualElement.setStaticValue("display", target.display || "block");
}
/**
* Record origins before we render and update styles
*/
changedKeys.forEach((key) => {
origin[key] = positionalValues[key](originBbox, elementComputedStyle);
});
// Apply the latest values (as set in checkAndConvertChangedValueTypes)
visualElement.render();
const targetBbox = visualElement.measureViewportBox();
changedKeys.forEach((key) => {
// Restore styles to their **calculated computed style**, not their actual
// originally set style. This allows us to animate between equivalent pixel units.
const value = visualElement.getValue(key);
value && value.jump(origin[key]);
target[key] = positionalValues[key](targetBbox, elementComputedStyle);
});
return target;
};
const checkAndConvertChangedValueTypes = (visualElement, target, origin = {}, transitionEnd = {}) => {
target = { ...target };
transitionEnd = { ...transitionEnd };
const targetPositionalKeys = Object.keys(target).filter(isPositionalKey);
// We want to remove any transform values that could affect the element's bounding box before
// it's measured. We'll reapply these later.
let removedTransformValues = [];
let hasAttemptedToRemoveTransformValues = false;
const changedValueTypeKeys = [];
targetPositionalKeys.forEach((key) => {
const value = visualElement.getValue(key);
if (!visualElement.hasValue(key))
return;
let from = origin[key];
let fromType = findDimensionValueType(from);
const to = target[key];
let toType;
// TODO: The current implementation of this basically throws an error
// if you try and do value conversion via keyframes. There's probably
// a way of doing this but the performance implications would need greater scrutiny,
// as it'd be doing multiple resize-remeasure operations.
if (isKeyframesTarget(to)) {
const numKeyframes = to.length;
const fromIndex = to[0] === null ? 1 : 0;
from = to[fromIndex];
fromType = findDimensionValueType(from);
for (let i = fromIndex; i < numKeyframes; i++) {
/**
* Don't allow wildcard keyframes to be used to detect
* a difference in value types.
*/
if (to[i] === null)
break;
if (!toType) {
toType = findDimensionValueType(to[i]);
invariant(toType === fromType ||
(isNumOrPxType(fromType) && isNumOrPxType(toType)), "Keyframes must be of the same dimension as the current value");
}
else {
invariant(findDimensionValueType(to[i]) === toType, "All keyframes must be of the same type");
}
}
}
else {
toType = findDimensionValueType(to);
}
if (fromType !== toType) {
// If they're both just number or px, convert them both to numbers rather than
// relying on resize/remeasure to convert (which is wasteful in this situation)
if (isNumOrPxType(fromType) && isNumOrPxType(toType)) {
const current = value.get();
if (typeof current === "string") {
value.set(parseFloat(current));
}
if (typeof to === "string") {
target[key] = parseFloat(to);
}
else if (Array.isArray(to) && toType === px) {
target[key] = to.map(parseFloat);
}
}
else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) &&
(toType === null || toType === void 0 ? void 0 : toType.transform) &&
(from === 0 || to === 0)) {
// If one or the other value is 0, it's safe to coerce it to the
// type of the other without measurement
if (from === 0) {
value.set(toType.transform(from));
}
else {
target[key] = fromType.transform(to);
}
}
else {
// If we're going to do value conversion via DOM measurements, we first
// need to remove non-positional transform values that could affect the bbox measurements.
if (!hasAttemptedToRemoveTransformValues) {
removedTransformValues =
removeNonTranslationalTransform(visualElement);
hasAttemptedToRemoveTransformValues = true;
}
changedValueTypeKeys.push(key);
transitionEnd[key] =
transitionEnd[key] !== undefined
? transitionEnd[key]
: target[key];
value.jump(to);
}
}
});
if (changedValueTypeKeys.length) {
const scrollY = changedValueTypeKeys.indexOf("height") >= 0
? window.pageYOffset
: null;
const convertedTarget = convertChangedValueTypes(target, visualElement, changedValueTypeKeys);
// If we removed transform values, reapply them before the next render
if (removedTransformValues.length) {
removedTransformValues.forEach(([key, value]) => {
visualElement.getValue(key).set(value);
});
}
// Reapply original values
visualElement.render();
// Restore scroll position
if (isBrowser && scrollY !== null) {
window.scrollTo({ top: scrollY });
}
return { target: convertedTarget, transitionEnd };
}
else {
return { target, transitionEnd };
}
};
/**
* Convert value types for x/y/width/height/top/left/bottom/right
*
* Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'`
*
* @internal
*/
function unitConversion(visualElement, target, origin, transitionEnd) {
return hasPositionalKey(target)
? checkAndConvertChangedValueTypes(visualElement, target, origin, transitionEnd)
: { target, transitionEnd };
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/parse-dom-variant.mjs
/**
* Parse a DOM variant to make it animatable. This involves resolving CSS variables
* and ensuring animations like "20%" => "calc(50vw)" are performed in pixels.
*/
const parseDomVariant = (visualElement, target, origin, transitionEnd) => {
const resolved = resolveCSSVariables(visualElement, target, transitionEnd);
target = resolved.target;
transitionEnd = resolved.transitionEnd;
return unitConversion(visualElement, target, origin, transitionEnd);
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/motion-values.mjs
function updateMotionValuesFromProps(element, next, prev) {
const { willChange } = next;
for (const key in next) {
const nextValue = next[key];
const prevValue = prev[key];
if (isMotionValue(nextValue)) {
/**
* If this is a motion value found in props or style, we want to add it
* to our visual element's motion value map.
*/
element.addValue(key, nextValue);
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
}
/**
* Check the version of the incoming motion value with this version
* and warn against mismatches.
*/
if (false) {}
}
else if (isMotionValue(prevValue)) {
/**
* If we're swapping from a motion value to a static value,
* create a new motion value from that
*/
element.addValue(key, motionValue(nextValue, { owner: element }));
if (isWillChangeMotionValue(willChange)) {
willChange.remove(key);
}
}
else if (prevValue !== nextValue) {
/**
* If this is a flat value that has changed, update the motion value
* or create one if it doesn't exist. We only want to do this if we're
* not handling the value with our animation state.
*/
if (element.hasValue(key)) {
const existingValue = element.getValue(key);
// TODO: Only update values that aren't being animated or even looked at
!existingValue.hasAnimated && existingValue.set(nextValue);
}
else {
const latestValue = element.getStaticValue(key);
element.addValue(key, motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element }));
}
}
}
// Handle removed values
for (const key in prev) {
if (next[key] === undefined)
element.removeValue(key);
}
return next;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/store.mjs
const visualElementStore = new WeakMap();
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/VisualElement.mjs
const featureNames = Object.keys(featureDefinitions);
const numFeatures = featureNames.length;
const propEventHandlers = [
"AnimationStart",
"AnimationComplete",
"Update",
"BeforeLayoutMeasure",
"LayoutMeasure",
"LayoutAnimationStart",
"LayoutAnimationComplete",
];
const numVariantProps = variantProps.length;
/**
* A VisualElement is an imperative abstraction around UI elements such as
* HTMLElement, SVGElement, Three.Object3D etc.
*/
class VisualElement {
constructor({ parent, props, presenceContext, reducedMotionConfig, visualState, }, options = {}) {
/**
* A reference to the current underlying Instance, e.g. a HTMLElement
* or Three.Mesh etc.
*/
this.current = null;
/**
* A set containing references to this VisualElement's children.
*/
this.children = new Set();
/**
* Determine what role this visual element should take in the variant tree.
*/
this.isVariantNode = false;
this.isControllingVariants = false;
/**
* Decides whether this VisualElement should animate in reduced motion
* mode.
*
* TODO: This is currently set on every individual VisualElement but feels
* like it could be set globally.
*/
this.shouldReduceMotion = null;
/**
* A map of all motion values attached to this visual element. Motion
* values are source of truth for any given animated value. A motion
* value might be provided externally by the component via props.
*/
this.values = new Map();
/**
* Cleanup functions for active features (hover/tap/exit etc)
*/
this.features = {};
/**
* A map of every subscription that binds the provided or generated
* motion values onChange listeners to this visual element.
*/
this.valueSubscriptions = new Map();
/**
* A reference to the previously-provided motion values as returned
* from scrapeMotionValuesFromProps. We use the keys in here to determine
* if any motion values need to be removed after props are updated.
*/
this.prevMotionValues = {};
/**
* An object containing a SubscriptionManager for each active event.
*/
this.events = {};
/**
* An object containing an unsubscribe function for each prop event subscription.
* For example, every "Update" event can have multiple subscribers via
* VisualElement.on(), but only one of those can be defined via the onUpdate prop.
*/
this.propEventSubscriptions = {};
this.notifyUpdate = () => this.notify("Update", this.latestValues);
this.render = () => {
if (!this.current)
return;
this.triggerBuild();
this.renderInstance(this.current, this.renderState, this.props.style, this.projection);
};
this.scheduleRender = () => sync.render(this.render, false, true);
const { latestValues, renderState } = visualState;
this.latestValues = latestValues;
this.baseTarget = { ...latestValues };
this.initialValues = props.initial ? { ...latestValues } : {};
this.renderState = renderState;
this.parent = parent;
this.props = props;
this.presenceContext = presenceContext;
this.depth = parent ? parent.depth + 1 : 0;
this.reducedMotionConfig = reducedMotionConfig;
this.options = options;
this.isControllingVariants = isControllingVariants(props);
this.isVariantNode = isVariantNode(props);
if (this.isVariantNode) {
this.variantChildren = new Set();
}
this.manuallyAnimateOnMount = Boolean(parent && parent.current);
/**
* Any motion values that are provided to the element when created
* aren't yet bound to the element, as this would technically be impure.
* However, we iterate through the motion values and set them to the
* initial values for this component.
*
* TODO: This is impure and we should look at changing this to run on mount.
* Doing so will break some tests but this isn't neccessarily a breaking change,
* more a reflection of the test.
*/
const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {});
for (const key in initialMotionValues) {
const value = initialMotionValues[key];
if (latestValues[key] !== undefined && isMotionValue(value)) {
value.set(latestValues[key], false);
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
}
}
}
}
/**
* This method takes React props and returns found MotionValues. For example, HTML
* MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.
*
* This isn't an abstract method as it needs calling in the constructor, but it is
* intended to be one.
*/
scrapeMotionValuesFromProps(_props, _prevProps) {
return {};
}
mount(instance) {
this.current = instance;
visualElementStore.set(instance, this);
if (this.projection) {
this.projection.mount(instance);
}
if (this.parent && this.isVariantNode && !this.isControllingVariants) {
this.removeFromVariantTree = this.parent.addVariantChild(this);
}
this.values.forEach((value, key) => this.bindToMotionValue(key, value));
if (!hasReducedMotionListener.current) {
initPrefersReducedMotion();
}
this.shouldReduceMotion =
this.reducedMotionConfig === "never"
? false
: this.reducedMotionConfig === "always"
? true
: prefersReducedMotion.current;
if (false) {}
if (this.parent)
this.parent.children.add(this);
this.update(this.props, this.presenceContext);
}
unmount() {
visualElementStore["delete"](this.current);
this.projection && this.projection.unmount();
cancelSync.update(this.notifyUpdate);
cancelSync.render(this.render);
this.valueSubscriptions.forEach((remove) => remove());
this.removeFromVariantTree && this.removeFromVariantTree();
this.parent && this.parent.children.delete(this);
for (const key in this.events) {
this.events[key].clear();
}
for (const key in this.features) {
this.features[key].unmount();
}
this.current = null;
}
bindToMotionValue(key, value) {
const valueIsTransform = transformProps.has(key);
const removeOnChange = value.on("change", (latestValue) => {
this.latestValues[key] = latestValue;
this.props.onUpdate &&
sync.update(this.notifyUpdate, false, true);
if (valueIsTransform && this.projection) {
this.projection.isTransformDirty = true;
}
});
const removeOnRenderRequest = value.on("renderRequest", this.scheduleRender);
this.valueSubscriptions.set(key, () => {
removeOnChange();
removeOnRenderRequest();
});
}
sortNodePosition(other) {
/**
* If these nodes aren't even of the same type we can't compare their depth.
*/
if (!this.current ||
!this.sortInstanceNodePosition ||
this.type !== other.type) {
return 0;
}
return this.sortInstanceNodePosition(this.current, other.current);
}
loadFeatures({ children, ...renderedProps }, isStrict, preloadedFeatures, projectionId, initialLayoutGroupConfig) {
let ProjectionNodeConstructor;
let MeasureLayout;
/**
* If we're in development mode, check to make sure we're not rendering a motion component
* as a child of LazyMotion, as this will break the file-size benefits of using it.
*/
if (false) {}
for (let i = 0; i < numFeatures; i++) {
const name = featureNames[i];
const { isEnabled, Feature: FeatureConstructor, ProjectionNode, MeasureLayout: MeasureLayoutComponent, } = featureDefinitions[name];
if (ProjectionNode)
ProjectionNodeConstructor = ProjectionNode;
if (isEnabled(renderedProps)) {
if (!this.features[name] && FeatureConstructor) {
this.features[name] = new FeatureConstructor(this);
}
if (MeasureLayoutComponent) {
MeasureLayout = MeasureLayoutComponent;
}
}
}
if (!this.projection && ProjectionNodeConstructor) {
this.projection = new ProjectionNodeConstructor(projectionId, this.latestValues, this.parent && this.parent.projection);
const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, } = renderedProps;
this.projection.setOptions({
layoutId,
layout,
alwaysMeasureLayout: Boolean(drag) ||
(dragConstraints && is_ref_object_isRefObject(dragConstraints)),
visualElement: this,
scheduleRender: () => this.scheduleRender(),
/**
* TODO: Update options in an effect. This could be tricky as it'll be too late
* to update by the time layout animations run.
* We also need to fix this safeToRemove by linking it up to the one returned by usePresence,
* ensuring it gets called if there's no potential layout animations.
*
*/
animationType: typeof layout === "string" ? layout : "both",
initialPromotionConfig: initialLayoutGroupConfig,
layoutScroll,
layoutRoot,
});
}
return MeasureLayout;
}
updateFeatures() {
for (const key in this.features) {
const feature = this.features[key];
if (feature.isMounted) {
feature.update(this.props, this.prevProps);
}
else {
feature.mount();
feature.isMounted = true;
}
}
}
triggerBuild() {
this.build(this.renderState, this.latestValues, this.options, this.props);
}
/**
* Measure the current viewport box with or without transforms.
* Only measures axis-aligned boxes, rotate and skew must be manually
* removed with a re-render to work.
*/
measureViewportBox() {
return this.current
? this.measureInstanceViewportBox(this.current, this.props)
: createBox();
}
getStaticValue(key) {
return this.latestValues[key];
}
setStaticValue(key, value) {
this.latestValues[key] = value;
}
/**
* Make a target animatable by Popmotion. For instance, if we're
* trying to animate width from 100px to 100vw we need to measure 100vw
* in pixels to determine what we really need to animate to. This is also
* pluggable to support Framer's custom value types like Color,
* and CSS variables.
*/
makeTargetAnimatable(target, canMutate = true) {
return this.makeTargetAnimatableFromInstance(target, this.props, canMutate);
}
/**
* Update the provided props. Ensure any newly-added motion values are
* added to our map, old ones removed, and listeners updated.
*/
update(props, presenceContext) {
if (props.transformTemplate || this.props.transformTemplate) {
this.scheduleRender();
}
this.prevProps = this.props;
this.props = props;
this.prevPresenceContext = this.presenceContext;
this.presenceContext = presenceContext;
/**
* Update prop event handlers ie onAnimationStart, onAnimationComplete
*/
for (let i = 0; i < propEventHandlers.length; i++) {
const key = propEventHandlers[i];
if (this.propEventSubscriptions[key]) {
this.propEventSubscriptions[key]();
delete this.propEventSubscriptions[key];
}
const listener = props["on" + key];
if (listener) {
this.propEventSubscriptions[key] = this.on(key, listener);
}
}
this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps), this.prevMotionValues);
if (this.handleChildMotionValue) {
this.handleChildMotionValue();
}
}
getProps() {
return this.props;
}
/**
* Returns the variant definition with a given name.
*/
getVariant(name) {
return this.props.variants ? this.props.variants[name] : undefined;
}
/**
* Returns the defined default transition on this component.
*/
getDefaultTransition() {
return this.props.transition;
}
getTransformPagePoint() {
return this.props.transformPagePoint;
}
getClosestVariantNode() {
return this.isVariantNode
? this
: this.parent
? this.parent.getClosestVariantNode()
: undefined;
}
getVariantContext(startAtParent = false) {
if (startAtParent) {
return this.parent ? this.parent.getVariantContext() : undefined;
}
if (!this.isControllingVariants) {
const context = this.parent
? this.parent.getVariantContext() || {}
: {};
if (this.props.initial !== undefined) {
context.initial = this.props.initial;
}
return context;
}
const context = {};
for (let i = 0; i < numVariantProps; i++) {
const name = variantProps[i];
const prop = this.props[name];
if (isVariantLabel(prop) || prop === false) {
context[name] = prop;
}
}
return context;
}
/**
* Add a child visual element to our set of children.
*/
addVariantChild(child) {
const closestVariantNode = this.getClosestVariantNode();
if (closestVariantNode) {
closestVariantNode.variantChildren &&
closestVariantNode.variantChildren.add(child);
return () => closestVariantNode.variantChildren.delete(child);
}
}
/**
* Add a motion value and bind it to this visual element.
*/
addValue(key, value) {
// Remove existing value if it exists
if (value !== this.values.get(key)) {
this.removeValue(key);
this.bindToMotionValue(key, value);
}
this.values.set(key, value);
this.latestValues[key] = value.get();
}
/**
* Remove a motion value and unbind any active subscriptions.
*/
removeValue(key) {
this.values.delete(key);
const unsubscribe = this.valueSubscriptions.get(key);
if (unsubscribe) {
unsubscribe();
this.valueSubscriptions.delete(key);
}
delete this.latestValues[key];
this.removeValueFromRenderState(key, this.renderState);
}
/**
* Check whether we have a motion value for this key
*/
hasValue(key) {
return this.values.has(key);
}
getValue(key, defaultValue) {
if (this.props.values && this.props.values[key]) {
return this.props.values[key];
}
let value = this.values.get(key);
if (value === undefined && defaultValue !== undefined) {
value = motionValue(defaultValue, { owner: this });
this.addValue(key, value);
}
return value;
}
/**
* If we're trying to animate to a previously unencountered value,
* we need to check for it in our state and as a last resort read it
* directly from the instance (which might have performance implications).
*/
readValue(key) {
return this.latestValues[key] !== undefined || !this.current
? this.latestValues[key]
: this.readValueFromInstance(this.current, key, this.options);
}
/**
* Set the base target to later animate back to. This is currently
* only hydrated on creation and when we first read a value.
*/
setBaseTarget(key, value) {
this.baseTarget[key] = value;
}
/**
* Find the base target for a value thats been removed from all animation
* props.
*/
getBaseTarget(key) {
var _a;
const { initial } = this.props;
const valueFromInitial = typeof initial === "string" || typeof initial === "object"
? (_a = resolveVariantFromProps(this.props, initial)) === null || _a === void 0 ? void 0 : _a[key]
: undefined;
/**
* If this value still exists in the current initial variant, read that.
*/
if (initial && valueFromInitial !== undefined) {
return valueFromInitial;
}
/**
* Alternatively, if this VisualElement config has defined a getBaseTarget
* so we can read the value from an alternative source, try that.
*/
const target = this.getBaseTargetFromProps(this.props, key);
if (target !== undefined && !isMotionValue(target))
return target;
/**
* If the value was initially defined on initial, but it doesn't any more,
* return undefined. Otherwise return the value as initially read from the DOM.
*/
return this.initialValues[key] !== undefined &&
valueFromInitial === undefined
? undefined
: this.baseTarget[key];
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = new SubscriptionManager();
}
return this.events[eventName].add(callback);
}
notify(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].notify(...args);
}
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs
class DOMVisualElement extends VisualElement {
sortInstanceNodePosition(a, b) {
/**
* compareDocumentPosition returns a bitmask, by using the bitwise &
* we're returning true if 2 in that bitmask is set to true. 2 is set
* to true if b preceeds a.
*/
return a.compareDocumentPosition(b) & 2 ? 1 : -1;
}
getBaseTargetFromProps(props, key) {
return props.style ? props.style[key] : undefined;
}
removeValueFromRenderState(key, { vars, style }) {
delete vars[key];
delete style[key];
}
makeTargetAnimatableFromInstance({ transition, transitionEnd, ...target }, { transformValues }, isMounted) {
let origin = getOrigin(target, transition || {}, this);
/**
* If Framer has provided a function to convert `Color` etc value types, convert them
*/
if (transformValues) {
if (transitionEnd)
transitionEnd = transformValues(transitionEnd);
if (target)
target = transformValues(target);
if (origin)
origin = transformValues(origin);
}
if (isMounted) {
checkTargetForNewValues(this, target, origin);
const parsed = parseDomVariant(this, target, origin, transitionEnd);
transitionEnd = parsed.transitionEnd;
target = parsed.target;
}
return {
transition,
transitionEnd,
...target,
};
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs
function HTMLVisualElement_getComputedStyle(element) {
return window.getComputedStyle(element);
}
class HTMLVisualElement extends DOMVisualElement {
readValueFromInstance(instance, key) {
if (transformProps.has(key)) {
const defaultType = getDefaultValueType(key);
return defaultType ? defaultType.default || 0 : 0;
}
else {
const computedStyle = HTMLVisualElement_getComputedStyle(instance);
const value = (isCSSVariableName(key)
? computedStyle.getPropertyValue(key)
: computedStyle[key]) || 0;
return typeof value === "string" ? value.trim() : value;
}
}
measureInstanceViewportBox(instance, { transformPagePoint }) {
return measureViewportBox(instance, transformPagePoint);
}
build(renderState, latestValues, options, props) {
buildHTMLStyles(renderState, latestValues, options, props.transformTemplate);
}
scrapeMotionValuesFromProps(props, prevProps) {
return scrapeMotionValuesFromProps(props, prevProps);
}
handleChildMotionValue() {
if (this.childSubscription) {
this.childSubscription();
delete this.childSubscription;
}
const { children } = this.props;
if (isMotionValue(children)) {
this.childSubscription = children.on("change", (latest) => {
if (this.current)
this.current.textContent = `${latest}`;
});
}
}
renderInstance(instance, renderState, styleProp, projection) {
renderHTML(instance, renderState, styleProp, projection);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs
class SVGVisualElement extends DOMVisualElement {
constructor() {
super(...arguments);
this.isSVGTag = false;
}
getBaseTargetFromProps(props, key) {
return props[key];
}
readValueFromInstance(instance, key) {
if (transformProps.has(key)) {
const defaultType = getDefaultValueType(key);
return defaultType ? defaultType.default || 0 : 0;
}
key = !camelCaseAttributes.has(key) ? camelToDash(key) : key;
return instance.getAttribute(key);
}
measureInstanceViewportBox() {
return createBox();
}
scrapeMotionValuesFromProps(props, prevProps) {
return scrape_motion_values_scrapeMotionValuesFromProps(props, prevProps);
}
build(renderState, latestValues, options, props) {
buildSVGAttrs(renderState, latestValues, options, this.isSVGTag, props.transformTemplate);
}
renderInstance(instance, renderState, styleProp, projection) {
renderSVG(instance, renderState, styleProp, projection);
}
mount(instance) {
this.isSVGTag = isSVGTag(instance.tagName);
super.mount(instance);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs
const create_visual_element_createDomVisualElement = (Component, options) => {
return isSVGComponent(Component)
? new SVGVisualElement(options, { enableHardwareAcceleration: false })
: new HTMLVisualElement(options, { enableHardwareAcceleration: true });
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/layout.mjs
const layout = {
layout: {
ProjectionNode: HTMLProjectionNode,
MeasureLayout: MeasureLayout,
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/motion.mjs
const preloadedFeatures = {
...animations,
...gestureAnimations,
...drag,
...layout,
};
/**
* HTML & SVG components, optimised for use with gestures and animation. These can be used as
* drop-in replacements for any HTML & SVG component, all CSS & SVG properties are supported.
*
* @public
*/
const motion = /*@__PURE__*/ createMotionProxy((Component, config) => create_config_createDomMotionConfig(Component, config, preloadedFeatures, create_visual_element_createDomVisualElement));
/**
* Create a DOM `motion` component with the provided string. This is primarily intended
* as a full alternative to `motion` for consumers who have to support environments that don't
* support `Proxy`.
*
* ```javascript
* import { createDomMotionComponent } from "framer-motion"
*
* const motion = {
* div: createDomMotionComponent('div')
* }
* ```
*
* @public
*/
function createDomMotionComponent(key) {
return createMotionComponent(createDomMotionConfig(key, { forwardMotionProps: false }, preloadedFeatures, createDomVisualElement));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
const close_close = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
}));
/* harmony default export */ var library_close = (close_close);
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: external ["wp","dom"]
var external_wp_dom_namespaceObject = window["wp"]["dom"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dashicon/index.js
/**
* @typedef OwnProps
*
* @property {import('./types').IconKey} icon Icon name
* @property {string} [className] Class name
* @property {number} [size] Size of the icon
*/
/**
* Internal dependencies
*/
function Dashicon({
icon,
className,
size = 20,
style = {},
...extraProps
}) {
const iconClass = ['dashicon', 'dashicons', 'dashicons-' + icon, className].filter(Boolean).join(' '); // For retro-compatibility reasons (for example if people are overriding icon size with CSS), we add inline styles just if the size is different to the default
const sizeStyles = // using `!=` to catch both 20 and "20"
// eslint-disable-next-line eqeqeq
20 != size ? {
fontSize: `${size}px`,
width: `${size}px`,
height: `${size}px`
} : {};
const styles = { ...sizeStyles,
...style
};
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: iconClass,
style: styles,
...extraProps
});
}
/* harmony default export */ var dashicon = (Dashicon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/icon/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Icon({
icon = null,
size = 'string' === typeof icon ? 20 : 24,
...additionalProps
}) {
if ('string' === typeof icon) {
return (0,external_wp_element_namespaceObject.createElement)(dashicon, {
icon: icon,
size: size,
...additionalProps
});
}
if ((0,external_wp_element_namespaceObject.isValidElement)(icon) && dashicon === icon.type) {
return (0,external_wp_element_namespaceObject.cloneElement)(icon, { ...additionalProps
});
}
if ('function' === typeof icon) {
return (0,external_wp_element_namespaceObject.createElement)(icon, {
size,
...additionalProps
});
}
if (icon && (icon.type === 'svg' || icon.type === external_wp_primitives_namespaceObject.SVG)) {
const appliedProps = { ...icon.props,
width: size,
height: size,
...additionalProps
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, { ...appliedProps
});
}
if ((0,external_wp_element_namespaceObject.isValidElement)(icon)) {
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
// @ts-ignore Just forwarding the size prop along
size,
...additionalProps
});
}
return icon;
}
/* harmony default export */ var build_module_icon = (Icon);
;// CONCATENATED MODULE: external ["wp","warning"]
var external_wp_warning_namespaceObject = window["wp"]["warning"];
// EXTERNAL MODULE: ./node_modules/deepmerge/dist/cjs.js
var cjs = __webpack_require__(1919);
var cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);
// EXTERNAL MODULE: ./node_modules/fast-deep-equal/es6/index.js
var es6 = __webpack_require__(5619);
var es6_default = /*#__PURE__*/__webpack_require__.n(es6);
;// CONCATENATED MODULE: ./node_modules/is-plain-object/dist/is-plain-object.mjs
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function is_plain_object_isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function is_plain_object_isPlainObject(o) {
var ctor,prot;
if (is_plain_object_isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (is_plain_object_isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-update-effect.js
/**
* WordPress dependencies
*/
/**
* A `React.useEffect` that will not run on the first render.
* Source:
* https://github.com/reakit/reakit/blob/HEAD/packages/reakit-utils/src/useUpdateEffect.ts
*
* @param {import('react').EffectCallback} effect
* @param {import('react').DependencyList} deps
*/
function useUpdateEffect(effect, deps) {
const mounted = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (mounted.current) {
return effect();
}
mounted.current = true;
return undefined; // Disable reasons:
// 1. This hook needs to pass a dep list that isn't an array literal
// 2. `effect` is missing from the array, and will need to be added carefully to avoid additional warnings
// see https://github.com/WordPress/gutenberg/pull/41166
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
/* harmony default export */ var use_update_effect = (useUpdateEffect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/context-system-provider.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ComponentsContext = (0,external_wp_element_namespaceObject.createContext)(
/** @type {Record<string, any>} */
{});
const useComponentsContext = () => (0,external_wp_element_namespaceObject.useContext)(ComponentsContext);
/**
* Consolidates incoming ContextSystem values with a (potential) parent ContextSystem value.
*
* Note: This function will warn if it detects an un-memoized `value`
*
* @param {Object} props
* @param {Record<string, any>} props.value
* @return {Record<string, any>} The consolidated value.
*/
function useContextSystemBridge({
value
}) {
const parentContext = useComponentsContext();
const valueRef = (0,external_wp_element_namespaceObject.useRef)(value);
use_update_effect(() => {
if ( // Objects are equivalent.
es6_default()(valueRef.current, value) && // But not the same reference.
valueRef.current !== value) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
}
}, [value]); // `parentContext` will always be memoized (i.e., the result of this hook itself)
// or the default value from when the `ComponentsContext` was originally
// initialized (which will never change, it's a static variable)
// so this memoization will prevent `deepmerge()` from rerunning unless
// the references to `value` change OR the `parentContext` has an actual material change
// (because again, it's guaranteed to be memoized or a static reference to the empty object
// so we know that the only changes for `parentContext` are material ones... i.e., why we
// don't have to warn in the `useUpdateEffect` hook above for `parentContext` and we only
// need to bother with the `value`). The `useUpdateEffect` above will ensure that we are
// correctly warning when the `value` isn't being properly memoized. All of that to say
// that this should be super safe to assume that `useMemo` will only run on actual
// changes to the two dependencies, therefore saving us calls to `deepmerge()`!
const config = (0,external_wp_element_namespaceObject.useMemo)(() => {
// Deep clone `parentContext` to avoid mutating it later.
return cjs_default()(parentContext !== null && parentContext !== void 0 ? parentContext : {}, value !== null && value !== void 0 ? value : {}, {
isMergeableObject: is_plain_object_isPlainObject
});
}, [parentContext, value]);
return config;
}
/**
* A Provider component that can modify props for connected components within
* the Context system.
*
* @example
* ```jsx
* <ContextSystemProvider value={{ Button: { size: 'small' }}}>
* <Button>...</Button>
* </ContextSystemProvider>
* ```
*
* @template {Record<string, any>} T
* @param {Object} options
* @param {import('react').ReactNode} options.children Children to render.
* @param {T} options.value Props to render into connected components.
* @return {JSX.Element} A Provider wrapped component.
*/
const BaseContextSystemProvider = ({
children,
value
}) => {
const contextValue = useContextSystemBridge({
value
});
return (0,external_wp_element_namespaceObject.createElement)(ComponentsContext.Provider, {
value: contextValue
}, children);
};
const ContextSystemProvider = (0,external_wp_element_namespaceObject.memo)(BaseContextSystemProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/constants.js
const REACT_TYPEOF_KEY = '$$typeof';
const COMPONENT_NAMESPACE = 'data-wp-component';
const CONNECTED_NAMESPACE = 'data-wp-c16t';
const CONTEXT_COMPONENT_NAMESPACE = 'data-wp-c5tc8t';
/**
* Special key where the connected namespaces are stored.
* This is attached to Context connected components as a static property.
*/
const CONNECT_STATIC_NAMESPACE = '__contextSystemKey__';
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/utils.js
/**
* Internal dependencies
*/
/**
* Creates a dedicated context namespace HTML attribute for components.
* ns is short for "namespace"
*
* @example
* ```jsx
* <div {...ns('Container')} />
* ```
*
* @param {string} componentName The name for the component.
* @return {Record<string, any>} A props object with the namespaced HTML attribute.
*/
function getNamespace(componentName) {
return {
[COMPONENT_NAMESPACE]: componentName
};
}
/**
* Creates a dedicated connected context namespace HTML attribute for components.
* ns is short for "namespace"
*
* @example
* ```jsx
* <div {...cns()} />
* ```
*
* @return {Record<string, any>} A props object with the namespaced HTML attribute.
*/
function getConnectedNamespace() {
return {
[CONNECTED_NAMESPACE]: true
};
}
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.mjs
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
function __runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
function __propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
};
function __setFunctionName(f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function __classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function __disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
catch (e) {
fail(e);
}
}
if (env.hasError) throw env.error;
}
return next();
}
/* harmony default export */ var tslib_es6 = ({
__extends,
__assign,
__rest,
__decorate,
__param,
__metadata,
__awaiter,
__generator,
__createBinding,
__exportStar,
__values,
__read,
__spread,
__spreadArrays,
__spreadArray,
__await,
__asyncGenerator,
__asyncDelegator,
__asyncValues,
__makeTemplateObject,
__importStar,
__importDefault,
__classPrivateFieldGet,
__classPrivateFieldSet,
__classPrivateFieldIn,
__addDisposableResource,
__disposeResources,
});
;// CONCATENATED MODULE: ./node_modules/lower-case/dist.es2015/index.js
/**
* Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
*/
var SUPPORTED_LOCALE = {
tr: {
regexp: /\u0130|\u0049|\u0049\u0307/g,
map: {
İ: "\u0069",
I: "\u0131",
İ: "\u0069",
},
},
az: {
regexp: /\u0130/g,
map: {
İ: "\u0069",
I: "\u0131",
İ: "\u0069",
},
},
lt: {
regexp: /\u0049|\u004A|\u012E|\u00CC|\u00CD|\u0128/g,
map: {
I: "\u0069\u0307",
J: "\u006A\u0307",
Į: "\u012F\u0307",
Ì: "\u0069\u0307\u0300",
Í: "\u0069\u0307\u0301",
Ĩ: "\u0069\u0307\u0303",
},
},
};
/**
* Localized lower case.
*/
function localeLowerCase(str, locale) {
var lang = SUPPORTED_LOCALE[locale.toLowerCase()];
if (lang)
return lowerCase(str.replace(lang.regexp, function (m) { return lang.map[m]; }));
return lowerCase(str);
}
/**
* Lower case as a function.
*/
function lowerCase(str) {
return str.toLowerCase();
}
;// CONCATENATED MODULE: ./node_modules/no-case/dist.es2015/index.js
// Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case").
var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
// Remove all non-word characters.
var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
/**
* Normalize the string into something other libraries can manipulate easier.
*/
function noCase(input, options) {
if (options === void 0) { options = {}; }
var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
var result = dist_es2015_replace(dist_es2015_replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
var start = 0;
var end = result.length;
// Trim the delimiter from around the output string.
while (result.charAt(start) === "\0")
start++;
while (result.charAt(end - 1) === "\0")
end--;
// Transform each token independently.
return result.slice(start, end).split("\0").map(transform).join(delimiter);
}
/**
* Replace `re` in the input string with the replacement value.
*/
function dist_es2015_replace(input, re, value) {
if (re instanceof RegExp)
return input.replace(re, value);
return re.reduce(function (input, re) { return input.replace(re, value); }, input);
}
;// CONCATENATED MODULE: ./node_modules/dot-case/dist.es2015/index.js
function dotCase(input, options) {
if (options === void 0) { options = {}; }
return noCase(input, __assign({ delimiter: "." }, options));
}
;// CONCATENATED MODULE: ./node_modules/param-case/dist.es2015/index.js
function paramCase(input, options) {
if (options === void 0) { options = {}; }
return dotCase(input, __assign({ delimiter: "-" }, options));
}
;// CONCATENATED MODULE: ./node_modules/memize/dist/index.js
/**
* Memize options object.
*
* @typedef MemizeOptions
*
* @property {number} [maxSize] Maximum size of the cache.
*/
/**
* Internal cache entry.
*
* @typedef MemizeCacheNode
*
* @property {?MemizeCacheNode|undefined} [prev] Previous node.
* @property {?MemizeCacheNode|undefined} [next] Next node.
* @property {Array<*>} args Function arguments for cache
* entry.
* @property {*} val Function result.
*/
/**
* Properties of the enhanced function for controlling cache.
*
* @typedef MemizeMemoizedFunction
*
* @property {()=>void} clear Clear the cache.
*/
/**
* Accepts a function to be memoized, and returns a new memoized function, with
* optional options.
*
* @template {(...args: any[]) => any} F
*
* @param {F} fn Function to memoize.
* @param {MemizeOptions} [options] Options object.
*
* @return {((...args: Parameters<F>) => ReturnType<F>) & MemizeMemoizedFunction} Memoized function.
*/
function memize(fn, options) {
var size = 0;
/** @type {?MemizeCacheNode|undefined} */
var head;
/** @type {?MemizeCacheNode|undefined} */
var tail;
options = options || {};
function memoized(/* ...args */) {
var node = head,
len = arguments.length,
args,
i;
searchCache: while (node) {
// Perform a shallow equality test to confirm that whether the node
// under test is a candidate for the arguments passed. Two arrays
// are shallowly equal if their length matches and each entry is
// strictly equal between the two sets. Avoid abstracting to a
// function which could incur an arguments leaking deoptimization.
// Check whether node arguments match arguments length
if (node.args.length !== arguments.length) {
node = node.next;
continue;
}
// Check whether node arguments match arguments values
for (i = 0; i < len; i++) {
if (node.args[i] !== arguments[i]) {
node = node.next;
continue searchCache;
}
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== head) {
// As tail, shift to previous. Must only shift if not also
// head, since if both head and tail, there is no previous.
if (node === tail) {
tail = node.prev;
}
// Adjust siblings to point to each other. If node was tail,
// this also handles new tail's empty `next` assignment.
/** @type {MemizeCacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
/** @type {MemizeCacheNode} */ (head).prev = node;
head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
// Create a copy of arguments (avoid leaking deoptimization)
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
node = {
args: args,
// Generate the result from original function
val: fn.apply(null, args),
};
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (head) {
head.prev = node;
node.next = head;
} else {
// If no head, follows that there's no tail (at initial or reset)
tail = node;
}
// Trim tail if we're reached max size and are pending cache insertion
if (size === /** @type {MemizeOptions} */ (options).maxSize) {
tail = /** @type {MemizeCacheNode} */ (tail).prev;
/** @type {MemizeCacheNode} */ (tail).next = null;
} else {
size++;
}
head = node;
return node.val;
}
memoized.clear = function () {
head = null;
tail = null;
size = 0;
};
// Ignore reason: There's not a clear solution to create an intersection of
// the function with additional properties, where the goal is to retain the
// function signature of the incoming argument and add control properties
// on the return value.
// @ts-ignore
return memoized;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/get-styled-class-name-from-key.js
/**
* External dependencies
*/
/**
* Generates the connected component CSS className based on the namespace.
*
* @param namespace The name of the connected component.
* @return The generated CSS className.
*/
function getStyledClassName(namespace) {
const kebab = paramCase(namespace);
return `components-${kebab}`;
}
const getStyledClassNameFromKey = memize(getStyledClassName);
;// CONCATENATED MODULE: ./node_modules/@emotion/sheet/dist/emotion-sheet.browser.esm.js
/*
Based off glamor's StyleSheet, thanks Sunil ❤️
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
// usage
import { StyleSheet } from '@emotion/sheet'
let styleSheet = new StyleSheet({ key: '', container: document.head })
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/
// $FlowFixMe
function sheetForTag(tag) {
if (tag.sheet) {
// $FlowFixMe
return tag.sheet;
} // this weirdness brought to you by firefox
/* istanbul ignore next */
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
// $FlowFixMe
return document.styleSheets[i];
}
}
}
function createStyleElement(options) {
var tag = document.createElement('style');
tag.setAttribute('data-emotion', options.key);
if (options.nonce !== undefined) {
tag.setAttribute('nonce', options.nonce);
}
tag.appendChild(document.createTextNode(''));
tag.setAttribute('data-s', '');
return tag;
}
var StyleSheet = /*#__PURE__*/function () {
// Using Node instead of HTMLElement since container may be a ShadowRoot
function StyleSheet(options) {
var _this = this;
this._insertTag = function (tag) {
var before;
if (_this.tags.length === 0) {
if (_this.insertionPoint) {
before = _this.insertionPoint.nextSibling;
} else if (_this.prepend) {
before = _this.container.firstChild;
} else {
before = _this.before;
}
} else {
before = _this.tags[_this.tags.length - 1].nextSibling;
}
_this.container.insertBefore(tag, before);
_this.tags.push(tag);
};
this.isSpeedy = options.speedy === undefined ? "production" === 'production' : options.speedy;
this.tags = [];
this.ctr = 0;
this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets
this.key = options.key;
this.container = options.container;
this.prepend = options.prepend;
this.insertionPoint = options.insertionPoint;
this.before = null;
}
var _proto = StyleSheet.prototype;
_proto.hydrate = function hydrate(nodes) {
nodes.forEach(this._insertTag);
};
_proto.insert = function insert(rule) {
// the max length is how many rules we have per style tag, it's 65000 in speedy mode
// it's 1 in dev because we insert source maps that map a single rule to a location
// and you can only have one source map per style tag
if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
this._insertTag(createStyleElement(this));
}
var tag = this.tags[this.tags.length - 1];
if (false) { var isImportRule; }
if (this.isSpeedy) {
var sheet = sheetForTag(tag);
try {
// this is the ultrafast version, works across browsers
// the big drawback is that the css won't be editable in devtools
sheet.insertRule(rule, sheet.cssRules.length);
} catch (e) {
if (false) {}
}
} else {
tag.appendChild(document.createTextNode(rule));
}
this.ctr++;
};
_proto.flush = function flush() {
// $FlowFixMe
this.tags.forEach(function (tag) {
return tag.parentNode && tag.parentNode.removeChild(tag);
});
this.tags = [];
this.ctr = 0;
if (false) {}
};
return StyleSheet;
}();
;// CONCATENATED MODULE: ./node_modules/stylis/src/Utility.js
/**
* @param {number}
* @return {number}
*/
var abs = Math.abs
/**
* @param {number}
* @return {string}
*/
var Utility_from = String.fromCharCode
/**
* @param {object}
* @return {object}
*/
var Utility_assign = Object.assign
/**
* @param {string} value
* @param {number} length
* @return {number}
*/
function hash (value, length) {
return Utility_charat(value, 0) ^ 45 ? (((((((length << 2) ^ Utility_charat(value, 0)) << 2) ^ Utility_charat(value, 1)) << 2) ^ Utility_charat(value, 2)) << 2) ^ Utility_charat(value, 3) : 0
}
/**
* @param {string} value
* @return {string}
*/
function trim (value) {
return value.trim()
}
/**
* @param {string} value
* @param {RegExp} pattern
* @return {string?}
*/
function Utility_match (value, pattern) {
return (value = pattern.exec(value)) ? value[0] : value
}
/**
* @param {string} value
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @return {string}
*/
function Utility_replace (value, pattern, replacement) {
return value.replace(pattern, replacement)
}
/**
* @param {string} value
* @param {string} search
* @return {number}
*/
function indexof (value, search) {
return value.indexOf(search)
}
/**
* @param {string} value
* @param {number} index
* @return {number}
*/
function Utility_charat (value, index) {
return value.charCodeAt(index) | 0
}
/**
* @param {string} value
* @param {number} begin
* @param {number} end
* @return {string}
*/
function Utility_substr (value, begin, end) {
return value.slice(begin, end)
}
/**
* @param {string} value
* @return {number}
*/
function Utility_strlen (value) {
return value.length
}
/**
* @param {any[]} value
* @return {number}
*/
function Utility_sizeof (value) {
return value.length
}
/**
* @param {any} value
* @param {any[]} array
* @return {any}
*/
function Utility_append (value, array) {
return array.push(value), value
}
/**
* @param {string[]} array
* @param {function} callback
* @return {string}
*/
function Utility_combine (array, callback) {
return array.map(callback).join('')
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Tokenizer.js
var line = 1
var column = 1
var Tokenizer_length = 0
var position = 0
var character = 0
var characters = ''
/**
* @param {string} value
* @param {object | null} root
* @param {object | null} parent
* @param {string} type
* @param {string[] | string} props
* @param {object[] | string} children
* @param {number} length
*/
function node (value, root, parent, type, props, children, length) {
return {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''}
}
/**
* @param {object} root
* @param {object} props
* @return {object}
*/
function Tokenizer_copy (root, props) {
return Utility_assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)
}
/**
* @return {number}
*/
function Tokenizer_char () {
return character
}
/**
* @return {number}
*/
function prev () {
character = position > 0 ? Utility_charat(characters, --position) : 0
if (column--, character === 10)
column = 1, line--
return character
}
/**
* @return {number}
*/
function next () {
character = position < Tokenizer_length ? Utility_charat(characters, position++) : 0
if (column++, character === 10)
column = 1, line++
return character
}
/**
* @return {number}
*/
function peek () {
return Utility_charat(characters, position)
}
/**
* @return {number}
*/
function caret () {
return position
}
/**
* @param {number} begin
* @param {number} end
* @return {string}
*/
function slice (begin, end) {
return Utility_substr(characters, begin, end)
}
/**
* @param {number} type
* @return {number}
*/
function token (type) {
switch (type) {
// \0 \t \n \r \s whitespace token
case 0: case 9: case 10: case 13: case 32:
return 5
// ! + , / > @ ~ isolate token
case 33: case 43: case 44: case 47: case 62: case 64: case 126:
// ; { } breakpoint token
case 59: case 123: case 125:
return 4
// : accompanied token
case 58:
return 3
// " ' ( [ opening delimit token
case 34: case 39: case 40: case 91:
return 2
// ) ] closing delimit token
case 41: case 93:
return 1
}
return 0
}
/**
* @param {string} value
* @return {any[]}
*/
function alloc (value) {
return line = column = 1, Tokenizer_length = Utility_strlen(characters = value), position = 0, []
}
/**
* @param {any} value
* @return {any}
*/
function dealloc (value) {
return characters = '', value
}
/**
* @param {number} type
* @return {string}
*/
function delimit (type) {
return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))
}
/**
* @param {string} value
* @return {string[]}
*/
function Tokenizer_tokenize (value) {
return dealloc(tokenizer(alloc(value)))
}
/**
* @param {number} type
* @return {string}
*/
function whitespace (type) {
while (character = peek())
if (character < 33)
next()
else
break
return token(type) > 2 || token(character) > 3 ? '' : ' '
}
/**
* @param {string[]} children
* @return {string[]}
*/
function tokenizer (children) {
while (next())
switch (token(character)) {
case 0: append(identifier(position - 1), children)
break
case 2: append(delimit(character), children)
break
default: append(from(character), children)
}
return children
}
/**
* @param {number} index
* @param {number} count
* @return {string}
*/
function escaping (index, count) {
while (--count && next())
// not 0-9 A-F a-f
if (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))
break
return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))
}
/**
* @param {number} type
* @return {number}
*/
function delimiter (type) {
while (next())
switch (character) {
// ] ) " '
case type:
return position
// " '
case 34: case 39:
if (type !== 34 && type !== 39)
delimiter(character)
break
// (
case 40:
if (type === 41)
delimiter(type)
break
// \
case 92:
next()
break
}
return position
}
/**
* @param {number} type
* @param {number} index
* @return {number}
*/
function commenter (type, index) {
while (next())
// //
if (type + character === 47 + 10)
break
// /*
else if (type + character === 42 + 42 && peek() === 47)
break
return '/*' + slice(index, position - 1) + '*' + Utility_from(type === 47 ? type : next())
}
/**
* @param {number} index
* @return {string}
*/
function identifier (index) {
while (!token(peek()))
next()
return slice(index, position)
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Enum.js
var Enum_MS = '-ms-'
var Enum_MOZ = '-moz-'
var Enum_WEBKIT = '-webkit-'
var COMMENT = 'comm'
var Enum_RULESET = 'rule'
var Enum_DECLARATION = 'decl'
var PAGE = '@page'
var MEDIA = '@media'
var IMPORT = '@import'
var CHARSET = '@charset'
var VIEWPORT = '@viewport'
var SUPPORTS = '@supports'
var DOCUMENT = '@document'
var NAMESPACE = '@namespace'
var Enum_KEYFRAMES = '@keyframes'
var FONT_FACE = '@font-face'
var COUNTER_STYLE = '@counter-style'
var FONT_FEATURE_VALUES = '@font-feature-values'
var LAYER = '@layer'
;// CONCATENATED MODULE: ./node_modules/stylis/src/Serializer.js
/**
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function Serializer_serialize (children, callback) {
var output = ''
var length = Utility_sizeof(children)
for (var i = 0; i < length; i++)
output += callback(children[i], i, children, callback) || ''
return output
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function stringify (element, index, children, callback) {
switch (element.type) {
case LAYER: if (element.children.length) break
case IMPORT: case Enum_DECLARATION: return element.return = element.return || element.value
case COMMENT: return ''
case Enum_KEYFRAMES: return element.return = element.value + '{' + Serializer_serialize(element.children, callback) + '}'
case Enum_RULESET: element.value = element.props.join(',')
}
return Utility_strlen(children = Serializer_serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Middleware.js
/**
* @param {function[]} collection
* @return {function}
*/
function middleware (collection) {
var length = Utility_sizeof(collection)
return function (element, index, children, callback) {
var output = ''
for (var i = 0; i < length; i++)
output += collection[i](element, index, children, callback) || ''
return output
}
}
/**
* @param {function} callback
* @return {function}
*/
function rulesheet (callback) {
return function (element) {
if (!element.root)
if (element = element.return)
callback(element)
}
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
*/
function prefixer (element, index, children, callback) {
if (element.length > -1)
if (!element.return)
switch (element.type) {
case DECLARATION: element.return = prefix(element.value, element.length, children)
return
case KEYFRAMES:
return serialize([copy(element, {value: replace(element.value, '@', '@' + WEBKIT)})], callback)
case RULESET:
if (element.length)
return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only': case ':read-write':
return serialize([copy(element, {props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]})], callback)
// :placeholder
case '::placeholder':
return serialize([
copy(element, {props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]}),
copy(element, {props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]}),
copy(element, {props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]})
], callback)
}
return ''
})
}
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
*/
function namespace (element) {
switch (element.type) {
case RULESET:
element.props = element.props.map(function (value) {
return combine(tokenize(value), function (value, index, children) {
switch (charat(value, 0)) {
// \f
case 12:
return substr(value, 1, strlen(value))
// \0 ( + > ~
case 0: case 40: case 43: case 62: case 126:
return value
// :
case 58:
if (children[++index] === 'global')
children[index] = '', children[++index] = '\f' + substr(children[index], index = 1, -1)
// \s
case 32:
return index === 1 ? '' : value
default:
switch (index) {
case 0: element = value
return sizeof(children) > 1 ? '' : value
case index = sizeof(children) - 1: case 2:
return index === 2 ? value + element + element : value + element
default:
return value
}
}
})
})
}
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Parser.js
/**
* @param {string} value
* @return {object[]}
*/
function compile (value) {
return dealloc(Parser_parse('', null, null, null, [''], value = alloc(value), 0, [0], value))
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string[]} rule
* @param {string[]} rules
* @param {string[]} rulesets
* @param {number[]} pseudo
* @param {number[]} points
* @param {string[]} declarations
* @return {object}
*/
function Parser_parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
var index = 0
var offset = 0
var length = pseudo
var atrule = 0
var property = 0
var previous = 0
var variable = 1
var scanning = 1
var ampersand = 1
var character = 0
var type = ''
var props = rules
var children = rulesets
var reference = rule
var characters = type
while (scanning)
switch (previous = character, character = next()) {
// (
case 40:
if (previous != 108 && Utility_charat(characters, length - 1) == 58) {
if (indexof(characters += Utility_replace(delimit(character), '&', '&\f'), '&\f') != -1)
ampersand = -1
break
}
// " ' [
case 34: case 39: case 91:
characters += delimit(character)
break
// \t \n \r \s
case 9: case 10: case 13: case 32:
characters += whitespace(previous)
break
// \
case 92:
characters += escaping(caret() - 1, 7)
continue
// /
case 47:
switch (peek()) {
case 42: case 47:
Utility_append(comment(commenter(next(), caret()), root, parent), declarations)
break
default:
characters += '/'
}
break
// {
case 123 * variable:
points[index++] = Utility_strlen(characters) * ampersand
// } ; \0
case 125 * variable: case 59: case 0:
switch (character) {
// \0 }
case 0: case 125: scanning = 0
// ;
case 59 + offset: if (ampersand == -1) characters = Utility_replace(characters, /\f/g, '')
if (property > 0 && (Utility_strlen(characters) - length))
Utility_append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(Utility_replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations)
break
// @ ;
case 59: characters += ';'
// { rule/at-rule
default:
Utility_append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets)
if (character === 123)
if (offset === 0)
Parser_parse(characters, root, reference, reference, props, rulesets, length, points, children)
else
switch (atrule === 99 && Utility_charat(characters, 3) === 110 ? 100 : atrule) {
// d l m s
case 100: case 108: case 109: case 115:
Parser_parse(value, reference, reference, rule && Utility_append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children)
break
default:
Parser_parse(characters, reference, reference, reference, [''], children, 0, points, children)
}
}
index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo
break
// :
case 58:
length = 1 + Utility_strlen(characters), property = previous
default:
if (variable < 1)
if (character == 123)
--variable
else if (character == 125 && variable++ == 0 && prev() == 125)
continue
switch (characters += Utility_from(character), character * variable) {
// &
case 38:
ampersand = offset > 0 ? 1 : (characters += '\f', -1)
break
// ,
case 44:
points[index++] = (Utility_strlen(characters) - 1) * ampersand, ampersand = 1
break
// @
case 64:
// -
if (peek() === 45)
characters += delimit(next())
atrule = peek(), offset = length = Utility_strlen(type = characters += identifier(caret())), character++
break
// -
case 45:
if (previous === 45 && Utility_strlen(characters) == 2)
variable = 0
}
}
return rulesets
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} index
* @param {number} offset
* @param {string[]} rules
* @param {number[]} points
* @param {string} type
* @param {string[]} props
* @param {string[]} children
* @param {number} length
* @return {object}
*/
function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) {
var post = offset - 1
var rule = offset === 0 ? rules : ['']
var size = Utility_sizeof(rule)
for (var i = 0, j = 0, k = 0; i < index; ++i)
for (var x = 0, y = Utility_substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)
if (z = trim(j > 0 ? rule[x] + ' ' + y : Utility_replace(y, /&\f/g, rule[x])))
props[k++] = z
return node(value, root, parent, offset === 0 ? Enum_RULESET : type, props, children, length)
}
/**
* @param {number} value
* @param {object} root
* @param {object?} parent
* @return {object}
*/
function comment (value, root, parent) {
return node(value, root, parent, COMMENT, Utility_from(Tokenizer_char()), Utility_substr(value, 2, -2), 0)
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} length
* @return {object}
*/
function declaration (value, root, parent, length) {
return node(value, root, parent, Enum_DECLARATION, Utility_substr(value, 0, length), Utility_substr(value, length + 1, -1), length)
}
;// CONCATENATED MODULE: ./node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += Utility_from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value,
parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function emotion_cache_browser_esm_prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return Enum_WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return Enum_WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return Enum_WEBKIT + value + Enum_MOZ + value + Enum_MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return Enum_WEBKIT + value + Enum_MS + value + value;
// order
case 6165:
return Enum_WEBKIT + value + Enum_MS + 'flex-' + value + value;
// align-items
case 5187:
return Enum_WEBKIT + value + Utility_replace(value, /(\w+).+(:[^]+)/, Enum_WEBKIT + 'box-$1$2' + Enum_MS + 'flex-$1$2') + value;
// align-self
case 5443:
return Enum_WEBKIT + value + Enum_MS + 'flex-item-' + Utility_replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return Enum_WEBKIT + value + Enum_MS + 'flex-line-pack' + Utility_replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return Enum_WEBKIT + 'box-' + Utility_replace(value, '-grow', '') + Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return Enum_WEBKIT + Utility_replace(value, /([^-])(transform)/g, '$1' + Enum_WEBKIT + '$2') + value;
// cursor
case 6187:
return Utility_replace(Utility_replace(Utility_replace(value, /(zoom-|grab)/, Enum_WEBKIT + '$1'), /(image-set)/, Enum_WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return Utility_replace(value, /(image-set\([^]*)/, Enum_WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return Utility_replace(Utility_replace(value, /(.+:)(flex-)?(.*)/, Enum_WEBKIT + 'box-pack:$3' + Enum_MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + Enum_WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return Utility_replace(value, /(.+)-inline(.+)/, Enum_WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (Utility_strlen(value) - 1 - length > 6) switch (Utility_charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (Utility_charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return Utility_replace(value, /(.+:)(.+)-([^]+)/, '$1' + Enum_WEBKIT + '$2-$3' + '$1' + Enum_MOZ + (Utility_charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? emotion_cache_browser_esm_prefix(Utility_replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (Utility_charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (Utility_charat(value, Utility_strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return Utility_replace(value, ':', ':' + Enum_WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return Utility_replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + Enum_WEBKIT + (Utility_charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + Enum_WEBKIT + '$2$3' + '$1' + Enum_MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (Utility_charat(value, length + 11)) {
// vertical-l(r)
case 114:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return Enum_WEBKIT + value + Enum_MS + value + value;
}
return value;
}
var emotion_cache_browser_esm_prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case Enum_DECLARATION:
element["return"] = emotion_cache_browser_esm_prefix(element.value, element.length);
break;
case Enum_KEYFRAMES:
return Serializer_serialize([Tokenizer_copy(element, {
value: Utility_replace(element.value, '@', '@' + Enum_WEBKIT)
})], callback);
case Enum_RULESET:
if (element.length) return Utility_combine(element.props, function (value) {
switch (Utility_match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return Serializer_serialize([Tokenizer_copy(element, {
props: [Utility_replace(value, /:(read-\w+)/, ':' + Enum_MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return Serializer_serialize([Tokenizer_copy(element, {
props: [Utility_replace(value, /:(plac\w+)/, ':' + Enum_WEBKIT + 'input-$1')]
}), Tokenizer_copy(element, {
props: [Utility_replace(value, /:(plac\w+)/, ':' + Enum_MOZ + '$1')]
}), Tokenizer_copy(element, {
props: [Utility_replace(value, /:(plac\w+)/, Enum_MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [emotion_cache_browser_esm_prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (false) {}
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
if (false) {}
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' '); // $FlowFixMe
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (false) {}
{
var currentSheet;
var finalizingPlugins = [stringify, false ? 0 : rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return Serializer_serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (false) {}
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
;// CONCATENATED MODULE: ./node_modules/@emotion/hash/dist/emotion-hash.esm.js
/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
;// CONCATENATED MODULE: ./node_modules/@emotion/unitless/dist/emotion-unitless.esm.js
var unitlessKeys = {
animationIterationCount: 1,
aspectRatio: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
};
;// CONCATENATED MODULE: ./node_modules/@emotion/serialize/node_modules/@emotion/memoize/dist/emotion-memoize.esm.js
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
;// CONCATENATED MODULE: ./node_modules/@emotion/serialize/dist/emotion-serialize.browser.esm.js
var ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var UNDEFINED_AS_OBJECT_KEY_ERROR = "You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).";
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var isCustomProperty = function isCustomProperty(property) {
return property.charCodeAt(1) === 45;
};
var isProcessableValue = function isProcessableValue(value) {
return value != null && typeof value !== 'boolean';
};
var processStyleName = /* #__PURE__ */memoize(function (styleName) {
return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
switch (key) {
case 'animation':
case 'animationName':
{
if (typeof value === 'string') {
return value.replace(animationRegex, function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor
};
return p1;
});
}
}
}
if (unitlessKeys[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {
return value + 'px';
}
return value;
};
if (false) { var hyphenatedCache, hyphenPattern, msPattern, oldProcessStyleValue, contentValues, contentValuePattern; }
var noComponentSelectorMessage = (/* unused pure expression or super */ null && ('Component selectors can only be used in conjunction with ' + '@emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware ' + 'compiler transform.'));
function handleInterpolation(mergedProps, registered, interpolation) {
if (interpolation == null) {
return '';
}
if (interpolation.__emotion_styles !== undefined) {
if (false) {}
return interpolation;
}
switch (typeof interpolation) {
case 'boolean':
{
return '';
}
case 'object':
{
if (interpolation.anim === 1) {
cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor
};
return interpolation.name;
}
if (interpolation.styles !== undefined) {
var next = interpolation.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor
};
next = next.next;
}
}
var styles = interpolation.styles + ";";
if (false) {}
return styles;
}
return createStringFromObject(mergedProps, registered, interpolation);
}
case 'function':
{
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(mergedProps, registered, result);
} else if (false) {}
break;
}
case 'string':
if (false) { var replaced, matched; }
break;
} // finalize string values (regular strings and functions interpolated into css calls)
if (registered == null) {
return interpolation;
}
var cached = registered[interpolation];
return cached !== undefined ? cached : interpolation;
}
function createStringFromObject(mergedProps, registered, obj) {
var string = '';
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
}
} else {
for (var _key in obj) {
var value = obj[_key];
if (typeof value !== 'object') {
if (registered != null && registered[value] !== undefined) {
string += _key + "{" + registered[value] + "}";
} else if (isProcessableValue(value)) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";";
}
} else {
if (_key === 'NO_COMPONENT_SELECTOR' && "production" !== 'production') {}
if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
for (var _i = 0; _i < value.length; _i++) {
if (isProcessableValue(value[_i])) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";";
}
}
} else {
var interpolated = handleInterpolation(mergedProps, registered, value);
switch (_key) {
case 'animation':
case 'animationName':
{
string += processStyleName(_key) + ":" + interpolated + ";";
break;
}
default:
{
if (false) {}
string += _key + "{" + interpolated + "}";
}
}
}
}
}
}
return string;
}
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
var sourceMapPattern;
if (false) {} // this is the cursor for keyframes
// keyframes are stored on the SerializedStyles object as a linked list
var cursor;
var emotion_serialize_browser_esm_serializeStyles = function serializeStyles(args, registered, mergedProps) {
if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
return args[0];
}
var stringMode = true;
var styles = '';
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
styles += handleInterpolation(mergedProps, registered, strings);
} else {
if (false) {}
styles += strings[0];
} // we start at 1 since we've already handled the first arg
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(mergedProps, registered, args[i]);
if (stringMode) {
if (false) {}
styles += strings[i];
}
}
var sourceMap;
if (false) {} // using a global regex with .exec is stateful so lastIndex has to be reset each time
labelPattern.lastIndex = 0;
var identifierName = '';
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName += '-' + // $FlowFixMe we know it's not null
match[1];
}
var name = murmur2(styles) + identifierName;
if (false) {}
return {
name: name,
styles: styles,
next: cursor
};
};
;// CONCATENATED MODULE: ./node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js
var syncFallback = function syncFallback(create) {
return create();
};
var useInsertionEffect = external_React_['useInsertion' + 'Effect'] ? external_React_['useInsertion' + 'Effect'] : false;
var emotion_use_insertion_effect_with_fallbacks_browser_esm_useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback;
var emotion_use_insertion_effect_with_fallbacks_browser_esm_useInsertionEffectWithLayoutFallback = useInsertionEffect || external_React_.useLayoutEffect;
;// CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-element-c39617d8.browser.esm.js
var emotion_element_c39617d8_browser_esm_isBrowser = "object" !== 'undefined';
var emotion_element_c39617d8_browser_esm_hasOwnProperty = {}.hasOwnProperty;
var EmotionCacheContext = /* #__PURE__ */external_React_.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
typeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache({
key: 'css'
}) : null);
if (false) {}
var CacheProvider = EmotionCacheContext.Provider;
var __unsafe_useEmotionCache = function useEmotionCache() {
return (0,external_React_.useContext)(EmotionCacheContext);
};
var emotion_element_c39617d8_browser_esm_withEmotionCache = function withEmotionCache(func) {
// $FlowFixMe
return /*#__PURE__*/(0,external_React_.forwardRef)(function (props, ref) {
// the cache will never be null in the browser
var cache = (0,external_React_.useContext)(EmotionCacheContext);
return func(props, cache, ref);
});
};
if (!emotion_element_c39617d8_browser_esm_isBrowser) {
emotion_element_c39617d8_browser_esm_withEmotionCache = function withEmotionCache(func) {
return function (props) {
var cache = (0,external_React_.useContext)(EmotionCacheContext);
if (cache === null) {
// yes, we're potentially creating this on every render
// it doesn't actually matter though since it's only on the server
// so there will only every be a single render
// that could change in the future because of suspense and etc. but for now,
// this works and i don't want to optimise for a future thing that we aren't sure about
cache = createCache({
key: 'css'
});
return /*#__PURE__*/external_React_.createElement(EmotionCacheContext.Provider, {
value: cache
}, func(props, cache));
} else {
return func(props, cache);
}
};
};
}
var emotion_element_c39617d8_browser_esm_ThemeContext = /* #__PURE__ */external_React_.createContext({});
if (false) {}
var useTheme = function useTheme() {
return React.useContext(emotion_element_c39617d8_browser_esm_ThemeContext);
};
var getTheme = function getTheme(outerTheme, theme) {
if (typeof theme === 'function') {
var mergedTheme = theme(outerTheme);
if (false) {}
return mergedTheme;
}
if (false) {}
return _extends({}, outerTheme, theme);
};
var createCacheWithTheme = /* #__PURE__ */(/* unused pure expression or super */ null && (weakMemoize(function (outerTheme) {
return weakMemoize(function (theme) {
return getTheme(outerTheme, theme);
});
})));
var ThemeProvider = function ThemeProvider(props) {
var theme = React.useContext(emotion_element_c39617d8_browser_esm_ThemeContext);
if (props.theme !== theme) {
theme = createCacheWithTheme(theme)(props.theme);
}
return /*#__PURE__*/React.createElement(emotion_element_c39617d8_browser_esm_ThemeContext.Provider, {
value: theme
}, props.children);
};
function withTheme(Component) {
var componentName = Component.displayName || Component.name || 'Component';
var render = function render(props, ref) {
var theme = React.useContext(emotion_element_c39617d8_browser_esm_ThemeContext);
return /*#__PURE__*/React.createElement(Component, _extends({
theme: theme,
ref: ref
}, props));
}; // $FlowFixMe
var WithTheme = /*#__PURE__*/React.forwardRef(render);
WithTheme.displayName = "WithTheme(" + componentName + ")";
return hoistNonReactStatics(WithTheme, Component);
}
var getLastPart = function getLastPart(functionName) {
// The match may be something like 'Object.createEmotionProps' or
// 'Loader.prototype.render'
var parts = functionName.split('.');
return parts[parts.length - 1];
};
var getFunctionNameFromStackTraceLine = function getFunctionNameFromStackTraceLine(line) {
// V8
var match = /^\s+at\s+([A-Za-z0-9$.]+)\s/.exec(line);
if (match) return getLastPart(match[1]); // Safari / Firefox
match = /^([A-Za-z0-9$.]+)@/.exec(line);
if (match) return getLastPart(match[1]);
return undefined;
};
var internalReactFunctionNames = /* #__PURE__ */new Set(['renderWithHooks', 'processChild', 'finishClassComponent', 'renderToString']); // These identifiers come from error stacks, so they have to be valid JS
// identifiers, thus we only need to replace what is a valid character for JS,
// but not for CSS.
var sanitizeIdentifier = function sanitizeIdentifier(identifier) {
return identifier.replace(/\$/g, '-');
};
var getLabelFromStackTrace = function getLabelFromStackTrace(stackTrace) {
if (!stackTrace) return undefined;
var lines = stackTrace.split('\n');
for (var i = 0; i < lines.length; i++) {
var functionName = getFunctionNameFromStackTraceLine(lines[i]); // The first line of V8 stack traces is just "Error"
if (!functionName) continue; // If we reach one of these, we have gone too far and should quit
if (internalReactFunctionNames.has(functionName)) break; // The component name is the first function in the stack that starts with an
// uppercase letter
if (/^[A-Z]/.test(functionName)) return sanitizeIdentifier(functionName);
}
return undefined;
};
var typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';
var labelPropName = '__EMOTION_LABEL_PLEASE_DO_NOT_USE__';
var emotion_element_c39617d8_browser_esm_createEmotionProps = function createEmotionProps(type, props) {
if (false) {}
var newProps = {};
for (var key in props) {
if (emotion_element_c39617d8_browser_esm_hasOwnProperty.call(props, key)) {
newProps[key] = props[key];
}
}
newProps[typePropName] = type; // For performance, only call getLabelFromStackTrace in development and when
// the label hasn't already been computed
if (false) { var label; }
return newProps;
};
var Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serialized = _ref.serialized,
isStringTag = _ref.isStringTag;
registerStyles(cache, serialized, isStringTag);
useInsertionEffectAlwaysWithSyncFallback(function () {
return insertStyles(cache, serialized, isStringTag);
});
return null;
};
var emotion_element_c39617d8_browser_esm_Emotion = /* #__PURE__ */(/* unused pure expression or super */ null && (emotion_element_c39617d8_browser_esm_withEmotionCache(function (props, cache, ref) {
var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works
// not passing the registered cache to serializeStyles because it would
// make certain babel optimisations not possible
if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {
cssProp = cache.registered[cssProp];
}
var WrappedComponent = props[typePropName];
var registeredStyles = [cssProp];
var className = '';
if (typeof props.className === 'string') {
className = getRegisteredStyles(cache.registered, registeredStyles, props.className);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = serializeStyles(registeredStyles, undefined, React.useContext(emotion_element_c39617d8_browser_esm_ThemeContext));
if (false) { var labelFromStack; }
className += cache.key + "-" + serialized.name;
var newProps = {};
for (var key in props) {
if (emotion_element_c39617d8_browser_esm_hasOwnProperty.call(props, key) && key !== 'css' && key !== typePropName && ( true || 0)) {
newProps[key] = props[key];
}
}
newProps.ref = ref;
newProps.className = className;
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof WrappedComponent === 'string'
}), /*#__PURE__*/React.createElement(WrappedComponent, newProps));
})));
if (false) {}
var Emotion$1 = (/* unused pure expression or super */ null && (emotion_element_c39617d8_browser_esm_Emotion));
;// CONCATENATED MODULE: ./node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js
var emotion_utils_browser_esm_isBrowser = "object" !== 'undefined';
function emotion_utils_browser_esm_getRegisteredStyles(registered, registeredStyles, classNames) {
var rawClassName = '';
classNames.split(' ').forEach(function (className) {
if (registered[className] !== undefined) {
registeredStyles.push(registered[className] + ";");
} else {
rawClassName += className + " ";
}
});
return rawClassName;
}
var emotion_utils_browser_esm_registerStyles = function registerStyles(cache, serialized, isStringTag) {
var className = cache.key + "-" + serialized.name;
if ( // we only need to add the styles to the registered cache if the
// class name could be used further down
// the tree but if it's a string tag, we know it won't
// so we don't have to add it to registered cache.
// this improves memory usage since we can avoid storing the whole style string
(isStringTag === false || // we need to always store it if we're in compat mode and
// in node since emotion-server relies on whether a style is in
// the registered cache to know whether a style is global or not
// also, note that this check will be dead code eliminated in the browser
emotion_utils_browser_esm_isBrowser === false ) && cache.registered[className] === undefined) {
cache.registered[className] = serialized.styles;
}
};
var emotion_utils_browser_esm_insertStyles = function insertStyles(cache, serialized, isStringTag) {
emotion_utils_browser_esm_registerStyles(cache, serialized, isStringTag);
var className = cache.key + "-" + serialized.name;
if (cache.inserted[serialized.name] === undefined) {
var current = serialized;
do {
cache.insert(serialized === current ? "." + className : '', current, cache.sheet, true);
current = current.next;
} while (current !== undefined);
}
};
;// CONCATENATED MODULE: ./node_modules/@emotion/css/create-instance/dist/emotion-css-create-instance.esm.js
function insertWithoutScoping(cache, serialized) {
if (cache.inserted[serialized.name] === undefined) {
return cache.insert('', serialized, cache.sheet, true);
}
}
function merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = emotion_utils_browser_esm_getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var createEmotion = function createEmotion(options) {
var cache = createCache(options); // $FlowFixMe
cache.sheet.speedy = function (value) {
if (false) {}
this.isSpeedy = value;
};
cache.compat = true;
var css = function css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = emotion_serialize_browser_esm_serializeStyles(args, cache.registered, undefined);
emotion_utils_browser_esm_insertStyles(cache, serialized, false);
return cache.key + "-" + serialized.name;
};
var keyframes = function keyframes() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var serialized = emotion_serialize_browser_esm_serializeStyles(args, cache.registered);
var animation = "animation-" + serialized.name;
insertWithoutScoping(cache, {
name: serialized.name,
styles: "@keyframes " + animation + "{" + serialized.styles + "}"
});
return animation;
};
var injectGlobal = function injectGlobal() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var serialized = emotion_serialize_browser_esm_serializeStyles(args, cache.registered);
insertWithoutScoping(cache, serialized);
};
var cx = function cx() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return merge(cache.registered, css, emotion_css_create_instance_esm_classnames(args));
};
return {
css: css,
cx: cx,
injectGlobal: injectGlobal,
keyframes: keyframes,
hydrate: function hydrate(ids) {
ids.forEach(function (key) {
cache.inserted[key] = true;
});
},
flush: function flush() {
cache.registered = {};
cache.inserted = {};
cache.sheet.flush();
},
// $FlowFixMe
sheet: cache.sheet,
cache: cache,
getRegisteredStyles: emotion_utils_browser_esm_getRegisteredStyles.bind(null, cache.registered),
merge: merge.bind(null, cache.registered, css)
};
};
var emotion_css_create_instance_esm_classnames = function classnames(args) {
var cls = '';
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
;// CONCATENATED MODULE: ./node_modules/@emotion/css/dist/emotion-css.esm.js
var _createEmotion = createEmotion({
key: 'css'
}),
flush = _createEmotion.flush,
hydrate = _createEmotion.hydrate,
emotion_css_esm_cx = _createEmotion.cx,
emotion_css_esm_merge = _createEmotion.merge,
emotion_css_esm_getRegisteredStyles = _createEmotion.getRegisteredStyles,
injectGlobal = _createEmotion.injectGlobal,
emotion_css_esm_keyframes = _createEmotion.keyframes,
css = _createEmotion.css,
sheet = _createEmotion.sheet,
cache = _createEmotion.cache;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-cx.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
const isSerializedStyles = o => typeof o !== 'undefined' && o !== null && ['name', 'styles'].every(p => typeof o[p] !== 'undefined');
/**
* Retrieve a `cx` function that knows how to handle `SerializedStyles`
* returned by the `@emotion/react` `css` function in addition to what
* `cx` normally knows how to handle. It also hooks into the Emotion
* Cache, allowing `css` calls to work inside iframes.
*
* @example
* import { css } from '@emotion/react';
*
* const styles = css`
* color: red
* `;
*
* function RedText( { className, ...props } ) {
* const cx = useCx();
*
* const classes = cx(styles, className);
*
* return <span className={classes} {...props} />;
* }
*/
const useCx = () => {
const cache = __unsafe_useEmotionCache();
const cx = (0,external_wp_element_namespaceObject.useCallback)((...classNames) => {
if (cache === null) {
throw new Error('The `useCx` hook should be only used within a valid Emotion Cache Context');
}
return emotion_css_esm_cx(...classNames.map(arg => {
if (isSerializedStyles(arg)) {
emotion_utils_browser_esm_insertStyles(cache, arg, false);
return `${cache.key}-${arg.name}`;
}
return arg;
}));
}, [cache]);
return cx;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/use-context-system.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @template TProps
* @typedef {TProps & { className: string }} ConnectedProps
*/
/**
* Custom hook that derives registered props from the Context system.
* These derived props are then consolidated with incoming component props.
*
* @template {{ className?: string }} P
* @param {P} props Incoming props from the component.
* @param {string} namespace The namespace to register and to derive context props from.
* @return {ConnectedProps<P>} The connected props.
*/
function useContextSystem(props, namespace) {
const contextSystemProps = useComponentsContext();
if (typeof namespace === 'undefined') {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
}
const contextProps = contextSystemProps?.[namespace] || {};
/* eslint-disable jsdoc/no-undefined-types */
/** @type {ConnectedProps<P>} */
// @ts-ignore We fill in the missing properties below
const finalComponentProps = { ...getConnectedNamespace(),
...getNamespace(namespace)
};
/* eslint-enable jsdoc/no-undefined-types */
const {
_overrides: overrideProps,
...otherContextProps
} = contextProps;
const initialMergedProps = Object.entries(otherContextProps).length ? Object.assign({}, otherContextProps, props) : props;
const cx = useCx();
const classes = cx(getStyledClassNameFromKey(namespace), props.className); // Provides the ability to customize the render of the component.
const rendered = typeof initialMergedProps.renderChildren === 'function' ? initialMergedProps.renderChildren(initialMergedProps) : initialMergedProps.children;
for (const key in initialMergedProps) {
// @ts-ignore filling in missing props
finalComponentProps[key] = initialMergedProps[key];
}
for (const key in overrideProps) {
// @ts-ignore filling in missing props
finalComponentProps[key] = overrideProps[key];
} // Setting an `undefined` explicitly can cause unintended overwrites
// when a `cloneElement()` is involved.
if (rendered !== undefined) {
// @ts-ignore
finalComponentProps.children = rendered;
}
finalComponentProps.className = classes;
return finalComponentProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/context-connect.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Forwards ref (React.ForwardRef) and "Connects" (or registers) a component
* within the Context system under a specified namespace.
*
* @param Component The component to register into the Context system.
* @param namespace The namespace to register the component under.
* @return The connected WordPressComponent
*/
function contextConnect(Component, namespace) {
return _contextConnect(Component, namespace, {
forwardsRef: true
});
}
/**
* "Connects" (or registers) a component within the Context system under a specified namespace.
* Does not forward a ref.
*
* @param Component The component to register into the Context system.
* @param namespace The namespace to register the component under.
* @return The connected WordPressComponent
*/
function contextConnectWithoutRef(Component, namespace) {
return _contextConnect(Component, namespace);
} // This is an (experimental) evolution of the initial connect() HOC.
// The hope is that we can improve render performance by removing functional
// component wrappers.
function _contextConnect(Component, namespace, options) {
const WrappedComponent = options?.forwardsRef ? (0,external_wp_element_namespaceObject.forwardRef)(Component) : Component;
if (typeof namespace === 'undefined') {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
} // @ts-expect-error internal property
let mergedNamespace = WrappedComponent[CONNECT_STATIC_NAMESPACE] || [namespace];
/**
* Consolidate (merge) namespaces before attaching it to the WrappedComponent.
*/
if (Array.isArray(namespace)) {
mergedNamespace = [...mergedNamespace, ...namespace];
}
if (typeof namespace === 'string') {
mergedNamespace = [...mergedNamespace, namespace];
} // @ts-expect-error We can't rely on inferred types here because of the
// `as` prop polymorphism we're handling in https://github.com/WordPress/gutenberg/blob/9620bae6fef4fde7cc2b7833f416e240207cda29/packages/components/src/ui/context/wordpress-component.ts#L32-L33
return Object.assign(WrappedComponent, {
[CONNECT_STATIC_NAMESPACE]: [...new Set(mergedNamespace)],
displayName: namespace,
selector: `.${getStyledClassNameFromKey(namespace)}`
});
}
/**
* Attempts to retrieve the connected namespace from a component.
*
* @param Component The component to retrieve a namespace from.
* @return The connected namespaces.
*/
function getConnectNamespace(Component) {
if (!Component) return [];
let namespaces = []; // @ts-ignore internal property
if (Component[CONNECT_STATIC_NAMESPACE]) {
// @ts-ignore internal property
namespaces = Component[CONNECT_STATIC_NAMESPACE];
} // @ts-ignore
if (Component.type && Component.type[CONNECT_STATIC_NAMESPACE]) {
// @ts-ignore
namespaces = Component.type[CONNECT_STATIC_NAMESPACE];
}
return namespaces;
}
/**
* Checks to see if a component is connected within the Context system.
*
* @param Component The component to retrieve a namespace from.
* @param match The namespace to check.
*/
function hasConnectNamespace(Component, match) {
if (!Component) return false;
if (typeof match === 'string') {
return getConnectNamespace(Component).includes(match);
}
if (Array.isArray(match)) {
return match.some(result => getConnectNamespace(Component).includes(result));
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/visually-hidden/styles.js
/**
* External dependencies
*/
const visuallyHidden = {
border: 0,
clip: 'rect(1px, 1px, 1px, 1px)',
WebkitClipPath: 'inset( 50% )',
clipPath: 'inset( 50% )',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
width: '1px',
wordWrap: 'normal'
};
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function extends_extends() {
extends_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return extends_extends.apply(this, arguments);
}
;// CONCATENATED MODULE: ./node_modules/@emotion/styled/node_modules/@emotion/memoize/dist/emotion-memoize.esm.js
function emotion_memoize_esm_memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
;// CONCATENATED MODULE: ./node_modules/@emotion/styled/node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js
var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23
var isPropValid = /* #__PURE__ */emotion_memoize_esm_memoize(function (prop) {
return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
/* o */
&& prop.charCodeAt(1) === 110
/* n */
&& prop.charCodeAt(2) < 91;
}
/* Z+1 */
);
;// CONCATENATED MODULE: ./node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js
var testOmitPropsOnStringTag = isPropValid;
var testOmitPropsOnComponent = function testOmitPropsOnComponent(key) {
return key !== 'theme';
};
var getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) {
return typeof tag === 'string' && // 96 is one less than the char code
// for "a" so this is checking that
// it's a lowercase character
tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;
};
var composeShouldForwardProps = function composeShouldForwardProps(tag, options, isReal) {
var shouldForwardProp;
if (options) {
var optionsShouldForwardProp = options.shouldForwardProp;
shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName) {
return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName);
} : optionsShouldForwardProp;
}
if (typeof shouldForwardProp !== 'function' && isReal) {
shouldForwardProp = tag.__emotion_forwardProp;
}
return shouldForwardProp;
};
var emotion_styled_base_browser_esm_ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var emotion_styled_base_browser_esm_Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serialized = _ref.serialized,
isStringTag = _ref.isStringTag;
emotion_utils_browser_esm_registerStyles(cache, serialized, isStringTag);
emotion_use_insertion_effect_with_fallbacks_browser_esm_useInsertionEffectAlwaysWithSyncFallback(function () {
return emotion_utils_browser_esm_insertStyles(cache, serialized, isStringTag);
});
return null;
};
var createStyled = function createStyled(tag, options) {
if (false) {}
var isReal = tag.__emotion_real === tag;
var baseTag = isReal && tag.__emotion_base || tag;
var identifierName;
var targetClassName;
if (options !== undefined) {
identifierName = options.label;
targetClassName = options.target;
}
var shouldForwardProp = composeShouldForwardProps(tag, options, isReal);
var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);
var shouldUseAs = !defaultShouldForwardProp('as');
return function () {
var args = arguments;
var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];
if (identifierName !== undefined) {
styles.push("label:" + identifierName + ";");
}
if (args[0] == null || args[0].raw === undefined) {
styles.push.apply(styles, args);
} else {
if (false) {}
styles.push(args[0][0]);
var len = args.length;
var i = 1;
for (; i < len; i++) {
if (false) {}
styles.push(args[i], args[0][i]);
}
} // $FlowFixMe: we need to cast StatelessFunctionalComponent to our PrivateStyledComponent class
var Styled = emotion_element_c39617d8_browser_esm_withEmotionCache(function (props, cache, ref) {
var FinalTag = shouldUseAs && props.as || baseTag;
var className = '';
var classInterpolations = [];
var mergedProps = props;
if (props.theme == null) {
mergedProps = {};
for (var key in props) {
mergedProps[key] = props[key];
}
mergedProps.theme = external_React_.useContext(emotion_element_c39617d8_browser_esm_ThemeContext);
}
if (typeof props.className === 'string') {
className = emotion_utils_browser_esm_getRegisteredStyles(cache.registered, classInterpolations, props.className);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = emotion_serialize_browser_esm_serializeStyles(styles.concat(classInterpolations), cache.registered, mergedProps);
className += cache.key + "-" + serialized.name;
if (targetClassName !== undefined) {
className += " " + targetClassName;
}
var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;
var newProps = {};
for (var _key in props) {
if (shouldUseAs && _key === 'as') continue;
if ( // $FlowFixMe
finalShouldForwardProp(_key)) {
newProps[_key] = props[_key];
}
}
newProps.className = className;
newProps.ref = ref;
return /*#__PURE__*/external_React_.createElement(external_React_.Fragment, null, /*#__PURE__*/external_React_.createElement(emotion_styled_base_browser_esm_Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof FinalTag === 'string'
}), /*#__PURE__*/external_React_.createElement(FinalTag, newProps));
});
Styled.displayName = identifierName !== undefined ? identifierName : "Styled(" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + ")";
Styled.defaultProps = tag.defaultProps;
Styled.__emotion_real = Styled;
Styled.__emotion_base = baseTag;
Styled.__emotion_styles = styles;
Styled.__emotion_forwardProp = shouldForwardProp;
Object.defineProperty(Styled, 'toString', {
value: function value() {
if (targetClassName === undefined && "production" !== 'production') {} // $FlowFixMe: coerce undefined to string
return "." + targetClassName;
}
});
Styled.withComponent = function (nextTag, nextOptions) {
return createStyled(nextTag, extends_extends({}, options, nextOptions, {
shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true)
})).apply(void 0, styles);
};
return Styled;
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/view/component.js
/**
* External dependencies
*/
/**
* `View` is a core component that renders everything in the library.
* It is the principle component in the entire library.
*
* @example
* ```jsx
* import { View } from `@wordpress/components`;
*
* function Example() {
* return (
* <View>
* Code is Poetry
* </View>
* );
* }
* ```
*/
const View = createStyled("div", true ? {
target: "e19lxcc00"
} : 0)( true ? "" : 0);
View.selector = '.components-view';
View.displayName = 'View';
/* harmony default export */ var component = (View);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/visually-hidden/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedVisuallyHidden(props, forwardedRef) {
const {
style: styleProp,
...contextProps
} = useContextSystem(props, 'VisuallyHidden');
return (0,external_wp_element_namespaceObject.createElement)(component, {
ref: forwardedRef,
...contextProps,
style: { ...visuallyHidden,
...(styleProp || {})
}
});
}
/**
* `VisuallyHidden` is a component used to render text intended to be visually
* hidden, but will show for alternate devices, for example a screen reader.
*
* ```jsx
* import { VisuallyHidden } from `@wordpress/components`;
*
* function Example() {
* return (
* <VisuallyHidden>
* <label>Code is Poetry</label>
* </VisuallyHidden>
* );
* }
* ```
*/
const VisuallyHidden = contextConnect(UnconnectedVisuallyHidden, 'VisuallyHidden');
/* harmony default export */ var visually_hidden_component = (VisuallyHidden);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const disabledEventsOnDisabledButton = ['onMouseDown', 'onClick'];
function useDeprecatedProps({
isDefault,
isPrimary,
isSecondary,
isTertiary,
isLink,
isSmall,
size,
variant,
...otherProps
}) {
let computedSize = size;
let computedVariant = variant;
if (isSmall) {
var _computedSize;
(_computedSize = computedSize) !== null && _computedSize !== void 0 ? _computedSize : computedSize = 'small';
}
if (isPrimary) {
var _computedVariant;
(_computedVariant = computedVariant) !== null && _computedVariant !== void 0 ? _computedVariant : computedVariant = 'primary';
}
if (isTertiary) {
var _computedVariant2;
(_computedVariant2 = computedVariant) !== null && _computedVariant2 !== void 0 ? _computedVariant2 : computedVariant = 'tertiary';
}
if (isSecondary) {
var _computedVariant3;
(_computedVariant3 = computedVariant) !== null && _computedVariant3 !== void 0 ? _computedVariant3 : computedVariant = 'secondary';
}
if (isDefault) {
var _computedVariant4;
external_wp_deprecated_default()('Button isDefault prop', {
since: '5.4',
alternative: 'variant="secondary"',
version: '6.2'
});
(_computedVariant4 = computedVariant) !== null && _computedVariant4 !== void 0 ? _computedVariant4 : computedVariant = 'secondary';
}
if (isLink) {
var _computedVariant5;
(_computedVariant5 = computedVariant) !== null && _computedVariant5 !== void 0 ? _computedVariant5 : computedVariant = 'link';
}
return { ...otherProps,
size: computedSize,
variant: computedVariant
};
}
function UnforwardedButton(props, ref) {
const {
__next40pxDefaultSize,
isPressed,
isBusy,
isDestructive,
className,
disabled,
icon,
iconPosition = 'left',
iconSize,
showTooltip,
tooltipPosition,
shortcut,
label,
children,
size = 'default',
text,
variant,
__experimentalIsFocusable: isFocusable,
describedBy,
...buttonOrAnchorProps
} = useDeprecatedProps(props);
const {
href,
target,
...additionalProps
} = 'href' in buttonOrAnchorProps ? buttonOrAnchorProps : {
href: undefined,
target: undefined,
...buttonOrAnchorProps
};
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Button, 'components-button__description');
const hasChildren = 'string' === typeof children && !!children || Array.isArray(children) && children?.[0] && children[0] !== null && // Tooltip should not considered as a child
children?.[0]?.props?.className !== 'components-tooltip';
const classes = classnames_default()('components-button', className, {
'is-next-40px-default-size': __next40pxDefaultSize,
'is-secondary': variant === 'secondary',
'is-primary': variant === 'primary',
'is-small': size === 'small',
'is-compact': size === 'compact',
'is-tertiary': variant === 'tertiary',
'is-pressed': isPressed,
'is-busy': isBusy,
'is-link': variant === 'link',
'is-destructive': isDestructive,
'has-text': !!icon && hasChildren,
'has-icon': !!icon
});
const trulyDisabled = disabled && !isFocusable;
const Tag = href !== undefined && !trulyDisabled ? 'a' : 'button';
const buttonProps = Tag === 'button' ? {
type: 'button',
disabled: trulyDisabled,
'aria-pressed': isPressed
} : {};
const anchorProps = Tag === 'a' ? {
href,
target
} : {};
if (disabled && isFocusable) {
// In this case, the button will be disabled, but still focusable and
// perceivable by screen reader users.
buttonProps['aria-disabled'] = true;
anchorProps['aria-disabled'] = true;
for (const disabledEvent of disabledEventsOnDisabledButton) {
additionalProps[disabledEvent] = event => {
if (event) {
event.stopPropagation();
event.preventDefault();
}
};
}
} // Should show the tooltip if...
const shouldShowTooltip = !trulyDisabled && ( // An explicit tooltip is passed or...
showTooltip && label || // There's a shortcut or...
shortcut || // There's a label and...
!!label && // The children are empty and...
!children?.length && // The tooltip is not explicitly disabled.
false !== showTooltip);
const descriptionId = describedBy ? instanceId : undefined;
const describedById = additionalProps['aria-describedby'] || descriptionId;
const commonProps = {
className: classes,
'aria-label': additionalProps['aria-label'] || label,
'aria-describedby': describedById,
ref
};
const elementChildren = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, icon && iconPosition === 'left' && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon,
size: iconSize
}), text && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, text), icon && iconPosition === 'right' && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon,
size: iconSize
}), children);
const element = Tag === 'a' ? (0,external_wp_element_namespaceObject.createElement)("a", { ...anchorProps,
...additionalProps,
...commonProps
}, elementChildren) : (0,external_wp_element_namespaceObject.createElement)("button", { ...buttonProps,
...additionalProps,
...commonProps
}, elementChildren);
if (!shouldShowTooltip) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, element, describedBy && (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, null, (0,external_wp_element_namespaceObject.createElement)("span", {
id: descriptionId
}, describedBy)));
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: children?.length && describedBy ? describedBy : label,
shortcut: shortcut,
position: tooltipPosition
}, element), describedBy && (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, null, (0,external_wp_element_namespaceObject.createElement)("span", {
id: descriptionId
}, describedBy)));
}
/**
* Lets users take actions and make choices with a single click or tap.
*
* ```jsx
* import { Button } from '@wordpress/components';
* const Mybutton = () => (
* <Button
* variant="primary"
* onClick={ handleClick }
* >
* Click here
* </Button>
* );
* ```
*/
const Button = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedButton);
/* harmony default export */ var build_module_button = (Button);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scroll-lock/index.js
/**
* WordPress dependencies
*/
/*
* Setting `overflow: hidden` on html and body elements resets body scroll in iOS.
* Save scroll top so we can restore it after locking scroll.
*
* NOTE: It would be cleaner and possibly safer to find a localized solution such
* as preventing default on certain touchmove events.
*/
let previousScrollTop = 0;
function setLocked(locked) {
const scrollingElement = document.scrollingElement || document.body;
if (locked) {
previousScrollTop = scrollingElement.scrollTop;
}
const methodName = locked ? 'add' : 'remove';
scrollingElement.classList[methodName]('lockscroll'); // Adding the class to the document element seems to be necessary in iOS.
document.documentElement.classList[methodName]('lockscroll');
if (!locked) {
scrollingElement.scrollTop = previousScrollTop;
}
}
let lockCounter = 0;
/**
* ScrollLock is a content-free React component for declaratively preventing
* scroll bleed from modal UI to the page body. This component applies a
* `lockscroll` class to the `document.documentElement` and
* `document.scrollingElement` elements to stop the body from scrolling. When it
* is present, the lock is applied.
*
* ```jsx
* import { ScrollLock, Button } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyScrollLock = () => {
* const [ isScrollLocked, setIsScrollLocked ] = useState( false );
*
* const toggleLock = () => {
* setIsScrollLocked( ( locked ) => ! locked ) );
* };
*
* return (
* <div>
* <Button variant="secondary" onClick={ toggleLock }>
* Toggle scroll lock
* </Button>
* { isScrollLocked && <ScrollLock /> }
* <p>
* Scroll locked:
* <strong>{ isScrollLocked ? 'Yes' : 'No' }</strong>
* </p>
* </div>
* );
* };
* ```
*/
function ScrollLock() {
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (lockCounter === 0) {
setLocked(true);
}
++lockCounter;
return () => {
if (lockCounter === 1) {
setLocked(false);
}
--lockCounter;
};
}, []);
return null;
}
/* harmony default export */ var scroll_lock = (ScrollLock);
;// CONCATENATED MODULE: ./node_modules/proxy-compare/dist/index.modern.js
const index_modern_e=Symbol(),index_modern_t=Symbol(),index_modern_r=Symbol();let index_modern_n=(e,t)=>new Proxy(e,t);const index_modern_o=Object.getPrototypeOf,index_modern_s=new WeakMap,index_modern_c=e=>e&&(index_modern_s.has(e)?index_modern_s.get(e):index_modern_o(e)===Object.prototype||index_modern_o(e)===Array.prototype),index_modern_l=e=>"object"==typeof e&&null!==e,index_modern_a=new WeakMap,index_modern_f=e=>e[index_modern_r]||e,index_modern_i=(s,l,p)=>{if(!index_modern_c(s))return s;const y=index_modern_f(s),u=(e=>Object.isFrozen(e)||Object.values(Object.getOwnPropertyDescriptors(e)).some(e=>!e.writable))(y);let g=p&&p.get(y);return g&&g[1].f===u||(g=((n,o)=>{const s={f:o};let c=!1;const l=(t,r)=>{if(!c){let o=s.a.get(n);o||(o=new Set,s.a.set(n,o)),r&&o.has(index_modern_e)||o.add(t)}},a={get:(e,t)=>t===index_modern_r?n:(l(t),index_modern_i(e[t],s.a,s.c)),has:(e,r)=>r===index_modern_t?(c=!0,s.a.delete(n),!0):(l(r),r in e),getOwnPropertyDescriptor:(e,t)=>(l(t,!0),Object.getOwnPropertyDescriptor(e,t)),ownKeys:t=>(l(index_modern_e),Reflect.ownKeys(t))};return o&&(a.set=a.deleteProperty=()=>!1),[a,s]})(y,u),g[1].p=index_modern_n(u?(e=>{let t=index_modern_a.get(e);if(!t){if(Array.isArray(e))t=Array.from(e);else{const r=Object.getOwnPropertyDescriptors(e);Object.values(r).forEach(e=>{e.configurable=!0}),t=Object.create(index_modern_o(e),r)}index_modern_a.set(e,t)}return t})(y):y,g[0]),p&&p.set(y,g)),g[1].a=l,g[1].c=p,g[1].p},index_modern_p=(e,t)=>{const r=Reflect.ownKeys(e),n=Reflect.ownKeys(t);return r.length!==n.length||r.some((e,t)=>e!==n[t])},index_modern_y=(t,r,n,o)=>{if(Object.is(t,r))return!1;if(!index_modern_l(t)||!index_modern_l(r))return!0;const s=n.get(index_modern_f(t));if(!s)return!0;if(o){const e=o.get(t);if(e&&e.n===r)return e.g;o.set(t,{n:r,g:!1})}let c=null;for(const l of s){const s=l===index_modern_e?index_modern_p(t,r):index_modern_y(t[l],r[l],n,o);if(!0!==s&&!1!==s||(c=s),c)break}return null===c&&(c=!0),o&&o.set(t,{n:r,g:c}),c},index_modern_u=e=>!!index_modern_c(e)&&index_modern_t in e,index_modern_g=e=>index_modern_c(e)&&e[index_modern_r]||null,index_modern_b=(e,t=!0)=>{index_modern_s.set(e,t)},index_modern_O=(e,t)=>{const r=[],n=new WeakSet,o=(e,s)=>{if(n.has(e))return;index_modern_l(e)&&n.add(e);const c=index_modern_l(e)&&t.get(index_modern_f(e));c?c.forEach(t=>{o(e[t],s?[...s,t]:[t])}):s&&r.push(s)};return o(e),r},index_modern_w=e=>{index_modern_n=e};
// EXTERNAL MODULE: ./node_modules/use-sync-external-store/shim/index.js
var shim = __webpack_require__(635);
;// CONCATENATED MODULE: ./node_modules/valtio/esm/vanilla.js
const vanilla_isObject = (x) => typeof x === "object" && x !== null;
const refSet = /* @__PURE__ */ new WeakSet();
const VERSION = true ? Symbol("VERSION") : 0;
const LISTENERS = true ? Symbol("LISTENERS") : 0;
const SNAPSHOT = true ? Symbol("SNAPSHOT") : 0;
const buildProxyFunction = (objectIs = Object.is, newProxy = (target, handler) => new Proxy(target, handler), canProxy = (x) => vanilla_isObject(x) && !refSet.has(x) && (Array.isArray(x) || !(Symbol.iterator in x)) && !(x instanceof WeakMap) && !(x instanceof WeakSet) && !(x instanceof Error) && !(x instanceof Number) && !(x instanceof Date) && !(x instanceof String) && !(x instanceof RegExp) && !(x instanceof ArrayBuffer), PROMISE_RESULT = true ? Symbol("PROMISE_RESULT") : 0, PROMISE_ERROR = true ? Symbol("PROMISE_ERROR") : 0, snapshotCache = /* @__PURE__ */ new WeakMap(), createSnapshot = (version, target, receiver) => {
const cache = snapshotCache.get(receiver);
if ((cache == null ? void 0 : cache[0]) === version) {
return cache[1];
}
const snapshot2 = Array.isArray(target) ? [] : Object.create(Object.getPrototypeOf(target));
index_modern_b(snapshot2, true);
snapshotCache.set(receiver, [version, snapshot2]);
Reflect.ownKeys(target).forEach((key) => {
const value = Reflect.get(target, key, receiver);
if (refSet.has(value)) {
index_modern_b(value, false);
snapshot2[key] = value;
} else if (value instanceof Promise) {
if (PROMISE_RESULT in value) {
snapshot2[key] = value[PROMISE_RESULT];
} else {
const errorOrPromise = value[PROMISE_ERROR] || value;
Object.defineProperty(snapshot2, key, {
get() {
if (PROMISE_RESULT in value) {
return value[PROMISE_RESULT];
}
throw errorOrPromise;
}
});
}
} else if (value == null ? void 0 : value[LISTENERS]) {
snapshot2[key] = value[SNAPSHOT];
} else {
snapshot2[key] = value;
}
});
return Object.freeze(snapshot2);
}, proxyCache = /* @__PURE__ */ new WeakMap(), versionHolder = [1], proxyFunction2 = (initialObject) => {
if (!vanilla_isObject(initialObject)) {
throw new Error("object required");
}
const found = proxyCache.get(initialObject);
if (found) {
return found;
}
let version = versionHolder[0];
const listeners = /* @__PURE__ */ new Set();
const notifyUpdate = (op, nextVersion = ++versionHolder[0]) => {
if (version !== nextVersion) {
version = nextVersion;
listeners.forEach((listener) => listener(op, nextVersion));
}
};
const propListeners = /* @__PURE__ */ new Map();
const getPropListener = (prop) => {
let propListener = propListeners.get(prop);
if (!propListener) {
propListener = (op, nextVersion) => {
const newOp = [...op];
newOp[1] = [prop, ...newOp[1]];
notifyUpdate(newOp, nextVersion);
};
propListeners.set(prop, propListener);
}
return propListener;
};
const popPropListener = (prop) => {
const propListener = propListeners.get(prop);
propListeners.delete(prop);
return propListener;
};
const baseObject = Array.isArray(initialObject) ? [] : Object.create(Object.getPrototypeOf(initialObject));
const handler = {
get(target, prop, receiver) {
if (prop === VERSION) {
return version;
}
if (prop === LISTENERS) {
return listeners;
}
if (prop === SNAPSHOT) {
return createSnapshot(version, target, receiver);
}
return Reflect.get(target, prop, receiver);
},
deleteProperty(target, prop) {
const prevValue = Reflect.get(target, prop);
const childListeners = prevValue == null ? void 0 : prevValue[LISTENERS];
if (childListeners) {
childListeners.delete(popPropListener(prop));
}
const deleted = Reflect.deleteProperty(target, prop);
if (deleted) {
notifyUpdate(["delete", [prop], prevValue]);
}
return deleted;
},
set(target, prop, value, receiver) {
var _a;
const hasPrevValue = Reflect.has(target, prop);
const prevValue = Reflect.get(target, prop, receiver);
if (hasPrevValue && objectIs(prevValue, value)) {
return true;
}
const childListeners = prevValue == null ? void 0 : prevValue[LISTENERS];
if (childListeners) {
childListeners.delete(popPropListener(prop));
}
if (vanilla_isObject(value)) {
value = index_modern_g(value) || value;
}
let nextValue;
if ((_a = Object.getOwnPropertyDescriptor(target, prop)) == null ? void 0 : _a.set) {
nextValue = value;
} else if (value instanceof Promise) {
nextValue = value.then((v) => {
nextValue[PROMISE_RESULT] = v;
notifyUpdate(["resolve", [prop], v]);
return v;
}).catch((e) => {
nextValue[PROMISE_ERROR] = e;
notifyUpdate(["reject", [prop], e]);
});
} else if (value == null ? void 0 : value[LISTENERS]) {
nextValue = value;
nextValue[LISTENERS].add(getPropListener(prop));
} else if (canProxy(value)) {
nextValue = vanilla_proxy(value);
nextValue[LISTENERS].add(getPropListener(prop));
} else {
nextValue = value;
}
Reflect.set(target, prop, nextValue, receiver);
notifyUpdate(["set", [prop], value, prevValue]);
return true;
}
};
const proxyObject = newProxy(baseObject, handler);
proxyCache.set(initialObject, proxyObject);
Reflect.ownKeys(initialObject).forEach((key) => {
const desc = Object.getOwnPropertyDescriptor(
initialObject,
key
);
if (desc.get || desc.set) {
Object.defineProperty(baseObject, key, desc);
} else {
proxyObject[key] = initialObject[key];
}
});
return proxyObject;
}) => [
proxyFunction2,
refSet,
VERSION,
LISTENERS,
SNAPSHOT,
objectIs,
newProxy,
canProxy,
PROMISE_RESULT,
PROMISE_ERROR,
snapshotCache,
createSnapshot,
proxyCache,
versionHolder
];
const [proxyFunction] = buildProxyFunction();
function vanilla_proxy(initialObject = {}) {
return proxyFunction(initialObject);
}
function vanilla_getVersion(proxyObject) {
return vanilla_isObject(proxyObject) ? proxyObject[VERSION] : void 0;
}
function vanilla_subscribe(proxyObject, callback, notifyInSync) {
if ( true && !(proxyObject == null ? void 0 : proxyObject[LISTENERS])) {
console.warn("Please use proxy object");
}
let promise;
const ops = [];
const listener = (op) => {
ops.push(op);
if (notifyInSync) {
callback(ops.splice(0));
return;
}
if (!promise) {
promise = Promise.resolve().then(() => {
promise = void 0;
callback(ops.splice(0));
});
}
};
proxyObject[LISTENERS].add(listener);
return () => {
proxyObject[LISTENERS].delete(listener);
};
}
function vanilla_snapshot(proxyObject) {
if ( true && !(proxyObject == null ? void 0 : proxyObject[SNAPSHOT])) {
console.warn("Please use proxy object");
}
return proxyObject[SNAPSHOT];
}
function vanilla_ref(obj) {
refSet.add(obj);
return obj;
}
const unstable_buildProxyFunction = (/* unused pure expression or super */ null && (buildProxyFunction));
;// CONCATENATED MODULE: ./node_modules/valtio/esm/index.js
const { useSyncExternalStore } = shim;
const useAffectedDebugValue = (state, affected) => {
const pathList = (0,external_React_.useRef)();
(0,external_React_.useEffect)(() => {
pathList.current = index_modern_O(state, affected);
});
(0,external_React_.useDebugValue)(pathList.current);
};
function useSnapshot(proxyObject, options) {
const notifyInSync = options == null ? void 0 : options.sync;
const lastSnapshot = (0,external_React_.useRef)();
const lastAffected = (0,external_React_.useRef)();
let inRender = true;
const currSnapshot = useSyncExternalStore(
(0,external_React_.useCallback)(
(callback) => {
const unsub = vanilla_subscribe(proxyObject, callback, notifyInSync);
callback();
return unsub;
},
[proxyObject, notifyInSync]
),
() => {
const nextSnapshot = vanilla_snapshot(proxyObject);
try {
if (!inRender && lastSnapshot.current && lastAffected.current && !index_modern_y(
lastSnapshot.current,
nextSnapshot,
lastAffected.current,
/* @__PURE__ */ new WeakMap()
)) {
return lastSnapshot.current;
}
} catch (e) {
}
return nextSnapshot;
},
() => vanilla_snapshot(proxyObject)
);
inRender = false;
const currAffected = /* @__PURE__ */ new WeakMap();
(0,external_React_.useEffect)(() => {
lastSnapshot.current = currSnapshot;
lastAffected.current = currAffected;
});
if (true) {
useAffectedDebugValue(currSnapshot, currAffected);
}
const proxyCache = (0,external_React_.useMemo)(() => /* @__PURE__ */ new WeakMap(), []);
return index_modern_i(currSnapshot, currAffected, proxyCache);
}
;// CONCATENATED MODULE: ./node_modules/valtio/esm/utils.js
function subscribeKey(proxyObject, key, callback, notifyInSync) {
return subscribe(
proxyObject,
(ops) => {
if (ops.some((op) => op[1][0] === key)) {
callback(proxyObject[key]);
}
},
notifyInSync
);
}
let currentCleanups;
function watch(callback, options) {
let alive = true;
const cleanups = /* @__PURE__ */ new Set();
const subscriptions = /* @__PURE__ */ new Map();
const cleanup = () => {
if (alive) {
alive = false;
cleanups.forEach((clean) => clean());
cleanups.clear();
subscriptions.forEach((unsubscribe) => unsubscribe());
subscriptions.clear();
}
};
const revalidate = () => {
if (!alive) {
return;
}
cleanups.forEach((clean) => clean());
cleanups.clear();
const proxiesToSubscribe = /* @__PURE__ */ new Set();
const parent = currentCleanups;
currentCleanups = cleanups;
try {
const cleanupReturn = callback((proxyObject) => {
proxiesToSubscribe.add(proxyObject);
return proxyObject;
});
if (cleanupReturn) {
cleanups.add(cleanupReturn);
}
} finally {
currentCleanups = parent;
}
subscriptions.forEach((unsubscribe, proxyObject) => {
if (proxiesToSubscribe.has(proxyObject)) {
proxiesToSubscribe.delete(proxyObject);
} else {
subscriptions.delete(proxyObject);
unsubscribe();
}
});
proxiesToSubscribe.forEach((proxyObject) => {
const unsubscribe = subscribe(proxyObject, revalidate, options == null ? void 0 : options.sync);
subscriptions.set(proxyObject, unsubscribe);
});
};
if (currentCleanups) {
currentCleanups.add(cleanup);
}
revalidate();
return cleanup;
}
const DEVTOOLS = Symbol();
function devtools(proxyObject, options) {
if (typeof options === "string") {
console.warn(
"string name option is deprecated, use { name }. https://github.com/pmndrs/valtio/pull/400"
);
options = { name: options };
}
const { enabled, name = "" } = options || {};
let extension;
try {
extension = (enabled != null ? enabled : (/* unsupported import.meta.env */ undefined && 0) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
} catch {
}
if (!extension) {
if ( true && enabled) {
console.warn("[Warning] Please install/enable Redux devtools extension");
}
return;
}
let isTimeTraveling = false;
const devtools2 = extension.connect({ name });
const unsub1 = subscribe(proxyObject, (ops) => {
const action = ops.filter(([_, path]) => path[0] !== DEVTOOLS).map(([op, path]) => `${op}:${path.map(String).join(".")}`).join(", ");
if (!action) {
return;
}
if (isTimeTraveling) {
isTimeTraveling = false;
} else {
const snapWithoutDevtools = Object.assign({}, snapshot(proxyObject));
delete snapWithoutDevtools[DEVTOOLS];
devtools2.send(
{
type: action,
updatedAt: new Date().toLocaleString()
},
snapWithoutDevtools
);
}
});
const unsub2 = devtools2.subscribe((message) => {
var _a, _b, _c, _d, _e, _f;
if (message.type === "ACTION" && message.payload) {
try {
Object.assign(proxyObject, JSON.parse(message.payload));
} catch (e) {
console.error(
"please dispatch a serializable value that JSON.parse() and proxy() support\n",
e
);
}
}
if (message.type === "DISPATCH" && message.state) {
if (((_a = message.payload) == null ? void 0 : _a.type) === "JUMP_TO_ACTION" || ((_b = message.payload) == null ? void 0 : _b.type) === "JUMP_TO_STATE") {
isTimeTraveling = true;
const state = JSON.parse(message.state);
Object.assign(proxyObject, state);
}
proxyObject[DEVTOOLS] = message;
} else if (message.type === "DISPATCH" && ((_c = message.payload) == null ? void 0 : _c.type) === "COMMIT") {
devtools2.init(snapshot(proxyObject));
} else if (message.type === "DISPATCH" && ((_d = message.payload) == null ? void 0 : _d.type) === "IMPORT_STATE") {
const actions = (_e = message.payload.nextLiftedState) == null ? void 0 : _e.actionsById;
const computedStates = ((_f = message.payload.nextLiftedState) == null ? void 0 : _f.computedStates) || [];
isTimeTraveling = true;
computedStates.forEach(({ state }, index) => {
const action = actions[index] || "No action found";
Object.assign(proxyObject, state);
if (index === 0) {
devtools2.init(snapshot(proxyObject));
} else {
devtools2.send(action, snapshot(proxyObject));
}
});
}
});
devtools2.init(snapshot(proxyObject));
return () => {
unsub1();
unsub2 == null ? void 0 : unsub2();
};
}
const sourceObjectMap = /* @__PURE__ */ new WeakMap();
const derivedObjectMap = /* @__PURE__ */ new WeakMap();
const markPending = (sourceObject, callback) => {
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry) {
sourceObjectEntry[0].forEach((subscription) => {
const { d: derivedObject } = subscription;
if (sourceObject !== derivedObject) {
markPending(derivedObject);
}
});
++sourceObjectEntry[2];
if (callback) {
sourceObjectEntry[3].add(callback);
}
}
};
const checkPending = (sourceObject, callback) => {
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry == null ? void 0 : sourceObjectEntry[2]) {
sourceObjectEntry[3].add(callback);
return true;
}
return false;
};
const unmarkPending = (sourceObject) => {
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry) {
--sourceObjectEntry[2];
if (!sourceObjectEntry[2]) {
sourceObjectEntry[3].forEach((callback) => callback());
sourceObjectEntry[3].clear();
}
sourceObjectEntry[0].forEach((subscription) => {
const { d: derivedObject } = subscription;
if (sourceObject !== derivedObject) {
unmarkPending(derivedObject);
}
});
}
};
const addSubscription = (subscription) => {
const { s: sourceObject, d: derivedObject } = subscription;
let derivedObjectEntry = derivedObjectMap.get(derivedObject);
if (!derivedObjectEntry) {
derivedObjectEntry = [/* @__PURE__ */ new Set()];
derivedObjectMap.set(subscription.d, derivedObjectEntry);
}
derivedObjectEntry[0].add(subscription);
let sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (!sourceObjectEntry) {
const subscriptions = /* @__PURE__ */ new Set();
const unsubscribe = vanilla_subscribe(
sourceObject,
(ops) => {
subscriptions.forEach((subscription2) => {
const {
d: derivedObject2,
c: callback,
n: notifyInSync,
i: ignoreKeys
} = subscription2;
if (sourceObject === derivedObject2 && ops.every(
(op) => op[1].length === 1 && ignoreKeys.includes(op[1][0])
)) {
return;
}
if (subscription2.p) {
return;
}
markPending(sourceObject, callback);
if (notifyInSync) {
unmarkPending(sourceObject);
} else {
subscription2.p = Promise.resolve().then(() => {
delete subscription2.p;
unmarkPending(sourceObject);
});
}
});
},
true
);
sourceObjectEntry = [subscriptions, unsubscribe, 0, /* @__PURE__ */ new Set()];
sourceObjectMap.set(sourceObject, sourceObjectEntry);
}
sourceObjectEntry[0].add(subscription);
};
const removeSubscription = (subscription) => {
const { s: sourceObject, d: derivedObject } = subscription;
const derivedObjectEntry = derivedObjectMap.get(derivedObject);
derivedObjectEntry == null ? void 0 : derivedObjectEntry[0].delete(subscription);
if ((derivedObjectEntry == null ? void 0 : derivedObjectEntry[0].size) === 0) {
derivedObjectMap.delete(derivedObject);
}
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry) {
const [subscriptions, unsubscribe] = sourceObjectEntry;
subscriptions.delete(subscription);
if (!subscriptions.size) {
unsubscribe();
sourceObjectMap.delete(sourceObject);
}
}
};
const listSubscriptions = (derivedObject) => {
const derivedObjectEntry = derivedObjectMap.get(derivedObject);
if (derivedObjectEntry) {
return Array.from(derivedObjectEntry[0]);
}
return [];
};
const unstable_deriveSubscriptions = {
add: addSubscription,
remove: removeSubscription,
list: listSubscriptions
};
function derive(derivedFns, options) {
const proxyObject = (options == null ? void 0 : options.proxy) || proxy({});
const notifyInSync = !!(options == null ? void 0 : options.sync);
const derivedKeys = Object.keys(derivedFns);
derivedKeys.forEach((key) => {
if (Object.getOwnPropertyDescriptor(proxyObject, key)) {
throw new Error("object property already defined");
}
const fn = derivedFns[key];
let lastDependencies = null;
const evaluate = () => {
if (lastDependencies) {
if (Array.from(lastDependencies).map(([p]) => checkPending(p, evaluate)).some((isPending) => isPending)) {
return;
}
if (Array.from(lastDependencies).every(
([p, entry]) => getVersion(p) === entry.v
)) {
return;
}
}
const dependencies = /* @__PURE__ */ new Map();
const get = (p) => {
dependencies.set(p, { v: getVersion(p) });
return p;
};
const value = fn(get);
const subscribeToDependencies = () => {
dependencies.forEach((entry, p) => {
var _a;
const lastSubscription = (_a = lastDependencies == null ? void 0 : lastDependencies.get(p)) == null ? void 0 : _a.s;
if (lastSubscription) {
entry.s = lastSubscription;
} else {
const subscription = {
s: p,
d: proxyObject,
k: key,
c: evaluate,
n: notifyInSync,
i: derivedKeys
};
addSubscription(subscription);
entry.s = subscription;
}
});
lastDependencies == null ? void 0 : lastDependencies.forEach((entry, p) => {
if (!dependencies.has(p) && entry.s) {
removeSubscription(entry.s);
}
});
lastDependencies = dependencies;
};
if (value instanceof Promise) {
value.finally(subscribeToDependencies);
} else {
subscribeToDependencies();
}
proxyObject[key] = value;
};
evaluate();
});
return proxyObject;
}
function underive(proxyObject, options) {
const keysToDelete = (options == null ? void 0 : options.delete) ? /* @__PURE__ */ new Set() : null;
listSubscriptions(proxyObject).forEach((subscription) => {
const { k: key } = subscription;
if (!(options == null ? void 0 : options.keys) || options.keys.includes(key)) {
removeSubscription(subscription);
if (keysToDelete) {
keysToDelete.add(key);
}
}
});
if (keysToDelete) {
keysToDelete.forEach((key) => {
delete proxyObject[key];
});
}
}
function addComputed_DEPRECATED(proxyObject, computedFns_FAKE, targetObject = proxyObject) {
console.warn(
"addComputed is deprecated. Please consider using `derive` or `proxyWithComputed` instead. Falling back to emulation with derive. https://github.com/pmndrs/valtio/pull/201"
);
const derivedFns = {};
Object.keys(computedFns_FAKE).forEach((key) => {
derivedFns[key] = (get) => computedFns_FAKE[key](get(proxyObject));
});
return derive(derivedFns, { proxy: targetObject });
}
function proxyWithComputed(initialObject, computedFns) {
Object.keys(computedFns).forEach((key) => {
if (Object.getOwnPropertyDescriptor(initialObject, key)) {
throw new Error("object property already defined");
}
const computedFn = computedFns[key];
const { get, set } = typeof computedFn === "function" ? { get: computedFn } : computedFn;
const desc = {};
desc.get = () => get(snapshot(proxyObject));
if (set) {
desc.set = (newValue) => set(proxyObject, newValue);
}
Object.defineProperty(initialObject, key, desc);
});
const proxyObject = proxy(initialObject);
return proxyObject;
}
const utils_isObject = (x) => typeof x === "object" && x !== null;
const deepClone = (obj) => {
if (!utils_isObject(obj)) {
return obj;
}
const baseObject = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj));
Reflect.ownKeys(obj).forEach((key) => {
baseObject[key] = deepClone(obj[key]);
});
return baseObject;
};
function proxyWithHistory(initialValue, skipSubscribe = false) {
const proxyObject = proxy({
value: initialValue,
history: ref({
wip: void 0,
snapshots: [],
index: -1
}),
canUndo: () => proxyObject.history.index > 0,
undo: () => {
if (proxyObject.canUndo()) {
proxyObject.value = proxyObject.history.wip = deepClone(
proxyObject.history.snapshots[--proxyObject.history.index]
);
}
},
canRedo: () => proxyObject.history.index < proxyObject.history.snapshots.length - 1,
redo: () => {
if (proxyObject.canRedo()) {
proxyObject.value = proxyObject.history.wip = deepClone(
proxyObject.history.snapshots[++proxyObject.history.index]
);
}
},
saveHistory: () => {
proxyObject.history.snapshots.splice(proxyObject.history.index + 1);
proxyObject.history.snapshots.push(snapshot(proxyObject).value);
++proxyObject.history.index;
},
subscribe: () => subscribe(proxyObject, (ops) => {
if (ops.every(
(op) => op[1][0] === "value" && (op[0] !== "set" || op[2] !== proxyObject.history.wip)
)) {
proxyObject.saveHistory();
}
})
});
proxyObject.saveHistory();
if (!skipSubscribe) {
proxyObject.subscribe();
}
return proxyObject;
}
function proxySet(initialValues) {
const set = proxy({
data: Array.from(new Set(initialValues)),
has(value) {
return this.data.indexOf(value) !== -1;
},
add(value) {
let hasProxy = false;
if (typeof value === "object" && value !== null) {
hasProxy = this.data.indexOf(proxy(value)) !== -1;
}
if (this.data.indexOf(value) === -1 && !hasProxy) {
this.data.push(value);
}
return this;
},
delete(value) {
const index = this.data.indexOf(value);
if (index === -1) {
return false;
}
this.data.splice(index, 1);
return true;
},
clear() {
this.data.splice(0);
},
get size() {
return this.data.length;
},
forEach(cb) {
this.data.forEach((value) => {
cb(value, value, this);
});
},
get [Symbol.toStringTag]() {
return "Set";
},
toJSON() {
return {};
},
[Symbol.iterator]() {
return this.data[Symbol.iterator]();
},
values() {
return this.data.values();
},
keys() {
return this.data.values();
},
entries() {
return new Set(this.data).entries();
}
});
Object.defineProperties(set, {
data: {
enumerable: false
},
size: {
enumerable: false
},
toJSON: {
enumerable: false
}
});
Object.seal(set);
return set;
}
function proxyMap(entries) {
const map = vanilla_proxy({
data: Array.from(entries || []),
has(key) {
return this.data.some((p) => p[0] === key);
},
set(key, value) {
const record = this.data.find((p) => p[0] === key);
if (record) {
record[1] = value;
} else {
this.data.push([key, value]);
}
return this;
},
get(key) {
var _a;
return (_a = this.data.find((p) => p[0] === key)) == null ? void 0 : _a[1];
},
delete(key) {
const index = this.data.findIndex((p) => p[0] === key);
if (index === -1) {
return false;
}
this.data.splice(index, 1);
return true;
},
clear() {
this.data.splice(0);
},
get size() {
return this.data.length;
},
toJSON() {
return {};
},
forEach(cb) {
this.data.forEach((p) => {
cb(p[1], p[0], this);
});
},
keys() {
return this.data.map((p) => p[0]).values();
},
values() {
return this.data.map((p) => p[1]).values();
},
entries() {
return new Map(this.data).entries();
},
get [Symbol.toStringTag]() {
return "Map";
},
[Symbol.iterator]() {
return this.entries();
}
});
Object.defineProperties(map, {
data: {
enumerable: false
},
size: {
enumerable: false
},
toJSON: {
enumerable: false
}
});
Object.seal(map);
return map;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot-fill-context.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const SlotFillContext = (0,external_wp_element_namespaceObject.createContext)({
slots: proxyMap(),
fills: proxyMap(),
registerSlot: () => {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
},
updateSlot: () => {},
unregisterSlot: () => {},
registerFill: () => {},
unregisterFill: () => {}
});
/* harmony default export */ var slot_fill_context = (SlotFillContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/use-slot.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSlot(name) {
const registry = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const slots = useSnapshot(registry.slots, {
sync: true
}); // The important bit here is that the `useSnapshot` call ensures that the
// hook only causes a re-render if the slot with the given name changes,
// not any other slot.
const slot = slots.get(name);
const api = (0,external_wp_element_namespaceObject.useMemo)(() => ({
updateSlot: fillProps => registry.updateSlot(name, fillProps),
unregisterSlot: ref => registry.unregisterSlot(name, ref),
registerFill: ref => registry.registerFill(name, ref),
unregisterFill: ref => registry.unregisterFill(name, ref)
}), [name, registry]);
return { ...slot,
...api
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/context.js
// @ts-nocheck
/**
* WordPress dependencies
*/
const context_SlotFillContext = (0,external_wp_element_namespaceObject.createContext)({
registerSlot: () => {},
unregisterSlot: () => {},
registerFill: () => {},
unregisterFill: () => {},
getSlot: () => {},
getFills: () => {},
subscribe: () => {}
});
/* harmony default export */ var context = (context_SlotFillContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/use-slot.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* React hook returning the active slot given a name.
*
* @param {string} name Slot name.
* @return {Object} Slot object.
*/
const use_slot_useSlot = name => {
const {
getSlot,
subscribe
} = (0,external_wp_element_namespaceObject.useContext)(context);
return (0,external_wp_element_namespaceObject.useSyncExternalStore)(subscribe, () => getSlot(name), () => getSlot(name));
};
/* harmony default export */ var use_slot = (use_slot_useSlot);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/fill.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Fill({
name,
children
}) {
const {
registerFill,
unregisterFill
} = (0,external_wp_element_namespaceObject.useContext)(context);
const slot = use_slot(name);
const ref = (0,external_wp_element_namespaceObject.useRef)({
name,
children
});
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const refValue = ref.current;
registerFill(name, refValue);
return () => unregisterFill(name, refValue); // Ignore reason: the useLayoutEffects here are written to fire at specific times, and introducing new dependencies could cause unexpected changes in behavior.
// We'll leave them as-is until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
ref.current.children = children;
if (slot) {
slot.forceUpdate();
} // Ignore reason: the useLayoutEffects here are written to fire at specific times, and introducing new dependencies could cause unexpected changes in behavior.
// We'll leave them as-is until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [children]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (name === ref.current.name) {
// Ignore initial effect.
return;
}
unregisterFill(ref.current.name, ref.current);
ref.current.name = name;
registerFill(name, ref.current); // Ignore reason: the useLayoutEffects here are written to fire at specific times, and introducing new dependencies could cause unexpected changes in behavior.
// We'll leave them as-is until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [name]);
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/slot.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Whether the argument is a function.
*
* @param {*} maybeFunc The argument to check.
* @return {boolean} True if the argument is a function, false otherwise.
*/
function isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
class SlotComponent extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.isUnmounted = false;
}
componentDidMount() {
const {
registerSlot
} = this.props;
this.isUnmounted = false;
registerSlot(this.props.name, this);
}
componentWillUnmount() {
const {
unregisterSlot
} = this.props;
this.isUnmounted = true;
unregisterSlot(this.props.name, this);
}
componentDidUpdate(prevProps) {
const {
name,
unregisterSlot,
registerSlot
} = this.props;
if (prevProps.name !== name) {
unregisterSlot(prevProps.name);
registerSlot(name, this);
}
}
forceUpdate() {
if (this.isUnmounted) {
return;
}
super.forceUpdate();
}
render() {
var _getFills;
const {
children,
name,
fillProps = {},
getFills
} = this.props;
const fills = ((_getFills = getFills(name, this)) !== null && _getFills !== void 0 ? _getFills : []).map(fill => {
const fillChildren = isFunction(fill.children) ? fill.children(fillProps) : fill.children;
return external_wp_element_namespaceObject.Children.map(fillChildren, (child, childIndex) => {
if (!child || typeof child === 'string') {
return child;
}
const childKey = child.key || childIndex;
return (0,external_wp_element_namespaceObject.cloneElement)(child, {
key: childKey
});
});
}).filter( // In some cases fills are rendered only when some conditions apply.
// This ensures that we only use non-empty fills when rendering, i.e.,
// it allows us to render wrappers only when the fills are actually present.
element => !(0,external_wp_element_namespaceObject.isEmptyElement)(element));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isFunction(children) ? children(fills) : fills);
}
}
const Slot = props => (0,external_wp_element_namespaceObject.createElement)(context.Consumer, null, ({
registerSlot,
unregisterSlot,
getFills
}) => (0,external_wp_element_namespaceObject.createElement)(SlotComponent, { ...props,
registerSlot: registerSlot,
unregisterSlot: unregisterSlot,
getFills: getFills
}));
/* harmony default export */ var slot = (Slot);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/node_modules/uuid/dist/esm-browser/rng.js
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
// lazy load so that environments that need to polyfill have a chance to do so
if (!getRandomValues) {
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
return getRandomValues(rnds8);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/node_modules/uuid/dist/esm-browser/regex.js
/* harmony default export */ var regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/node_modules/uuid/dist/esm-browser/validate.js
function validate(uuid) {
return typeof uuid === 'string' && regex.test(uuid);
}
/* harmony default export */ var esm_browser_validate = (validate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/node_modules/uuid/dist/esm-browser/stringify.js
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var stringify_i = 0; stringify_i < 256; ++stringify_i) {
byteToHex.push((stringify_i + 0x100).toString(16).substr(1));
}
function stringify_stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!esm_browser_validate(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
/* harmony default export */ var esm_browser_stringify = (stringify_stringify);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return esm_browser_stringify(rnds);
}
/* harmony default export */ var esm_browser_v4 = (v4);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/style-provider/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const uuidCache = new Set();
const memoizedCreateCacheWithContainer = memize(container => {
// Emotion only accepts alphabetical and hyphenated keys so we just
// strip the numbers from the UUID. It _should_ be fine.
let key = esm_browser_v4().replace(/[0-9]/g, '');
while (uuidCache.has(key)) {
key = esm_browser_v4().replace(/[0-9]/g, '');
}
uuidCache.add(key);
return createCache({
container,
key
});
});
function StyleProvider(props) {
const {
children,
document
} = props;
if (!document) {
return null;
}
const cache = memoizedCreateCacheWithContainer(document.head);
return (0,external_wp_element_namespaceObject.createElement)(CacheProvider, {
value: cache
}, children);
}
/* harmony default export */ var style_provider = (StyleProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/fill.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useForceUpdate() {
const [, setState] = (0,external_wp_element_namespaceObject.useState)({});
const mounted = (0,external_wp_element_namespaceObject.useRef)(true);
(0,external_wp_element_namespaceObject.useEffect)(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
return () => {
if (mounted.current) {
setState({});
}
};
}
function fill_Fill({
name,
children
}) {
const {
registerFill,
unregisterFill,
...slot
} = useSlot(name);
const rerender = useForceUpdate();
const ref = (0,external_wp_element_namespaceObject.useRef)({
rerender
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We register fills so we can keep track of their existence.
// Some Slot implementations need to know if there're already fills
// registered so they can choose to render themselves or not.
registerFill(ref);
return () => {
unregisterFill(ref);
};
}, [registerFill, unregisterFill]);
if (!slot.ref || !slot.ref.current) {
return null;
}
if (typeof children === 'function') {
children = children(slot.fillProps);
} // When using a `Fill`, the `children` will be rendered in the document of the
// `Slot`. This means that we need to wrap the `children` in a `StyleProvider`
// to make sure we're referencing the right document/iframe (instead of the
// context of the `Fill`'s parent).
const wrappedChildren = (0,external_wp_element_namespaceObject.createElement)(style_provider, {
document: slot.ref.current.ownerDocument
}, children);
return (0,external_wp_element_namespaceObject.createPortal)(wrappedChildren, slot.ref.current);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function slot_Slot({
name,
fillProps = {},
as: Component = 'div',
...props
}, forwardedRef) {
const {
registerSlot,
unregisterSlot,
...registry
} = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const ref = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
registerSlot(name, ref, fillProps);
return () => {
unregisterSlot(name, ref);
}; // Ignore reason: We don't want to unregister and register the slot whenever
// `fillProps` change, which would cause the fill to be re-mounted. Instead,
// we can just update the slot (see hook below).
// For more context, see https://github.com/WordPress/gutenberg/pull/44403#discussion_r994415973
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [registerSlot, unregisterSlot, name]); // fillProps may be an update that interacts with the layout, so we
// useLayoutEffect.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
registry.updateSlot(name, fillProps);
});
return (0,external_wp_element_namespaceObject.createElement)(Component, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([forwardedRef, ref]),
...props
});
}
/* harmony default export */ var bubbles_virtually_slot = ((0,external_wp_element_namespaceObject.forwardRef)(slot_Slot));
;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot-fill-provider.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function createSlotRegistry() {
const slots = proxyMap();
const fills = proxyMap();
function registerSlot(name, ref, fillProps) {
const slot = slots.get(name) || {};
slots.set(name, vanilla_ref({ ...slot,
ref: ref || slot.ref,
fillProps: fillProps || slot.fillProps || {}
}));
}
function unregisterSlot(name, ref) {
// Make sure we're not unregistering a slot registered by another element
// See https://github.com/WordPress/gutenberg/pull/19242#issuecomment-590295412
if (slots.get(name)?.ref === ref) {
slots.delete(name);
}
}
function updateSlot(name, fillProps) {
const slot = slots.get(name);
if (!slot) {
return;
}
if (external_wp_isShallowEqual_default()(slot.fillProps, fillProps)) {
return;
}
slot.fillProps = fillProps;
const slotFills = fills.get(name);
if (slotFills) {
// Force update fills.
slotFills.map(fill => fill.current.rerender());
}
}
function registerFill(name, ref) {
fills.set(name, vanilla_ref([...(fills.get(name) || []), ref]));
}
function unregisterFill(name, ref) {
const fillsForName = fills.get(name);
if (!fillsForName) {
return;
}
fills.set(name, vanilla_ref(fillsForName.filter(fillRef => fillRef !== ref)));
}
return {
slots,
fills,
registerSlot,
updateSlot,
unregisterSlot,
registerFill,
unregisterFill
};
}
function SlotFillProvider({
children
}) {
const [registry] = (0,external_wp_element_namespaceObject.useState)(createSlotRegistry);
return (0,external_wp_element_namespaceObject.createElement)(slot_fill_context.Provider, {
value: registry
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/provider.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
class provider_SlotFillProvider extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.registerSlot = this.registerSlot.bind(this);
this.registerFill = this.registerFill.bind(this);
this.unregisterSlot = this.unregisterSlot.bind(this);
this.unregisterFill = this.unregisterFill.bind(this);
this.getSlot = this.getSlot.bind(this);
this.getFills = this.getFills.bind(this);
this.subscribe = this.subscribe.bind(this);
this.slots = {};
this.fills = {};
this.listeners = [];
this.contextValue = {
registerSlot: this.registerSlot,
unregisterSlot: this.unregisterSlot,
registerFill: this.registerFill,
unregisterFill: this.unregisterFill,
getSlot: this.getSlot,
getFills: this.getFills,
subscribe: this.subscribe
};
}
registerSlot(name, slot) {
const previousSlot = this.slots[name];
this.slots[name] = slot;
this.triggerListeners(); // Sometimes the fills are registered after the initial render of slot
// But before the registerSlot call, we need to rerender the slot.
this.forceUpdateSlot(name); // If a new instance of a slot is being mounted while another with the
// same name exists, force its update _after_ the new slot has been
// assigned into the instance, such that its own rendering of children
// will be empty (the new Slot will subsume all fills for this name).
if (previousSlot) {
previousSlot.forceUpdate();
}
}
registerFill(name, instance) {
this.fills[name] = [...(this.fills[name] || []), instance];
this.forceUpdateSlot(name);
}
unregisterSlot(name, instance) {
// If a previous instance of a Slot by this name unmounts, do nothing,
// as the slot and its fills should only be removed for the current
// known instance.
if (this.slots[name] !== instance) {
return;
}
delete this.slots[name];
this.triggerListeners();
}
unregisterFill(name, instance) {
var _this$fills$name$filt;
this.fills[name] = (_this$fills$name$filt = this.fills[name]?.filter(fill => fill !== instance)) !== null && _this$fills$name$filt !== void 0 ? _this$fills$name$filt : [];
this.forceUpdateSlot(name);
}
getSlot(name) {
return this.slots[name];
}
getFills(name, slotInstance) {
// Fills should only be returned for the current instance of the slot
// in which they occupy.
if (this.slots[name] !== slotInstance) {
return [];
}
return this.fills[name];
}
forceUpdateSlot(name) {
const slot = this.getSlot(name);
if (slot) {
slot.forceUpdate();
}
}
triggerListeners() {
this.listeners.forEach(listener => listener());
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
};
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(context.Provider, {
value: this.contextValue
}, this.props.children);
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/index.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function slot_fill_Fill(props) {
// We're adding both Fills here so they can register themselves before
// their respective slot has been registered. Only the Fill that has a slot
// will render. The other one will return null.
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(Fill, { ...props
}), (0,external_wp_element_namespaceObject.createElement)(fill_Fill, { ...props
}));
}
const slot_fill_Slot = (0,external_wp_element_namespaceObject.forwardRef)(({
bubblesVirtually,
...props
}, ref) => {
if (bubblesVirtually) {
return (0,external_wp_element_namespaceObject.createElement)(bubbles_virtually_slot, { ...props,
ref: ref
});
}
return (0,external_wp_element_namespaceObject.createElement)(slot, { ...props
});
});
function Provider({
children,
...props
}) {
return (0,external_wp_element_namespaceObject.createElement)(provider_SlotFillProvider, { ...props
}, (0,external_wp_element_namespaceObject.createElement)(SlotFillProvider, null, children));
}
function createSlotFill(key) {
const baseName = typeof key === 'symbol' ? key.description : key;
const FillComponent = props => (0,external_wp_element_namespaceObject.createElement)(slot_fill_Fill, {
name: key,
...props
});
FillComponent.displayName = `${baseName}Fill`;
const SlotComponent = props => (0,external_wp_element_namespaceObject.createElement)(slot_fill_Slot, {
name: key,
...props
});
SlotComponent.displayName = `${baseName}Slot`;
SlotComponent.__unstableName = key;
return {
Fill: FillComponent,
Slot: SlotComponent
};
}
const createPrivateSlotFill = name => {
const privateKey = Symbol(name);
const privateSlotFill = createSlotFill(privateKey);
return {
privateKey,
...privateSlotFill
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/utils.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* Internal dependencies
*/
const POSITION_TO_PLACEMENT = {
bottom: 'bottom',
top: 'top',
'middle left': 'left',
'middle right': 'right',
'bottom left': 'bottom-end',
'bottom center': 'bottom',
'bottom right': 'bottom-start',
'top left': 'top-end',
'top center': 'top',
'top right': 'top-start',
'middle left left': 'left',
'middle left right': 'left',
'middle left bottom': 'left-end',
'middle left top': 'left-start',
'middle right left': 'right',
'middle right right': 'right',
'middle right bottom': 'right-end',
'middle right top': 'right-start',
'bottom left left': 'bottom-end',
'bottom left right': 'bottom-end',
'bottom left bottom': 'bottom-end',
'bottom left top': 'bottom-end',
'bottom center left': 'bottom',
'bottom center right': 'bottom',
'bottom center bottom': 'bottom',
'bottom center top': 'bottom',
'bottom right left': 'bottom-start',
'bottom right right': 'bottom-start',
'bottom right bottom': 'bottom-start',
'bottom right top': 'bottom-start',
'top left left': 'top-end',
'top left right': 'top-end',
'top left bottom': 'top-end',
'top left top': 'top-end',
'top center left': 'top',
'top center right': 'top',
'top center bottom': 'top',
'top center top': 'top',
'top right left': 'top-start',
'top right right': 'top-start',
'top right bottom': 'top-start',
'top right top': 'top-start',
// `middle`/`middle center [corner?]` positions are associated to a fallback
// `bottom` placement because there aren't any corresponding placement values.
middle: 'bottom',
'middle center': 'bottom',
'middle center bottom': 'bottom',
'middle center left': 'bottom',
'middle center right': 'bottom',
'middle center top': 'bottom'
};
/**
* Converts the `Popover`'s legacy "position" prop to the new "placement" prop
* (used by `floating-ui`).
*
* @param position The legacy position
* @return The corresponding placement
*/
const positionToPlacement = position => {
var _POSITION_TO_PLACEMEN;
return (_POSITION_TO_PLACEMEN = POSITION_TO_PLACEMENT[position]) !== null && _POSITION_TO_PLACEMEN !== void 0 ? _POSITION_TO_PLACEMEN : 'bottom';
};
/**
* @typedef AnimationOrigin
* @type {Object}
* @property {number} originX A number between 0 and 1 (in CSS logical properties jargon, 0 is "start", 0.5 is "center", and 1 is "end")
* @property {number} originY A number between 0 and 1 (0 is top, 0.5 is center, and 1 is bottom)
*/
const PLACEMENT_TO_ANIMATION_ORIGIN = {
top: {
originX: 0.5,
originY: 1
},
// open from bottom, center
'top-start': {
originX: 0,
originY: 1
},
// open from bottom, left
'top-end': {
originX: 1,
originY: 1
},
// open from bottom, right
right: {
originX: 0,
originY: 0.5
},
// open from middle, left
'right-start': {
originX: 0,
originY: 0
},
// open from top, left
'right-end': {
originX: 0,
originY: 1
},
// open from bottom, left
bottom: {
originX: 0.5,
originY: 0
},
// open from top, center
'bottom-start': {
originX: 0,
originY: 0
},
// open from top, left
'bottom-end': {
originX: 1,
originY: 0
},
// open from top, right
left: {
originX: 1,
originY: 0.5
},
// open from middle, right
'left-start': {
originX: 1,
originY: 0
},
// open from top, right
'left-end': {
originX: 1,
originY: 1
},
// open from bottom, right
overlay: {
originX: 0.5,
originY: 0.5
} // open from center, center
};
/**
* Given the floating-ui `placement`, compute the framer-motion props for the
* popover's entry animation.
*
* @param placement A placement string from floating ui
* @return The object containing the motion props
*/
const placementToMotionAnimationProps = placement => {
const translateProp = placement.startsWith('top') || placement.startsWith('bottom') ? 'translateY' : 'translateX';
const translateDirection = placement.startsWith('top') || placement.startsWith('left') ? 1 : -1;
return {
style: PLACEMENT_TO_ANIMATION_ORIGIN[placement],
initial: {
opacity: 0,
scale: 0,
[translateProp]: `${2 * translateDirection}em`
},
animate: {
opacity: 1,
scale: 1,
[translateProp]: 0
},
transition: {
duration: 0.1,
ease: [0, 0, 0.2, 1]
}
};
};
/**
* Returns the offset of a document's frame element.
*
* @param document The iframe's owner document.
*
* @return The offset of the document's frame element, or undefined if the
* document has no frame element.
*/
const getFrameOffset = document => {
const frameElement = document?.defaultView?.frameElement;
if (!frameElement) {
return;
}
const iframeRect = frameElement.getBoundingClientRect();
return {
x: iframeRect.left,
y: iframeRect.top
};
};
const getFrameScale = document => {
const frameElement = document?.defaultView?.frameElement;
if (!frameElement) {
return {
x: 1,
y: 1
};
}
const rect = frameElement.getBoundingClientRect();
return {
x: rect.width / frameElement.offsetWidth,
y: rect.height / frameElement.offsetHeight
};
};
const getReferenceOwnerDocument = ({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
fallbackDocument
}) => {
var _resultingReferenceOw;
// In floating-ui's terms:
// - "reference" refers to the popover's anchor element.
// - "floating" refers the floating popover's element.
// A floating element can also be positioned relative to a virtual element,
// instead of a real one. A virtual element is represented by an object
// with the `getBoundingClientRect()` function (like real elements).
// See https://floating-ui.com/docs/virtual-elements for more info.
let resultingReferenceOwnerDoc;
if (anchor) {
resultingReferenceOwnerDoc = anchor.ownerDocument;
} else if (anchorRef?.top) {
resultingReferenceOwnerDoc = anchorRef?.top.ownerDocument;
} else if (anchorRef?.startContainer) {
resultingReferenceOwnerDoc = anchorRef.startContainer.ownerDocument;
} else if (anchorRef?.current) {
resultingReferenceOwnerDoc = anchorRef.current.ownerDocument;
} else if (anchorRef) {
// This one should be deprecated.
resultingReferenceOwnerDoc = anchorRef.ownerDocument;
} else if (anchorRect && anchorRect?.ownerDocument) {
resultingReferenceOwnerDoc = anchorRect.ownerDocument;
} else if (getAnchorRect) {
resultingReferenceOwnerDoc = getAnchorRect(fallbackReferenceElement)?.ownerDocument;
}
return (_resultingReferenceOw = resultingReferenceOwnerDoc) !== null && _resultingReferenceOw !== void 0 ? _resultingReferenceOw : fallbackDocument;
};
const getReferenceElement = ({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
scale
}) => {
var _referenceElement;
let referenceElement = null;
if (anchor) {
referenceElement = anchor;
} else if (anchorRef?.top) {
// Create a virtual element for the ref. The expectation is that
// if anchorRef.top is defined, then anchorRef.bottom is defined too.
// Seems to be used by the block toolbar, when multiple blocks are selected
// (top and bottom blocks are used to calculate the resulting rect).
referenceElement = {
getBoundingClientRect() {
const topRect = anchorRef.top.getBoundingClientRect();
const bottomRect = anchorRef.bottom.getBoundingClientRect();
return new window.DOMRect(topRect.x, topRect.y, topRect.width, bottomRect.bottom - topRect.top);
}
};
} else if (anchorRef?.current) {
// Standard React ref.
referenceElement = anchorRef.current;
} else if (anchorRef) {
// If `anchorRef` holds directly the element's value (no `current` key)
// This is a weird scenario and should be deprecated.
referenceElement = anchorRef;
} else if (anchorRect) {
// Create a virtual element for the ref.
referenceElement = {
getBoundingClientRect() {
return anchorRect;
}
};
} else if (getAnchorRect) {
// Create a virtual element for the ref.
referenceElement = {
getBoundingClientRect() {
var _rect$x, _rect$y, _rect$width, _rect$height;
const rect = getAnchorRect(fallbackReferenceElement);
return new window.DOMRect((_rect$x = rect.x) !== null && _rect$x !== void 0 ? _rect$x : rect.left, (_rect$y = rect.y) !== null && _rect$y !== void 0 ? _rect$y : rect.top, (_rect$width = rect.width) !== null && _rect$width !== void 0 ? _rect$width : rect.right - rect.left, (_rect$height = rect.height) !== null && _rect$height !== void 0 ? _rect$height : rect.bottom - rect.top);
}
};
} else if (fallbackReferenceElement) {
// If no explicit ref is passed via props, fall back to
// anchoring to the popover's parent node.
referenceElement = fallbackReferenceElement.parentElement;
}
if (referenceElement && (scale.x !== 1 || scale.y !== 1)) {
// If the popover is inside an iframe, the coordinates of the
// reference element need to be scaled to match the iframe's scale.
const rect = referenceElement.getBoundingClientRect();
referenceElement = {
getBoundingClientRect() {
return new window.DOMRect(rect.x * scale.x, rect.y * scale.y, rect.width * scale.x, rect.height * scale.y);
}
};
} // Convert any `undefined` value to `null`.
return (_referenceElement = referenceElement) !== null && _referenceElement !== void 0 ? _referenceElement : null;
};
/**
* Computes the final coordinate that needs to be applied to the floating
* element when applying transform inline styles, defaulting to `undefined`
* if the provided value is `null` or `NaN`.
*
* @param c input coordinate (usually as returned from floating-ui)
* @return The coordinate's value to be used for inline styles. An `undefined`
* return value means "no style set" for this coordinate.
*/
const computePopoverPosition = c => c === null || Number.isNaN(c) ? undefined : Math.round(c);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/limit-shift.js
/**
* External dependencies
*/
/**
* Parts of this source were derived and modified from `floating-ui`,
* released under the MIT license.
*
* https://github.com/floating-ui/floating-ui
*
* Copyright (c) 2021 Floating UI contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Custom limiter function for the `shift` middleware.
* This function is mostly identical default `limitShift` from ``@floating-ui`;
* the only difference is that, when computing the min/max shift limits, it
* also takes into account the iframe offset that is added by the
* custom "frameOffset" middleware.
*
* All unexported types and functions are also from the `@floating-ui` library,
* and have been copied to this file for convenience.
*/
function getSide(placement) {
return placement.split('-')[0];
}
function getMainAxisFromPlacement(placement) {
return ['top', 'bottom'].includes(getSide(placement)) ? 'x' : 'y';
}
function getCrossAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
const limitShift = (options = {}) => ({
options,
fn(middlewareArguments) {
const {
x,
y,
placement,
rects,
middlewareData
} = middlewareArguments;
const {
offset = 0,
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true
} = options;
const coords = {
x,
y
};
const mainAxis = getMainAxisFromPlacement(placement);
const crossAxis = getCrossAxis(mainAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
const rawOffset = typeof offset === 'function' ? offset(middlewareArguments) : offset;
const computedOffset = typeof rawOffset === 'number' ? {
mainAxis: rawOffset,
crossAxis: 0
} : {
mainAxis: 0,
crossAxis: 0,
...rawOffset
}; // At the moment of writing, this is the only difference
// with the `limitShift` function from `@floating-ui`.
// This offset needs to be added to all min/max limits
// in order to make the shift-limiting work as expected.
const additionalFrameOffset = {
x: 0,
y: 0,
...middlewareData.frameOffset?.amount
};
if (checkMainAxis) {
const len = mainAxis === 'y' ? 'height' : 'width';
const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis + additionalFrameOffset[mainAxis];
const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis + additionalFrameOffset[mainAxis];
if (mainAxisCoord < limitMin) {
mainAxisCoord = limitMin;
} else if (mainAxisCoord > limitMax) {
mainAxisCoord = limitMax;
}
}
if (checkCrossAxis) {
var _middlewareData$offse, _middlewareData$offse2;
const len = mainAxis === 'y' ? 'width' : 'height';
const isOriginSide = ['top', 'left'].includes(getSide(placement));
const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? (_middlewareData$offse = middlewareData.offset?.[crossAxis]) !== null && _middlewareData$offse !== void 0 ? _middlewareData$offse : 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis) + additionalFrameOffset[crossAxis];
const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : (_middlewareData$offse2 = middlewareData.offset?.[crossAxis]) !== null && _middlewareData$offse2 !== void 0 ? _middlewareData$offse2 : 0) - (isOriginSide ? computedOffset.crossAxis : 0) + additionalFrameOffset[crossAxis];
if (crossAxisCoord < limitMin) {
crossAxisCoord = limitMin;
} else if (crossAxisCoord > limitMax) {
crossAxisCoord = limitMax;
}
}
return {
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
};
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/overlay-middlewares.js
/**
* External dependencies
*/
function overlayMiddlewares() {
return [{
name: 'overlay',
fn({
rects
}) {
return rects.reference;
}
}, C({
apply({
rects,
elements
}) {
var _elements$floating;
const {
firstElementChild
} = (_elements$floating = elements.floating) !== null && _elements$floating !== void 0 ? _elements$floating : {}; // Only HTMLElement instances have the `style` property.
if (!(firstElementChild instanceof HTMLElement)) return; // Reduce the height of the popover to the available space.
Object.assign(firstElementChild.style, {
width: `${rects.reference.width}px`,
height: `${rects.reference.height}px`
});
}
})];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/index.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Name of slot in which popover should fill.
*
* @type {string}
*/
const SLOT_NAME = 'Popover'; // An SVG displaying a triangle facing down, filled with a solid
// color and bordered in such a way to create an arrow-like effect.
// Keeping the SVG's viewbox squared simplify the arrow positioning
// calculations.
const ArrowTriangle = () => (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: `0 0 100 100`,
className: "components-popover__triangle",
role: "presentation"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
className: "components-popover__triangle-bg",
d: "M 0 0 L 50 50 L 100 0"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
className: "components-popover__triangle-border",
d: "M 0 0 L 50 50 L 100 0",
vectorEffect: "non-scaling-stroke"
}));
const AnimatedWrapper = (0,external_wp_element_namespaceObject.forwardRef)(({
style: receivedInlineStyles,
placement,
shouldAnimate = false,
...props
}, forwardedRef) => {
const shouldReduceMotion = useReducedMotion();
const {
style: motionInlineStyles,
...otherMotionProps
} = (0,external_wp_element_namespaceObject.useMemo)(() => placementToMotionAnimationProps(placement), [placement]);
const computedAnimationProps = shouldAnimate && !shouldReduceMotion ? {
style: { ...motionInlineStyles,
...receivedInlineStyles
},
...otherMotionProps
} : {
animate: false,
style: receivedInlineStyles
};
return (0,external_wp_element_namespaceObject.createElement)(motion.div, { ...computedAnimationProps,
...props,
ref: forwardedRef
});
});
const slotNameContext = (0,external_wp_element_namespaceObject.createContext)(undefined);
const UnforwardedPopover = (props, forwardedRef) => {
var _frameOffsetRef$curre, _frameOffsetRef$curre2;
const {
animate = true,
headerTitle,
onClose,
children,
className,
noArrow = true,
position,
placement: placementProp = 'bottom-start',
offset: offsetProp = 0,
focusOnMount = 'firstElement',
anchor,
expandOnMobile,
onFocusOutside,
__unstableSlotName = SLOT_NAME,
flip = true,
resize = true,
shift = false,
variant,
// Deprecated props
__unstableForcePosition,
anchorRef,
anchorRect,
getAnchorRect,
isAlternate,
// Rest
...contentProps
} = props;
let computedFlipProp = flip;
let computedResizeProp = resize;
if (__unstableForcePosition !== undefined) {
external_wp_deprecated_default()('`__unstableForcePosition` prop in wp.components.Popover', {
since: '6.1',
version: '6.3',
alternative: '`flip={ false }` and `resize={ false }`'
}); // Back-compat, set the `flip` and `resize` props
// to `false` to replicate `__unstableForcePosition`.
computedFlipProp = !__unstableForcePosition;
computedResizeProp = !__unstableForcePosition;
}
if (anchorRef !== undefined) {
external_wp_deprecated_default()('`anchorRef` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop'
});
}
if (anchorRect !== undefined) {
external_wp_deprecated_default()('`anchorRect` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop'
});
}
if (getAnchorRect !== undefined) {
external_wp_deprecated_default()('`getAnchorRect` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop'
});
}
const computedVariant = isAlternate ? 'toolbar' : variant;
if (isAlternate !== undefined) {
external_wp_deprecated_default()('`isAlternate` prop in wp.components.Popover', {
since: '6.2',
alternative: "`variant` prop with the `'toolbar'` value"
});
}
const arrowRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [fallbackReferenceElement, setFallbackReferenceElement] = (0,external_wp_element_namespaceObject.useState)(null);
const [referenceOwnerDocument, setReferenceOwnerDocument] = (0,external_wp_element_namespaceObject.useState)();
const anchorRefFallback = (0,external_wp_element_namespaceObject.useCallback)(node => {
setFallbackReferenceElement(node);
}, []);
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const isExpanded = expandOnMobile && isMobileViewport;
const hasArrow = !isExpanded && !noArrow;
const normalizedPlacementFromProps = position ? positionToPlacement(position) : placementProp;
/**
* Offsets the position of the popover when the anchor is inside an iframe.
*
* Store the offset in a ref, due to constraints with floating-ui:
* https://floating-ui.com/docs/react-dom#variables-inside-middleware-functions.
*/
const frameOffsetRef = (0,external_wp_element_namespaceObject.useRef)(getFrameOffset(referenceOwnerDocument));
const middleware = [...(placementProp === 'overlay' ? overlayMiddlewares() : []), // Custom middleware which adjusts the popover's position by taking into
// account the offset of the anchor's iframe (if any) compared to the page.
{
name: 'frameOffset',
fn({
x,
y
}) {
if (!frameOffsetRef.current) {
return {
x,
y
};
}
return {
x: x + frameOffsetRef.current.x,
y: y + frameOffsetRef.current.y,
data: {
// This will be used in the customLimitShift() function.
amount: frameOffsetRef.current
}
};
}
}, L(offsetProp), computedFlipProp ? A() : undefined, computedResizeProp ? C({
apply(sizeProps) {
var _refs$floating$curren;
const {
firstElementChild
} = (_refs$floating$curren = refs.floating.current) !== null && _refs$floating$curren !== void 0 ? _refs$floating$curren : {}; // Only HTMLElement instances have the `style` property.
if (!(firstElementChild instanceof HTMLElement)) return; // Reduce the height of the popover to the available space.
Object.assign(firstElementChild.style, {
maxHeight: `${sizeProps.availableHeight}px`,
overflow: 'auto'
});
}
}) : undefined, shift ? O({
crossAxis: true,
limiter: limitShift(),
padding: 1 // Necessary to avoid flickering at the edge of the viewport.
}) : undefined, arrow({
element: arrowRef
})].filter(m => m !== undefined);
const slotName = (0,external_wp_element_namespaceObject.useContext)(slotNameContext) || __unstableSlotName;
const slot = useSlot(slotName);
let onDialogClose;
if (onClose || onFocusOutside) {
onDialogClose = (type, event) => {
// Ideally the popover should have just a single onClose prop and
// not three props that potentially do the same thing.
if (type === 'focus-outside' && onFocusOutside) {
onFocusOutside(event);
} else if (onClose) {
onClose();
}
};
}
const [dialogRef, dialogProps] = (0,external_wp_compose_namespaceObject.__experimentalUseDialog)({
focusOnMount,
__unstableOnClose: onDialogClose,
// @ts-expect-error The __unstableOnClose property needs to be deprecated first (see https://github.com/WordPress/gutenberg/pull/27675)
onClose: onDialogClose
});
const {
// Positioning coordinates
x,
y,
// Callback refs (not regular refs). This allows the position to be updated.
// when either elements change.
reference: referenceCallbackRef,
floating,
// Object with "regular" refs to both "reference" and "floating"
refs,
// Type of CSS position property to use (absolute or fixed)
strategy,
update,
placement: computedPlacement,
middlewareData: {
arrow: arrowData
}
} = useFloating({
placement: normalizedPlacementFromProps === 'overlay' ? undefined : normalizedPlacementFromProps,
middleware,
whileElementsMounted: (referenceParam, floatingParam, updateParam) => floating_ui_dom_browser_min_A(referenceParam, floatingParam, updateParam, {
animationFrame: true
})
});
const arrowCallbackRef = (0,external_wp_element_namespaceObject.useCallback)(node => {
arrowRef.current = node;
update();
}, [update]); // When any of the possible anchor "sources" change,
// recompute the reference element (real or virtual) and its owner document.
const anchorRefTop = anchorRef?.top;
const anchorRefBottom = anchorRef?.bottom;
const anchorRefStartContainer = anchorRef?.startContainer;
const anchorRefCurrent = anchorRef?.current;
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const resultingReferenceOwnerDoc = getReferenceOwnerDocument({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
fallbackDocument: document
});
const scale = getFrameScale(resultingReferenceOwnerDoc);
const resultingReferenceElement = getReferenceElement({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
scale
});
referenceCallbackRef(resultingReferenceElement);
setReferenceOwnerDocument(resultingReferenceOwnerDoc);
}, [anchor, anchorRef, anchorRefTop, anchorRefBottom, anchorRefStartContainer, anchorRefCurrent, anchorRect, getAnchorRect, fallbackReferenceElement, referenceCallbackRef]); // If the reference element is in a different ownerDocument (e.g. iFrame),
// we need to manually update the floating's position as the reference's owner
// document scrolls. Also update the frame offset if the view resizes.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if ( // Reference and root documents are the same.
referenceOwnerDocument === document || // Reference and floating are in the same document.
referenceOwnerDocument === refs.floating.current?.ownerDocument || // The reference's document has no view (i.e. window)
// or frame element (ie. it's not an iframe).
!referenceOwnerDocument?.defaultView?.frameElement) {
frameOffsetRef.current = undefined;
return;
}
const {
defaultView
} = referenceOwnerDocument;
const {
frameElement
} = defaultView;
const scrollContainer = frameElement ? (0,external_wp_dom_namespaceObject.getScrollContainer)(frameElement) : null;
const updateFrameOffset = () => {
frameOffsetRef.current = getFrameOffset(referenceOwnerDocument);
update();
};
defaultView.addEventListener('resize', updateFrameOffset);
scrollContainer?.addEventListener('scroll', updateFrameOffset);
updateFrameOffset();
return () => {
defaultView.removeEventListener('resize', updateFrameOffset);
scrollContainer?.removeEventListener('scroll', updateFrameOffset);
};
}, [referenceOwnerDocument, update, refs.floating]);
const mergedFloatingRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([floating, dialogRef, forwardedRef]); // Disable reason: We care to capture the _bubbled_ events from inputs
// within popover as inferring close intent.
let content = // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)(AnimatedWrapper, {
shouldAnimate: animate && !isExpanded,
placement: computedPlacement,
className: classnames_default()('components-popover', className, {
'is-expanded': isExpanded,
'is-positioned': x !== null && y !== null,
// Use the 'alternate' classname for 'toolbar' variant for back compat.
[`is-${computedVariant === 'toolbar' ? 'alternate' : computedVariant}`]: computedVariant
}),
...contentProps,
ref: mergedFloatingRef,
...dialogProps,
tabIndex: -1,
style: isExpanded ? undefined : {
position: strategy,
top: 0,
left: 0,
// `x` and `y` are framer-motion specific props and are shorthands
// for `translateX` and `translateY`. Currently it is not possible
// to use `translateX` and `translateY` because those values would
// be overridden by the return value of the
// `placementToMotionAnimationProps` function in `AnimatedWrapper`
x: computePopoverPosition(x),
y: computePopoverPosition(y)
}
}, isExpanded && (0,external_wp_element_namespaceObject.createElement)(scroll_lock, null), isExpanded && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-popover__header"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-popover__header-title"
}, headerTitle), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-popover__close",
icon: library_close,
onClick: onClose
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-popover__content"
}, children), hasArrow && (0,external_wp_element_namespaceObject.createElement)("div", {
ref: arrowCallbackRef,
className: ['components-popover__arrow', `is-${computedPlacement.split('-')[0]}`].join(' '),
style: {
left: typeof arrowData?.x !== 'undefined' && Number.isFinite(arrowData.x) ? `${arrowData.x + ((_frameOffsetRef$curre = frameOffsetRef.current?.x) !== null && _frameOffsetRef$curre !== void 0 ? _frameOffsetRef$curre : 0)}px` : '',
top: typeof arrowData?.y !== 'undefined' && Number.isFinite(arrowData.y) ? `${arrowData.y + ((_frameOffsetRef$curre2 = frameOffsetRef.current?.y) !== null && _frameOffsetRef$curre2 !== void 0 ? _frameOffsetRef$curre2 : 0)}px` : ''
}
}, (0,external_wp_element_namespaceObject.createElement)(ArrowTriangle, null)));
if (slot.ref) {
content = (0,external_wp_element_namespaceObject.createElement)(slot_fill_Fill, {
name: slotName
}, content);
}
if (anchorRef || anchorRect || anchor) {
return content;
}
return (0,external_wp_element_namespaceObject.createElement)("span", {
ref: anchorRefFallback
}, content);
};
/**
* `Popover` renders its content in a floating modal. If no explicit anchor is passed via props, it anchors to its parent element by default.
*
* ```jsx
* import { Button, Popover } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyPopover = () => {
* const [ isVisible, setIsVisible ] = useState( false );
* const toggleVisible = () => {
* setIsVisible( ( state ) => ! state );
* };
*
* return (
* <Button variant="secondary" onClick={ toggleVisible }>
* Toggle Popover!
* { isVisible && <Popover>Popover is toggled!</Popover> }
* </Button>
* );
* };
* ```
*
*/
const Popover = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedPopover);
function PopoverSlot({
name = SLOT_NAME
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)(slot_fill_Slot // @ts-expect-error Need to type `SlotFill`
, {
bubblesVirtually: true,
name: name,
className: "popover-slot",
ref: ref
});
} // @ts-expect-error For Legacy Reasons
Popover.Slot = (0,external_wp_element_namespaceObject.forwardRef)(PopoverSlot); // @ts-expect-error For Legacy Reasons
Popover.__unstableSlotNameProvider = slotNameContext.Provider;
/* harmony default export */ var popover = (Popover);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/shortcut/index.js
/**
* Internal dependencies
*/
function Shortcut(props) {
const {
shortcut,
className
} = props;
if (!shortcut) {
return null;
}
let displayText;
let ariaLabel;
if (typeof shortcut === 'string') {
displayText = shortcut;
}
if (shortcut !== null && typeof shortcut === 'object') {
displayText = shortcut.display;
ariaLabel = shortcut.ariaLabel;
}
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: className,
"aria-label": ariaLabel
}, displayText);
}
/* harmony default export */ var build_module_shortcut = (Shortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tooltip/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Time over children to wait before showing tooltip
*
* @type {number}
*/
const TOOLTIP_DELAY = 700;
const eventCatcher = (0,external_wp_element_namespaceObject.createElement)("div", {
className: "event-catcher"
});
const getDisabledElement = ({
eventHandlers,
child,
childrenWithPopover,
mergedRefs
}) => {
return (0,external_wp_element_namespaceObject.cloneElement)((0,external_wp_element_namespaceObject.createElement)("span", {
className: "disabled-element-wrapper"
}, (0,external_wp_element_namespaceObject.cloneElement)(eventCatcher, eventHandlers), (0,external_wp_element_namespaceObject.cloneElement)(child, {
children: childrenWithPopover,
ref: mergedRefs
})), { ...eventHandlers
});
};
const getRegularElement = ({
child,
eventHandlers,
childrenWithPopover,
mergedRefs
}) => {
return (0,external_wp_element_namespaceObject.cloneElement)(child, { ...eventHandlers,
children: childrenWithPopover,
ref: mergedRefs
});
};
const addPopoverToGrandchildren = ({
anchor,
grandchildren,
isOver,
offset,
position,
shortcut,
text,
className,
...props
}) => (0,external_wp_element_namespaceObject.concatChildren)(grandchildren, isOver && (0,external_wp_element_namespaceObject.createElement)(popover, {
focusOnMount: false,
position: position,
className: classnames_default()('components-tooltip', className),
"aria-hidden": "true",
animate: false,
offset: offset,
anchor: anchor,
shift: true,
...props
}, text, (0,external_wp_element_namespaceObject.createElement)(build_module_shortcut, {
className: "components-tooltip__shortcut",
shortcut: shortcut
})));
const emitToChild = (children, eventName, event) => {
if (external_wp_element_namespaceObject.Children.count(children) !== 1) {
return;
}
const child = external_wp_element_namespaceObject.Children.only(children); // If the underlying element is disabled, do not emit the event.
if (child.props.disabled) {
return;
}
if (typeof child.props[eventName] === 'function') {
child.props[eventName](event);
}
};
function Tooltip(props) {
const {
children,
position = 'bottom middle',
text,
shortcut,
delay = TOOLTIP_DELAY,
...popoverProps
} = props;
/**
* Whether a mouse is currently pressed, used in determining whether
* to handle a focus event as displaying the tooltip immediately.
*
* @type {boolean}
*/
const [isMouseDown, setIsMouseDown] = (0,external_wp_element_namespaceObject.useState)(false);
const [isOver, setIsOver] = (0,external_wp_element_namespaceObject.useState)(false);
const delayedSetIsOver = (0,external_wp_compose_namespaceObject.useDebounce)(setIsOver, delay); // Using internal state (instead of a ref) for the popover anchor to make sure
// that the component re-renders when the anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Create a reference to the Tooltip's child, to be passed to the Popover
// so that the Tooltip can be correctly positioned. Also, merge with the
// existing ref for the first child, so that its ref is preserved.
const existingChildRef = external_wp_element_namespaceObject.Children.toArray(children)[0]?.ref;
const mergedChildRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([setPopoverAnchor, existingChildRef]);
const createMouseDown = event => {
// In firefox, the mouse down event is also fired when the select
// list is chosen.
// Cancel further processing because re-rendering of child components
// causes onChange to be triggered with the old value.
// See https://github.com/WordPress/gutenberg/pull/42483
if (event.target.tagName === 'OPTION') {
return;
} // Preserve original child callback behavior.
emitToChild(children, 'onMouseDown', event); // On mouse down, the next `mouseup` should revert the value of the
// instance property and remove its own event handler. The bind is
// made on the document since the `mouseup` might not occur within
// the bounds of the element.
document.addEventListener('mouseup', cancelIsMouseDown);
setIsMouseDown(true);
};
const createMouseUp = event => {
// In firefox, the mouse up event is also fired when the select
// list is chosen.
// Cancel further processing because re-rendering of child components
// causes onChange to be triggered with the old value.
// See https://github.com/WordPress/gutenberg/pull/42483
if (event.target.tagName === 'OPTION') {
return;
}
emitToChild(children, 'onMouseUp', event);
document.removeEventListener('mouseup', cancelIsMouseDown);
setIsMouseDown(false);
};
const createMouseEvent = type => {
if (type === 'mouseUp') return createMouseUp;
if (type === 'mouseDown') return createMouseDown;
};
/**
* Prebound `isInMouseDown` handler, created as a constant reference to
* assure ability to remove in component unmount.
*
* @type {Function}
*/
const cancelIsMouseDown = createMouseEvent('mouseUp');
const createToggleIsOver = (eventName, isDelayed) => {
return event => {
// Preserve original child callback behavior.
emitToChild(children, eventName, event); // Mouse events behave unreliably in React for disabled elements,
// firing on mouseenter but not mouseleave. Further, the default
// behavior for disabled elements in some browsers is to ignore
// mouse events. Don't bother trying to handle them.
//
// See: https://github.com/facebook/react/issues/4251
if (event.currentTarget.disabled) {
return;
} // A focus event will occur as a result of a mouse click, but it
// should be disambiguated between interacting with the button and
// using an explicit focus shift as a cue to display the tooltip.
if ('focus' === event.type && isMouseDown) {
return;
} // Needed in case unsetting is over while delayed set pending, i.e.
// quickly blur/mouseleave before delayedSetIsOver is called.
delayedSetIsOver.cancel();
const _isOver = ['focus', 'mouseenter'].includes(event.type);
if (_isOver === isOver) {
return;
}
if (isDelayed) {
delayedSetIsOver(_isOver);
} else {
setIsOver(_isOver);
}
};
};
const clearOnUnmount = () => {
delayedSetIsOver.cancel();
document.removeEventListener('mouseup', cancelIsMouseDown);
}; // Ignore reason: updating the deps array here could cause unexpected changes in behavior.
// Deferring until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
(0,external_wp_element_namespaceObject.useEffect)(() => clearOnUnmount, []);
if (external_wp_element_namespaceObject.Children.count(children) !== 1) {
if (false) {}
return children;
}
const eventHandlers = {
onMouseEnter: createToggleIsOver('onMouseEnter', true),
onMouseLeave: createToggleIsOver('onMouseLeave'),
onClick: createToggleIsOver('onClick'),
onFocus: createToggleIsOver('onFocus'),
onBlur: createToggleIsOver('onBlur'),
onMouseDown: createMouseEvent('mouseDown')
};
const child = external_wp_element_namespaceObject.Children.only(children);
const {
children: grandchildren,
disabled
} = child.props;
const getElementWithPopover = disabled ? getDisabledElement : getRegularElement;
const popoverData = {
anchor: popoverAnchor,
isOver,
offset: 4,
position,
shortcut,
text
};
const childrenWithPopover = addPopoverToGrandchildren({
grandchildren,
...popoverData,
...popoverProps
});
return getElementWithPopover({
child,
eventHandlers,
childrenWithPopover,
mergedRefs: mergedChildRefs
});
}
/* harmony default export */ var tooltip = (Tooltip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const GRID = [['top left', 'top center', 'top right'], ['center left', 'center center', 'center right'], ['bottom left', 'bottom center', 'bottom right']]; // Stored as map as i18n __() only accepts strings (not variables)
const ALIGNMENT_LABEL = {
'top left': (0,external_wp_i18n_namespaceObject.__)('Top Left'),
'top center': (0,external_wp_i18n_namespaceObject.__)('Top Center'),
'top right': (0,external_wp_i18n_namespaceObject.__)('Top Right'),
'center left': (0,external_wp_i18n_namespaceObject.__)('Center Left'),
'center center': (0,external_wp_i18n_namespaceObject.__)('Center'),
center: (0,external_wp_i18n_namespaceObject.__)('Center'),
'center right': (0,external_wp_i18n_namespaceObject.__)('Center Right'),
'bottom left': (0,external_wp_i18n_namespaceObject.__)('Bottom Left'),
'bottom center': (0,external_wp_i18n_namespaceObject.__)('Bottom Center'),
'bottom right': (0,external_wp_i18n_namespaceObject.__)('Bottom Right')
}; // Transforms GRID into a flat Array of values.
const ALIGNMENTS = GRID.flat();
/**
* Parses and transforms an incoming value to better match the alignment values
*
* @param value An alignment value to parse.
*
* @return The parsed value.
*/
function transformValue(value) {
const nextValue = value === 'center' ? 'center center' : value;
return nextValue.replace('-', ' ');
}
/**
* Creates an item ID based on a prefix ID and an alignment value.
*
* @param prefixId An ID to prefix.
* @param value An alignment value.
*
* @return The item id.
*/
function getItemId(prefixId, value) {
const valueId = transformValue(value).replace(' ', '-');
return `${prefixId}-${valueId}`;
}
/**
* Retrieves the alignment index from a value.
*
* @param alignment Value to check.
*
* @return The index of a matching alignment.
*/
function getAlignmentIndex(alignment = 'center') {
const item = transformValue(alignment);
const index = ALIGNMENTS.indexOf(item);
return index > -1 ? index : undefined;
}
// EXTERNAL MODULE: ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js
var hoist_non_react_statics_cjs = __webpack_require__(1281);
;// CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-react.browser.esm.js
var pkg = {
name: "@emotion/react",
version: "11.11.1",
main: "dist/emotion-react.cjs.js",
module: "dist/emotion-react.esm.js",
browser: {
"./dist/emotion-react.esm.js": "./dist/emotion-react.browser.esm.js"
},
exports: {
".": {
module: {
worker: "./dist/emotion-react.worker.esm.js",
browser: "./dist/emotion-react.browser.esm.js",
"default": "./dist/emotion-react.esm.js"
},
"import": "./dist/emotion-react.cjs.mjs",
"default": "./dist/emotion-react.cjs.js"
},
"./jsx-runtime": {
module: {
worker: "./jsx-runtime/dist/emotion-react-jsx-runtime.worker.esm.js",
browser: "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js",
"default": "./jsx-runtime/dist/emotion-react-jsx-runtime.esm.js"
},
"import": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.mjs",
"default": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.js"
},
"./_isolated-hnrs": {
module: {
worker: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.worker.esm.js",
browser: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js",
"default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.esm.js"
},
"import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.mjs",
"default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.js"
},
"./jsx-dev-runtime": {
module: {
worker: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.worker.esm.js",
browser: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js",
"default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.esm.js"
},
"import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.mjs",
"default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.js"
},
"./package.json": "./package.json",
"./types/css-prop": "./types/css-prop.d.ts",
"./macro": {
types: {
"import": "./macro.d.mts",
"default": "./macro.d.ts"
},
"default": "./macro.js"
}
},
types: "types/index.d.ts",
files: [
"src",
"dist",
"jsx-runtime",
"jsx-dev-runtime",
"_isolated-hnrs",
"types/*.d.ts",
"macro.*"
],
sideEffects: false,
author: "Emotion Contributors",
license: "MIT",
scripts: {
"test:typescript": "dtslint types"
},
dependencies: {
"@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.11.0",
"@emotion/cache": "^11.11.0",
"@emotion/serialize": "^1.1.2",
"@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",
"@emotion/utils": "^1.2.1",
"@emotion/weak-memoize": "^0.3.1",
"hoist-non-react-statics": "^3.3.1"
},
peerDependencies: {
react: ">=16.8.0"
},
peerDependenciesMeta: {
"@types/react": {
optional: true
}
},
devDependencies: {
"@definitelytyped/dtslint": "0.0.112",
"@emotion/css": "11.11.0",
"@emotion/css-prettifier": "1.1.3",
"@emotion/server": "11.11.0",
"@emotion/styled": "11.11.0",
"html-tag-names": "^1.1.2",
react: "16.14.0",
"svg-tag-names": "^1.1.1",
typescript: "^4.5.5"
},
repository: "https://github.com/emotion-js/emotion/tree/main/packages/react",
publishConfig: {
access: "public"
},
"umd:main": "dist/emotion-react.umd.min.js",
preconstruct: {
entrypoints: [
"./index.js",
"./jsx-runtime.js",
"./jsx-dev-runtime.js",
"./_isolated-hnrs.js"
],
umdName: "emotionReact",
exports: {
envConditions: [
"browser",
"worker"
],
extra: {
"./types/css-prop": "./types/css-prop.d.ts",
"./macro": {
types: {
"import": "./macro.d.mts",
"default": "./macro.d.ts"
},
"default": "./macro.js"
}
}
}
}
};
var jsx = function jsx(type, props) {
var args = arguments;
if (props == null || !hasOwnProperty.call(props, 'css')) {
// $FlowFixMe
return React.createElement.apply(undefined, args);
}
var argsLength = args.length;
var createElementArgArray = new Array(argsLength);
createElementArgArray[0] = Emotion;
createElementArgArray[1] = createEmotionProps(type, props);
for (var i = 2; i < argsLength; i++) {
createElementArgArray[i] = args[i];
} // $FlowFixMe
return React.createElement.apply(null, createElementArgArray);
};
var warnedAboutCssPropForGlobal = false; // maintain place over rerenders.
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag
var Global = /* #__PURE__ */(/* unused pure expression or super */ null && (withEmotionCache(function (props, cache) {
if (false) {}
var styles = props.styles;
var serialized = serializeStyles([styles], undefined, React.useContext(ThemeContext));
if (!isBrowser$1) {
var _ref;
var serializedNames = serialized.name;
var serializedStyles = serialized.styles;
var next = serialized.next;
while (next !== undefined) {
serializedNames += ' ' + next.name;
serializedStyles += next.styles;
next = next.next;
}
var shouldCache = cache.compat === true;
var rules = cache.insert("", {
name: serializedNames,
styles: serializedStyles
}, cache.sheet, shouldCache);
if (shouldCache) {
return null;
}
return /*#__PURE__*/React.createElement("style", (_ref = {}, _ref["data-emotion"] = cache.key + "-global " + serializedNames, _ref.dangerouslySetInnerHTML = {
__html: rules
}, _ref.nonce = cache.sheet.nonce, _ref));
} // yes, i know these hooks are used conditionally
// but it is based on a constant that will never change at runtime
// it's effectively like having two implementations and switching them out
// so it's not actually breaking anything
var sheetRef = React.useRef();
useInsertionEffectWithLayoutFallback(function () {
var key = cache.key + "-global"; // use case of https://github.com/emotion-js/emotion/issues/2675
var sheet = new cache.sheet.constructor({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy
});
var rehydrating = false; // $FlowFixMe
var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]");
if (cache.sheet.tags.length) {
sheet.before = cache.sheet.tags[0];
}
if (node !== null) {
rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other <Global/>s
node.setAttribute('data-emotion', key);
sheet.hydrate([node]);
}
sheetRef.current = [sheet, rehydrating];
return function () {
sheet.flush();
};
}, [cache]);
useInsertionEffectWithLayoutFallback(function () {
var sheetRefCurrent = sheetRef.current;
var sheet = sheetRefCurrent[0],
rehydrating = sheetRefCurrent[1];
if (rehydrating) {
sheetRefCurrent[1] = false;
return;
}
if (serialized.next !== undefined) {
// insert keyframes
insertStyles(cache, serialized.next, true);
}
if (sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
sheet.before = element;
sheet.flush();
}
cache.insert("", serialized, sheet, false);
}, [cache, serialized.name]);
return null;
})));
if (false) {}
function emotion_react_browser_esm_css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return emotion_serialize_browser_esm_serializeStyles(args);
}
var emotion_react_browser_esm_keyframes = function keyframes() {
var insertable = emotion_react_browser_esm_css.apply(void 0, arguments);
var name = "animation-" + insertable.name; // $FlowFixMe
return {
name: name,
styles: "@keyframes " + name + "{" + insertable.styles + "}",
anim: 1,
toString: function toString() {
return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
}
};
};
var emotion_react_browser_esm_classnames = function classnames(args) {
var len = args.length;
var i = 0;
var cls = '';
for (; i < len; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
if (false) {}
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
function emotion_react_browser_esm_merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var emotion_react_browser_esm_Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serializedArr = _ref.serializedArr;
useInsertionEffectAlwaysWithSyncFallback(function () {
for (var i = 0; i < serializedArr.length; i++) {
insertStyles(cache, serializedArr[i], false);
}
});
return null;
};
var ClassNames = /* #__PURE__ */(/* unused pure expression or super */ null && (withEmotionCache(function (props, cache) {
var hasRendered = false;
var serializedArr = [];
var css = function css() {
if (hasRendered && "production" !== 'production') {}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = serializeStyles(args, cache.registered);
serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`
registerStyles(cache, serialized, false);
return cache.key + "-" + serialized.name;
};
var cx = function cx() {
if (hasRendered && "production" !== 'production') {}
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return emotion_react_browser_esm_merge(cache.registered, css, emotion_react_browser_esm_classnames(args));
};
var content = {
css: css,
cx: cx,
theme: React.useContext(ThemeContext)
};
var ele = props.children(content);
hasRendered = true;
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(emotion_react_browser_esm_Insertion, {
cache: cache,
serializedArr: serializedArr
}), ele);
})));
if (false) {}
if (false) { var globalKey, globalContext, isTestEnv, emotion_react_browser_esm_isBrowser; }
;// CONCATENATED MODULE: ./node_modules/colord/index.mjs
var colord_r={grad:.9,turn:360,rad:360/(2*Math.PI)},colord_t=function(r){return"string"==typeof r?r.length>0:"number"==typeof r},colord_n=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=Math.pow(10,t)),Math.round(n*r)/n+0},colord_e=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=1),r>n?n:r>t?r:t},colord_u=function(r){return(r=isFinite(r)?r%360:0)>0?r:r+360},colord_a=function(r){return{r:colord_e(r.r,0,255),g:colord_e(r.g,0,255),b:colord_e(r.b,0,255),a:colord_e(r.a)}},colord_o=function(r){return{r:colord_n(r.r),g:colord_n(r.g),b:colord_n(r.b),a:colord_n(r.a,3)}},colord_i=/^#([0-9a-f]{3,8})$/i,colord_s=function(r){var t=r.toString(16);return t.length<2?"0"+t:t},colord_h=function(r){var t=r.r,n=r.g,e=r.b,u=r.a,a=Math.max(t,n,e),o=a-Math.min(t,n,e),i=o?a===t?(n-e)/o:a===n?2+(e-t)/o:4+(t-n)/o:0;return{h:60*(i<0?i+6:i),s:a?o/a*100:0,v:a/255*100,a:u}},colord_b=function(r){var t=r.h,n=r.s,e=r.v,u=r.a;t=t/360*6,n/=100,e/=100;var a=Math.floor(t),o=e*(1-n),i=e*(1-(t-a)*n),s=e*(1-(1-t+a)*n),h=a%6;return{r:255*[e,i,o,o,s,e][h],g:255*[s,e,e,i,o,o][h],b:255*[o,o,s,e,e,i][h],a:u}},colord_g=function(r){return{h:colord_u(r.h),s:colord_e(r.s,0,100),l:colord_e(r.l,0,100),a:colord_e(r.a)}},colord_d=function(r){return{h:colord_n(r.h),s:colord_n(r.s),l:colord_n(r.l),a:colord_n(r.a,3)}},colord_f=function(r){return colord_b((n=(t=r).s,{h:t.h,s:(n*=((e=t.l)<50?e:100-e)/100)>0?2*n/(e+n)*100:0,v:e+n,a:t.a}));var t,n,e},colord_c=function(r){return{h:(t=colord_h(r)).h,s:(u=(200-(n=t.s))*(e=t.v)/100)>0&&u<200?n*e/100/(u<=100?u:200-u)*100:0,l:u/2,a:t.a};var t,n,e,u},colord_l=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,colord_p=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,colord_v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,colord_m=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,colord_y={string:[[function(r){var t=colord_i.exec(r);return t?(r=t[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:4===r.length?colord_n(parseInt(r[3]+r[3],16)/255,2):1}:6===r.length||8===r.length?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:8===r.length?colord_n(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var t=colord_v.exec(r)||colord_m.exec(r);return t?t[2]!==t[4]||t[4]!==t[6]?null:colord_a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(t){var n=colord_l.exec(t)||colord_p.exec(t);if(!n)return null;var e,u,a=colord_g({h:(e=n[1],u=n[2],void 0===u&&(u="deg"),Number(e)*(colord_r[u]||1)),s:Number(n[3]),l:Number(n[4]),a:void 0===n[5]?1:Number(n[5])/(n[6]?100:1)});return colord_f(a)},"hsl"]],object:[[function(r){var n=r.r,e=r.g,u=r.b,o=r.a,i=void 0===o?1:o;return colord_t(n)&&colord_t(e)&&colord_t(u)?colord_a({r:Number(n),g:Number(e),b:Number(u),a:Number(i)}):null},"rgb"],[function(r){var n=r.h,e=r.s,u=r.l,a=r.a,o=void 0===a?1:a;if(!colord_t(n)||!colord_t(e)||!colord_t(u))return null;var i=colord_g({h:Number(n),s:Number(e),l:Number(u),a:Number(o)});return colord_f(i)},"hsl"],[function(r){var n=r.h,a=r.s,o=r.v,i=r.a,s=void 0===i?1:i;if(!colord_t(n)||!colord_t(a)||!colord_t(o))return null;var h=function(r){return{h:colord_u(r.h),s:colord_e(r.s,0,100),v:colord_e(r.v,0,100),a:colord_e(r.a)}}({h:Number(n),s:Number(a),v:Number(o),a:Number(s)});return colord_b(h)},"hsv"]]},N=function(r,t){for(var n=0;n<t.length;n++){var e=t[n][0](r);if(e)return[e,t[n][1]]}return[null,void 0]},colord_x=function(r){return"string"==typeof r?N(r.trim(),colord_y.string):"object"==typeof r&&null!==r?N(r,colord_y.object):[null,void 0]},I=function(r){return colord_x(r)[1]},colord_M=function(r,t){var n=colord_c(r);return{h:n.h,s:colord_e(n.s+100*t,0,100),l:n.l,a:n.a}},colord_H=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},$=function(r,t){var n=colord_c(r);return{h:n.h,s:n.s,l:colord_e(n.l+100*t,0,100),a:n.a}},j=function(){function r(r){this.parsed=colord_x(r)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return null!==this.parsed},r.prototype.brightness=function(){return colord_n(colord_H(this.rgba),2)},r.prototype.isDark=function(){return colord_H(this.rgba)<.5},r.prototype.isLight=function(){return colord_H(this.rgba)>=.5},r.prototype.toHex=function(){return r=colord_o(this.rgba),t=r.r,e=r.g,u=r.b,i=(a=r.a)<1?colord_s(colord_n(255*a)):"","#"+colord_s(t)+colord_s(e)+colord_s(u)+i;var r,t,e,u,a,i},r.prototype.toRgb=function(){return colord_o(this.rgba)},r.prototype.toRgbString=function(){return r=colord_o(this.rgba),t=r.r,n=r.g,e=r.b,(u=r.a)<1?"rgba("+t+", "+n+", "+e+", "+u+")":"rgb("+t+", "+n+", "+e+")";var r,t,n,e,u},r.prototype.toHsl=function(){return colord_d(colord_c(this.rgba))},r.prototype.toHslString=function(){return r=colord_d(colord_c(this.rgba)),t=r.h,n=r.s,e=r.l,(u=r.a)<1?"hsla("+t+", "+n+"%, "+e+"%, "+u+")":"hsl("+t+", "+n+"%, "+e+"%)";var r,t,n,e,u},r.prototype.toHsv=function(){return r=colord_h(this.rgba),{h:colord_n(r.h),s:colord_n(r.s),v:colord_n(r.v),a:colord_n(r.a,3)};var r},r.prototype.invert=function(){return colord_w({r:255-(r=this.rgba).r,g:255-r.g,b:255-r.b,a:r.a});var r},r.prototype.saturate=function(r){return void 0===r&&(r=.1),colord_w(colord_M(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),colord_w(colord_M(this.rgba,-r))},r.prototype.grayscale=function(){return colord_w(colord_M(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),colord_w($(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),colord_w($(this.rgba,-r))},r.prototype.rotate=function(r){return void 0===r&&(r=15),this.hue(this.hue()+r)},r.prototype.alpha=function(r){return"number"==typeof r?colord_w({r:(t=this.rgba).r,g:t.g,b:t.b,a:r}):colord_n(this.rgba.a,3);var t},r.prototype.hue=function(r){var t=colord_c(this.rgba);return"number"==typeof r?colord_w({h:r,s:t.s,l:t.l,a:t.a}):colord_n(t.h)},r.prototype.isEqual=function(r){return this.toHex()===colord_w(r).toHex()},r}(),colord_w=function(r){return r instanceof j?r:new j(r)},colord_S=[],colord_k=function(r){r.forEach(function(r){colord_S.indexOf(r)<0&&(r(j,colord_y),colord_S.push(r))})},colord_E=function(){return new j({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})};
;// CONCATENATED MODULE: ./node_modules/colord/plugins/names.mjs
/* harmony default export */ function names(e,f){var a={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var d,i,n=r[this.toHex()];if(n)return n;if(null==f?void 0:f.closest){var o=this.toRgb(),t=1/0,b="black";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(var g in a){var u=(d=o,i=l[g],Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2));u<t&&(t=u,b=g)}return b}};f.string.push([function(f){var r=f.toLowerCase(),d="transparent"===r?"#0000":a[r];return d?new e(d).toRgb():null},"name"])}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/colors.js
/**
* External dependencies
*/
colord_k([names]);
/**
* Generating a CSS compliant rgba() color value.
*
* @param {string} hexValue The hex value to convert to rgba().
* @param {number} alpha The alpha value for opacity.
* @return {string} The converted rgba() color value.
*
* @example
* rgba( '#000000', 0.5 )
* // rgba(0, 0, 0, 0.5)
*/
function colors_rgba(hexValue = '', alpha = 1) {
return colord_w(hexValue).alpha(alpha).toRgbString();
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/colors-values.js
/**
* Internal dependencies
*/
const white = '#fff'; // Matches the grays in @wordpress/base-styles
const GRAY = {
900: '#1e1e1e',
800: '#2f2f2f',
/** Meets 4.6:1 text contrast against white. */
700: '#757575',
/** Meets 3:1 UI or large text contrast against white. */
600: '#949494',
400: '#ccc',
/** Used for most borders. */
300: '#ddd',
/** Used sparingly for light borders. */
200: '#e0e0e0',
/** Used for light gray backgrounds. */
100: '#f0f0f0'
}; // Matches @wordpress/base-styles
const ALERT = {
yellow: '#f0b849',
red: '#d94f4f',
green: '#4ab866'
}; // Matches the Modern admin scheme in @wordpress/base-styles
const ADMIN = {
theme: 'var(--wp-components-color-accent, var(--wp-admin-theme-color, #3858e9))',
themeDark10: 'var(--wp-components-color-accent-darker-10, var(--wp-admin-theme-color-darker-10, #2145e6))'
};
const UI = {
theme: ADMIN.theme,
themeDark10: ADMIN.themeDark10,
background: white,
backgroundDisabled: GRAY[100],
border: GRAY[600],
borderHover: GRAY[700],
borderFocus: ADMIN.themeDark10,
borderDisabled: GRAY[400],
textDisabled: GRAY[600],
textDark: white,
// Matches @wordpress/base-styles
darkGrayPlaceholder: colors_rgba(GRAY[900], 0.62),
lightGrayPlaceholder: colors_rgba(white, 0.65)
};
const COLORS = Object.freeze({
/**
* The main gray color object.
*/
gray: GRAY,
white,
alert: ALERT,
ui: UI
});
/* harmony default export */ var colors_values = ((/* unused pure expression or super */ null && (COLORS)));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/reduce-motion.js
/**
* Allows users to opt-out of animations via OS-level preferences.
*
* @param {'transition' | 'animation' | string} [prop='transition'] CSS Property name
* @return {string} Generated CSS code for the reduced style
*/
function reduceMotion(prop = 'transition') {
let style;
switch (prop) {
case 'transition':
style = 'transition-duration: 0ms;';
break;
case 'animation':
style = 'animation-duration: 1ms;';
break;
default:
style = `
animation-duration: 1ms;
transition-duration: 0ms;
`;
}
return `
@media ( prefers-reduced-motion: reduce ) {
${style};
}
`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/styles/alignment-matrix-control-styles.js
function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
var _ref = true ? {
name: "93uojk",
styles: "border-radius:2px;box-sizing:border-box;direction:ltr;display:grid;grid-template-columns:repeat( 3, 1fr );outline:none"
} : 0;
const rootBase = () => {
return _ref;
};
const rootSize = ({
size = 92
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css("grid-template-rows:repeat( 3, calc( ", size, "px / 3 ) );width:", size, "px;" + ( true ? "" : 0), true ? "" : 0);
};
const Root = createStyled("div", true ? {
target: "ecapk1j3"
} : 0)(rootBase, ";border:1px solid transparent;cursor:pointer;grid-template-columns:auto;", rootSize, ";" + ( true ? "" : 0));
const Row = createStyled("div", true ? {
target: "ecapk1j2"
} : 0)( true ? {
name: "1x5gbbj",
styles: "box-sizing:border-box;display:grid;grid-template-columns:repeat( 3, 1fr )"
} : 0);
const pointActive = ({
isActive
}) => {
const boxShadow = isActive ? `0 0 0 2px ${COLORS.gray[900]}` : null;
const pointColor = isActive ? COLORS.gray[900] : COLORS.gray[400];
const pointColorHover = isActive ? COLORS.gray[900] : COLORS.ui.theme;
return /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:", boxShadow, ";color:", pointColor, ";*:hover>&{color:", pointColorHover, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const pointBase = props => {
return /*#__PURE__*/emotion_react_browser_esm_css("background:currentColor;box-sizing:border-box;display:grid;margin:auto;transition:all 120ms linear;", reduceMotion('transition'), " ", pointActive(props), ";" + ( true ? "" : 0), true ? "" : 0);
};
const Point = createStyled("span", true ? {
target: "ecapk1j1"
} : 0)("height:6px;width:6px;", pointBase, ";" + ( true ? "" : 0));
const Cell = createStyled("span", true ? {
target: "ecapk1j0"
} : 0)( true ? {
name: "rjf3ub",
styles: "appearance:none;border:none;box-sizing:border-box;margin:0;display:flex;position:relative;outline:none;align-items:center;justify-content:center;padding:0"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/cell.js
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
function cell_Cell({
isActive = false,
value,
...props
}) {
const tooltipText = ALIGNMENT_LABEL[value];
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: tooltipText
}, (0,external_wp_element_namespaceObject.createElement)(CompositeItem, {
as: Cell,
role: "gridcell",
...props
}, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, null, value), (0,external_wp_element_namespaceObject.createElement)(Point, {
isActive: isActive,
role: "presentation"
})));
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useSealedState.js
/**
* React custom hook that returns the very first value passed to `initialState`,
* even if it changes between re-renders.
*/
function useSealedState(initialState) {
var _React$useState = (0,external_React_.useState)(initialState),
sealed = _React$useState[0];
return sealed;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/reverse-30eaa122.js
function groupItems(items) {
var groups = [[]];
var _loop = function _loop() {
var item = _step.value;
var group = groups.find(function (g) {
return !g[0] || g[0].groupId === item.groupId;
});
if (group) {
group.push(item);
} else {
groups.push([item]);
}
};
for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
_loop();
}
return groups;
}
function flatten(grid) {
var flattened = [];
for (var _iterator = _createForOfIteratorHelperLoose(grid), _step; !(_step = _iterator()).done;) {
var row = _step.value;
flattened.push.apply(flattened, row);
}
return flattened;
}
function reverse(array) {
return array.slice().reverse();
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/findEnabledItemById-8ddca752.js
function findEnabledItemById(items, id) {
if (!id) return undefined;
return items === null || items === void 0 ? void 0 : items.find(function (item) {
return item.id === id && !item.disabled;
});
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/applyState.js
function isUpdater(argument) {
return typeof argument === "function";
}
/**
* Receives a `setState` argument and calls it with `currentValue` if it's a
* function. Otherwise return the argument as the new value.
*
* @example
* import { applyState } from "reakit-utils";
*
* applyState((value) => value + 1, 1); // 2
* applyState(2, 1); // 2
*/
function applyState_applyState(argument, currentValue) {
if (isUpdater(argument)) {
return argument(currentValue);
}
return argument;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Id/IdState.js
function unstable_useIdState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
initialBaseId = _useSealedState.baseId;
var generateId = (0,external_React_.useContext)(unstable_IdContext);
var idCountRef = (0,external_React_.useRef)(0);
var _React$useState = (0,external_React_.useState)(function () {
return initialBaseId || generateId();
}),
baseId = _React$useState[0],
setBaseId = _React$useState[1];
return {
baseId: baseId,
setBaseId: setBaseId,
unstable_idCountRef: idCountRef
};
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/CompositeState.js
function isElementPreceding(element1, element2) {
return Boolean(element2.compareDocumentPosition(element1) & Node.DOCUMENT_POSITION_PRECEDING);
}
function findDOMIndex(items, item) {
return items.findIndex(function (currentItem) {
if (!currentItem.ref.current || !item.ref.current) {
return false;
}
return isElementPreceding(item.ref.current, currentItem.ref.current);
});
}
function getMaxLength(rows) {
var maxLength = 0;
for (var _iterator = _createForOfIteratorHelperLoose(rows), _step; !(_step = _iterator()).done;) {
var length = _step.value.length;
if (length > maxLength) {
maxLength = length;
}
}
return maxLength;
}
/**
* Turns [row1, row1, row2, row2] into [row1, row2, row1, row2]
*/
function verticalizeItems(items) {
var groups = groupItems(items);
var maxLength = getMaxLength(groups);
var verticalized = [];
for (var i = 0; i < maxLength; i += 1) {
for (var _iterator = _createForOfIteratorHelperLoose(groups), _step; !(_step = _iterator()).done;) {
var group = _step.value;
if (group[i]) {
verticalized.push(_objectSpread2(_objectSpread2({}, group[i]), {}, {
// If there's no groupId, it means that it's not a grid composite,
// but a single row instead. So, instead of verticalizing it, that
// is, assigning a different groupId based on the column index, we
// keep it undefined so they will be part of the same group.
// It's useful when using up/down on one-dimensional composites.
groupId: group[i].groupId ? "" + i : undefined
}));
}
}
}
return verticalized;
}
function createEmptyItem(groupId) {
return {
id: "__EMPTY_ITEM__",
disabled: true,
ref: {
current: null
},
groupId: groupId
};
}
/**
* Turns [[row1, row1], [row2]] into [[row1, row1], [row2, row2]]
*/
function fillGroups(groups, currentId, shift) {
var maxLength = getMaxLength(groups);
for (var _iterator = _createForOfIteratorHelperLoose(groups), _step; !(_step = _iterator()).done;) {
var group = _step.value;
for (var i = 0; i < maxLength; i += 1) {
var item = group[i];
if (!item || shift && item.disabled) {
var isFrist = i === 0;
var previousItem = isFrist && shift ? findFirstEnabledItem(group) : group[i - 1];
group[i] = previousItem && currentId !== (previousItem === null || previousItem === void 0 ? void 0 : previousItem.id) && shift ? previousItem : createEmptyItem(previousItem === null || previousItem === void 0 ? void 0 : previousItem.groupId);
}
}
}
return groups;
}
var nullItem = {
id: null,
ref: {
current: null
}
};
function placeItemsAfter(items, id, shouldInsertNullItem) {
var index = items.findIndex(function (item) {
return item.id === id;
});
return [].concat(items.slice(index + 1), shouldInsertNullItem ? [nullItem] : [], items.slice(0, index));
}
function getItemsInGroup(items, groupId) {
return items.filter(function (item) {
return item.groupId === groupId;
});
}
var map = {
horizontal: "vertical",
vertical: "horizontal"
};
function getOppositeOrientation(orientation) {
return orientation && map[orientation];
}
function addItemAtIndex(array, item, index) {
if (!(index in array)) {
return [].concat(array, [item]);
}
return [].concat(array.slice(0, index), [item], array.slice(index));
}
function sortBasedOnDOMPosition(items) {
var pairs = items.map(function (item, index) {
return [index, item];
});
var isOrderDifferent = false;
pairs.sort(function (_ref, _ref2) {
var indexA = _ref[0],
a = _ref[1];
var indexB = _ref2[0],
b = _ref2[1];
var elementA = a.ref.current;
var elementB = b.ref.current;
if (!elementA || !elementB) return 0; // a before b
if (isElementPreceding(elementA, elementB)) {
if (indexA > indexB) {
isOrderDifferent = true;
}
return -1;
} // a after b
if (indexA < indexB) {
isOrderDifferent = true;
}
return 1;
});
if (isOrderDifferent) {
return pairs.map(function (_ref3) {
var _ = _ref3[0],
item = _ref3[1];
return item;
});
}
return items;
}
function setItemsBasedOnDOMPosition(items, setItems) {
var sortedItems = sortBasedOnDOMPosition(items);
if (items !== sortedItems) {
setItems(sortedItems);
}
}
function getCommonParent(items) {
var _firstItem$ref$curren;
var firstItem = items[0],
nextItems = items.slice(1);
var parentElement = firstItem === null || firstItem === void 0 ? void 0 : (_firstItem$ref$curren = firstItem.ref.current) === null || _firstItem$ref$curren === void 0 ? void 0 : _firstItem$ref$curren.parentElement;
var _loop = function _loop() {
var parent = parentElement;
if (nextItems.every(function (item) {
return parent.contains(item.ref.current);
})) {
return {
v: parentElement
};
}
parentElement = parentElement.parentElement;
};
while (parentElement) {
var _ret = _loop();
if (typeof _ret === "object") return _ret.v;
}
return getDocument_getDocument(parentElement).body;
} // istanbul ignore next: JSDOM doesn't support IntersectionObverser
// See https://github.com/jsdom/jsdom/issues/2032
function useIntersectionObserver(items, setItems) {
var previousItems = (0,external_React_.useRef)([]);
(0,external_React_.useEffect)(function () {
var callback = function callback() {
var hasPreviousItems = !!previousItems.current.length; // We don't want to sort items if items have been just registered.
if (hasPreviousItems) {
setItemsBasedOnDOMPosition(items, setItems);
}
previousItems.current = items;
};
var root = getCommonParent(items);
var observer = new IntersectionObserver(callback, {
root: root
});
for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
var item = _step.value;
if (item.ref.current) {
observer.observe(item.ref.current);
}
}
return function () {
observer.disconnect();
};
}, [items]);
}
function useTimeoutObserver(items, setItems) {
(0,external_React_.useEffect)(function () {
var callback = function callback() {
return setItemsBasedOnDOMPosition(items, setItems);
};
var timeout = setTimeout(callback, 250);
return function () {
return clearTimeout(timeout);
};
});
}
function useSortBasedOnDOMPosition(items, setItems) {
if (typeof IntersectionObserver === "function") {
useIntersectionObserver(items, setItems);
} else {
useTimeoutObserver(items, setItems);
}
}
function reducer(state, action) {
var virtual = state.unstable_virtual,
rtl = state.rtl,
orientation = state.orientation,
items = state.items,
groups = state.groups,
currentId = state.currentId,
loop = state.loop,
wrap = state.wrap,
pastIds = state.pastIds,
shift = state.shift,
moves = state.unstable_moves,
includesBaseElement = state.unstable_includesBaseElement,
initialVirtual = state.initialVirtual,
initialRTL = state.initialRTL,
initialOrientation = state.initialOrientation,
initialCurrentId = state.initialCurrentId,
initialLoop = state.initialLoop,
initialWrap = state.initialWrap,
initialShift = state.initialShift,
hasSetCurrentId = state.hasSetCurrentId;
switch (action.type) {
case "registerGroup":
{
var _group = action.group; // If there are no groups yet, just add it as the first one
if (groups.length === 0) {
return _objectSpread2(_objectSpread2({}, state), {}, {
groups: [_group]
});
} // Finds the group index based on DOM position
var index = findDOMIndex(groups, _group);
return _objectSpread2(_objectSpread2({}, state), {}, {
groups: addItemAtIndex(groups, _group, index)
});
}
case "unregisterGroup":
{
var _id = action.id;
var nextGroups = groups.filter(function (group) {
return group.id !== _id;
}); // The group isn't registered, so do nothing
if (nextGroups.length === groups.length) {
return state;
}
return _objectSpread2(_objectSpread2({}, state), {}, {
groups: nextGroups
});
}
case "registerItem":
{
var _item = action.item; // Finds the item group based on the DOM hierarchy
var _group2 = groups.find(function (r) {
var _r$ref$current;
return (_r$ref$current = r.ref.current) === null || _r$ref$current === void 0 ? void 0 : _r$ref$current.contains(_item.ref.current);
}); // Group will be null if it's a one-dimensional composite
var nextItem = _objectSpread2({
groupId: _group2 === null || _group2 === void 0 ? void 0 : _group2.id
}, _item);
var _index = findDOMIndex(items, nextItem);
var nextState = _objectSpread2(_objectSpread2({}, state), {}, {
items: addItemAtIndex(items, nextItem, _index)
});
if (!hasSetCurrentId && !moves && initialCurrentId === undefined) {
var _findFirstEnabledItem;
// Sets currentId to the first enabled item. This runs whenever an item
// is registered because the first enabled item may be registered
// asynchronously.
return _objectSpread2(_objectSpread2({}, nextState), {}, {
currentId: (_findFirstEnabledItem = findFirstEnabledItem(nextState.items)) === null || _findFirstEnabledItem === void 0 ? void 0 : _findFirstEnabledItem.id
});
}
return nextState;
}
case "unregisterItem":
{
var _id2 = action.id;
var nextItems = items.filter(function (item) {
return item.id !== _id2;
}); // The item isn't registered, so do nothing
if (nextItems.length === items.length) {
return state;
} // Filters out the item that is being removed from the pastIds list
var nextPastIds = pastIds.filter(function (pastId) {
return pastId !== _id2;
});
var _nextState = _objectSpread2(_objectSpread2({}, state), {}, {
pastIds: nextPastIds,
items: nextItems
}); // If the current item is the item that is being removed, focus pastId
if (currentId && currentId === _id2) {
var nextId = includesBaseElement ? null : getCurrentId(_objectSpread2(_objectSpread2({}, _nextState), {}, {
currentId: nextPastIds[0]
}));
return _objectSpread2(_objectSpread2({}, _nextState), {}, {
currentId: nextId
});
}
return _nextState;
}
case "move":
{
var _id3 = action.id; // move() does nothing
if (_id3 === undefined) {
return state;
} // Removes the current item and the item that is receiving focus from the
// pastIds list
var filteredPastIds = pastIds.filter(function (pastId) {
return pastId !== currentId && pastId !== _id3;
}); // If there's a currentId, add it to the pastIds list so it can be focused
// if the new item gets removed or disabled
var _nextPastIds = currentId ? [currentId].concat(filteredPastIds) : filteredPastIds;
var _nextState2 = _objectSpread2(_objectSpread2({}, state), {}, {
pastIds: _nextPastIds
}); // move(null) will focus the composite element itself, not an item
if (_id3 === null) {
return _objectSpread2(_objectSpread2({}, _nextState2), {}, {
unstable_moves: moves + 1,
currentId: getCurrentId(_nextState2, _id3)
});
}
var _item2 = findEnabledItemById(items, _id3);
return _objectSpread2(_objectSpread2({}, _nextState2), {}, {
unstable_moves: _item2 ? moves + 1 : moves,
currentId: getCurrentId(_nextState2, _item2 === null || _item2 === void 0 ? void 0 : _item2.id)
});
}
case "next":
{
// If there's no item focused, we just move the first one
if (currentId == null) {
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "first"
}));
} // RTL doesn't make sense on vertical navigation
var isHorizontal = orientation !== "vertical";
var isRTL = rtl && isHorizontal;
var allItems = isRTL ? reverse(items) : items;
var currentItem = allItems.find(function (item) {
return item.id === currentId;
}); // If there's no item focused, we just move the first one
if (!currentItem) {
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "first"
}));
}
var isGrid = !!currentItem.groupId;
var currentIndex = allItems.indexOf(currentItem);
var _nextItems = allItems.slice(currentIndex + 1);
var nextItemsInGroup = getItemsInGroup(_nextItems, currentItem.groupId); // Home, End
if (action.allTheWay) {
// We reverse so we can get the last enabled item in the group. If it's
// RTL, nextItems and nextItemsInGroup are already reversed and don't
// have the items before the current one anymore. So we have to get
// items in group again with allItems.
var _nextItem2 = findFirstEnabledItem(isRTL ? getItemsInGroup(allItems, currentItem.groupId) : reverse(nextItemsInGroup));
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextItem2 === null || _nextItem2 === void 0 ? void 0 : _nextItem2.id
}));
}
var oppositeOrientation = getOppositeOrientation( // If it's a grid and orientation is not set, it's a next/previous
// call, which is inherently horizontal. up/down will call next with
// orientation set to vertical by default (see below on up/down cases).
isGrid ? orientation || "horizontal" : orientation);
var canLoop = loop && loop !== oppositeOrientation;
var canWrap = isGrid && wrap && wrap !== oppositeOrientation;
var hasNullItem = // `previous` and `up` will set action.hasNullItem, but when calling
// next directly, hasNullItem will only be true if it's not a grid and
// loop is set to true, which means that pressing right or down keys on
// grids will never focus the composite element. On one-dimensional
// composites that don't loop, pressing right or down keys also doesn't
// focus the composite element.
action.hasNullItem || !isGrid && canLoop && includesBaseElement;
if (canLoop) {
var loopItems = canWrap && !hasNullItem ? allItems : getItemsInGroup(allItems, currentItem.groupId); // Turns [0, 1, current, 3, 4] into [3, 4, 0, 1]
var sortedItems = placeItemsAfter(loopItems, currentId, hasNullItem);
var _nextItem3 = findFirstEnabledItem(sortedItems, currentId);
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextItem3 === null || _nextItem3 === void 0 ? void 0 : _nextItem3.id
}));
}
if (canWrap) {
var _nextItem4 = findFirstEnabledItem( // We can use nextItems, which contains all the next items, including
// items from other groups, to wrap between groups. However, if there
// is a null item (the composite element), we'll only use the next
// items in the group. So moving next from the last item will focus
// the composite element (null). On grid composites, horizontal
// navigation never focuses the composite element, only vertical.
hasNullItem ? nextItemsInGroup : _nextItems, currentId);
var _nextId = hasNullItem ? (_nextItem4 === null || _nextItem4 === void 0 ? void 0 : _nextItem4.id) || null : _nextItem4 === null || _nextItem4 === void 0 ? void 0 : _nextItem4.id;
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextId
}));
}
var _nextItem = findFirstEnabledItem(nextItemsInGroup, currentId);
if (!_nextItem && hasNullItem) {
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: null
}));
}
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextItem === null || _nextItem === void 0 ? void 0 : _nextItem.id
}));
}
case "previous":
{
// If currentId is initially set to null, the composite element will be
// focusable while navigating with arrow keys. But, if it's a grid, we
// don't want to focus the composite element with horizontal navigation.
var _isGrid = !!groups.length;
var _hasNullItem = !_isGrid && includesBaseElement;
var _nextState3 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
items: reverse(items)
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "next",
hasNullItem: _hasNullItem
}));
return _objectSpread2(_objectSpread2({}, _nextState3), {}, {
items: items
});
}
case "down":
{
var shouldShift = shift && !action.allTheWay; // First, we make sure groups have the same number of items by filling it
// with disabled fake items. Then, we reorganize the items list so
// [1-1, 1-2, 2-1, 2-2] becomes [1-1, 2-1, 1-2, 2-2].
var verticalItems = verticalizeItems(flatten(fillGroups(groupItems(items), currentId, shouldShift)));
var _canLoop = loop && loop !== "horizontal"; // Pressing down arrow key will only focus the composite element if loop
// is true or vertical.
var _hasNullItem2 = _canLoop && includesBaseElement;
var _nextState4 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
orientation: "vertical",
items: verticalItems
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "next",
hasNullItem: _hasNullItem2
}));
return _objectSpread2(_objectSpread2({}, _nextState4), {}, {
orientation: orientation,
items: items
});
}
case "up":
{
var _shouldShift = shift && !action.allTheWay;
var _verticalItems = verticalizeItems(reverse(flatten(fillGroups(groupItems(items), currentId, _shouldShift)))); // If currentId is initially set to null, we'll always focus the
// composite element when the up arrow key is pressed in the first row.
var _hasNullItem3 = includesBaseElement;
var _nextState5 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
orientation: "vertical",
items: _verticalItems
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "next",
hasNullItem: _hasNullItem3
}));
return _objectSpread2(_objectSpread2({}, _nextState5), {}, {
orientation: orientation,
items: items
});
}
case "first":
{
var firstItem = findFirstEnabledItem(items);
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: firstItem === null || firstItem === void 0 ? void 0 : firstItem.id
}));
}
case "last":
{
var _nextState6 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
items: reverse(items)
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "first"
}));
return _objectSpread2(_objectSpread2({}, _nextState6), {}, {
items: items
});
}
case "sort":
{
return _objectSpread2(_objectSpread2({}, state), {}, {
items: sortBasedOnDOMPosition(items),
groups: sortBasedOnDOMPosition(groups)
});
}
case "setVirtual":
return _objectSpread2(_objectSpread2({}, state), {}, {
unstable_virtual: applyState_applyState(action.virtual, virtual)
});
case "setRTL":
return _objectSpread2(_objectSpread2({}, state), {}, {
rtl: applyState_applyState(action.rtl, rtl)
});
case "setOrientation":
return _objectSpread2(_objectSpread2({}, state), {}, {
orientation: applyState_applyState(action.orientation, orientation)
});
case "setCurrentId":
{
var nextCurrentId = getCurrentId(_objectSpread2(_objectSpread2({}, state), {}, {
currentId: applyState_applyState(action.currentId, currentId)
}));
return _objectSpread2(_objectSpread2({}, state), {}, {
currentId: nextCurrentId,
hasSetCurrentId: true
});
}
case "setLoop":
return _objectSpread2(_objectSpread2({}, state), {}, {
loop: applyState_applyState(action.loop, loop)
});
case "setWrap":
return _objectSpread2(_objectSpread2({}, state), {}, {
wrap: applyState_applyState(action.wrap, wrap)
});
case "setShift":
return _objectSpread2(_objectSpread2({}, state), {}, {
shift: applyState_applyState(action.shift, shift)
});
case "setIncludesBaseElement":
{
return _objectSpread2(_objectSpread2({}, state), {}, {
unstable_includesBaseElement: applyState_applyState(action.includesBaseElement, includesBaseElement)
});
}
case "reset":
return _objectSpread2(_objectSpread2({}, state), {}, {
unstable_virtual: initialVirtual,
rtl: initialRTL,
orientation: initialOrientation,
currentId: getCurrentId(_objectSpread2(_objectSpread2({}, state), {}, {
currentId: initialCurrentId
})),
loop: initialLoop,
wrap: initialWrap,
shift: initialShift,
unstable_moves: 0,
pastIds: []
});
case "setItems":
{
return _objectSpread2(_objectSpread2({}, state), {}, {
items: action.items
});
}
default:
throw new Error();
}
}
function useAction(fn) {
return (0,external_React_.useCallback)(fn, []);
}
function useIsUnmountedRef() {
var isUnmountedRef = (0,external_React_.useRef)(false);
useIsomorphicEffect(function () {
return function () {
isUnmountedRef.current = true;
};
}, []);
return isUnmountedRef;
}
function useCompositeState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$unsta = _useSealedState.unstable_virtual,
virtual = _useSealedState$unsta === void 0 ? false : _useSealedState$unsta,
_useSealedState$rtl = _useSealedState.rtl,
rtl = _useSealedState$rtl === void 0 ? false : _useSealedState$rtl,
orientation = _useSealedState.orientation,
currentId = _useSealedState.currentId,
_useSealedState$loop = _useSealedState.loop,
loop = _useSealedState$loop === void 0 ? false : _useSealedState$loop,
_useSealedState$wrap = _useSealedState.wrap,
wrap = _useSealedState$wrap === void 0 ? false : _useSealedState$wrap,
_useSealedState$shift = _useSealedState.shift,
shift = _useSealedState$shift === void 0 ? false : _useSealedState$shift,
unstable_includesBaseElement = _useSealedState.unstable_includesBaseElement,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["unstable_virtual", "rtl", "orientation", "currentId", "loop", "wrap", "shift", "unstable_includesBaseElement"]);
var idState = unstable_useIdState(sealed);
var _React$useReducer = (0,external_React_.useReducer)(reducer, {
unstable_virtual: virtual,
rtl: rtl,
orientation: orientation,
items: [],
groups: [],
currentId: currentId,
loop: loop,
wrap: wrap,
shift: shift,
unstable_moves: 0,
pastIds: [],
unstable_includesBaseElement: unstable_includesBaseElement != null ? unstable_includesBaseElement : currentId === null,
initialVirtual: virtual,
initialRTL: rtl,
initialOrientation: orientation,
initialCurrentId: currentId,
initialLoop: loop,
initialWrap: wrap,
initialShift: shift
}),
_React$useReducer$ = _React$useReducer[0],
pastIds = _React$useReducer$.pastIds,
initialVirtual = _React$useReducer$.initialVirtual,
initialRTL = _React$useReducer$.initialRTL,
initialOrientation = _React$useReducer$.initialOrientation,
initialCurrentId = _React$useReducer$.initialCurrentId,
initialLoop = _React$useReducer$.initialLoop,
initialWrap = _React$useReducer$.initialWrap,
initialShift = _React$useReducer$.initialShift,
hasSetCurrentId = _React$useReducer$.hasSetCurrentId,
state = _objectWithoutPropertiesLoose(_React$useReducer$, ["pastIds", "initialVirtual", "initialRTL", "initialOrientation", "initialCurrentId", "initialLoop", "initialWrap", "initialShift", "hasSetCurrentId"]),
dispatch = _React$useReducer[1];
var _React$useState = (0,external_React_.useState)(false),
hasActiveWidget = _React$useState[0],
setHasActiveWidget = _React$useState[1]; // register/unregister may be called when this component is unmounted. We
// store the unmounted state here so we don't update the state if it's true.
// This only happens in a very specific situation.
// See https://github.com/reakit/reakit/issues/650
var isUnmountedRef = useIsUnmountedRef();
var setItems = (0,external_React_.useCallback)(function (items) {
return dispatch({
type: "setItems",
items: items
});
}, []);
useSortBasedOnDOMPosition(state.items, setItems);
return _objectSpread2(_objectSpread2(_objectSpread2({}, idState), state), {}, {
unstable_hasActiveWidget: hasActiveWidget,
unstable_setHasActiveWidget: setHasActiveWidget,
registerItem: useAction(function (item) {
if (isUnmountedRef.current) return;
dispatch({
type: "registerItem",
item: item
});
}),
unregisterItem: useAction(function (id) {
if (isUnmountedRef.current) return;
dispatch({
type: "unregisterItem",
id: id
});
}),
registerGroup: useAction(function (group) {
if (isUnmountedRef.current) return;
dispatch({
type: "registerGroup",
group: group
});
}),
unregisterGroup: useAction(function (id) {
if (isUnmountedRef.current) return;
dispatch({
type: "unregisterGroup",
id: id
});
}),
move: useAction(function (id) {
return dispatch({
type: "move",
id: id
});
}),
next: useAction(function (allTheWay) {
return dispatch({
type: "next",
allTheWay: allTheWay
});
}),
previous: useAction(function (allTheWay) {
return dispatch({
type: "previous",
allTheWay: allTheWay
});
}),
up: useAction(function (allTheWay) {
return dispatch({
type: "up",
allTheWay: allTheWay
});
}),
down: useAction(function (allTheWay) {
return dispatch({
type: "down",
allTheWay: allTheWay
});
}),
first: useAction(function () {
return dispatch({
type: "first"
});
}),
last: useAction(function () {
return dispatch({
type: "last"
});
}),
sort: useAction(function () {
return dispatch({
type: "sort"
});
}),
unstable_setVirtual: useAction(function (value) {
return dispatch({
type: "setVirtual",
virtual: value
});
}),
setRTL: useAction(function (value) {
return dispatch({
type: "setRTL",
rtl: value
});
}),
setOrientation: useAction(function (value) {
return dispatch({
type: "setOrientation",
orientation: value
});
}),
setCurrentId: useAction(function (value) {
return dispatch({
type: "setCurrentId",
currentId: value
});
}),
setLoop: useAction(function (value) {
return dispatch({
type: "setLoop",
loop: value
});
}),
setWrap: useAction(function (value) {
return dispatch({
type: "setWrap",
wrap: value
});
}),
setShift: useAction(function (value) {
return dispatch({
type: "setShift",
shift: value
});
}),
unstable_setIncludesBaseElement: useAction(function (value) {
return dispatch({
type: "setIncludesBaseElement",
includesBaseElement: value
});
}),
reset: useAction(function () {
return dispatch({
type: "reset"
});
})
});
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/fireBlurEvent.js
function createFocusEvent(element, type, eventInit) {
if (eventInit === void 0) {
eventInit = {};
}
if (typeof FocusEvent === "function") {
return new FocusEvent(type, eventInit);
}
return createEvent(element, type, eventInit);
}
/**
* Creates and dispatches a blur event in a way that also works on IE 11.
*
* @example
* import { fireBlurEvent } from "reakit-utils";
*
* fireBlurEvent(document.getElementById("id"));
*/
function fireBlurEvent(element, eventInit) {
var event = createFocusEvent(element, "blur", eventInit);
var defaultAllowed = element.dispatchEvent(event);
var bubbleInit = _rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, eventInit), {}, {
bubbles: true
});
element.dispatchEvent(createFocusEvent(element, "focusout", bubbleInit));
return defaultAllowed;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/fireKeyboardEvent.js
function createKeyboardEvent(element, type, eventInit) {
if (eventInit === void 0) {
eventInit = {};
}
if (typeof KeyboardEvent === "function") {
return new KeyboardEvent(type, eventInit);
} // IE 11 doesn't support Event constructors
var event = getDocument_getDocument(element).createEvent("KeyboardEvent");
event.initKeyboardEvent(type, eventInit.bubbles, eventInit.cancelable, getWindow(element), eventInit.key, eventInit.location, eventInit.ctrlKey, eventInit.altKey, eventInit.shiftKey, eventInit.metaKey);
return event;
}
/**
* Creates and dispatches `KeyboardEvent` in a way that also works on IE 11.
*
* @example
* import { fireKeyboardEvent } from "reakit-utils";
*
* fireKeyboardEvent(document.getElementById("id"), "keydown", {
* key: "ArrowDown",
* shiftKey: true,
* });
*/
function fireKeyboardEvent(element, type, eventInit) {
return element.dispatchEvent(createKeyboardEvent(element, type, eventInit));
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getNextActiveElementOnBlur.js
var isIE11 = canUseDOM_canUseDOM && "msCrypto" in window;
/**
* Cross-browser method that returns the next active element (the element that
* is receiving focus) after a blur event is dispatched. It receives the blur
* event object as the argument.
*
* @example
* import { getNextActiveElementOnBlur } from "reakit-utils";
*
* const element = document.getElementById("id");
* element.addEventListener("blur", (event) => {
* const nextActiveElement = getNextActiveElementOnBlur(event);
* });
*/
function getNextActiveElementOnBlur(event) {
// IE 11 doesn't support event.relatedTarget on blur.
// document.activeElement points the the next active element.
// On modern browsers, document.activeElement points to the current target.
if (isIE11) {
var activeElement = getActiveElement_getActiveElement(event.currentTarget);
return activeElement;
}
return event.relatedTarget;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/Composite.js
var Composite_isIE11 = canUseDOM_canUseDOM && "msCrypto" in window;
function canProxyKeyboardEvent(event) {
if (!isSelfTarget(event)) return false;
if (event.metaKey) return false;
if (event.key === "Tab") return false;
return true;
}
function useKeyboardEventProxy(virtual, currentItem, htmlEventHandler) {
var eventHandlerRef = useLiveRef(htmlEventHandler);
return (0,external_React_.useCallback)(function (event) {
var _eventHandlerRef$curr;
(_eventHandlerRef$curr = eventHandlerRef.current) === null || _eventHandlerRef$curr === void 0 ? void 0 : _eventHandlerRef$curr.call(eventHandlerRef, event);
if (event.defaultPrevented) return;
if (virtual && canProxyKeyboardEvent(event)) {
var currentElement = currentItem === null || currentItem === void 0 ? void 0 : currentItem.ref.current;
if (currentElement) {
if (!fireKeyboardEvent(currentElement, event.type, event)) {
event.preventDefault();
} // The event will be triggered on the composite item and then
// propagated up to this composite element again, so we can pretend
// that it wasn't called on this component in the first place.
if (event.currentTarget.contains(currentElement)) {
event.stopPropagation();
}
}
}
}, [virtual, currentItem]);
} // istanbul ignore next
function useActiveElementRef(elementRef) {
var activeElementRef = (0,external_React_.useRef)(null);
(0,external_React_.useEffect)(function () {
var document = getDocument_getDocument(elementRef.current);
var onFocus = function onFocus(event) {
var target = event.target;
activeElementRef.current = target;
};
document.addEventListener("focus", onFocus, true);
return function () {
document.removeEventListener("focus", onFocus, true);
};
}, []);
return activeElementRef;
}
function findFirstEnabledItemInTheLastRow(items) {
return findFirstEnabledItem(flatten(reverse(groupItems(items))));
}
function isItem(items, element) {
return items === null || items === void 0 ? void 0 : items.some(function (item) {
return !!element && item.ref.current === element;
});
}
function useScheduleUserFocus(currentItem) {
var currentItemRef = useLiveRef(currentItem);
var _React$useReducer = (0,external_React_.useReducer)(function (n) {
return n + 1;
}, 0),
scheduled = _React$useReducer[0],
schedule = _React$useReducer[1];
(0,external_React_.useEffect)(function () {
var _currentItemRef$curre;
var currentElement = (_currentItemRef$curre = currentItemRef.current) === null || _currentItemRef$curre === void 0 ? void 0 : _currentItemRef$curre.ref.current;
if (scheduled && currentElement) {
userFocus(currentElement);
}
}, [scheduled]);
return schedule;
}
var useComposite = createHook({
name: "Composite",
compose: [useTabbable],
keys: COMPOSITE_KEYS,
useOptions: function useOptions(options) {
return _objectSpread2(_objectSpread2({}, options), {}, {
currentId: getCurrentId(options)
});
},
useProps: function useProps(options, _ref) {
var htmlRef = _ref.ref,
htmlOnFocusCapture = _ref.onFocusCapture,
htmlOnFocus = _ref.onFocus,
htmlOnBlurCapture = _ref.onBlurCapture,
htmlOnKeyDown = _ref.onKeyDown,
htmlOnKeyDownCapture = _ref.onKeyDownCapture,
htmlOnKeyUpCapture = _ref.onKeyUpCapture,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref", "onFocusCapture", "onFocus", "onBlurCapture", "onKeyDown", "onKeyDownCapture", "onKeyUpCapture"]);
var ref = (0,external_React_.useRef)(null);
var currentItem = findEnabledItemById(options.items, options.currentId);
var previousElementRef = (0,external_React_.useRef)(null);
var onFocusCaptureRef = useLiveRef(htmlOnFocusCapture);
var onFocusRef = useLiveRef(htmlOnFocus);
var onBlurCaptureRef = useLiveRef(htmlOnBlurCapture);
var onKeyDownRef = useLiveRef(htmlOnKeyDown);
var scheduleUserFocus = useScheduleUserFocus(currentItem); // IE 11 doesn't support event.relatedTarget, so we use the active element
// ref instead.
var activeElementRef = Composite_isIE11 ? useActiveElementRef(ref) : undefined;
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (options.unstable_moves && !currentItem) {
false ? 0 : void 0; // If composite.move(null) has been called, the composite container
// will receive focus.
element === null || element === void 0 ? void 0 : element.focus();
}
}, [options.unstable_moves, currentItem]);
var onKeyDownCapture = useKeyboardEventProxy(options.unstable_virtual, currentItem, htmlOnKeyDownCapture);
var onKeyUpCapture = useKeyboardEventProxy(options.unstable_virtual, currentItem, htmlOnKeyUpCapture);
var onFocusCapture = (0,external_React_.useCallback)(function (event) {
var _onFocusCaptureRef$cu;
(_onFocusCaptureRef$cu = onFocusCaptureRef.current) === null || _onFocusCaptureRef$cu === void 0 ? void 0 : _onFocusCaptureRef$cu.call(onFocusCaptureRef, event);
if (event.defaultPrevented) return;
if (!options.unstable_virtual) return; // IE11 doesn't support event.relatedTarget, so we use the active
// element ref instead.
var previousActiveElement = (activeElementRef === null || activeElementRef === void 0 ? void 0 : activeElementRef.current) || event.relatedTarget;
var previousActiveElementWasItem = isItem(options.items, previousActiveElement);
if (isSelfTarget(event) && previousActiveElementWasItem) {
// Composite has been focused as a result of an item receiving focus.
// The composite item will move focus back to the composite
// container. In this case, we don't want to propagate this
// additional event nor call the onFocus handler passed to
// <Composite onFocus={...} />.
event.stopPropagation(); // We keep track of the previous active item element so we can
// manually fire a blur event on it later when the focus is moved to
// another item on the onBlurCapture event below.
previousElementRef.current = previousActiveElement;
}
}, [options.unstable_virtual, options.items]);
var onFocus = (0,external_React_.useCallback)(function (event) {
var _onFocusRef$current;
(_onFocusRef$current = onFocusRef.current) === null || _onFocusRef$current === void 0 ? void 0 : _onFocusRef$current.call(onFocusRef, event);
if (event.defaultPrevented) return;
if (options.unstable_virtual) {
if (isSelfTarget(event)) {
// This means that the composite element has been focused while the
// composite item has not. For example, by clicking on the
// composite element without touching any item, or by tabbing into
// the composite element. In this case, we want to trigger focus on
// the item, just like it would happen with roving tabindex.
// When it receives focus, the composite item will put focus back
// on the composite element, in which case hasItemWithFocus will be
// true.
scheduleUserFocus();
}
} else if (isSelfTarget(event)) {
var _options$setCurrentId;
// When the roving tabindex composite gets intentionally focused (for
// example, by clicking directly on it, and not on an item), we make
// sure to set the current id to null (which means the composite
// itself is focused).
(_options$setCurrentId = options.setCurrentId) === null || _options$setCurrentId === void 0 ? void 0 : _options$setCurrentId.call(options, null);
}
}, [options.unstable_virtual, options.setCurrentId]);
var onBlurCapture = (0,external_React_.useCallback)(function (event) {
var _onBlurCaptureRef$cur;
(_onBlurCaptureRef$cur = onBlurCaptureRef.current) === null || _onBlurCaptureRef$cur === void 0 ? void 0 : _onBlurCaptureRef$cur.call(onBlurCaptureRef, event);
if (event.defaultPrevented) return;
if (!options.unstable_virtual) return; // When virtual is set to true, we move focus from the composite
// container (this component) to the composite item that is being
// selected. Then we move focus back to the composite container. This
// is so we can provide the same API as the roving tabindex method,
// which means people can attach onFocus/onBlur handlers on the
// CompositeItem component regardless of whether it's virtual or not.
// This sequence of blurring and focusing items and composite may be
// confusing, so we ignore intermediate focus and blurs by stopping its
// propagation and not calling the passed onBlur handler (htmlOnBlur).
var currentElement = (currentItem === null || currentItem === void 0 ? void 0 : currentItem.ref.current) || null;
var nextActiveElement = getNextActiveElementOnBlur(event);
var nextActiveElementIsItem = isItem(options.items, nextActiveElement);
if (isSelfTarget(event) && nextActiveElementIsItem) {
// This is an intermediate blur event: blurring the composite
// container to focus an item (nextActiveElement).
if (nextActiveElement === currentElement) {
// The next active element will be the same as the current item in
// the state in two scenarios:
// - Moving focus with keyboard: the state is updated before the
// blur event is triggered, so here the current item is already
// pointing to the next active element.
// - Clicking on the current active item with a pointer: this
// will trigger blur on the composite element and then the next
// active element will be the same as the current item. Clicking on
// an item other than the current one doesn't end up here as the
// currentItem state will be updated only after it.
if (previousElementRef.current && previousElementRef.current !== nextActiveElement) {
// If there's a previous active item and it's not a click action,
// then we fire a blur event on it so it will work just like if
// it had DOM focus before (like when using roving tabindex).
fireBlurEvent(previousElementRef.current, event);
}
} else if (currentElement) {
// This will be true when the next active element is not the
// current element, but there's a current item. This will only
// happen when clicking with a pointer on a different item, when
// there's already an item selected, in which case currentElement
// is the item that is getting blurred, and nextActiveElement is
// the item that is being clicked.
fireBlurEvent(currentElement, event);
} // We want to ignore intermediate blur events, so we stop its
// propagation and return early so onFocus will not be called.
event.stopPropagation();
} else {
var targetIsItem = isItem(options.items, event.target);
if (!targetIsItem && currentElement) {
// If target is not a composite item, it may be the composite
// element itself (isSelfTarget) or a tabbable element inside the
// composite widget. This may be triggered by clicking outside the
// composite widget or by tabbing out of it. In either cases we
// want to fire a blur event on the current item.
fireBlurEvent(currentElement, event);
}
}
}, [options.unstable_virtual, options.items, currentItem]);
var onKeyDown = (0,external_React_.useCallback)(function (event) {
var _onKeyDownRef$current, _options$groups;
(_onKeyDownRef$current = onKeyDownRef.current) === null || _onKeyDownRef$current === void 0 ? void 0 : _onKeyDownRef$current.call(onKeyDownRef, event);
if (event.defaultPrevented) return;
if (options.currentId !== null) return;
if (!isSelfTarget(event)) return;
var isVertical = options.orientation !== "horizontal";
var isHorizontal = options.orientation !== "vertical";
var isGrid = !!((_options$groups = options.groups) !== null && _options$groups !== void 0 && _options$groups.length);
var up = function up() {
if (isGrid) {
var item = findFirstEnabledItemInTheLastRow(options.items);
if (item !== null && item !== void 0 && item.id) {
var _options$move;
(_options$move = options.move) === null || _options$move === void 0 ? void 0 : _options$move.call(options, item.id);
}
} else {
var _options$last;
(_options$last = options.last) === null || _options$last === void 0 ? void 0 : _options$last.call(options);
}
};
var keyMap = {
ArrowUp: (isGrid || isVertical) && up,
ArrowRight: (isGrid || isHorizontal) && options.first,
ArrowDown: (isGrid || isVertical) && options.first,
ArrowLeft: (isGrid || isHorizontal) && options.last,
Home: options.first,
End: options.last,
PageUp: options.first,
PageDown: options.last
};
var action = keyMap[event.key];
if (action) {
event.preventDefault();
action();
}
}, [options.currentId, options.orientation, options.groups, options.items, options.move, options.last, options.first]);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
id: options.baseId,
onFocus: onFocus,
onFocusCapture: onFocusCapture,
onBlurCapture: onBlurCapture,
onKeyDownCapture: onKeyDownCapture,
onKeyDown: onKeyDown,
onKeyUpCapture: onKeyUpCapture,
"aria-activedescendant": options.unstable_virtual ? (currentItem === null || currentItem === void 0 ? void 0 : currentItem.id) || undefined : undefined
}, htmlProps);
},
useComposeProps: function useComposeProps(options, htmlProps) {
htmlProps = useRole(options, htmlProps, true);
var tabbableHTMLProps = useTabbable(options, htmlProps, true);
if (options.unstable_virtual || options.currentId === null) {
// Composite will only be tabbable by default if the focus is managed
// using aria-activedescendant, which requires DOM focus on the container
// element (the composite)
return _objectSpread2({
tabIndex: 0
}, tabbableHTMLProps);
}
return _objectSpread2(_objectSpread2({}, htmlProps), {}, {
ref: tabbableHTMLProps.ref
});
}
});
var Composite = createComponent({
as: "div",
useHook: useComposite,
useCreateElement: function useCreateElement$1(type, props, children) {
false ? 0 : void 0;
return useCreateElement(type, props, children);
}
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Group/Group.js
// Automatically generated
var GROUP_KEYS = [];
var useGroup = createHook({
name: "Group",
compose: useRole,
keys: GROUP_KEYS,
useProps: function useProps(_, htmlProps) {
return _objectSpread2({
role: "group"
}, htmlProps);
}
});
var Group = createComponent({
as: "div",
useHook: useGroup
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/CompositeGroup.js
var useCompositeGroup = createHook({
name: "CompositeGroup",
compose: [useGroup, unstable_useId],
keys: COMPOSITE_GROUP_KEYS,
propsAreEqual: function propsAreEqual(prev, next) {
if (!next.id || prev.id !== next.id) {
return useGroup.unstable_propsAreEqual(prev, next);
}
var prevCurrentId = prev.currentId,
prevMoves = prev.unstable_moves,
prevProps = _objectWithoutPropertiesLoose(prev, ["currentId", "unstable_moves"]);
var nextCurrentId = next.currentId,
nextMoves = next.unstable_moves,
nextProps = _objectWithoutPropertiesLoose(next, ["currentId", "unstable_moves"]);
if (prev.items && next.items) {
var prevCurrentItem = findEnabledItemById(prev.items, prevCurrentId);
var nextCurrentItem = findEnabledItemById(next.items, nextCurrentId);
var prevGroupId = prevCurrentItem === null || prevCurrentItem === void 0 ? void 0 : prevCurrentItem.groupId;
var nextGroupId = nextCurrentItem === null || nextCurrentItem === void 0 ? void 0 : nextCurrentItem.groupId;
if (next.id === nextGroupId || next.id === prevGroupId) {
return false;
}
}
return useGroup.unstable_propsAreEqual(prevProps, nextProps);
},
useProps: function useProps(options, _ref) {
var htmlRef = _ref.ref,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref"]);
var ref = (0,external_React_.useRef)(null);
var id = options.id; // We need this to be called before CompositeItems' register
useIsomorphicEffect(function () {
var _options$registerGrou;
if (!id) return undefined;
(_options$registerGrou = options.registerGroup) === null || _options$registerGrou === void 0 ? void 0 : _options$registerGrou.call(options, {
id: id,
ref: ref
});
return function () {
var _options$unregisterGr;
(_options$unregisterGr = options.unregisterGroup) === null || _options$unregisterGr === void 0 ? void 0 : _options$unregisterGr.call(options, id);
};
}, [id, options.registerGroup, options.unregisterGroup]);
return _objectSpread2({
ref: useForkRef(ref, htmlRef)
}, htmlProps);
}
});
var CompositeGroup = createComponent({
as: "div",
useHook: useCompositeGroup
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/styles/alignment-matrix-control-icon-styles.js
function alignment_matrix_control_icon_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const alignment_matrix_control_icon_styles_rootSize = () => {
const padding = 1.5;
const size = 24;
return /*#__PURE__*/emotion_react_browser_esm_css({
gridTemplateRows: `repeat( 3, calc( ${size - padding * 2}px / 3))`,
padding,
maxHeight: size,
maxWidth: size
}, true ? "" : 0, true ? "" : 0);
};
const rootPointerEvents = ({
disablePointerEvents
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css({
pointerEvents: disablePointerEvents ? 'none' : undefined
}, true ? "" : 0, true ? "" : 0);
};
const Wrapper = createStyled("div", true ? {
target: "erowt52"
} : 0)( true ? {
name: "ogl07i",
styles: "box-sizing:border-box;padding:2px"
} : 0);
const alignment_matrix_control_icon_styles_Root = createStyled("div", true ? {
target: "erowt51"
} : 0)("transform-origin:top left;height:100%;width:100%;", rootBase, ";", alignment_matrix_control_icon_styles_rootSize, ";", rootPointerEvents, ";" + ( true ? "" : 0));
const alignment_matrix_control_icon_styles_pointActive = ({
isActive
}) => {
const boxShadow = isActive ? `0 0 0 1px currentColor` : null;
return /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:", boxShadow, ";color:currentColor;*:hover>&{color:currentColor;}" + ( true ? "" : 0), true ? "" : 0);
};
const alignment_matrix_control_icon_styles_Point = createStyled("span", true ? {
target: "erowt50"
} : 0)("height:2px;width:2px;", pointBase, ";", alignment_matrix_control_icon_styles_pointActive, ";" + ( true ? "" : 0));
const alignment_matrix_control_icon_styles_Cell = Cell;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/icon.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const BASE_SIZE = 24;
function AlignmentMatrixControlIcon({
className,
disablePointerEvents = true,
size = BASE_SIZE,
style = {},
value = 'center',
...props
}) {
const alignIndex = getAlignmentIndex(value);
const scale = (size / BASE_SIZE).toFixed(2);
const classes = classnames_default()('component-alignment-matrix-control-icon', className);
const styles = { ...style,
transform: `scale(${scale})`
};
return (0,external_wp_element_namespaceObject.createElement)(alignment_matrix_control_icon_styles_Root, { ...props,
className: classes,
disablePointerEvents: disablePointerEvents,
role: "presentation",
style: styles
}, ALIGNMENTS.map((align, index) => {
const isActive = alignIndex === index;
return (0,external_wp_element_namespaceObject.createElement)(alignment_matrix_control_icon_styles_Cell, {
key: align
}, (0,external_wp_element_namespaceObject.createElement)(alignment_matrix_control_icon_styles_Point, {
isActive: isActive
}));
}));
}
/* harmony default export */ var icon = (AlignmentMatrixControlIcon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const alignment_matrix_control_noop = () => {};
function useBaseId(id) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(AlignmentMatrixControl, 'alignment-matrix-control');
return id || instanceId;
}
/**
*
* AlignmentMatrixControl components enable adjustments to horizontal and vertical alignments for UI.
*
* ```jsx
* import { __experimentalAlignmentMatrixControl as AlignmentMatrixControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ alignment, setAlignment ] = useState( 'center center' );
*
* return (
* <AlignmentMatrixControl
* value={ alignment }
* onChange={ setAlignment }
* />
* );
* };
* ```
*/
function AlignmentMatrixControl({
className,
id,
label = (0,external_wp_i18n_namespaceObject.__)('Alignment Matrix Control'),
defaultValue = 'center center',
value,
onChange = alignment_matrix_control_noop,
width = 92,
...props
}) {
const [immutableDefaultValue] = (0,external_wp_element_namespaceObject.useState)(value !== null && value !== void 0 ? value : defaultValue);
const baseId = useBaseId(id);
const initialCurrentId = getItemId(baseId, immutableDefaultValue);
const composite = useCompositeState({
baseId,
currentId: initialCurrentId,
rtl: (0,external_wp_i18n_namespaceObject.isRTL)()
});
const handleOnChange = nextValue => {
onChange(nextValue);
};
const {
setCurrentId
} = composite;
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (typeof value !== 'undefined') {
setCurrentId(getItemId(baseId, value));
}
}, [value, setCurrentId, baseId]);
const classes = classnames_default()('component-alignment-matrix-control', className);
return (0,external_wp_element_namespaceObject.createElement)(Composite, { ...props,
...composite,
"aria-label": label,
as: Root,
className: classes,
role: "grid",
size: width
}, GRID.map((cells, index) => (0,external_wp_element_namespaceObject.createElement)(CompositeGroup, { ...composite,
as: Row,
role: "row",
key: index
}, cells.map(cell => {
const cellId = getItemId(baseId, cell);
const isActive = composite.currentId === cellId;
return (0,external_wp_element_namespaceObject.createElement)(cell_Cell, { ...composite,
id: cellId,
isActive: isActive,
key: cell,
value: cell,
onFocus: () => handleOnChange(cell),
tabIndex: isActive ? 0 : -1
});
}))));
}
AlignmentMatrixControl.Icon = icon;
/* harmony default export */ var alignment_matrix_control = (AlignmentMatrixControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/animate/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* @param type The animation type
* @return Default origin
*/
function getDefaultOrigin(type) {
return type === 'appear' ? 'top' : 'left';
}
/**
* @param options
*
* @return ClassName that applies the animations
*/
function getAnimateClassName(options) {
if (options.type === 'loading') {
return classnames_default()('components-animate__loading');
}
const {
type,
origin = getDefaultOrigin(type)
} = options;
if (type === 'appear') {
const [yAxis, xAxis = 'center'] = origin.split(' ');
return classnames_default()('components-animate__appear', {
['is-from-' + xAxis]: xAxis !== 'center',
['is-from-' + yAxis]: yAxis !== 'middle'
});
}
if (type === 'slide-in') {
return classnames_default()('components-animate__slide-in', 'is-from-' + origin);
}
return undefined;
}
/**
* Simple interface to introduce animations to components.
*
* ```jsx
* import { Animate, Notice } from '@wordpress/components';
*
* const MyAnimatedNotice = () => (
* <Animate type="slide-in" options={ { origin: 'top' } }>
* { ( { className } ) => (
* <Notice className={ className } status="success">
* <p>Animation finished.</p>
* </Notice>
* ) }
* </Animate>
* );
* ```
*/
function Animate({
type,
options = {},
children
}) {
return children({
className: getAnimateClassName({
type,
...options
})
});
}
/* harmony default export */ var animate = (Animate);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs
function useIsMounted() {
const isMounted = (0,external_React_.useRef)(false);
useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-force-update.mjs
function use_force_update_useForceUpdate() {
const isMounted = useIsMounted();
const [forcedRenderCount, setForcedRenderCount] = (0,external_React_.useState)(0);
const forceRender = (0,external_React_.useCallback)(() => {
isMounted.current && setForcedRenderCount(forcedRenderCount + 1);
}, [forcedRenderCount]);
/**
* Defer this to the end of the next animation frame in case there are multiple
* synchronous calls.
*/
const deferredForceRender = (0,external_React_.useCallback)(() => sync.postRender(forceRender), [forceRender]);
return [deferredForceRender, forcedRenderCount];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs
/**
* Measurement functionality has to be within a separate component
* to leverage snapshot lifecycle.
*/
class PopChildMeasure extends external_React_.Component {
getSnapshotBeforeUpdate(prevProps) {
const element = this.props.childRef.current;
if (element && prevProps.isPresent && !this.props.isPresent) {
const size = this.props.sizeRef.current;
size.height = element.offsetHeight || 0;
size.width = element.offsetWidth || 0;
size.top = element.offsetTop;
size.left = element.offsetLeft;
}
return null;
}
/**
* Required with getSnapshotBeforeUpdate to stop React complaining.
*/
componentDidUpdate() { }
render() {
return this.props.children;
}
}
function PopChild({ children, isPresent }) {
const id = (0,external_React_.useId)();
const ref = (0,external_React_.useRef)(null);
const size = (0,external_React_.useRef)({
width: 0,
height: 0,
top: 0,
left: 0,
});
/**
* We create and inject a style block so we can apply this explicit
* sizing in a non-destructive manner by just deleting the style block.
*
* We can't apply size via render as the measurement happens
* in getSnapshotBeforeUpdate (post-render), likewise if we apply the
* styles directly on the DOM node, we might be overwriting
* styles set via the style prop.
*/
(0,external_React_.useInsertionEffect)(() => {
const { width, height, top, left } = size.current;
if (isPresent || !ref.current || !width || !height)
return;
ref.current.dataset.motionPopId = id;
const style = document.createElement("style");
document.head.appendChild(style);
if (style.sheet) {
style.sheet.insertRule(`
[data-motion-pop-id="${id}"] {
position: absolute !important;
width: ${width}px !important;
height: ${height}px !important;
top: ${top}px !important;
left: ${left}px !important;
}
`);
}
return () => {
document.head.removeChild(style);
};
}, [isPresent]);
return (external_React_.createElement(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size }, external_React_.cloneElement(children, { ref })));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs
const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, }) => {
const presenceChildren = useConstant(newChildrenMap);
const id = (0,external_React_.useId)();
const context = (0,external_React_.useMemo)(() => ({
id,
initial,
isPresent,
custom,
onExitComplete: (childId) => {
presenceChildren.set(childId, true);
for (const isComplete of presenceChildren.values()) {
if (!isComplete)
return; // can stop searching when any is incomplete
}
onExitComplete && onExitComplete();
},
register: (childId) => {
presenceChildren.set(childId, false);
return () => presenceChildren.delete(childId);
},
}),
/**
* If the presence of a child affects the layout of the components around it,
* we want to make a new context value to ensure they get re-rendered
* so they can detect that layout change.
*/
presenceAffectsLayout ? undefined : [isPresent]);
(0,external_React_.useMemo)(() => {
presenceChildren.forEach((_, key) => presenceChildren.set(key, false));
}, [isPresent]);
/**
* If there's no `motion` components to fire exit animations, we want to remove this
* component immediately.
*/
external_React_.useEffect(() => {
!isPresent &&
!presenceChildren.size &&
onExitComplete &&
onExitComplete();
}, [isPresent]);
if (mode === "popLayout") {
children = external_React_.createElement(PopChild, { isPresent: isPresent }, children);
}
return (external_React_.createElement(PresenceContext_PresenceContext.Provider, { value: context }, children));
};
function newChildrenMap() {
return new Map();
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs
function useUnmountEffect(callback) {
return (0,external_React_.useEffect)(() => () => callback(), []);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs
const getChildKey = (child) => child.key || "";
function updateChildLookup(children, allChildren) {
children.forEach((child) => {
const key = getChildKey(child);
allChildren.set(key, child);
});
}
function onlyElements(children) {
const filtered = [];
// We use forEach here instead of map as map mutates the component key by preprending `.$`
external_React_.Children.forEach(children, (child) => {
if ((0,external_React_.isValidElement)(child))
filtered.push(child);
});
return filtered;
}
/**
* `AnimatePresence` enables the animation of components that have been removed from the tree.
*
* When adding/removing more than a single child, every child **must** be given a unique `key` prop.
*
* Any `motion` components that have an `exit` property defined will animate out when removed from
* the tree.
*
* ```jsx
* import { motion, AnimatePresence } from 'framer-motion'
*
* export const Items = ({ items }) => (
* <AnimatePresence>
* {items.map(item => (
* <motion.div
* key={item.id}
* initial={{ opacity: 0 }}
* animate={{ opacity: 1 }}
* exit={{ opacity: 0 }}
* />
* ))}
* </AnimatePresence>
* )
* ```
*
* You can sequence exit animations throughout a tree using variants.
*
* If a child contains multiple `motion` components with `exit` props, it will only unmount the child
* once all `motion` components have finished animating out. Likewise, any components using
* `usePresence` all need to call `safeToRemove`.
*
* @public
*/
const AnimatePresence = ({ children, custom, initial = true, onExitComplete, exitBeforeEnter, presenceAffectsLayout = true, mode = "sync", }) => {
invariant(!exitBeforeEnter, "Replace exitBeforeEnter with mode='wait'");
// We want to force a re-render once all exiting animations have finished. We
// either use a local forceRender function, or one from a parent context if it exists.
let [forceRender] = use_force_update_useForceUpdate();
const forceRenderLayoutGroup = (0,external_React_.useContext)(LayoutGroupContext).forceRender;
if (forceRenderLayoutGroup)
forceRender = forceRenderLayoutGroup;
const isMounted = useIsMounted();
// Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key
const filteredChildren = onlyElements(children);
let childrenToRender = filteredChildren;
const exiting = new Set();
// Keep a living record of the children we're actually rendering so we
// can diff to figure out which are entering and exiting
const presentChildren = (0,external_React_.useRef)(childrenToRender);
// A lookup table to quickly reference components by key
const allChildren = (0,external_React_.useRef)(new Map()).current;
// If this is the initial component render, just deal with logic surrounding whether
// we play onMount animations or not.
const isInitialRender = (0,external_React_.useRef)(true);
useIsomorphicLayoutEffect(() => {
isInitialRender.current = false;
updateChildLookup(filteredChildren, allChildren);
presentChildren.current = childrenToRender;
});
useUnmountEffect(() => {
isInitialRender.current = true;
allChildren.clear();
exiting.clear();
});
if (isInitialRender.current) {
return (external_React_.createElement(external_React_.Fragment, null, childrenToRender.map((child) => (external_React_.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, initial: initial ? undefined : false, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child)))));
}
// If this is a subsequent render, deal with entering and exiting children
childrenToRender = [...childrenToRender];
// Diff the keys of the currently-present and target children to update our
// exiting list.
const presentKeys = presentChildren.current.map(getChildKey);
const targetKeys = filteredChildren.map(getChildKey);
// Diff the present children with our target children and mark those that are exiting
const numPresent = presentKeys.length;
for (let i = 0; i < numPresent; i++) {
const key = presentKeys[i];
if (targetKeys.indexOf(key) === -1) {
exiting.add(key);
}
}
// If we currently have exiting children, and we're deferring rendering incoming children
// until after all current children have exiting, empty the childrenToRender array
if (mode === "wait" && exiting.size) {
childrenToRender = [];
}
// Loop through all currently exiting components and clone them to overwrite `animate`
// with any `exit` prop they might have defined.
exiting.forEach((key) => {
// If this component is actually entering again, early return
if (targetKeys.indexOf(key) !== -1)
return;
const child = allChildren.get(key);
if (!child)
return;
const insertionIndex = presentKeys.indexOf(key);
const onExit = () => {
allChildren.delete(key);
exiting.delete(key);
// Remove this child from the present children
const removeIndex = presentChildren.current.findIndex((presentChild) => presentChild.key === key);
presentChildren.current.splice(removeIndex, 1);
// Defer re-rendering until all exiting children have indeed left
if (!exiting.size) {
presentChildren.current = filteredChildren;
if (isMounted.current === false)
return;
forceRender();
onExitComplete && onExitComplete();
}
};
childrenToRender.splice(insertionIndex, 0, external_React_.createElement(PresenceChild, { key: getChildKey(child), isPresent: false, onExitComplete: onExit, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child));
});
// Add `MotionContext` even to children that don't need it to ensure we're rendering
// the same tree between renders
childrenToRender = childrenToRender.map((child) => {
const key = child.key;
return exiting.has(key) ? (child) : (external_React_.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child));
});
if (false) {}
return (external_React_.createElement(external_React_.Fragment, null, exiting.size
? childrenToRender
: childrenToRender.map((child) => (0,external_React_.cloneElement)(child))));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/context.js
/**
* WordPress dependencies
*/
const FlexContext = (0,external_wp_element_namespaceObject.createContext)({
flexItemDisplay: undefined
});
const useFlexContext = () => (0,external_wp_element_namespaceObject.useContext)(FlexContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/styles.js
function styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const Flex = true ? {
name: "zjik7",
styles: "display:flex"
} : 0;
const Item = true ? {
name: "qgaee5",
styles: "display:block;max-height:100%;max-width:100%;min-height:0;min-width:0"
} : 0;
const block = true ? {
name: "82a6rk",
styles: "flex:1"
} : 0;
/**
* Workaround to optimize DOM rendering.
* We'll enhance alignment with naive parent flex assumptions.
*
* Trade-off:
* Far less DOM less. However, UI rendering is not as reliable.
*/
/**
* Improves stability of width/height rendering.
* https://github.com/ItsJonQ/g2/pull/149
*/
const ItemsColumn = true ? {
name: "13nosa1",
styles: ">*{min-height:0;}"
} : 0;
const ItemsRow = true ? {
name: "1pwxzk4",
styles: ">*{min-width:0;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-item/hook.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function useFlexItem(props) {
const {
className,
display: displayProp,
isBlock = false,
...otherProps
} = useContextSystem(props, 'FlexItem');
const sx = {};
const contextDisplay = useFlexContext().flexItemDisplay;
sx.Base = /*#__PURE__*/emotion_react_browser_esm_css({
display: displayProp || contextDisplay
}, true ? "" : 0, true ? "" : 0);
const cx = useCx();
const classes = cx(Item, sx.Base, isBlock && block, className);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-block/hook.js
/**
* Internal dependencies
*/
function useFlexBlock(props) {
const otherProps = useContextSystem(props, 'FlexBlock');
const flexItemProps = useFlexItem({
isBlock: true,
...otherProps
});
return flexItemProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-block/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlexBlock(props, forwardedRef) {
const flexBlockProps = useFlexBlock(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...flexBlockProps,
ref: forwardedRef
});
}
/**
* `FlexBlock` is a primitive layout component that adaptively resizes content
* within layout containers like `Flex`.
*
* ```jsx
* import { Flex, FlexBlock } from '@wordpress/components';
*
* function Example() {
* return (
* <Flex>
* <FlexBlock>...</FlexBlock>
* </Flex>
* );
* }
* ```
*/
const FlexBlock = contextConnect(UnconnectedFlexBlock, 'FlexBlock');
/* harmony default export */ var flex_block_component = (FlexBlock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/space.js
/**
* The argument value for the `space()` utility function.
*
* When this is a number or a numeric string, it will be interpreted as a
* multiplier for the grid base value (4px). For example, `space( 2 )` will be 8px.
*
* Otherwise, it will be interpreted as a literal CSS length value. For example,
* `space( 'auto' )` will be 'auto', and `space( '2px' )` will be 2px.
*/
const GRID_BASE = '4px';
/**
* A function that handles numbers, numeric strings, and unit values.
*
* When given a number or a numeric string, it will return the grid-based
* value as a factor of GRID_BASE, defined above.
*
* When given a unit value or one of the named CSS values like `auto`,
* it will simply return the value back.
*
* @param value A number, numeric string, or a unit value.
*/
function space(value) {
if (typeof value === 'undefined') {
return undefined;
} // Handle empty strings, if it's the number 0 this still works.
if (!value) {
return '0';
}
const asInt = typeof value === 'number' ? value : Number(value); // Test if the input has a unit, was NaN, or was one of the named CSS values (like `auto`), in which case just use that value.
if (typeof window !== 'undefined' && window.CSS?.supports?.('margin', value.toString()) || Number.isNaN(asInt)) {
return value.toString();
}
return `calc(${GRID_BASE} * ${value})`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/rtl.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const LOWER_LEFT_REGEXP = new RegExp(/-left/g);
const LOWER_RIGHT_REGEXP = new RegExp(/-right/g);
const UPPER_LEFT_REGEXP = new RegExp(/Left/g);
const UPPER_RIGHT_REGEXP = new RegExp(/Right/g);
/**
* Flips a CSS property from left <-> right.
*
* @param {string} key The CSS property name.
*
* @return {string} The flipped CSS property name, if applicable.
*/
function getConvertedKey(key) {
if (key === 'left') {
return 'right';
}
if (key === 'right') {
return 'left';
}
if (LOWER_LEFT_REGEXP.test(key)) {
return key.replace(LOWER_LEFT_REGEXP, '-right');
}
if (LOWER_RIGHT_REGEXP.test(key)) {
return key.replace(LOWER_RIGHT_REGEXP, '-left');
}
if (UPPER_LEFT_REGEXP.test(key)) {
return key.replace(UPPER_LEFT_REGEXP, 'Right');
}
if (UPPER_RIGHT_REGEXP.test(key)) {
return key.replace(UPPER_RIGHT_REGEXP, 'Left');
}
return key;
}
/**
* An incredibly basic ltr -> rtl converter for style properties
*
* @param {import('react').CSSProperties} ltrStyles
*
* @return {import('react').CSSProperties} Converted ltr -> rtl styles
*/
const convertLTRToRTL = (ltrStyles = {}) => {
return Object.fromEntries(Object.entries(ltrStyles).map(([key, value]) => [getConvertedKey(key), value]));
};
/**
* A higher-order function that create an incredibly basic ltr -> rtl style converter for CSS objects.
*
* @param {import('react').CSSProperties} ltrStyles Ltr styles. Converts and renders from ltr -> rtl styles, if applicable.
* @param {import('react').CSSProperties} [rtlStyles] Rtl styles. Renders if provided.
*
* @return {() => import('@emotion/react').SerializedStyles} A function to output CSS styles for Emotion's renderer
*/
function rtl(ltrStyles = {}, rtlStyles) {
return () => {
if (rtlStyles) {
// @ts-ignore: `css` types are wrong, it can accept an object: https://emotion.sh/docs/object-styles#with-css
return (0,external_wp_i18n_namespaceObject.isRTL)() ? /*#__PURE__*/emotion_react_browser_esm_css(rtlStyles, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(ltrStyles, true ? "" : 0);
} // @ts-ignore: `css` types are wrong, it can accept an object: https://emotion.sh/docs/object-styles#with-css
return (0,external_wp_i18n_namespaceObject.isRTL)() ? /*#__PURE__*/emotion_react_browser_esm_css(convertLTRToRTL(ltrStyles), true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(ltrStyles, true ? "" : 0);
};
}
/**
* Call this in the `useMemo` dependency array to ensure that subsequent renders will
* cause rtl styles to update based on the `isRTL` return value even if all other dependencies
* remain the same.
*
* @example
* const styles = useMemo( () => {
* return css`
* ${ rtl( { marginRight: '10px' } ) }
* `;
* }, [ rtl.watch() ] );
*/
rtl.watch = () => (0,external_wp_i18n_namespaceObject.isRTL)();
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spacer/hook.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const isDefined = o => typeof o !== 'undefined' && o !== null;
function useSpacer(props) {
const {
className,
margin,
marginBottom = 2,
marginLeft,
marginRight,
marginTop,
marginX,
marginY,
padding,
paddingBottom,
paddingLeft,
paddingRight,
paddingTop,
paddingX,
paddingY,
...otherProps
} = useContextSystem(props, 'Spacer');
const cx = useCx();
const classes = cx(isDefined(margin) && /*#__PURE__*/emotion_react_browser_esm_css("margin:", space(margin), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginY) && /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(marginY), ";margin-top:", space(marginY), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginX) && /*#__PURE__*/emotion_react_browser_esm_css("margin-left:", space(marginX), ";margin-right:", space(marginX), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginTop) && /*#__PURE__*/emotion_react_browser_esm_css("margin-top:", space(marginTop), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginBottom) && /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(marginBottom), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginLeft) && rtl({
marginLeft: space(marginLeft)
})(), isDefined(marginRight) && rtl({
marginRight: space(marginRight)
})(), isDefined(padding) && /*#__PURE__*/emotion_react_browser_esm_css("padding:", space(padding), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingY) && /*#__PURE__*/emotion_react_browser_esm_css("padding-bottom:", space(paddingY), ";padding-top:", space(paddingY), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingX) && /*#__PURE__*/emotion_react_browser_esm_css("padding-left:", space(paddingX), ";padding-right:", space(paddingX), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingTop) && /*#__PURE__*/emotion_react_browser_esm_css("padding-top:", space(paddingTop), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingBottom) && /*#__PURE__*/emotion_react_browser_esm_css("padding-bottom:", space(paddingBottom), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingLeft) && rtl({
paddingLeft: space(paddingLeft)
})(), isDefined(paddingRight) && rtl({
paddingRight: space(paddingRight)
})(), className);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spacer/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedSpacer(props, forwardedRef) {
const spacerProps = useSpacer(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...spacerProps,
ref: forwardedRef
});
}
/**
* `Spacer` is a primitive layout component that providers inner (`padding`) or outer (`margin`) space in-between components. It can also be used to adaptively provide space within an `HStack` or `VStack`.
*
* `Spacer` comes with a bunch of shorthand props to adjust `margin` and `padding`. The values of these props
* can either be a number (which will act as a multiplier to the library's grid system base of 4px),
* or a literal CSS value string.
*
* ```jsx
* import { Spacer } from `@wordpress/components`
*
* function Example() {
* return (
* <View>
* <Spacer>
* <Heading>WordPress.org</Heading>
* </Spacer>
* <Text>
* Code is Poetry
* </Text>
* </View>
* );
* }
* ```
*/
const Spacer = contextConnect(UnconnectedSpacer, 'Spacer');
/* harmony default export */ var spacer_component = (Spacer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/reset.js
/**
* WordPress dependencies
*/
const reset_reset = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M7 11.5h10V13H7z"
}));
/* harmony default export */ var library_reset = (reset_reset);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/use-responsive-value.js
/**
* WordPress dependencies
*/
const breakpoints = ['40em', '52em', '64em'];
const useBreakpointIndex = (options = {}) => {
const {
defaultIndex = 0
} = options;
if (typeof defaultIndex !== 'number') {
throw new TypeError(`Default breakpoint index should be a number. Got: ${defaultIndex}, ${typeof defaultIndex}`);
} else if (defaultIndex < 0 || defaultIndex > breakpoints.length - 1) {
throw new RangeError(`Default breakpoint index out of range. Theme has ${breakpoints.length} breakpoints, got index ${defaultIndex}`);
}
const [value, setValue] = (0,external_wp_element_namespaceObject.useState)(defaultIndex);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const getIndex = () => breakpoints.filter(bp => {
return typeof window !== 'undefined' ? window.matchMedia(`screen and (min-width: ${bp})`).matches : false;
}).length;
const onResize = () => {
const newValue = getIndex();
if (value !== newValue) {
setValue(newValue);
}
};
onResize();
if (typeof window !== 'undefined') {
window.addEventListener('resize', onResize);
}
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('resize', onResize);
}
};
}, [value]);
return value;
};
function useResponsiveValue(values, options = {}) {
const index = useBreakpointIndex(options); // Allow calling the function with a "normal" value without having to check on the outside.
if (!Array.isArray(values) && typeof values !== 'function') return values;
const array = values || [];
/* eslint-disable jsdoc/no-undefined-types */
return (
/** @type {T[]} */
array[
/* eslint-enable jsdoc/no-undefined-types */
index >= array.length ? array.length - 1 : index]
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function hook_useDeprecatedProps(props) {
const {
isReversed,
...otherProps
} = props;
if (typeof isReversed !== 'undefined') {
external_wp_deprecated_default()('Flex isReversed', {
alternative: 'Flex direction="row-reverse" or "column-reverse"',
since: '5.9'
});
return { ...otherProps,
direction: isReversed ? 'row-reverse' : 'row'
};
}
return otherProps;
}
function useFlex(props) {
const {
align,
className,
direction: directionProp = 'row',
expanded = true,
gap = 2,
justify = 'space-between',
wrap = false,
...otherProps
} = useContextSystem(hook_useDeprecatedProps(props), 'Flex');
const directionAsArray = Array.isArray(directionProp) ? directionProp : [directionProp];
const direction = useResponsiveValue(directionAsArray);
const isColumn = typeof direction === 'string' && !!direction.includes('column');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const base = /*#__PURE__*/emotion_react_browser_esm_css({
alignItems: align !== null && align !== void 0 ? align : isColumn ? 'normal' : 'center',
flexDirection: direction,
flexWrap: wrap ? 'wrap' : undefined,
gap: space(gap),
justifyContent: justify,
height: isColumn && expanded ? '100%' : undefined,
width: !isColumn && expanded ? '100%' : undefined
}, true ? "" : 0, true ? "" : 0);
return cx(Flex, base, isColumn ? ItemsColumn : ItemsRow, className);
}, [align, className, cx, direction, expanded, gap, isColumn, justify, wrap]);
return { ...otherProps,
className: classes,
isColumn
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlex(props, forwardedRef) {
const {
children,
isColumn,
...otherProps
} = useFlex(props);
return (0,external_wp_element_namespaceObject.createElement)(FlexContext.Provider, {
value: {
flexItemDisplay: isColumn ? 'block' : undefined
}
}, (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
}, children));
}
/**
* `Flex` is a primitive layout component that adaptively aligns child content
* horizontally or vertically. `Flex` powers components like `HStack` and
* `VStack`.
*
* `Flex` is used with any of its two sub-components, `FlexItem` and
* `FlexBlock`.
*
* ```jsx
* import { Flex, FlexBlock, FlexItem } from '@wordpress/components';
*
* function Example() {
* return (
* <Flex>
* <FlexItem>
* <p>Code</p>
* </FlexItem>
* <FlexBlock>
* <p>Poetry</p>
* </FlexBlock>
* </Flex>
* );
* }
* ```
*/
const component_Flex = contextConnect(UnconnectedFlex, 'Flex');
/* harmony default export */ var flex_component = (component_Flex);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-item/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlexItem(props, forwardedRef) {
const flexItemProps = useFlexItem(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...flexItemProps,
ref: forwardedRef
});
}
/**
* `FlexItem` is a primitive layout component that aligns content within layout
* containers like `Flex`.
*
* ```jsx
* import { Flex, FlexItem } from '@wordpress/components';
*
* function Example() {
* return (
* <Flex>
* <FlexItem>...</FlexItem>
* </Flex>
* );
* }
* ```
*/
const FlexItem = contextConnect(UnconnectedFlexItem, 'FlexItem');
/* harmony default export */ var flex_item_component = (FlexItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/styles.js
function truncate_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const Truncate = true ? {
name: "hdknak",
styles: "display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/values.js
/* eslint-disable jsdoc/valid-types */
/**
* Determines if a value is null or undefined.
*
* @template T
*
* @param {T} value The value to check.
* @return {value is Exclude<T, null | undefined>} Whether value is not null or undefined.
*/
function isValueDefined(value) {
return value !== undefined && value !== null;
}
/* eslint-enable jsdoc/valid-types */
/* eslint-disable jsdoc/valid-types */
/**
* Determines if a value is empty, null, or undefined.
*
* @param {string | number | null | undefined} value The value to check.
* @return {value is ("" | null | undefined)} Whether value is empty.
*/
function isValueEmpty(value) {
const isEmptyString = value === '';
return !isValueDefined(value) || isEmptyString;
}
/* eslint-enable jsdoc/valid-types */
/**
* Get the first defined/non-null value from an array.
*
* @template T
*
* @param {Array<T | null | undefined>} values Values to derive from.
* @param {T} fallbackValue Fallback value if there are no defined values.
* @return {T} A defined value or the fallback value.
*/
function getDefinedValue(values = [], fallbackValue) {
var _values$find;
return (_values$find = values.find(isValueDefined)) !== null && _values$find !== void 0 ? _values$find : fallbackValue;
}
/**
* @param {string} [locale]
* @return {[RegExp, RegExp]} The delimiter and decimal regexp
*/
const getDelimiterAndDecimalRegex = locale => {
const formatted = Intl.NumberFormat(locale).format(1000.1);
const delimiter = formatted[1];
const decimal = formatted[formatted.length - 2];
return [new RegExp(`\\${delimiter}`, 'g'), new RegExp(`\\${decimal}`, 'g')];
}; // https://en.wikipedia.org/wiki/Decimal_separator#Current_standards
const INTERNATIONAL_THOUSANDS_DELIMITER = / /g;
const ARABIC_NUMERAL_LOCALES = (/* unused pure expression or super */ null && (['ar', 'fa', 'ur', 'ckb', 'ps']));
const EASTERN_ARABIC_NUMBERS = /([۰-۹]|[٠-٩])/g;
/**
* Checks to see if a value is a numeric value (`number` or `string`).
*
* Intentionally ignores whether the thousands delimiters are only
* in the thousands marks.
*
* @param {any} value
* @param {string} [locale]
* @return {boolean} Whether value is numeric.
*/
function isValueNumeric(value, locale = window.navigator.language) {
if (ARABIC_NUMERAL_LOCALES.some(l => locale.startsWith(l))) {
locale = 'en-GB';
if (EASTERN_ARABIC_NUMBERS.test(value)) {
value = value.replace(/[٠-٩]/g, (
/** @type {string} */
d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)).replace(/[۰-۹]/g, (
/** @type {string} */
d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/٬/g, ',').replace(/٫/g, '.');
}
}
const [delimiterRegexp, decimalRegexp] = getDelimiterAndDecimalRegex(locale);
const valueToCheck = typeof value === 'string' ? value.replace(delimiterRegexp, '').replace(decimalRegexp, '.').replace(INTERNATIONAL_THOUSANDS_DELIMITER, '') : value;
return !isNaN(parseFloat(valueToCheck)) && isFinite(valueToCheck);
}
/**
* Converts a string to a number.
*
* @param {string} value
* @return {number} String as a number.
*/
const stringToNumber = value => {
return parseFloat(value);
};
/**
* Converts a number to a string.
*
* @param {number} value
* @return {string} Number as a string.
*/
const numberToString = value => {
return `${value}`;
};
/**
* Regardless of the input being a string or a number, returns a number.
*
* Returns `undefined` in case the string is `undefined` or not a valid numeric value.
*
* @param {string | number} value
* @return {number} The parsed number.
*/
const ensureNumber = value => {
return typeof value === 'string' ? stringToNumber(value) : value;
};
/**
* Regardless of the input being a string or a number, returns a number.
*
* Returns `undefined` in case the string is `undefined` or not a valid numeric value.
*
* @param {string | number} value
* @return {string} The converted string, or `undefined` in case the input is `undefined` or `NaN`.
*/
const ensureString = value => {
return typeof value === 'string' ? value : numberToString(value);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/utils.js
/**
* Internal dependencies
*/
const TRUNCATE_ELLIPSIS = '…';
const TRUNCATE_TYPE = {
auto: 'auto',
head: 'head',
middle: 'middle',
tail: 'tail',
none: 'none'
};
const TRUNCATE_DEFAULT_PROPS = {
ellipsis: TRUNCATE_ELLIPSIS,
ellipsizeMode: TRUNCATE_TYPE.auto,
limit: 0,
numberOfLines: 0
}; // Source
// https://github.com/kahwee/truncate-middle
function truncateMiddle(word, headLength, tailLength, ellipsis) {
if (typeof word !== 'string') {
return '';
}
const wordLength = word.length; // Setting default values
// eslint-disable-next-line no-bitwise
const frontLength = ~~headLength; // Will cast to integer
// eslint-disable-next-line no-bitwise
const backLength = ~~tailLength;
/* istanbul ignore next */
const truncateStr = isValueDefined(ellipsis) ? ellipsis : TRUNCATE_ELLIPSIS;
if (frontLength === 0 && backLength === 0 || frontLength >= wordLength || backLength >= wordLength || frontLength + backLength >= wordLength) {
return word;
} else if (backLength === 0) {
return word.slice(0, frontLength) + truncateStr;
}
return word.slice(0, frontLength) + truncateStr + word.slice(wordLength - backLength);
}
function truncateContent(words = '', props) {
const mergedProps = { ...TRUNCATE_DEFAULT_PROPS,
...props
};
const {
ellipsis,
ellipsizeMode,
limit
} = mergedProps;
if (ellipsizeMode === TRUNCATE_TYPE.none) {
return words;
}
let truncateHead;
let truncateTail;
switch (ellipsizeMode) {
case TRUNCATE_TYPE.head:
truncateHead = 0;
truncateTail = limit;
break;
case TRUNCATE_TYPE.middle:
truncateHead = Math.floor(limit / 2);
truncateTail = Math.floor(limit / 2);
break;
default:
truncateHead = limit;
truncateTail = 0;
}
const truncatedContent = ellipsizeMode !== TRUNCATE_TYPE.auto ? truncateMiddle(words, truncateHead, truncateTail, ellipsis) : words;
return truncatedContent;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useTruncate(props) {
const {
className,
children,
ellipsis = TRUNCATE_ELLIPSIS,
ellipsizeMode = TRUNCATE_TYPE.auto,
limit = 0,
numberOfLines = 0,
...otherProps
} = useContextSystem(props, 'Truncate');
const cx = useCx();
const truncatedContent = truncateContent(typeof children === 'string' ? children : '', {
ellipsis,
ellipsizeMode,
limit,
numberOfLines
});
const shouldTruncate = ellipsizeMode === TRUNCATE_TYPE.auto;
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const truncateLines = /*#__PURE__*/emotion_react_browser_esm_css("-webkit-box-orient:vertical;-webkit-line-clamp:", numberOfLines, ";display:-webkit-box;overflow:hidden;" + ( true ? "" : 0), true ? "" : 0);
return cx(shouldTruncate && !numberOfLines && Truncate, shouldTruncate && !!numberOfLines && truncateLines, className);
}, [className, cx, numberOfLines, shouldTruncate]);
return { ...otherProps,
className: classes,
children: truncatedContent
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/colors.js
/**
* External dependencies
*/
/** @type {HTMLDivElement} */
let colorComputationNode;
colord_k([names]);
/**
* @return {HTMLDivElement | undefined} The HTML element for color computation.
*/
function getColorComputationNode() {
if (typeof document === 'undefined') return;
if (!colorComputationNode) {
// Create a temporary element for style computation.
const el = document.createElement('div');
el.setAttribute('data-g2-color-computation-node', ''); // Inject for window computed style.
document.body.appendChild(el);
colorComputationNode = el;
}
return colorComputationNode;
}
/**
* @param {string | unknown} value
*
* @return {boolean} Whether the value is a valid color.
*/
function isColor(value) {
if (typeof value !== 'string') return false;
const test = colord_w(value);
return test.isValid();
}
/**
* Retrieves the computed background color. This is useful for getting the
* value of a CSS variable color.
*
* @param {string | unknown} backgroundColor The background color to compute.
*
* @return {string} The computed background color.
*/
function _getComputedBackgroundColor(backgroundColor) {
if (typeof backgroundColor !== 'string') return '';
if (isColor(backgroundColor)) return backgroundColor;
if (!backgroundColor.includes('var(')) return '';
if (typeof document === 'undefined') return ''; // Attempts to gracefully handle CSS variables color values.
const el = getColorComputationNode();
if (!el) return '';
el.style.background = backgroundColor; // Grab the style.
const computedColor = window?.getComputedStyle(el).background; // Reset.
el.style.background = '';
return computedColor || '';
}
const getComputedBackgroundColor = memize(_getComputedBackgroundColor);
/**
* Get the text shade optimized for readability, based on a background color.
*
* @param {string | unknown} backgroundColor The background color.
*
* @return {string} The optimized text color (black or white).
*/
function getOptimalTextColor(backgroundColor) {
const background = getComputedBackgroundColor(backgroundColor);
return colord_w(background).isLight() ? '#000000' : '#ffffff';
}
/**
* Get the text shade optimized for readability, based on a background color.
*
* @param {string | unknown} backgroundColor The background color.
*
* @return {string} The optimized text shade (dark or light).
*/
function getOptimalTextShade(backgroundColor) {
const result = getOptimalTextColor(backgroundColor);
return result === '#000000' ? 'dark' : 'light';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/config-values.js
/**
* Internal dependencies
*/
const CONTROL_HEIGHT = '36px';
const CONTROL_PADDING_X = '12px';
const CONTROL_PROPS = {
controlSurfaceColor: COLORS.white,
controlTextActiveColor: COLORS.ui.theme,
controlPaddingX: CONTROL_PADDING_X,
controlPaddingXLarge: `calc(${CONTROL_PADDING_X} * 1.3334)`,
controlPaddingXSmall: `calc(${CONTROL_PADDING_X} / 1.3334)`,
controlBackgroundColor: COLORS.white,
controlBorderRadius: '2px',
controlBoxShadow: 'transparent',
controlBoxShadowFocus: `0 0 0 0.5px ${COLORS.ui.theme}`,
controlDestructiveBorderColor: COLORS.alert.red,
controlHeight: CONTROL_HEIGHT,
controlHeightXSmall: `calc( ${CONTROL_HEIGHT} * 0.6 )`,
controlHeightSmall: `calc( ${CONTROL_HEIGHT} * 0.8 )`,
controlHeightLarge: `calc( ${CONTROL_HEIGHT} * 1.2 )`,
controlHeightXLarge: `calc( ${CONTROL_HEIGHT} * 1.4 )`
};
const TOGGLE_GROUP_CONTROL_PROPS = {
toggleGroupControlBackgroundColor: CONTROL_PROPS.controlBackgroundColor,
toggleGroupControlBorderColor: COLORS.ui.border,
toggleGroupControlBackdropBackgroundColor: CONTROL_PROPS.controlSurfaceColor,
toggleGroupControlBackdropBorderColor: COLORS.ui.border,
toggleGroupControlButtonColorActive: CONTROL_PROPS.controlBackgroundColor
}; // Using Object.assign to avoid creating circular references when emitting
// TypeScript type declarations.
/* harmony default export */ var config_values = (Object.assign({}, CONTROL_PROPS, TOGGLE_GROUP_CONTROL_PROPS, {
colorDivider: 'rgba(0, 0, 0, 0.1)',
colorScrollbarThumb: 'rgba(0, 0, 0, 0.2)',
colorScrollbarThumbHover: 'rgba(0, 0, 0, 0.5)',
colorScrollbarTrack: 'rgba(0, 0, 0, 0.04)',
elevationIntensity: 1,
radiusBlockUi: '2px',
borderWidth: '1px',
borderWidthFocus: '1.5px',
borderWidthTab: '4px',
spinnerSize: 16,
fontSize: '13px',
fontSizeH1: 'calc(2.44 * 13px)',
fontSizeH2: 'calc(1.95 * 13px)',
fontSizeH3: 'calc(1.56 * 13px)',
fontSizeH4: 'calc(1.25 * 13px)',
fontSizeH5: '13px',
fontSizeH6: 'calc(0.8 * 13px)',
fontSizeInputMobile: '16px',
fontSizeMobile: '15px',
fontSizeSmall: 'calc(0.92 * 13px)',
fontSizeXSmall: 'calc(0.75 * 13px)',
fontLineHeightBase: '1.2',
fontWeight: 'normal',
fontWeightHeading: '600',
gridBase: '4px',
cardBorderRadius: '2px',
cardPaddingXSmall: `${space(2)}`,
cardPaddingSmall: `${space(4)}`,
cardPaddingMedium: `${space(4)} ${space(6)}`,
cardPaddingLarge: `${space(6)} ${space(8)}`,
popoverShadow: `0 0.7px 1px rgba(0, 0, 0, 0.1), 0 1.2px 1.7px -0.2px rgba(0, 0, 0, 0.1), 0 2.3px 3.3px -0.5px rgba(0, 0, 0, 0.1)`,
surfaceBackgroundColor: COLORS.white,
surfaceBackgroundSubtleColor: '#F3F3F3',
surfaceBackgroundTintColor: '#F5F5F5',
surfaceBorderColor: 'rgba(0, 0, 0, 0.1)',
surfaceBorderBoldColor: 'rgba(0, 0, 0, 0.15)',
surfaceBorderSubtleColor: 'rgba(0, 0, 0, 0.05)',
surfaceBackgroundTertiaryColor: COLORS.white,
surfaceColor: COLORS.white,
transitionDuration: '200ms',
transitionDurationFast: '160ms',
transitionDurationFaster: '120ms',
transitionDurationFastest: '100ms',
transitionTimingFunction: 'cubic-bezier(0.08, 0.52, 0.52, 1)',
transitionTimingFunctionControl: 'cubic-bezier(0.12, 0.8, 0.32, 1)'
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/styles.js
function text_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const Text = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";line-height:", config_values.fontLineHeightBase, ";margin:0;" + ( true ? "" : 0), true ? "" : 0);
const styles_block = true ? {
name: "4zleql",
styles: "display:block"
} : 0;
const positive = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.alert.green, ";" + ( true ? "" : 0), true ? "" : 0);
const destructive = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.alert.red, ";" + ( true ? "" : 0), true ? "" : 0);
const muted = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[700], ";" + ( true ? "" : 0), true ? "" : 0);
const highlighterText = /*#__PURE__*/emotion_react_browser_esm_css("mark{background:", COLORS.alert.yellow, ";border-radius:2px;box-shadow:0 0 0 1px rgba( 0, 0, 0, 0.05 ) inset,0 -1px 0 rgba( 0, 0, 0, 0.1 ) inset;}" + ( true ? "" : 0), true ? "" : 0);
const upperCase = true ? {
name: "50zrmy",
styles: "text-transform:uppercase"
} : 0;
// EXTERNAL MODULE: ./node_modules/highlight-words-core/dist/index.js
var dist = __webpack_require__(3138);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Source:
* https://github.com/bvaughn/react-highlight-words/blob/HEAD/src/Highlighter.js
*/
/* eslint-disable jsdoc/valid-types */
/**
* @typedef Options
* @property {string} [activeClassName=''] Classname for active highlighted areas.
* @property {number} [activeIndex=-1] The index of the active highlighted area.
* @property {import('react').AllHTMLAttributes<HTMLDivElement>['style']} [activeStyle] Styles to apply to the active highlighted area.
* @property {boolean} [autoEscape] Whether to automatically escape text.
* @property {boolean} [caseSensitive=false] Whether to highlight in a case-sensitive manner.
* @property {string} children Children to highlight.
* @property {import('highlight-words-core').FindAllArgs['findChunks']} [findChunks] Custom `findChunks` function to pass to `highlight-words-core`.
* @property {string | Record<string, unknown>} [highlightClassName=''] Classname to apply to highlighted text or a Record of classnames to apply to given text (which should be the key).
* @property {import('react').AllHTMLAttributes<HTMLDivElement>['style']} [highlightStyle={}] Styles to apply to highlighted text.
* @property {keyof JSX.IntrinsicElements} [highlightTag='mark'] Tag to use for the highlighted text.
* @property {import('highlight-words-core').FindAllArgs['sanitize']} [sanitize] Custom `santize` function to pass to `highlight-words-core`.
* @property {string[]} [searchWords=[]] Words to search for and highlight.
* @property {string} [unhighlightClassName=''] Classname to apply to unhighlighted text.
* @property {import('react').AllHTMLAttributes<HTMLDivElement>['style']} [unhighlightStyle] Style to apply to unhighlighted text.
*/
/**
* Maps props to lowercase names.
*
* @template {Record<string, unknown>} T
* @param {T} object Props to map.
* @return {{[K in keyof T as Lowercase<string & K>]: T[K]}} The mapped props.
*/
/* eslint-enable jsdoc/valid-types */
const lowercaseProps = object => {
/** @type {any} */
const mapped = {};
for (const key in object) {
mapped[key.toLowerCase()] = object[key];
}
return mapped;
};
const memoizedLowercaseProps = memize(lowercaseProps);
/**
*
* @param {Options} options
*/
function createHighlighterText({
activeClassName = '',
activeIndex = -1,
activeStyle,
autoEscape,
caseSensitive = false,
children,
findChunks,
highlightClassName = '',
highlightStyle = {},
highlightTag = 'mark',
sanitize,
searchWords = [],
unhighlightClassName = '',
unhighlightStyle
}) {
if (!children) return null;
if (typeof children !== 'string') return children;
const textToHighlight = children;
const chunks = (0,dist.findAll)({
autoEscape,
caseSensitive,
findChunks,
sanitize,
searchWords,
textToHighlight
});
const HighlightTag = highlightTag;
let highlightIndex = -1;
let highlightClassNames = '';
let highlightStyles;
const textContent = chunks.map((chunk, index) => {
const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start);
if (chunk.highlight) {
highlightIndex++;
let highlightClass;
if (typeof highlightClassName === 'object') {
if (!caseSensitive) {
highlightClassName = memoizedLowercaseProps(highlightClassName);
highlightClass = highlightClassName[text.toLowerCase()];
} else {
highlightClass = highlightClassName[text];
}
} else {
highlightClass = highlightClassName;
}
const isActive = highlightIndex === +activeIndex;
highlightClassNames = `${highlightClass} ${isActive ? activeClassName : ''}`;
highlightStyles = isActive === true && activeStyle !== null ? Object.assign({}, highlightStyle, activeStyle) : highlightStyle;
/** @type {Record<string, any>} */
const props = {
children: text,
className: highlightClassNames,
key: index,
style: highlightStyles
}; // Don't attach arbitrary props to DOM elements; this triggers React DEV warnings (https://fb.me/react-unknown-prop)
// Only pass through the highlightIndex attribute for custom components.
if (typeof HighlightTag !== 'string') {
props.highlightIndex = highlightIndex;
}
return (0,external_wp_element_namespaceObject.createElement)(HighlightTag, props);
}
return (0,external_wp_element_namespaceObject.createElement)('span', {
children: text,
className: unhighlightClassName,
key: index,
style: unhighlightStyle
});
});
return textContent;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/font-size.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const BASE_FONT_SIZE = 13;
const PRESET_FONT_SIZES = {
body: BASE_FONT_SIZE,
caption: 10,
footnote: 11,
largeTitle: 28,
subheadline: 12,
title: 20
};
const HEADING_FONT_SIZES = [1, 2, 3, 4, 5, 6].flatMap(n => [n, n.toString()]);
function getFontSize(size = BASE_FONT_SIZE) {
if (size in PRESET_FONT_SIZES) {
return getFontSize(PRESET_FONT_SIZES[size]);
}
if (typeof size !== 'number') {
const parsed = parseFloat(size);
if (Number.isNaN(parsed)) return size;
size = parsed;
}
const ratio = `(${size} / ${BASE_FONT_SIZE})`;
return `calc(${ratio} * ${config_values.fontSize})`;
}
function getHeadingFontSize(size = 3) {
if (!HEADING_FONT_SIZES.includes(size)) {
return getFontSize(size);
}
const headingSize = `fontSizeH${size}`;
return config_values[headingSize];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/get-line-height.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function getLineHeight(adjustLineHeightForInnerControls, lineHeight) {
if (lineHeight) return lineHeight;
if (!adjustLineHeightForInnerControls) return;
let value = `calc(${config_values.controlHeight} + ${space(2)})`;
switch (adjustLineHeightForInnerControls) {
case 'large':
value = `calc(${config_values.controlHeightLarge} + ${space(2)})`;
break;
case 'small':
value = `calc(${config_values.controlHeightSmall} + ${space(2)})`;
break;
case 'xSmall':
value = `calc(${config_values.controlHeightXSmall} + ${space(2)})`;
break;
default:
break;
}
return value;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/hook.js
function hook_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @param {import('../ui/context').WordPressComponentProps<import('./types').Props, 'span'>} props
*/
var hook_ref = true ? {
name: "50zrmy",
styles: "text-transform:uppercase"
} : 0;
function useText(props) {
const {
adjustLineHeightForInnerControls,
align,
children,
className,
color,
ellipsizeMode,
isDestructive = false,
display,
highlightEscape = false,
highlightCaseSensitive = false,
highlightWords,
highlightSanitize,
isBlock = false,
letterSpacing,
lineHeight: lineHeightProp,
optimizeReadabilityFor,
size,
truncate = false,
upperCase = false,
variant,
weight = config_values.fontWeight,
...otherProps
} = useContextSystem(props, 'Text');
/** @type {import('react').ReactNode} */
let content = children;
const isHighlighter = Array.isArray(highlightWords);
const isCaption = size === 'caption';
if (isHighlighter) {
if (typeof children !== 'string') {
throw new TypeError('`children` of `Text` must only be `string` types when `highlightWords` is defined');
}
content = createHighlighterText({
autoEscape: highlightEscape,
// Disable reason: We need to disable this otherwise it erases the cast
// eslint-disable-next-line object-shorthand
children:
/** @type {string} */
children,
caseSensitive: highlightCaseSensitive,
searchWords: highlightWords,
sanitize: highlightSanitize
});
}
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const sx = {};
const lineHeight = getLineHeight(adjustLineHeightForInnerControls, lineHeightProp);
sx.Base = /*#__PURE__*/emotion_react_browser_esm_css({
color,
display,
fontSize: getFontSize(size),
/* eslint-disable jsdoc/valid-types */
fontWeight:
/** @type {import('react').CSSProperties['fontWeight']} */
weight,
/* eslint-enable jsdoc/valid-types */
lineHeight,
letterSpacing,
textAlign: align
}, true ? "" : 0, true ? "" : 0);
sx.upperCase = hook_ref;
sx.optimalTextColor = null;
if (optimizeReadabilityFor) {
const isOptimalTextColorDark = getOptimalTextShade(optimizeReadabilityFor) === 'dark';
sx.optimalTextColor = isOptimalTextColorDark ? /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.gray[900]
}, true ? "" : 0, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.white
}, true ? "" : 0, true ? "" : 0);
}
return cx(Text, sx.Base, sx.optimalTextColor, isDestructive && destructive, !!isHighlighter && highlighterText, isBlock && styles_block, isCaption && muted, variant && text_styles_namespaceObject[variant], upperCase && sx.upperCase, className);
}, [adjustLineHeightForInnerControls, align, className, color, cx, display, isBlock, isCaption, isDestructive, isHighlighter, letterSpacing, lineHeightProp, optimizeReadabilityFor, size, upperCase, variant, weight]);
/** @type {undefined | 'auto' | 'none'} */
let finalEllipsizeMode;
if (truncate === true) {
finalEllipsizeMode = 'auto';
}
if (truncate === false) {
finalEllipsizeMode = 'none';
}
const finalComponentProps = { ...otherProps,
className: classes,
children,
ellipsizeMode: ellipsizeMode || finalEllipsizeMode
};
const truncateProps = useTruncate(finalComponentProps);
/**
* Enhance child `<Link />` components to inherit font size.
*/
if (!truncate && Array.isArray(children)) {
content = external_wp_element_namespaceObject.Children.map(children, child => {
if (typeof child !== 'object' || child === null || !('props' in child)) {
return child;
}
const isLink = hasConnectNamespace(child, ['Link']);
if (isLink) {
return (0,external_wp_element_namespaceObject.cloneElement)(child, {
size: child.props.size || 'inherit'
});
}
return child;
});
}
return { ...truncateProps,
children: truncate ? truncateProps.children : content
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/component.js
/**
* Internal dependencies
*/
/**
* @param {import('../ui/context').WordPressComponentProps<import('./types').Props, 'span'>} props
* @param {import('react').ForwardedRef<any>} forwardedRef
*/
function component_Text(props, forwardedRef) {
const textProps = useText(props);
return (0,external_wp_element_namespaceObject.createElement)(component, {
as: "span",
...textProps,
ref: forwardedRef
});
}
/**
* `Text` is a core component that renders text in the library, using the
* library's typography system.
*
* `Text` can be used to render any text-content, like an HTML `p` or `span`.
*
* @example
*
* ```jsx
* import { __experimentalText as Text } from `@wordpress/components`;
*
* function Example() {
* return <Text>Code is Poetry</Text>;
* }
* ```
*/
const ConnectedText = contextConnect(component_Text, 'Text');
/* harmony default export */ var text_component = (ConnectedText);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/base-label.js
function base_label_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
// This is a very low-level mixin which you shouldn't have to use directly.
// Try to use BaseControl's StyledLabel or BaseControl.VisualLabel if you can.
const baseLabelTypography = true ? {
name: "9amh4a",
styles: "font-size:11px;font-weight:500;line-height:1.4;text-transform:uppercase"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/styles/input-control-styles.js
function input_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
var _ref2 = true ? {
name: "1739oy8",
styles: "z-index:1"
} : 0;
const rootFocusedStyles = ({
isFocused
}) => {
if (!isFocused) return '';
return _ref2;
};
const input_control_styles_Root = /*#__PURE__*/createStyled(flex_component, true ? {
target: "em5sgkm7"
} : 0)("box-sizing:border-box;position:relative;border-radius:2px;padding-top:0;", rootFocusedStyles, ";" + ( true ? "" : 0));
const containerDisabledStyles = ({
disabled
}) => {
const backgroundColor = disabled ? COLORS.ui.backgroundDisabled : COLORS.ui.background;
return /*#__PURE__*/emotion_react_browser_esm_css({
backgroundColor
}, true ? "" : 0, true ? "" : 0);
};
var input_control_styles_ref = true ? {
name: "1d3w5wq",
styles: "width:100%"
} : 0;
const containerWidthStyles = ({
__unstableInputWidth,
labelPosition
}) => {
if (!__unstableInputWidth) return input_control_styles_ref;
if (labelPosition === 'side') return '';
if (labelPosition === 'edge') {
return /*#__PURE__*/emotion_react_browser_esm_css({
flex: `0 0 ${__unstableInputWidth}`
}, true ? "" : 0, true ? "" : 0);
}
return /*#__PURE__*/emotion_react_browser_esm_css({
width: __unstableInputWidth
}, true ? "" : 0, true ? "" : 0);
};
const Container = createStyled("div", true ? {
target: "em5sgkm6"
} : 0)("align-items:center;box-sizing:border-box;border-radius:inherit;display:flex;flex:1;position:relative;", containerDisabledStyles, " ", containerWidthStyles, ";" + ( true ? "" : 0));
const disabledStyles = ({
disabled
}) => {
if (!disabled) return '';
return /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.ui.textDisabled
}, true ? "" : 0, true ? "" : 0);
};
const fontSizeStyles = ({
inputSize: size
}) => {
const sizes = {
default: '13px',
small: '11px',
'__unstable-large': '13px'
};
const fontSize = sizes[size] || sizes.default;
const fontSizeMobile = '16px';
if (!fontSize) return '';
return /*#__PURE__*/emotion_react_browser_esm_css("font-size:", fontSizeMobile, ";@media ( min-width: 600px ){font-size:", fontSize, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const getSizeConfig = ({
inputSize: size,
__next36pxDefaultSize
}) => {
// Paddings may be overridden by the custom paddings props.
const sizes = {
default: {
height: 36,
lineHeight: 1,
minHeight: 36,
paddingLeft: space(4),
paddingRight: space(4)
},
small: {
height: 24,
lineHeight: 1,
minHeight: 24,
paddingLeft: space(2),
paddingRight: space(2)
},
'__unstable-large': {
height: 40,
lineHeight: 1,
minHeight: 40,
paddingLeft: space(4),
paddingRight: space(4)
}
};
if (!__next36pxDefaultSize) {
sizes.default = {
height: 30,
lineHeight: 1,
minHeight: 30,
paddingLeft: space(2),
paddingRight: space(2)
};
}
return sizes[size] || sizes.default;
};
const sizeStyles = props => {
return /*#__PURE__*/emotion_react_browser_esm_css(getSizeConfig(props), true ? "" : 0, true ? "" : 0);
};
const customPaddings = ({
paddingInlineStart,
paddingInlineEnd
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css({
paddingInlineStart,
paddingInlineEnd
}, true ? "" : 0, true ? "" : 0);
};
const dragStyles = ({
isDragging,
dragCursor
}) => {
let defaultArrowStyles;
let activeDragCursorStyles;
if (isDragging) {
defaultArrowStyles = /*#__PURE__*/emotion_react_browser_esm_css("cursor:", dragCursor, ";user-select:none;&::-webkit-outer-spin-button,&::-webkit-inner-spin-button{-webkit-appearance:none!important;margin:0!important;}" + ( true ? "" : 0), true ? "" : 0);
}
if (isDragging && dragCursor) {
activeDragCursorStyles = /*#__PURE__*/emotion_react_browser_esm_css("&:active{cursor:", dragCursor, ";}" + ( true ? "" : 0), true ? "" : 0);
}
return /*#__PURE__*/emotion_react_browser_esm_css(defaultArrowStyles, " ", activeDragCursorStyles, ";" + ( true ? "" : 0), true ? "" : 0);
}; // TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const Input = createStyled("input", true ? {
target: "em5sgkm5"
} : 0)("&&&{background-color:transparent;box-sizing:border-box;border:none;box-shadow:none!important;color:", COLORS.gray[900], ";display:block;font-family:inherit;margin:0;outline:none;width:100%;", dragStyles, " ", disabledStyles, " ", fontSizeStyles, " ", sizeStyles, " ", customPaddings, " &::-webkit-input-placeholder{line-height:normal;}}" + ( true ? "" : 0));
const BaseLabel = /*#__PURE__*/createStyled(text_component, true ? {
target: "em5sgkm4"
} : 0)("&&&{", baseLabelTypography, ";box-sizing:border-box;display:block;padding-top:0;padding-bottom:0;max-width:100%;z-index:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}" + ( true ? "" : 0));
const Label = props => (0,external_wp_element_namespaceObject.createElement)(BaseLabel, { ...props,
as: "label"
});
const LabelWrapper = /*#__PURE__*/createStyled(flex_item_component, true ? {
target: "em5sgkm3"
} : 0)( true ? {
name: "1b6uupn",
styles: "max-width:calc( 100% - 10px )"
} : 0);
const backdropFocusedStyles = ({
disabled,
isFocused
}) => {
let borderColor = isFocused ? COLORS.ui.borderFocus : COLORS.ui.border;
let boxShadow;
let outline;
let outlineOffset;
if (isFocused) {
boxShadow = `0 0 0 1px ${COLORS.ui.borderFocus} inset`; // Windows High Contrast mode will show this outline, but not the box-shadow.
outline = `2px solid transparent`;
outlineOffset = `-2px`;
}
if (disabled) {
borderColor = COLORS.ui.borderDisabled;
}
return /*#__PURE__*/emotion_react_browser_esm_css({
boxShadow,
borderColor,
borderStyle: 'solid',
borderWidth: 1,
outline,
outlineOffset
}, true ? "" : 0, true ? "" : 0);
};
const BackdropUI = createStyled("div", true ? {
target: "em5sgkm2"
} : 0)("&&&{box-sizing:border-box;border-radius:inherit;bottom:0;left:0;margin:0;padding:0;pointer-events:none;position:absolute;right:0;top:0;", backdropFocusedStyles, " ", rtl({
paddingLeft: 2
}), ";}" + ( true ? "" : 0));
const Prefix = createStyled("span", true ? {
target: "em5sgkm1"
} : 0)( true ? {
name: "pvvbxf",
styles: "box-sizing:border-box;display:block"
} : 0);
const Suffix = createStyled("span", true ? {
target: "em5sgkm0"
} : 0)( true ? {
name: "jgf79h",
styles: "align-items:center;align-self:stretch;box-sizing:border-box;display:flex"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/backdrop.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Backdrop({
disabled = false,
isFocused = false
}) {
return (0,external_wp_element_namespaceObject.createElement)(BackdropUI, {
"aria-hidden": "true",
className: "components-input-control__backdrop",
disabled: disabled,
isFocused: isFocused
});
}
const MemoizedBackdrop = (0,external_wp_element_namespaceObject.memo)(Backdrop);
/* harmony default export */ var backdrop = (MemoizedBackdrop);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/label.js
/**
* Internal dependencies
*/
function label_Label({
children,
hideLabelFromVision,
htmlFor,
...props
}) {
if (!children) return null;
if (hideLabelFromVision) {
return (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label",
htmlFor: htmlFor
}, children);
}
return (0,external_wp_element_namespaceObject.createElement)(LabelWrapper, null, (0,external_wp_element_namespaceObject.createElement)(Label, {
htmlFor: htmlFor,
...props
}, children));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-base.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(InputBase);
const id = `input-base-control-${instanceId}`;
return idProp || id;
} // Adapter to map props for the new ui/flex component.
function getUIFlexProps(labelPosition) {
const props = {};
switch (labelPosition) {
case 'top':
props.direction = 'column';
props.expanded = false;
props.gap = 0;
break;
case 'bottom':
props.direction = 'column-reverse';
props.expanded = false;
props.gap = 0;
break;
case 'edge':
props.justify = 'space-between';
break;
}
return props;
}
function InputBase({
__next36pxDefaultSize,
__unstableInputWidth,
children,
className,
disabled = false,
hideLabelFromVision = false,
labelPosition,
id: idProp,
isFocused = false,
label,
prefix,
size = 'default',
suffix,
...props
}, ref) {
const id = useUniqueId(idProp);
const hideLabel = hideLabelFromVision || !label;
const {
paddingLeft,
paddingRight
} = getSizeConfig({
inputSize: size,
__next36pxDefaultSize
});
const prefixSuffixContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => {
return {
InputControlPrefixWrapper: {
paddingLeft
},
InputControlSuffixWrapper: {
paddingRight
}
};
}, [paddingLeft, paddingRight]);
return (// @ts-expect-error The `direction` prop from Flex (FlexDirection) conflicts with legacy SVGAttributes `direction` (string) that come from React intrinsic prop definitions.
(0,external_wp_element_namespaceObject.createElement)(input_control_styles_Root, { ...props,
...getUIFlexProps(labelPosition),
className: className,
gap: 2,
isFocused: isFocused,
labelPosition: labelPosition,
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)(label_Label, {
className: "components-input-control__label",
hideLabelFromVision: hideLabelFromVision,
labelPosition: labelPosition,
htmlFor: id
}, label), (0,external_wp_element_namespaceObject.createElement)(Container, {
__unstableInputWidth: __unstableInputWidth,
className: "components-input-control__container",
disabled: disabled,
hideLabel: hideLabel,
labelPosition: labelPosition
}, (0,external_wp_element_namespaceObject.createElement)(ContextSystemProvider, {
value: prefixSuffixContextValue
}, prefix && (0,external_wp_element_namespaceObject.createElement)(Prefix, {
className: "components-input-control__prefix"
}, prefix), children, suffix && (0,external_wp_element_namespaceObject.createElement)(Suffix, {
className: "components-input-control__suffix"
}, suffix)), (0,external_wp_element_namespaceObject.createElement)(backdrop, {
disabled: disabled,
isFocused: isFocused
})))
);
}
/* harmony default export */ var input_base = ((0,external_wp_element_namespaceObject.forwardRef)(InputBase));
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/maths-0ab39ae9.esm.js
function maths_0ab39ae9_esm_clamp(v, min, max) {
return Math.max(min, Math.min(v, max));
}
const maths_0ab39ae9_esm_V = {
toVector(v, fallback) {
if (v === undefined) v = fallback;
return Array.isArray(v) ? v : [v, v];
},
add(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
},
sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
},
addTo(v1, v2) {
v1[0] += v2[0];
v1[1] += v2[1];
},
subTo(v1, v2) {
v1[0] -= v2[0];
v1[1] -= v2[1];
}
};
function rubberband(distance, dimension, constant) {
if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
return distance * dimension * constant / (dimension + constant * distance);
}
function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
if (constant === 0) return maths_0ab39ae9_esm_clamp(position, min, max);
if (position < min) return -rubberband(min - position, max - min, constant) + min;
if (position > max) return +rubberband(position - max, max - min, constant) + max;
return position;
}
function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
const [[X0, X1], [Y0, Y1]] = bounds;
return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
}
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/actions-76b8683e.esm.js
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function actions_76b8683e_esm_defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function actions_76b8683e_esm_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function actions_76b8683e_esm_objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? actions_76b8683e_esm_ownKeys(Object(source), !0).forEach(function (key) {
actions_76b8683e_esm_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : actions_76b8683e_esm_ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
const EVENT_TYPE_MAP = {
pointer: {
start: 'down',
change: 'move',
end: 'up'
},
mouse: {
start: 'down',
change: 'move',
end: 'up'
},
touch: {
start: 'start',
change: 'move',
end: 'end'
},
gesture: {
start: 'start',
change: 'change',
end: 'end'
}
};
function capitalize(string) {
if (!string) return '';
return string[0].toUpperCase() + string.slice(1);
}
const actionsWithoutCaptureSupported = ['enter', 'leave'];
function hasCapture(capture = false, actionKey) {
return capture && !actionsWithoutCaptureSupported.includes(actionKey);
}
function toHandlerProp(device, action = '', capture = false) {
const deviceProps = EVENT_TYPE_MAP[device];
const actionKey = deviceProps ? deviceProps[action] || action : action;
return 'on' + capitalize(device) + capitalize(actionKey) + (hasCapture(capture, actionKey) ? 'Capture' : '');
}
const pointerCaptureEvents = ['gotpointercapture', 'lostpointercapture'];
function parseProp(prop) {
let eventKey = prop.substring(2).toLowerCase();
const passive = !!~eventKey.indexOf('passive');
if (passive) eventKey = eventKey.replace('passive', '');
const captureKey = pointerCaptureEvents.includes(eventKey) ? 'capturecapture' : 'capture';
const capture = !!~eventKey.indexOf(captureKey);
if (capture) eventKey = eventKey.replace('capture', '');
return {
device: eventKey,
capture,
passive
};
}
function toDomEventType(device, action = '') {
const deviceProps = EVENT_TYPE_MAP[device];
const actionKey = deviceProps ? deviceProps[action] || action : action;
return device + actionKey;
}
function isTouch(event) {
return 'touches' in event;
}
function getPointerType(event) {
if (isTouch(event)) return 'touch';
if ('pointerType' in event) return event.pointerType;
return 'mouse';
}
function getCurrentTargetTouchList(event) {
return Array.from(event.touches).filter(e => {
var _event$currentTarget, _event$currentTarget$;
return e.target === event.currentTarget || ((_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 ? void 0 : (_event$currentTarget$ = _event$currentTarget.contains) === null || _event$currentTarget$ === void 0 ? void 0 : _event$currentTarget$.call(_event$currentTarget, e.target));
});
}
function getTouchList(event) {
return event.type === 'touchend' || event.type === 'touchcancel' ? event.changedTouches : event.targetTouches;
}
function getValueEvent(event) {
return isTouch(event) ? getTouchList(event)[0] : event;
}
function distanceAngle(P1, P2) {
try {
const dx = P2.clientX - P1.clientX;
const dy = P2.clientY - P1.clientY;
const cx = (P2.clientX + P1.clientX) / 2;
const cy = (P2.clientY + P1.clientY) / 2;
const distance = Math.hypot(dx, dy);
const angle = -(Math.atan2(dx, dy) * 180) / Math.PI;
const origin = [cx, cy];
return {
angle,
distance,
origin
};
} catch (_unused) {}
return null;
}
function touchIds(event) {
return getCurrentTargetTouchList(event).map(touch => touch.identifier);
}
function touchDistanceAngle(event, ids) {
const [P1, P2] = Array.from(event.touches).filter(touch => ids.includes(touch.identifier));
return distanceAngle(P1, P2);
}
function pointerId(event) {
const valueEvent = getValueEvent(event);
return isTouch(event) ? valueEvent.identifier : valueEvent.pointerId;
}
function pointerValues(event) {
const valueEvent = getValueEvent(event);
return [valueEvent.clientX, valueEvent.clientY];
}
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
function wheelValues(event) {
let {
deltaX,
deltaY,
deltaMode
} = event;
if (deltaMode === 1) {
deltaX *= LINE_HEIGHT;
deltaY *= LINE_HEIGHT;
} else if (deltaMode === 2) {
deltaX *= PAGE_HEIGHT;
deltaY *= PAGE_HEIGHT;
}
return [deltaX, deltaY];
}
function scrollValues(event) {
var _ref, _ref2;
const {
scrollX,
scrollY,
scrollLeft,
scrollTop
} = event.currentTarget;
return [(_ref = scrollX !== null && scrollX !== void 0 ? scrollX : scrollLeft) !== null && _ref !== void 0 ? _ref : 0, (_ref2 = scrollY !== null && scrollY !== void 0 ? scrollY : scrollTop) !== null && _ref2 !== void 0 ? _ref2 : 0];
}
function getEventDetails(event) {
const payload = {};
if ('buttons' in event) payload.buttons = event.buttons;
if ('shiftKey' in event) {
const {
shiftKey,
altKey,
metaKey,
ctrlKey
} = event;
Object.assign(payload, {
shiftKey,
altKey,
metaKey,
ctrlKey
});
}
return payload;
}
function call(v, ...args) {
if (typeof v === 'function') {
return v(...args);
} else {
return v;
}
}
function actions_76b8683e_esm_noop() {}
function chain(...fns) {
if (fns.length === 0) return actions_76b8683e_esm_noop;
if (fns.length === 1) return fns[0];
return function () {
let result;
for (const fn of fns) {
result = fn.apply(this, arguments) || result;
}
return result;
};
}
function assignDefault(value, fallback) {
return Object.assign({}, fallback, value || {});
}
const BEFORE_LAST_KINEMATICS_DELAY = 32;
class Engine {
constructor(ctrl, args, key) {
this.ctrl = ctrl;
this.args = args;
this.key = key;
if (!this.state) {
this.state = {};
this.computeValues([0, 0]);
this.computeInitial();
if (this.init) this.init();
this.reset();
}
}
get state() {
return this.ctrl.state[this.key];
}
set state(state) {
this.ctrl.state[this.key] = state;
}
get shared() {
return this.ctrl.state.shared;
}
get eventStore() {
return this.ctrl.gestureEventStores[this.key];
}
get timeoutStore() {
return this.ctrl.gestureTimeoutStores[this.key];
}
get config() {
return this.ctrl.config[this.key];
}
get sharedConfig() {
return this.ctrl.config.shared;
}
get handler() {
return this.ctrl.handlers[this.key];
}
reset() {
const {
state,
shared,
ingKey,
args
} = this;
shared[ingKey] = state._active = state.active = state._blocked = state._force = false;
state._step = [false, false];
state.intentional = false;
state._movement = [0, 0];
state._distance = [0, 0];
state._direction = [0, 0];
state._delta = [0, 0];
state._bounds = [[-Infinity, Infinity], [-Infinity, Infinity]];
state.args = args;
state.axis = undefined;
state.memo = undefined;
state.elapsedTime = state.timeDelta = 0;
state.direction = [0, 0];
state.distance = [0, 0];
state.overflow = [0, 0];
state._movementBound = [false, false];
state.velocity = [0, 0];
state.movement = [0, 0];
state.delta = [0, 0];
state.timeStamp = 0;
}
start(event) {
const state = this.state;
const config = this.config;
if (!state._active) {
this.reset();
this.computeInitial();
state._active = true;
state.target = event.target;
state.currentTarget = event.currentTarget;
state.lastOffset = config.from ? call(config.from, state) : state.offset;
state.offset = state.lastOffset;
state.startTime = state.timeStamp = event.timeStamp;
}
}
computeValues(values) {
const state = this.state;
state._values = values;
state.values = this.config.transform(values);
}
computeInitial() {
const state = this.state;
state._initial = state._values;
state.initial = state.values;
}
compute(event) {
const {
state,
config,
shared
} = this;
state.args = this.args;
let dt = 0;
if (event) {
state.event = event;
if (config.preventDefault && event.cancelable) state.event.preventDefault();
state.type = event.type;
shared.touches = this.ctrl.pointerIds.size || this.ctrl.touchIds.size;
shared.locked = !!document.pointerLockElement;
Object.assign(shared, getEventDetails(event));
shared.down = shared.pressed = shared.buttons % 2 === 1 || shared.touches > 0;
dt = event.timeStamp - state.timeStamp;
state.timeStamp = event.timeStamp;
state.elapsedTime = state.timeStamp - state.startTime;
}
if (state._active) {
const _absoluteDelta = state._delta.map(Math.abs);
maths_0ab39ae9_esm_V.addTo(state._distance, _absoluteDelta);
}
if (this.axisIntent) this.axisIntent(event);
const [_m0, _m1] = state._movement;
const [t0, t1] = config.threshold;
const {
_step,
values
} = state;
if (config.hasCustomTransform) {
if (_step[0] === false) _step[0] = Math.abs(_m0) >= t0 && values[0];
if (_step[1] === false) _step[1] = Math.abs(_m1) >= t1 && values[1];
} else {
if (_step[0] === false) _step[0] = Math.abs(_m0) >= t0 && Math.sign(_m0) * t0;
if (_step[1] === false) _step[1] = Math.abs(_m1) >= t1 && Math.sign(_m1) * t1;
}
state.intentional = _step[0] !== false || _step[1] !== false;
if (!state.intentional) return;
const movement = [0, 0];
if (config.hasCustomTransform) {
const [v0, v1] = values;
movement[0] = _step[0] !== false ? v0 - _step[0] : 0;
movement[1] = _step[1] !== false ? v1 - _step[1] : 0;
} else {
movement[0] = _step[0] !== false ? _m0 - _step[0] : 0;
movement[1] = _step[1] !== false ? _m1 - _step[1] : 0;
}
if (this.restrictToAxis && !state._blocked) this.restrictToAxis(movement);
const previousOffset = state.offset;
const gestureIsActive = state._active && !state._blocked || state.active;
if (gestureIsActive) {
state.first = state._active && !state.active;
state.last = !state._active && state.active;
state.active = shared[this.ingKey] = state._active;
if (event) {
if (state.first) {
if ('bounds' in config) state._bounds = call(config.bounds, state);
if (this.setup) this.setup();
}
state.movement = movement;
this.computeOffset();
}
}
const [ox, oy] = state.offset;
const [[x0, x1], [y0, y1]] = state._bounds;
state.overflow = [ox < x0 ? -1 : ox > x1 ? 1 : 0, oy < y0 ? -1 : oy > y1 ? 1 : 0];
state._movementBound[0] = state.overflow[0] ? state._movementBound[0] === false ? state._movement[0] : state._movementBound[0] : false;
state._movementBound[1] = state.overflow[1] ? state._movementBound[1] === false ? state._movement[1] : state._movementBound[1] : false;
const rubberband = state._active ? config.rubberband || [0, 0] : [0, 0];
state.offset = computeRubberband(state._bounds, state.offset, rubberband);
state.delta = maths_0ab39ae9_esm_V.sub(state.offset, previousOffset);
this.computeMovement();
if (gestureIsActive && (!state.last || dt > BEFORE_LAST_KINEMATICS_DELAY)) {
state.delta = maths_0ab39ae9_esm_V.sub(state.offset, previousOffset);
const absoluteDelta = state.delta.map(Math.abs);
maths_0ab39ae9_esm_V.addTo(state.distance, absoluteDelta);
state.direction = state.delta.map(Math.sign);
state._direction = state._delta.map(Math.sign);
if (!state.first && dt > 0) {
state.velocity = [absoluteDelta[0] / dt, absoluteDelta[1] / dt];
state.timeDelta = dt;
}
}
}
emit() {
const state = this.state;
const shared = this.shared;
const config = this.config;
if (!state._active) this.clean();
if ((state._blocked || !state.intentional) && !state._force && !config.triggerAllEvents) return;
const memo = this.handler(actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, shared), state), {}, {
[this.aliasKey]: state.values
}));
if (memo !== undefined) state.memo = memo;
}
clean() {
this.eventStore.clean();
this.timeoutStore.clean();
}
}
function selectAxis([dx, dy], threshold) {
const absDx = Math.abs(dx);
const absDy = Math.abs(dy);
if (absDx > absDy && absDx > threshold) {
return 'x';
}
if (absDy > absDx && absDy > threshold) {
return 'y';
}
return undefined;
}
class CoordinatesEngine extends Engine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "aliasKey", 'xy');
}
reset() {
super.reset();
this.state.axis = undefined;
}
init() {
this.state.offset = [0, 0];
this.state.lastOffset = [0, 0];
}
computeOffset() {
this.state.offset = maths_0ab39ae9_esm_V.add(this.state.lastOffset, this.state.movement);
}
computeMovement() {
this.state.movement = maths_0ab39ae9_esm_V.sub(this.state.offset, this.state.lastOffset);
}
axisIntent(event) {
const state = this.state;
const config = this.config;
if (!state.axis && event) {
const threshold = typeof config.axisThreshold === 'object' ? config.axisThreshold[getPointerType(event)] : config.axisThreshold;
state.axis = selectAxis(state._movement, threshold);
}
state._blocked = (config.lockDirection || !!config.axis) && !state.axis || !!config.axis && config.axis !== state.axis;
}
restrictToAxis(v) {
if (this.config.axis || this.config.lockDirection) {
switch (this.state.axis) {
case 'x':
v[1] = 0;
break;
case 'y':
v[0] = 0;
break;
}
}
}
}
const identity = v => v;
const DEFAULT_RUBBERBAND = 0.15;
const commonConfigResolver = {
enabled(value = true) {
return value;
},
eventOptions(value, _k, config) {
return actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, config.shared.eventOptions), value);
},
preventDefault(value = false) {
return value;
},
triggerAllEvents(value = false) {
return value;
},
rubberband(value = 0) {
switch (value) {
case true:
return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND];
case false:
return [0, 0];
default:
return maths_0ab39ae9_esm_V.toVector(value);
}
},
from(value) {
if (typeof value === 'function') return value;
if (value != null) return maths_0ab39ae9_esm_V.toVector(value);
},
transform(value, _k, config) {
const transform = value || config.shared.transform;
this.hasCustomTransform = !!transform;
if (false) {}
return transform || identity;
},
threshold(value) {
return maths_0ab39ae9_esm_V.toVector(value, 0);
}
};
if (false) {}
const DEFAULT_AXIS_THRESHOLD = 0;
const coordinatesConfigResolver = actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, commonConfigResolver), {}, {
axis(_v, _k, {
axis
}) {
this.lockDirection = axis === 'lock';
if (!this.lockDirection) return axis;
},
axisThreshold(value = DEFAULT_AXIS_THRESHOLD) {
return value;
},
bounds(value = {}) {
if (typeof value === 'function') {
return state => coordinatesConfigResolver.bounds(value(state));
}
if ('current' in value) {
return () => value.current;
}
if (typeof HTMLElement === 'function' && value instanceof HTMLElement) {
return value;
}
const {
left = -Infinity,
right = Infinity,
top = -Infinity,
bottom = Infinity
} = value;
return [[left, right], [top, bottom]];
}
});
const KEYS_DELTA_MAP = {
ArrowRight: (displacement, factor = 1) => [displacement * factor, 0],
ArrowLeft: (displacement, factor = 1) => [-1 * displacement * factor, 0],
ArrowUp: (displacement, factor = 1) => [0, -1 * displacement * factor],
ArrowDown: (displacement, factor = 1) => [0, displacement * factor]
};
class DragEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "ingKey", 'dragging');
}
reset() {
super.reset();
const state = this.state;
state._pointerId = undefined;
state._pointerActive = false;
state._keyboardActive = false;
state._preventScroll = false;
state._delayed = false;
state.swipe = [0, 0];
state.tap = false;
state.canceled = false;
state.cancel = this.cancel.bind(this);
}
setup() {
const state = this.state;
if (state._bounds instanceof HTMLElement) {
const boundRect = state._bounds.getBoundingClientRect();
const targetRect = state.currentTarget.getBoundingClientRect();
const _bounds = {
left: boundRect.left - targetRect.left + state.offset[0],
right: boundRect.right - targetRect.right + state.offset[0],
top: boundRect.top - targetRect.top + state.offset[1],
bottom: boundRect.bottom - targetRect.bottom + state.offset[1]
};
state._bounds = coordinatesConfigResolver.bounds(_bounds);
}
}
cancel() {
const state = this.state;
if (state.canceled) return;
state.canceled = true;
state._active = false;
setTimeout(() => {
this.compute();
this.emit();
}, 0);
}
setActive() {
this.state._active = this.state._pointerActive || this.state._keyboardActive;
}
clean() {
this.pointerClean();
this.state._pointerActive = false;
this.state._keyboardActive = false;
super.clean();
}
pointerDown(event) {
const config = this.config;
const state = this.state;
if (event.buttons != null && (Array.isArray(config.pointerButtons) ? !config.pointerButtons.includes(event.buttons) : config.pointerButtons !== -1 && config.pointerButtons !== event.buttons)) return;
const ctrlIds = this.ctrl.setEventIds(event);
if (config.pointerCapture) {
event.target.setPointerCapture(event.pointerId);
}
if (ctrlIds && ctrlIds.size > 1 && state._pointerActive) return;
this.start(event);
this.setupPointer(event);
state._pointerId = pointerId(event);
state._pointerActive = true;
this.computeValues(pointerValues(event));
this.computeInitial();
if (config.preventScrollAxis && getPointerType(event) !== 'mouse') {
state._active = false;
this.setupScrollPrevention(event);
} else if (config.delay > 0) {
this.setupDelayTrigger(event);
if (config.triggerAllEvents) {
this.compute(event);
this.emit();
}
} else {
this.startPointerDrag(event);
}
}
startPointerDrag(event) {
const state = this.state;
state._active = true;
state._preventScroll = true;
state._delayed = false;
this.compute(event);
this.emit();
}
pointerMove(event) {
const state = this.state;
const config = this.config;
if (!state._pointerActive) return;
const id = pointerId(event);
if (state._pointerId !== undefined && id !== state._pointerId) return;
const _values = pointerValues(event);
if (document.pointerLockElement === event.target) {
state._delta = [event.movementX, event.movementY];
} else {
state._delta = maths_0ab39ae9_esm_V.sub(_values, state._values);
this.computeValues(_values);
}
maths_0ab39ae9_esm_V.addTo(state._movement, state._delta);
this.compute(event);
if (state._delayed && state.intentional) {
this.timeoutStore.remove('dragDelay');
state.active = false;
this.startPointerDrag(event);
return;
}
if (config.preventScrollAxis && !state._preventScroll) {
if (state.axis) {
if (state.axis === config.preventScrollAxis || config.preventScrollAxis === 'xy') {
state._active = false;
this.clean();
return;
} else {
this.timeoutStore.remove('startPointerDrag');
this.startPointerDrag(event);
return;
}
} else {
return;
}
}
this.emit();
}
pointerUp(event) {
this.ctrl.setEventIds(event);
try {
if (this.config.pointerCapture && event.target.hasPointerCapture(event.pointerId)) {
;
event.target.releasePointerCapture(event.pointerId);
}
} catch (_unused) {
if (false) {}
}
const state = this.state;
const config = this.config;
if (!state._active || !state._pointerActive) return;
const id = pointerId(event);
if (state._pointerId !== undefined && id !== state._pointerId) return;
this.state._pointerActive = false;
this.setActive();
this.compute(event);
const [dx, dy] = state._distance;
state.tap = dx <= config.tapsThreshold && dy <= config.tapsThreshold;
if (state.tap && config.filterTaps) {
state._force = true;
} else {
const [_dx, _dy] = state._delta;
const [_mx, _my] = state._movement;
const [svx, svy] = config.swipe.velocity;
const [sx, sy] = config.swipe.distance;
const sdt = config.swipe.duration;
if (state.elapsedTime < sdt) {
const _vx = Math.abs(_dx / state.timeDelta);
const _vy = Math.abs(_dy / state.timeDelta);
if (_vx > svx && Math.abs(_mx) > sx) state.swipe[0] = Math.sign(_dx);
if (_vy > svy && Math.abs(_my) > sy) state.swipe[1] = Math.sign(_dy);
}
}
this.emit();
}
pointerClick(event) {
if (!this.state.tap && event.detail > 0) {
event.preventDefault();
event.stopPropagation();
}
}
setupPointer(event) {
const config = this.config;
const device = config.device;
if (false) {}
if (config.pointerLock) {
event.currentTarget.requestPointerLock();
}
if (!config.pointerCapture) {
this.eventStore.add(this.sharedConfig.window, device, 'change', this.pointerMove.bind(this));
this.eventStore.add(this.sharedConfig.window, device, 'end', this.pointerUp.bind(this));
this.eventStore.add(this.sharedConfig.window, device, 'cancel', this.pointerUp.bind(this));
}
}
pointerClean() {
if (this.config.pointerLock && document.pointerLockElement === this.state.currentTarget) {
document.exitPointerLock();
}
}
preventScroll(event) {
if (this.state._preventScroll && event.cancelable) {
event.preventDefault();
}
}
setupScrollPrevention(event) {
this.state._preventScroll = false;
persistEvent(event);
const remove = this.eventStore.add(this.sharedConfig.window, 'touch', 'change', this.preventScroll.bind(this), {
passive: false
});
this.eventStore.add(this.sharedConfig.window, 'touch', 'end', remove);
this.eventStore.add(this.sharedConfig.window, 'touch', 'cancel', remove);
this.timeoutStore.add('startPointerDrag', this.startPointerDrag.bind(this), this.config.preventScrollDelay, event);
}
setupDelayTrigger(event) {
this.state._delayed = true;
this.timeoutStore.add('dragDelay', () => {
this.state._step = [0, 0];
this.startPointerDrag(event);
}, this.config.delay);
}
keyDown(event) {
const deltaFn = KEYS_DELTA_MAP[event.key];
if (deltaFn) {
const state = this.state;
const factor = event.shiftKey ? 10 : event.altKey ? 0.1 : 1;
this.start(event);
state._delta = deltaFn(this.config.keyboardDisplacement, factor);
state._keyboardActive = true;
maths_0ab39ae9_esm_V.addTo(state._movement, state._delta);
this.compute(event);
this.emit();
}
}
keyUp(event) {
if (!(event.key in KEYS_DELTA_MAP)) return;
this.state._keyboardActive = false;
this.setActive();
this.compute(event);
this.emit();
}
bind(bindFunction) {
const device = this.config.device;
bindFunction(device, 'start', this.pointerDown.bind(this));
if (this.config.pointerCapture) {
bindFunction(device, 'change', this.pointerMove.bind(this));
bindFunction(device, 'end', this.pointerUp.bind(this));
bindFunction(device, 'cancel', this.pointerUp.bind(this));
bindFunction('lostPointerCapture', '', this.pointerUp.bind(this));
}
if (this.config.keys) {
bindFunction('key', 'down', this.keyDown.bind(this));
bindFunction('key', 'up', this.keyUp.bind(this));
}
if (this.config.filterTaps) {
bindFunction('click', '', this.pointerClick.bind(this), {
capture: true,
passive: false
});
}
}
}
function persistEvent(event) {
'persist' in event && typeof event.persist === 'function' && event.persist();
}
const actions_76b8683e_esm_isBrowser = typeof window !== 'undefined' && window.document && window.document.createElement;
function supportsTouchEvents() {
return actions_76b8683e_esm_isBrowser && 'ontouchstart' in window;
}
function isTouchScreen() {
return supportsTouchEvents() || actions_76b8683e_esm_isBrowser && window.navigator.maxTouchPoints > 1;
}
function supportsPointerEvents() {
return actions_76b8683e_esm_isBrowser && 'onpointerdown' in window;
}
function supportsPointerLock() {
return actions_76b8683e_esm_isBrowser && 'exitPointerLock' in window.document;
}
function supportsGestureEvents() {
try {
return 'constructor' in GestureEvent;
} catch (e) {
return false;
}
}
const SUPPORT = {
isBrowser: actions_76b8683e_esm_isBrowser,
gesture: supportsGestureEvents(),
touch: isTouchScreen(),
touchscreen: isTouchScreen(),
pointer: supportsPointerEvents(),
pointerLock: supportsPointerLock()
};
const DEFAULT_PREVENT_SCROLL_DELAY = 250;
const DEFAULT_DRAG_DELAY = 180;
const DEFAULT_SWIPE_VELOCITY = 0.5;
const DEFAULT_SWIPE_DISTANCE = 50;
const DEFAULT_SWIPE_DURATION = 250;
const DEFAULT_KEYBOARD_DISPLACEMENT = 10;
const DEFAULT_DRAG_AXIS_THRESHOLD = {
mouse: 0,
touch: 0,
pen: 8
};
const dragConfigResolver = actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, coordinatesConfigResolver), {}, {
device(_v, _k, {
pointer: {
touch = false,
lock = false,
mouse = false
} = {}
}) {
this.pointerLock = lock && SUPPORT.pointerLock;
if (SUPPORT.touch && touch) return 'touch';
if (this.pointerLock) return 'mouse';
if (SUPPORT.pointer && !mouse) return 'pointer';
if (SUPPORT.touch) return 'touch';
return 'mouse';
},
preventScrollAxis(value, _k, {
preventScroll
}) {
this.preventScrollDelay = typeof preventScroll === 'number' ? preventScroll : preventScroll || preventScroll === undefined && value ? DEFAULT_PREVENT_SCROLL_DELAY : undefined;
if (!SUPPORT.touchscreen || preventScroll === false) return undefined;
return value ? value : preventScroll !== undefined ? 'y' : undefined;
},
pointerCapture(_v, _k, {
pointer: {
capture = true,
buttons = 1,
keys = true
} = {}
}) {
this.pointerButtons = buttons;
this.keys = keys;
return !this.pointerLock && this.device === 'pointer' && capture;
},
threshold(value, _k, {
filterTaps = false,
tapsThreshold = 3,
axis = undefined
}) {
const threshold = maths_0ab39ae9_esm_V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0);
this.filterTaps = filterTaps;
this.tapsThreshold = tapsThreshold;
return threshold;
},
swipe({
velocity = DEFAULT_SWIPE_VELOCITY,
distance = DEFAULT_SWIPE_DISTANCE,
duration = DEFAULT_SWIPE_DURATION
} = {}) {
return {
velocity: this.transform(maths_0ab39ae9_esm_V.toVector(velocity)),
distance: this.transform(maths_0ab39ae9_esm_V.toVector(distance)),
duration
};
},
delay(value = 0) {
switch (value) {
case true:
return DEFAULT_DRAG_DELAY;
case false:
return 0;
default:
return value;
}
},
axisThreshold(value) {
if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD;
return actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value);
},
keyboardDisplacement(value = DEFAULT_KEYBOARD_DISPLACEMENT) {
return value;
}
});
if (false) {}
function clampStateInternalMovementToBounds(state) {
const [ox, oy] = state.overflow;
const [dx, dy] = state._delta;
const [dirx, diry] = state._direction;
if (ox < 0 && dx > 0 && dirx < 0 || ox > 0 && dx < 0 && dirx > 0) {
state._movement[0] = state._movementBound[0];
}
if (oy < 0 && dy > 0 && diry < 0 || oy > 0 && dy < 0 && diry > 0) {
state._movement[1] = state._movementBound[1];
}
}
const SCALE_ANGLE_RATIO_INTENT_DEG = 30;
const PINCH_WHEEL_RATIO = 100;
class PinchEngine extends Engine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "ingKey", 'pinching');
actions_76b8683e_esm_defineProperty(this, "aliasKey", 'da');
}
init() {
this.state.offset = [1, 0];
this.state.lastOffset = [1, 0];
this.state._pointerEvents = new Map();
}
reset() {
super.reset();
const state = this.state;
state._touchIds = [];
state.canceled = false;
state.cancel = this.cancel.bind(this);
state.turns = 0;
}
computeOffset() {
const {
type,
movement,
lastOffset
} = this.state;
if (type === 'wheel') {
this.state.offset = maths_0ab39ae9_esm_V.add(movement, lastOffset);
} else {
this.state.offset = [(1 + movement[0]) * lastOffset[0], movement[1] + lastOffset[1]];
}
}
computeMovement() {
const {
offset,
lastOffset
} = this.state;
this.state.movement = [offset[0] / lastOffset[0], offset[1] - lastOffset[1]];
}
axisIntent() {
const state = this.state;
const [_m0, _m1] = state._movement;
if (!state.axis) {
const axisMovementDifference = Math.abs(_m0) * SCALE_ANGLE_RATIO_INTENT_DEG - Math.abs(_m1);
if (axisMovementDifference < 0) state.axis = 'angle';else if (axisMovementDifference > 0) state.axis = 'scale';
}
}
restrictToAxis(v) {
if (this.config.lockDirection) {
if (this.state.axis === 'scale') v[1] = 0;else if (this.state.axis === 'angle') v[0] = 0;
}
}
cancel() {
const state = this.state;
if (state.canceled) return;
setTimeout(() => {
state.canceled = true;
state._active = false;
this.compute();
this.emit();
}, 0);
}
touchStart(event) {
this.ctrl.setEventIds(event);
const state = this.state;
const ctrlTouchIds = this.ctrl.touchIds;
if (state._active) {
if (state._touchIds.every(id => ctrlTouchIds.has(id))) return;
}
if (ctrlTouchIds.size < 2) return;
this.start(event);
state._touchIds = Array.from(ctrlTouchIds).slice(0, 2);
const payload = touchDistanceAngle(event, state._touchIds);
if (!payload) return;
this.pinchStart(event, payload);
}
pointerStart(event) {
if (event.buttons != null && event.buttons % 2 !== 1) return;
this.ctrl.setEventIds(event);
event.target.setPointerCapture(event.pointerId);
const state = this.state;
const _pointerEvents = state._pointerEvents;
const ctrlPointerIds = this.ctrl.pointerIds;
if (state._active) {
if (Array.from(_pointerEvents.keys()).every(id => ctrlPointerIds.has(id))) return;
}
if (_pointerEvents.size < 2) {
_pointerEvents.set(event.pointerId, event);
}
if (state._pointerEvents.size < 2) return;
this.start(event);
const payload = distanceAngle(...Array.from(_pointerEvents.values()));
if (!payload) return;
this.pinchStart(event, payload);
}
pinchStart(event, payload) {
const state = this.state;
state.origin = payload.origin;
this.computeValues([payload.distance, payload.angle]);
this.computeInitial();
this.compute(event);
this.emit();
}
touchMove(event) {
if (!this.state._active) return;
const payload = touchDistanceAngle(event, this.state._touchIds);
if (!payload) return;
this.pinchMove(event, payload);
}
pointerMove(event) {
const _pointerEvents = this.state._pointerEvents;
if (_pointerEvents.has(event.pointerId)) {
_pointerEvents.set(event.pointerId, event);
}
if (!this.state._active) return;
const payload = distanceAngle(...Array.from(_pointerEvents.values()));
if (!payload) return;
this.pinchMove(event, payload);
}
pinchMove(event, payload) {
const state = this.state;
const prev_a = state._values[1];
const delta_a = payload.angle - prev_a;
let delta_turns = 0;
if (Math.abs(delta_a) > 270) delta_turns += Math.sign(delta_a);
this.computeValues([payload.distance, payload.angle - 360 * delta_turns]);
state.origin = payload.origin;
state.turns = delta_turns;
state._movement = [state._values[0] / state._initial[0] - 1, state._values[1] - state._initial[1]];
this.compute(event);
this.emit();
}
touchEnd(event) {
this.ctrl.setEventIds(event);
if (!this.state._active) return;
if (this.state._touchIds.some(id => !this.ctrl.touchIds.has(id))) {
this.state._active = false;
this.compute(event);
this.emit();
}
}
pointerEnd(event) {
const state = this.state;
this.ctrl.setEventIds(event);
try {
event.target.releasePointerCapture(event.pointerId);
} catch (_unused) {}
if (state._pointerEvents.has(event.pointerId)) {
state._pointerEvents.delete(event.pointerId);
}
if (!state._active) return;
if (state._pointerEvents.size < 2) {
state._active = false;
this.compute(event);
this.emit();
}
}
gestureStart(event) {
if (event.cancelable) event.preventDefault();
const state = this.state;
if (state._active) return;
this.start(event);
this.computeValues([event.scale, event.rotation]);
state.origin = [event.clientX, event.clientY];
this.compute(event);
this.emit();
}
gestureMove(event) {
if (event.cancelable) event.preventDefault();
if (!this.state._active) return;
const state = this.state;
this.computeValues([event.scale, event.rotation]);
state.origin = [event.clientX, event.clientY];
const _previousMovement = state._movement;
state._movement = [event.scale - 1, event.rotation];
state._delta = maths_0ab39ae9_esm_V.sub(state._movement, _previousMovement);
this.compute(event);
this.emit();
}
gestureEnd(event) {
if (!this.state._active) return;
this.state._active = false;
this.compute(event);
this.emit();
}
wheel(event) {
const modifierKey = this.config.modifierKey;
if (modifierKey && !event[modifierKey]) return;
if (!this.state._active) this.wheelStart(event);else this.wheelChange(event);
this.timeoutStore.add('wheelEnd', this.wheelEnd.bind(this));
}
wheelStart(event) {
this.start(event);
this.wheelChange(event);
}
wheelChange(event) {
const isR3f = ('uv' in event);
if (!isR3f) {
if (event.cancelable) {
event.preventDefault();
}
if (false) {}
}
const state = this.state;
state._delta = [-wheelValues(event)[1] / PINCH_WHEEL_RATIO * state.offset[0], 0];
maths_0ab39ae9_esm_V.addTo(state._movement, state._delta);
clampStateInternalMovementToBounds(state);
this.state.origin = [event.clientX, event.clientY];
this.compute(event);
this.emit();
}
wheelEnd() {
if (!this.state._active) return;
this.state._active = false;
this.compute();
this.emit();
}
bind(bindFunction) {
const device = this.config.device;
if (!!device) {
bindFunction(device, 'start', this[device + 'Start'].bind(this));
bindFunction(device, 'change', this[device + 'Move'].bind(this));
bindFunction(device, 'end', this[device + 'End'].bind(this));
bindFunction(device, 'cancel', this[device + 'End'].bind(this));
bindFunction('lostPointerCapture', '', this[device + 'End'].bind(this));
}
if (this.config.pinchOnWheel) {
bindFunction('wheel', '', this.wheel.bind(this), {
passive: false
});
}
}
}
const pinchConfigResolver = actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, commonConfigResolver), {}, {
device(_v, _k, {
shared,
pointer: {
touch = false
} = {}
}) {
const sharedConfig = shared;
if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return 'gesture';
if (SUPPORT.touch && touch) return 'touch';
if (SUPPORT.touchscreen) {
if (SUPPORT.pointer) return 'pointer';
if (SUPPORT.touch) return 'touch';
}
},
bounds(_v, _k, {
scaleBounds = {},
angleBounds = {}
}) {
const _scaleBounds = state => {
const D = assignDefault(call(scaleBounds, state), {
min: -Infinity,
max: Infinity
});
return [D.min, D.max];
};
const _angleBounds = state => {
const A = assignDefault(call(angleBounds, state), {
min: -Infinity,
max: Infinity
});
return [A.min, A.max];
};
if (typeof scaleBounds !== 'function' && typeof angleBounds !== 'function') return [_scaleBounds(), _angleBounds()];
return state => [_scaleBounds(state), _angleBounds(state)];
},
threshold(value, _k, config) {
this.lockDirection = config.axis === 'lock';
const threshold = maths_0ab39ae9_esm_V.toVector(value, this.lockDirection ? [0.1, 3] : 0);
return threshold;
},
modifierKey(value) {
if (value === undefined) return 'ctrlKey';
return value;
},
pinchOnWheel(value = true) {
return value;
}
});
class MoveEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "ingKey", 'moving');
}
move(event) {
if (this.config.mouseOnly && event.pointerType !== 'mouse') return;
if (!this.state._active) this.moveStart(event);else this.moveChange(event);
this.timeoutStore.add('moveEnd', this.moveEnd.bind(this));
}
moveStart(event) {
this.start(event);
this.computeValues(pointerValues(event));
this.compute(event);
this.computeInitial();
this.emit();
}
moveChange(event) {
if (!this.state._active) return;
const values = pointerValues(event);
const state = this.state;
state._delta = maths_0ab39ae9_esm_V.sub(values, state._values);
maths_0ab39ae9_esm_V.addTo(state._movement, state._delta);
this.computeValues(values);
this.compute(event);
this.emit();
}
moveEnd(event) {
if (!this.state._active) return;
this.state._active = false;
this.compute(event);
this.emit();
}
bind(bindFunction) {
bindFunction('pointer', 'change', this.move.bind(this));
bindFunction('pointer', 'leave', this.moveEnd.bind(this));
}
}
const moveConfigResolver = actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, coordinatesConfigResolver), {}, {
mouseOnly: (value = true) => value
});
class ScrollEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "ingKey", 'scrolling');
}
scroll(event) {
if (!this.state._active) this.start(event);
this.scrollChange(event);
this.timeoutStore.add('scrollEnd', this.scrollEnd.bind(this));
}
scrollChange(event) {
if (event.cancelable) event.preventDefault();
const state = this.state;
const values = scrollValues(event);
state._delta = maths_0ab39ae9_esm_V.sub(values, state._values);
maths_0ab39ae9_esm_V.addTo(state._movement, state._delta);
this.computeValues(values);
this.compute(event);
this.emit();
}
scrollEnd() {
if (!this.state._active) return;
this.state._active = false;
this.compute();
this.emit();
}
bind(bindFunction) {
bindFunction('scroll', '', this.scroll.bind(this));
}
}
const scrollConfigResolver = coordinatesConfigResolver;
class WheelEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "ingKey", 'wheeling');
}
wheel(event) {
if (!this.state._active) this.start(event);
this.wheelChange(event);
this.timeoutStore.add('wheelEnd', this.wheelEnd.bind(this));
}
wheelChange(event) {
const state = this.state;
state._delta = wheelValues(event);
maths_0ab39ae9_esm_V.addTo(state._movement, state._delta);
clampStateInternalMovementToBounds(state);
this.compute(event);
this.emit();
}
wheelEnd() {
if (!this.state._active) return;
this.state._active = false;
this.compute();
this.emit();
}
bind(bindFunction) {
bindFunction('wheel', '', this.wheel.bind(this));
}
}
const wheelConfigResolver = coordinatesConfigResolver;
class HoverEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_76b8683e_esm_defineProperty(this, "ingKey", 'hovering');
}
enter(event) {
if (this.config.mouseOnly && event.pointerType !== 'mouse') return;
this.start(event);
this.computeValues(pointerValues(event));
this.compute(event);
this.emit();
}
leave(event) {
if (this.config.mouseOnly && event.pointerType !== 'mouse') return;
const state = this.state;
if (!state._active) return;
state._active = false;
const values = pointerValues(event);
state._movement = state._delta = maths_0ab39ae9_esm_V.sub(values, state._values);
this.computeValues(values);
this.compute(event);
state.delta = state.movement;
this.emit();
}
bind(bindFunction) {
bindFunction('pointer', 'enter', this.enter.bind(this));
bindFunction('pointer', 'leave', this.leave.bind(this));
}
}
const hoverConfigResolver = actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, coordinatesConfigResolver), {}, {
mouseOnly: (value = true) => value
});
const actions_76b8683e_esm_EngineMap = new Map();
const ConfigResolverMap = new Map();
function actions_76b8683e_esm_registerAction(action) {
actions_76b8683e_esm_EngineMap.set(action.key, action.engine);
ConfigResolverMap.set(action.key, action.resolver);
}
const actions_76b8683e_esm_dragAction = {
key: 'drag',
engine: DragEngine,
resolver: dragConfigResolver
};
const actions_76b8683e_esm_hoverAction = {
key: 'hover',
engine: HoverEngine,
resolver: hoverConfigResolver
};
const actions_76b8683e_esm_moveAction = {
key: 'move',
engine: MoveEngine,
resolver: moveConfigResolver
};
const actions_76b8683e_esm_pinchAction = {
key: 'pinch',
engine: PinchEngine,
resolver: pinchConfigResolver
};
const actions_76b8683e_esm_scrollAction = {
key: 'scroll',
engine: ScrollEngine,
resolver: scrollConfigResolver
};
const actions_76b8683e_esm_wheelAction = {
key: 'wheel',
engine: WheelEngine,
resolver: wheelConfigResolver
};
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/use-gesture-core.esm.js
function use_gesture_core_esm_objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = use_gesture_core_esm_objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const sharedConfigResolver = {
target(value) {
if (value) {
return () => 'current' in value ? value.current : value;
}
return undefined;
},
enabled(value = true) {
return value;
},
window(value = SUPPORT.isBrowser ? window : undefined) {
return value;
},
eventOptions({
passive = true,
capture = false
} = {}) {
return {
passive,
capture
};
},
transform(value) {
return value;
}
};
const _excluded = ["target", "eventOptions", "window", "enabled", "transform"];
function resolveWith(config = {}, resolvers) {
const result = {};
for (const [key, resolver] of Object.entries(resolvers)) {
switch (typeof resolver) {
case 'function':
if (false) {} else {
result[key] = resolver.call(result, config[key], key, config);
}
break;
case 'object':
result[key] = resolveWith(config[key], resolver);
break;
case 'boolean':
if (resolver) result[key] = config[key];
break;
}
}
return result;
}
function use_gesture_core_esm_parse(newConfig, gestureKey, _config = {}) {
const _ref = newConfig,
{
target,
eventOptions,
window,
enabled,
transform
} = _ref,
rest = _objectWithoutProperties(_ref, _excluded);
_config.shared = resolveWith({
target,
eventOptions,
window,
enabled,
transform
}, sharedConfigResolver);
if (gestureKey) {
const resolver = ConfigResolverMap.get(gestureKey);
_config[gestureKey] = resolveWith(actions_76b8683e_esm_objectSpread2({
shared: _config.shared
}, rest), resolver);
} else {
for (const key in rest) {
const resolver = ConfigResolverMap.get(key);
if (resolver) {
_config[key] = resolveWith(actions_76b8683e_esm_objectSpread2({
shared: _config.shared
}, rest[key]), resolver);
} else if (false) {}
}
}
return _config;
}
class EventStore {
constructor(ctrl, gestureKey) {
actions_76b8683e_esm_defineProperty(this, "_listeners", new Set());
this._ctrl = ctrl;
this._gestureKey = gestureKey;
}
add(element, device, action, handler, options) {
const listeners = this._listeners;
const type = toDomEventType(device, action);
const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {};
const eventOptions = actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, _options), options);
element.addEventListener(type, handler, eventOptions);
const remove = () => {
element.removeEventListener(type, handler, eventOptions);
listeners.delete(remove);
};
listeners.add(remove);
return remove;
}
clean() {
this._listeners.forEach(remove => remove());
this._listeners.clear();
}
}
class TimeoutStore {
constructor() {
actions_76b8683e_esm_defineProperty(this, "_timeouts", new Map());
}
add(key, callback, ms = 140, ...args) {
this.remove(key);
this._timeouts.set(key, window.setTimeout(callback, ms, ...args));
}
remove(key) {
const timeout = this._timeouts.get(key);
if (timeout) window.clearTimeout(timeout);
}
clean() {
this._timeouts.forEach(timeout => void window.clearTimeout(timeout));
this._timeouts.clear();
}
}
class Controller {
constructor(handlers) {
actions_76b8683e_esm_defineProperty(this, "gestures", new Set());
actions_76b8683e_esm_defineProperty(this, "_targetEventStore", new EventStore(this));
actions_76b8683e_esm_defineProperty(this, "gestureEventStores", {});
actions_76b8683e_esm_defineProperty(this, "gestureTimeoutStores", {});
actions_76b8683e_esm_defineProperty(this, "handlers", {});
actions_76b8683e_esm_defineProperty(this, "config", {});
actions_76b8683e_esm_defineProperty(this, "pointerIds", new Set());
actions_76b8683e_esm_defineProperty(this, "touchIds", new Set());
actions_76b8683e_esm_defineProperty(this, "state", {
shared: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}
});
resolveGestures(this, handlers);
}
setEventIds(event) {
if (isTouch(event)) {
this.touchIds = new Set(touchIds(event));
return this.touchIds;
} else if ('pointerId' in event) {
if (event.type === 'pointerup' || event.type === 'pointercancel') this.pointerIds.delete(event.pointerId);else if (event.type === 'pointerdown') this.pointerIds.add(event.pointerId);
return this.pointerIds;
}
}
applyHandlers(handlers, nativeHandlers) {
this.handlers = handlers;
this.nativeHandlers = nativeHandlers;
}
applyConfig(config, gestureKey) {
this.config = use_gesture_core_esm_parse(config, gestureKey, this.config);
}
clean() {
this._targetEventStore.clean();
for (const key of this.gestures) {
this.gestureEventStores[key].clean();
this.gestureTimeoutStores[key].clean();
}
}
effect() {
if (this.config.shared.target) this.bind();
return () => this._targetEventStore.clean();
}
bind(...args) {
const sharedConfig = this.config.shared;
const props = {};
let target;
if (sharedConfig.target) {
target = sharedConfig.target();
if (!target) return;
}
if (sharedConfig.enabled) {
for (const gestureKey of this.gestures) {
const gestureConfig = this.config[gestureKey];
const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target);
if (gestureConfig.enabled) {
const Engine = actions_76b8683e_esm_EngineMap.get(gestureKey);
new Engine(this, args, gestureKey).bind(bindFunction);
}
}
const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target);
for (const eventKey in this.nativeHandlers) {
nativeBindFunction(eventKey, '', event => this.nativeHandlers[eventKey](actions_76b8683e_esm_objectSpread2(actions_76b8683e_esm_objectSpread2({}, this.state.shared), {}, {
event,
args
})), undefined, true);
}
}
for (const handlerProp in props) {
props[handlerProp] = chain(...props[handlerProp]);
}
if (!target) return props;
for (const handlerProp in props) {
const {
device,
capture,
passive
} = parseProp(handlerProp);
this._targetEventStore.add(target, device, '', props[handlerProp], {
capture,
passive
});
}
}
}
function setupGesture(ctrl, gestureKey) {
ctrl.gestures.add(gestureKey);
ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey);
ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore();
}
function resolveGestures(ctrl, internalHandlers) {
if (internalHandlers.drag) setupGesture(ctrl, 'drag');
if (internalHandlers.wheel) setupGesture(ctrl, 'wheel');
if (internalHandlers.scroll) setupGesture(ctrl, 'scroll');
if (internalHandlers.move) setupGesture(ctrl, 'move');
if (internalHandlers.pinch) setupGesture(ctrl, 'pinch');
if (internalHandlers.hover) setupGesture(ctrl, 'hover');
}
const bindToProps = (props, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => {
var _options$capture, _options$passive;
const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture;
const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive;
let handlerProp = isNative ? device : toHandlerProp(device, action, capture);
if (withPassiveOption && passive) handlerProp += 'Passive';
props[handlerProp] = props[handlerProp] || [];
props[handlerProp].push(handler);
};
const RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;
function sortHandlers(_handlers) {
const native = {};
const handlers = {};
const actions = new Set();
for (let key in _handlers) {
if (RE_NOT_NATIVE.test(key)) {
actions.add(RegExp.lastMatch);
handlers[key] = _handlers[key];
} else {
native[key] = _handlers[key];
}
}
return [handlers, native, actions];
}
function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) {
if (!actions.has(handlerKey)) return;
if (!EngineMap.has(key)) {
if (false) {}
return;
}
const startKey = handlerKey + 'Start';
const endKey = handlerKey + 'End';
const fn = state => {
let memo = undefined;
if (state.first && startKey in handlers) handlers[startKey](state);
if (handlerKey in handlers) memo = handlers[handlerKey](state);
if (state.last && endKey in handlers) handlers[endKey](state);
return memo;
};
internalHandlers[key] = fn;
config[key] = config[key] || {};
}
function use_gesture_core_esm_parseMergedHandlers(mergedHandlers, mergedConfig) {
const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers);
const internalHandlers = {};
registerGesture(actions, handlers, 'onDrag', 'drag', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onWheel', 'wheel', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onScroll', 'scroll', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onPinch', 'pinch', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onMove', 'move', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onHover', 'hover', internalHandlers, mergedConfig);
return {
handlers: internalHandlers,
config: mergedConfig,
nativeHandlers
};
}
;// CONCATENATED MODULE: ./node_modules/@use-gesture/react/dist/use-gesture-react.esm.js
function useRecognizers(handlers, config = {}, gestureKey, nativeHandlers) {
const ctrl = external_React_default().useMemo(() => new Controller(handlers), []);
ctrl.applyHandlers(handlers, nativeHandlers);
ctrl.applyConfig(config, gestureKey);
external_React_default().useEffect(ctrl.effect.bind(ctrl));
external_React_default().useEffect(() => {
return ctrl.clean.bind(ctrl);
}, []);
if (config.target === undefined) {
return ctrl.bind.bind(ctrl);
}
return undefined;
}
function useDrag(handler, config) {
actions_76b8683e_esm_registerAction(actions_76b8683e_esm_dragAction);
return useRecognizers({
drag: handler
}, config || {}, 'drag');
}
function usePinch(handler, config) {
registerAction(pinchAction);
return useRecognizers({
pinch: handler
}, config || {}, 'pinch');
}
function useWheel(handler, config) {
registerAction(wheelAction);
return useRecognizers({
wheel: handler
}, config || {}, 'wheel');
}
function useScroll(handler, config) {
registerAction(scrollAction);
return useRecognizers({
scroll: handler
}, config || {}, 'scroll');
}
function useMove(handler, config) {
registerAction(moveAction);
return useRecognizers({
move: handler
}, config || {}, 'move');
}
function useHover(handler, config) {
actions_76b8683e_esm_registerAction(actions_76b8683e_esm_hoverAction);
return useRecognizers({
hover: handler
}, config || {}, 'hover');
}
function createUseGesture(actions) {
actions.forEach(registerAction);
return function useGesture(_handlers, _config) {
const {
handlers,
nativeHandlers,
config
} = parseMergedHandlers(_handlers, _config || {});
return useRecognizers(handlers, config, undefined, nativeHandlers);
};
}
function useGesture(handlers, config) {
const hook = createUseGesture([dragAction, pinchAction, scrollAction, wheelAction, moveAction, hoverAction]);
return hook(handlers, config || {});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Gets a CSS cursor value based on a drag direction.
*
* @param dragDirection The drag direction.
* @return The CSS cursor value.
*/
function getDragCursor(dragDirection) {
let dragCursor = 'ns-resize';
switch (dragDirection) {
case 'n':
case 's':
dragCursor = 'ns-resize';
break;
case 'e':
case 'w':
dragCursor = 'ew-resize';
break;
}
return dragCursor;
}
/**
* Custom hook that renders a drag cursor when dragging.
*
* @param {boolean} isDragging The dragging state.
* @param {string} dragDirection The drag direction.
*
* @return {string} The CSS cursor value.
*/
function useDragCursor(isDragging, dragDirection) {
const dragCursor = getDragCursor(dragDirection);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isDragging) {
document.documentElement.style.cursor = dragCursor;
} else {
// @ts-expect-error
document.documentElement.style.cursor = null;
}
}, [isDragging, dragCursor]);
return dragCursor;
}
function useDraft(props) {
const refPreviousValue = (0,external_wp_element_namespaceObject.useRef)(props.value);
const [draft, setDraft] = (0,external_wp_element_namespaceObject.useState)({});
const value = draft.value !== undefined ? draft.value : props.value; // Determines when to discard the draft value to restore controlled status.
// To do so, it tracks the previous value and marks the draft value as stale
// after each render.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const {
current: previousValue
} = refPreviousValue;
refPreviousValue.current = props.value;
if (draft.value !== undefined && !draft.isStale) setDraft({ ...draft,
isStale: true
});else if (draft.isStale && props.value !== previousValue) setDraft({});
}, [props.value, draft]);
const onChange = (nextValue, extra) => {
// Mutates the draft value to avoid an extra effect run.
setDraft(current => Object.assign(current, {
value: nextValue,
isStale: false
}));
props.onChange(nextValue, extra);
};
const onBlur = event => {
setDraft({});
props.onBlur?.(event);
};
return {
value,
onBlur,
onChange
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/reducer/state.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const initialStateReducer = state => state;
const initialInputControlState = {
error: null,
initialValue: '',
isDirty: false,
isDragEnabled: false,
isDragging: false,
isPressEnterToChange: false,
value: ''
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/reducer/actions.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const CHANGE = 'CHANGE';
const COMMIT = 'COMMIT';
const CONTROL = 'CONTROL';
const DRAG_END = 'DRAG_END';
const DRAG_START = 'DRAG_START';
const DRAG = 'DRAG';
const INVALIDATE = 'INVALIDATE';
const PRESS_DOWN = 'PRESS_DOWN';
const PRESS_ENTER = 'PRESS_ENTER';
const PRESS_UP = 'PRESS_UP';
const RESET = 'RESET';
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/reducer/reducer.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Prepares initialState for the reducer.
*
* @param initialState The initial state.
* @return Prepared initialState for the reducer
*/
function mergeInitialState(initialState = initialInputControlState) {
const {
value
} = initialState;
return { ...initialInputControlState,
...initialState,
initialValue: value
};
}
/**
* Creates the base reducer which may be coupled to a specializing reducer.
* As its final step, for all actions other than CONTROL, the base reducer
* passes the state and action on through the specializing reducer. The
* exception for CONTROL actions is because they represent controlled updates
* from props and no case has yet presented for their specialization.
*
* @param composedStateReducers A reducer to specialize state changes.
* @return The reducer.
*/
function inputControlStateReducer(composedStateReducers) {
return (state, action) => {
const nextState = { ...state
};
switch (action.type) {
/*
* Controlled updates
*/
case CONTROL:
nextState.value = action.payload.value;
nextState.isDirty = false;
nextState._event = undefined; // Returns immediately to avoid invoking additional reducers.
return nextState;
/**
* Keyboard events
*/
case PRESS_UP:
nextState.isDirty = false;
break;
case PRESS_DOWN:
nextState.isDirty = false;
break;
/**
* Drag events
*/
case DRAG_START:
nextState.isDragging = true;
break;
case DRAG_END:
nextState.isDragging = false;
break;
/**
* Input events
*/
case CHANGE:
nextState.error = null;
nextState.value = action.payload.value;
if (state.isPressEnterToChange) {
nextState.isDirty = true;
}
break;
case COMMIT:
nextState.value = action.payload.value;
nextState.isDirty = false;
break;
case RESET:
nextState.error = null;
nextState.isDirty = false;
nextState.value = action.payload.value || state.initialValue;
break;
/**
* Validation
*/
case INVALIDATE:
nextState.error = action.payload.error;
break;
}
nextState._event = action.payload.event;
/**
* Send the nextState + action to the composedReducers via
* this "bridge" mechanism. This allows external stateReducers
* to hook into actions, and modify state if needed.
*/
return composedStateReducers(nextState, action);
};
}
/**
* A custom hook that connects and external stateReducer with an internal
* reducer. This hook manages the internal state of InputControl.
* However, by connecting an external stateReducer function, other
* components can react to actions as well as modify state before it is
* applied.
*
* This technique uses the "stateReducer" design pattern:
* https://kentcdodds.com/blog/the-state-reducer-pattern/
*
* @param stateReducer An external state reducer.
* @param initialState The initial state for the reducer.
* @param onChangeHandler A handler for the onChange event.
* @return State, dispatch, and a collection of actions.
*/
function useInputControlStateReducer(stateReducer = initialStateReducer, initialState = initialInputControlState, onChangeHandler) {
const [state, dispatch] = (0,external_wp_element_namespaceObject.useReducer)(inputControlStateReducer(stateReducer), mergeInitialState(initialState));
const createChangeEvent = type => (nextValue, event) => {
dispatch({
type,
payload: {
value: nextValue,
event
}
});
};
const createKeyEvent = type => event => {
dispatch({
type,
payload: {
event
}
});
};
const createDragEvent = type => payload => {
dispatch({
type,
payload
});
};
/**
* Actions for the reducer
*/
const change = createChangeEvent(CHANGE);
const invalidate = (error, event) => dispatch({
type: INVALIDATE,
payload: {
error,
event
}
});
const reset = createChangeEvent(RESET);
const commit = createChangeEvent(COMMIT);
const dragStart = createDragEvent(DRAG_START);
const drag = createDragEvent(DRAG);
const dragEnd = createDragEvent(DRAG_END);
const pressUp = createKeyEvent(PRESS_UP);
const pressDown = createKeyEvent(PRESS_DOWN);
const pressEnter = createKeyEvent(PRESS_ENTER);
const currentState = (0,external_wp_element_namespaceObject.useRef)(state);
const refProps = (0,external_wp_element_namespaceObject.useRef)({
value: initialState.value,
onChangeHandler
}); // Freshens refs to props and state so that subsequent effects have access
// to their latest values without their changes causing effect runs.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
currentState.current = state;
refProps.current = {
value: initialState.value,
onChangeHandler
};
}); // Propagates the latest state through onChange.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (currentState.current._event !== undefined && state.value !== refProps.current.value && !state.isDirty) {
var _state$value;
refProps.current.onChangeHandler((_state$value = state.value) !== null && _state$value !== void 0 ? _state$value : '', {
event: currentState.current._event
});
}
}, [state.value, state.isDirty]); // Updates the state from props.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (initialState.value !== currentState.current.value && !currentState.current.isDirty) {
var _initialState$value;
dispatch({
type: CONTROL,
payload: {
value: (_initialState$value = initialState.value) !== null && _initialState$value !== void 0 ? _initialState$value : ''
}
});
}
}, [initialState.value]);
return {
change,
commit,
dispatch,
drag,
dragEnd,
dragStart,
invalidate,
pressDown,
pressEnter,
pressUp,
reset,
state
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-field.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const input_field_noop = () => {};
function InputField({
disabled = false,
dragDirection = 'n',
dragThreshold = 10,
id,
isDragEnabled = false,
isFocused,
isPressEnterToChange = false,
onBlur = input_field_noop,
onChange = input_field_noop,
onDrag = input_field_noop,
onDragEnd = input_field_noop,
onDragStart = input_field_noop,
onFocus = input_field_noop,
onKeyDown = input_field_noop,
onValidate = input_field_noop,
size = 'default',
setIsFocused,
stateReducer = state => state,
value: valueProp,
type,
...props
}, ref) {
const {
// State.
state,
// Actions.
change,
commit,
drag,
dragEnd,
dragStart,
invalidate,
pressDown,
pressEnter,
pressUp,
reset
} = useInputControlStateReducer(stateReducer, {
isDragEnabled,
value: valueProp,
isPressEnterToChange
}, onChange);
const {
value,
isDragging,
isDirty
} = state;
const wasDirtyOnBlur = (0,external_wp_element_namespaceObject.useRef)(false);
const dragCursor = useDragCursor(isDragging, dragDirection);
const handleOnBlur = event => {
onBlur(event);
setIsFocused?.(false);
/**
* If isPressEnterToChange is set, this commits the value to
* the onChange callback.
*/
if (isDirty || !event.target.validity.valid) {
wasDirtyOnBlur.current = true;
handleOnCommit(event);
}
};
const handleOnFocus = event => {
onFocus(event);
setIsFocused?.(true);
};
const handleOnChange = event => {
const nextValue = event.target.value;
change(nextValue, event);
};
const handleOnCommit = event => {
const nextValue = event.currentTarget.value;
try {
onValidate(nextValue);
commit(nextValue, event);
} catch (err) {
invalidate(err, event);
}
};
const handleOnKeyDown = event => {
const {
key
} = event;
onKeyDown(event);
switch (key) {
case 'ArrowUp':
pressUp(event);
break;
case 'ArrowDown':
pressDown(event);
break;
case 'Enter':
pressEnter(event);
if (isPressEnterToChange) {
event.preventDefault();
handleOnCommit(event);
}
break;
case 'Escape':
if (isPressEnterToChange && isDirty) {
event.preventDefault();
reset(valueProp, event);
}
break;
}
};
const dragGestureProps = useDrag(dragProps => {
const {
distance,
dragging,
event,
target
} = dragProps; // The `target` prop always references the `input` element while, by
// default, the `dragProps.event.target` property would reference the real
// event target (i.e. any DOM element that the pointer is hovering while
// dragging). Ensuring that the `target` is always the `input` element
// allows consumers of `InputControl` (or any higher-level control) to
// check the input's validity by accessing `event.target.validity.valid`.
dragProps.event = { ...dragProps.event,
target
};
if (!distance) return;
event.stopPropagation();
/**
* Quick return if no longer dragging.
* This prevents unnecessary value calculations.
*/
if (!dragging) {
onDragEnd(dragProps);
dragEnd(dragProps);
return;
}
onDrag(dragProps);
drag(dragProps);
if (!isDragging) {
onDragStart(dragProps);
dragStart(dragProps);
}
}, {
axis: dragDirection === 'e' || dragDirection === 'w' ? 'x' : 'y',
threshold: dragThreshold,
enabled: isDragEnabled,
pointer: {
capture: false
}
});
const dragProps = isDragEnabled ? dragGestureProps() : {};
/*
* Works around the odd UA (e.g. Firefox) that does not focus inputs of
* type=number when their spinner arrows are pressed.
*/
let handleOnMouseDown;
if (type === 'number') {
handleOnMouseDown = event => {
props.onMouseDown?.(event);
if (event.currentTarget !== event.currentTarget.ownerDocument.activeElement) {
event.currentTarget.focus();
}
};
}
return (0,external_wp_element_namespaceObject.createElement)(Input, { ...props,
...dragProps,
className: "components-input-control__input",
disabled: disabled,
dragCursor: dragCursor,
isDragging: isDragging,
id: id,
onBlur: handleOnBlur,
onChange: handleOnChange,
onFocus: handleOnFocus,
onKeyDown: handleOnKeyDown,
onMouseDown: handleOnMouseDown,
ref: ref,
inputSize: size // Fallback to `''` to avoid "uncontrolled to controlled" warning.
// See https://github.com/WordPress/gutenberg/pull/47250 for details.
,
value: value !== null && value !== void 0 ? value : '',
type: type
});
}
const ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(InputField);
/* harmony default export */ var input_field = (ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/font-values.js
/* harmony default export */ var font_values = ({
'default.fontFamily': "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif",
'default.fontSize': '13px',
'helpText.fontSize': '12px',
mobileTextMinFontSize: '16px'
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/font.js
/**
* Internal dependencies
*/
/**
*
* @param {keyof FONT} value Path of value from `FONT`
* @return {string} Font rule value
*/
function font(value) {
var _FONT$value;
return (_FONT$value = font_values[value]) !== null && _FONT$value !== void 0 ? _FONT$value : '';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/box-sizing.js
function box_sizing_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const boxSizingReset = true ? {
name: "kv6lnz",
styles: "box-sizing:border-box;*,*::before,*::after{box-sizing:inherit;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/base-control/styles/base-control-styles.js
function base_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const base_control_styles_Wrapper = createStyled("div", true ? {
target: "ej5x27r4"
} : 0)("font-family:", font('default.fontFamily'), ";font-size:", font('default.fontSize'), ";", boxSizingReset, ";" + ( true ? "" : 0));
const deprecatedMarginField = ({
__nextHasNoMarginBottom = false
}) => {
return !__nextHasNoMarginBottom && /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(2), ";" + ( true ? "" : 0), true ? "" : 0);
};
const StyledField = createStyled("div", true ? {
target: "ej5x27r3"
} : 0)(deprecatedMarginField, " .components-panel__row &{margin-bottom:inherit;}" + ( true ? "" : 0));
const labelStyles = /*#__PURE__*/emotion_react_browser_esm_css(baseLabelTypography, ";display:inline-block;margin-bottom:", space(2), ";padding:0;" + ( true ? "" : 0), true ? "" : 0);
const StyledLabel = createStyled("label", true ? {
target: "ej5x27r2"
} : 0)(labelStyles, ";" + ( true ? "" : 0));
var base_control_styles_ref = true ? {
name: "11yad0w",
styles: "margin-bottom:revert"
} : 0;
const deprecatedMarginHelp = ({
__nextHasNoMarginBottom = false
}) => {
return !__nextHasNoMarginBottom && base_control_styles_ref;
};
const StyledHelp = createStyled("p", true ? {
target: "ej5x27r1"
} : 0)("margin-top:", space(2), ";margin-bottom:0;font-size:", font('helpText.fontSize'), ";font-style:normal;color:", COLORS.gray[700], ";", deprecatedMarginHelp, ";" + ( true ? "" : 0));
const StyledVisualLabel = createStyled("span", true ? {
target: "ej5x27r0"
} : 0)(labelStyles, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/base-control/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* `BaseControl` is a component used to generate labels and help text for components handling user inputs.
*
* ```jsx
* import { BaseControl, useBaseControlProps } from '@wordpress/components';
*
* // Render a `BaseControl` for a textarea input
* const MyCustomTextareaControl = ({ children, ...baseProps }) => (
* // `useBaseControlProps` is a convenience hook to get the props for the `BaseControl`
* // and the inner control itself. Namely, it takes care of generating a unique `id`,
* // properly associating it with the `label` and `help` elements.
* const { baseControlProps, controlProps } = useBaseControlProps( baseProps );
*
* return (
* <BaseControl { ...baseControlProps } __nextHasNoMarginBottom={ true }>
* <textarea { ...controlProps }>
* { children }
* </textarea>
* </BaseControl>
* );
* );
* ```
*/
const BaseControl = ({
__nextHasNoMarginBottom = false,
id,
label,
hideLabelFromVision = false,
help,
className,
children
}) => {
return (0,external_wp_element_namespaceObject.createElement)(base_control_styles_Wrapper, {
className: classnames_default()('components-base-control', className)
}, (0,external_wp_element_namespaceObject.createElement)(StyledField, {
className: "components-base-control__field" // TODO: Official deprecation for this should start after all internal usages have been migrated
,
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, label && id && (hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label",
htmlFor: id
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, {
className: "components-base-control__label",
htmlFor: id
}, label)), label && !id && (hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label"
}, label) : (0,external_wp_element_namespaceObject.createElement)(BaseControl.VisualLabel, null, label)), children), !!help && (0,external_wp_element_namespaceObject.createElement)(StyledHelp, {
id: id ? id + '__help' : undefined,
className: "components-base-control__help",
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, help));
};
/**
* `BaseControl.VisualLabel` is used to render a purely visual label inside a `BaseControl` component.
*
* It should only be used in cases where the children being rendered inside `BaseControl` are already accessibly labeled,
* e.g., a button, but we want an additional visual label for that section equivalent to the labels `BaseControl` would
* otherwise use if the `label` prop was passed.
*
* @example
* import { BaseControl } from '@wordpress/components';
*
* const MyBaseControl = () => (
* <BaseControl help="This button is already accessibly labeled.">
* <BaseControl.VisualLabel>Author</BaseControl.VisualLabel>
* <Button>Select an author</Button>
* </BaseControl>
* );
*/
const VisualLabel = ({
className,
children,
...props
}) => {
return (0,external_wp_element_namespaceObject.createElement)(StyledVisualLabel, { ...props,
className: classnames_default()('components-base-control__label', className)
}, children);
};
BaseControl.VisualLabel = VisualLabel;
/* harmony default export */ var base_control = (BaseControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const input_control_noop = () => {};
function input_control_useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(InputControl);
const id = `inspector-input-control-${instanceId}`;
return idProp || id;
}
function UnforwardedInputControl({
__next36pxDefaultSize,
__unstableStateReducer: stateReducer = state => state,
__unstableInputWidth,
className,
disabled = false,
help,
hideLabelFromVision = false,
id: idProp,
isPressEnterToChange = false,
label,
labelPosition = 'top',
onChange = input_control_noop,
onValidate = input_control_noop,
onKeyDown = input_control_noop,
prefix,
size = 'default',
style,
suffix,
value,
...props
}, ref) {
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const id = input_control_useUniqueId(idProp);
const classes = classnames_default()('components-input-control', className);
const draftHookProps = useDraft({
value,
onBlur: props.onBlur,
onChange
}); // ARIA descriptions can only contain plain text, so fall back to aria-details if not.
const helpPropName = typeof help === 'string' ? 'aria-describedby' : 'aria-details';
const helpProp = !!help ? {
[helpPropName]: `${id}__help`
} : {};
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
className: classes,
help: help,
id: id,
__nextHasNoMarginBottom: true
}, (0,external_wp_element_namespaceObject.createElement)(input_base, {
__next36pxDefaultSize: __next36pxDefaultSize,
__unstableInputWidth: __unstableInputWidth,
disabled: disabled,
gap: 3,
hideLabelFromVision: hideLabelFromVision,
id: id,
isFocused: isFocused,
justify: "left",
label: label,
labelPosition: labelPosition,
prefix: prefix,
size: size,
style: style,
suffix: suffix
}, (0,external_wp_element_namespaceObject.createElement)(input_field, { ...props,
...helpProp,
__next36pxDefaultSize: __next36pxDefaultSize,
className: "components-input-control__input",
disabled: disabled,
id: id,
isFocused: isFocused,
isPressEnterToChange: isPressEnterToChange,
onKeyDown: onKeyDown,
onValidate: onValidate,
paddingInlineStart: prefix ? space(2) : undefined,
paddingInlineEnd: suffix ? space(2) : undefined,
ref: ref,
setIsFocused: setIsFocused,
size: size,
stateReducer: stateReducer,
...draftHookProps
})));
}
/**
* InputControl components let users enter and edit text. This is an experimental component
* intended to (in time) merge with or replace `TextControl`.
*
* ```jsx
* import { __experimentalInputControl as InputControl } from '@wordpress/components';
* import { useState } from '@wordpress/compose';
*
* const Example = () => {
* const [ value, setValue ] = useState( '' );
*
* return (
* <InputControl
* value={ value }
* onChange={ ( nextValue ) => setValue( nextValue ?? '' ) }
* />
* );
* };
* ```
*/
const InputControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedInputControl);
/* harmony default export */ var input_control = (InputControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/number-control/styles/number-control-styles.js
function number_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
var number_control_styles_ref = true ? {
name: "euqsgg",
styles: "input[type='number']::-webkit-outer-spin-button,input[type='number']::-webkit-inner-spin-button{-webkit-appearance:none!important;margin:0!important;}input[type='number']{-moz-appearance:textfield;}"
} : 0;
const htmlArrowStyles = ({
hideHTMLArrows
}) => {
if (!hideHTMLArrows) {
return ``;
}
return number_control_styles_ref;
};
const number_control_styles_Input = /*#__PURE__*/createStyled(input_control, true ? {
target: "ep09it41"
} : 0)(htmlArrowStyles, ";" + ( true ? "" : 0));
const SpinButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "ep09it40"
} : 0)("&&&&&{color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const smallSpinButtons = /*#__PURE__*/emotion_react_browser_esm_css("width:", space(5), ";min-width:", space(5), ";height:", space(5), ";" + ( true ? "" : 0), true ? "" : 0);
const styles = {
smallSpinButtons
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/math.js
/**
* Parses and retrieves a number value.
*
* @param {unknown} value The incoming value.
*
* @return {number} The parsed number value.
*/
function getNumber(value) {
const number = Number(value);
return isNaN(number) ? 0 : number;
}
/**
* Safely adds 2 values.
*
* @param {Array<number|string>} args Values to add together.
*
* @return {number} The sum of values.
*/
function add(...args) {
return args.reduce(
/** @type {(sum:number, arg: number|string) => number} */
(sum, arg) => sum + getNumber(arg), 0);
}
/**
* Safely subtracts 2 values.
*
* @param {Array<number|string>} args Values to subtract together.
*
* @return {number} The difference of the values.
*/
function subtract(...args) {
return args.reduce(
/** @type {(diff:number, arg: number|string, index:number) => number} */
(diff, arg, index) => {
const value = getNumber(arg);
return index === 0 ? value : diff - value;
}, 0);
}
/**
* Determines the decimal position of a number value.
*
* @param {number} value The number to evaluate.
*
* @return {number} The number of decimal places.
*/
function getPrecision(value) {
const split = (value + '').split('.');
return split[1] !== undefined ? split[1].length : 0;
}
/**
* Clamps a value based on a min/max range.
*
* @param {number} value The value.
* @param {number} min The minimum range.
* @param {number} max The maximum range.
*
* @return {number} The clamped value.
*/
function math_clamp(value, min, max) {
const baseValue = getNumber(value);
return Math.max(min, Math.min(baseValue, max));
}
/**
* Clamps a value based on a min/max range with rounding
*
* @param {number | string} value The value.
* @param {number} min The minimum range.
* @param {number} max The maximum range.
* @param {number} step A multiplier for the value.
*
* @return {number} The rounded and clamped value.
*/
function roundClamp(value = 0, min = Infinity, max = Infinity, step = 1) {
const baseValue = getNumber(value);
const stepValue = getNumber(step);
const precision = getPrecision(step);
const rounded = Math.round(baseValue / stepValue) * stepValue;
const clampedValue = math_clamp(rounded, min, max);
return precision ? getNumber(clampedValue.toFixed(precision)) : clampedValue;
}
/**
* Clamps a value based on a min/max range with rounding.
* Returns a string.
*
* @param {Parameters<typeof roundClamp>} args Arguments for roundClamp().
* @return {string} The rounded and clamped value.
*/
function roundClampString(...args) {
return roundClamp(...args).toString();
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/h-stack/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const H_ALIGNMENTS = {
bottom: {
align: 'flex-end',
justify: 'center'
},
bottomLeft: {
align: 'flex-end',
justify: 'flex-start'
},
bottomRight: {
align: 'flex-end',
justify: 'flex-end'
},
center: {
align: 'center',
justify: 'center'
},
edge: {
align: 'center',
justify: 'space-between'
},
left: {
align: 'center',
justify: 'flex-start'
},
right: {
align: 'center',
justify: 'flex-end'
},
stretch: {
align: 'stretch'
},
top: {
align: 'flex-start',
justify: 'center'
},
topLeft: {
align: 'flex-start',
justify: 'flex-start'
},
topRight: {
align: 'flex-start',
justify: 'flex-end'
}
};
const V_ALIGNMENTS = {
bottom: {
justify: 'flex-end',
align: 'center'
},
bottomLeft: {
justify: 'flex-end',
align: 'flex-start'
},
bottomRight: {
justify: 'flex-end',
align: 'flex-end'
},
center: {
justify: 'center',
align: 'center'
},
edge: {
justify: 'space-between',
align: 'center'
},
left: {
justify: 'center',
align: 'flex-start'
},
right: {
justify: 'center',
align: 'flex-end'
},
stretch: {
align: 'stretch'
},
top: {
justify: 'flex-start',
align: 'center'
},
topLeft: {
justify: 'flex-start',
align: 'flex-start'
},
topRight: {
justify: 'flex-start',
align: 'flex-end'
}
};
function getAlignmentProps(alignment, direction = 'row') {
if (!isValueDefined(alignment)) {
return {};
}
const isVertical = direction === 'column';
const props = isVertical ? V_ALIGNMENTS : H_ALIGNMENTS;
const alignmentProps = alignment in props ? props[alignment] : {
align: alignment
};
return alignmentProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/get-valid-children.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Gets a collection of available children elements from a React component's children prop.
*
* @param children
*
* @return An array of available children.
*/
function getValidChildren(children) {
if (typeof children === 'string') return [children];
return external_wp_element_namespaceObject.Children.toArray(children).filter(child => (0,external_wp_element_namespaceObject.isValidElement)(child));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/h-stack/hook.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function useHStack(props) {
const {
alignment = 'edge',
children,
direction,
spacing = 2,
...otherProps
} = useContextSystem(props, 'HStack');
const align = getAlignmentProps(alignment, direction);
const validChildren = getValidChildren(children);
const clonedChildren = validChildren.map((child, index) => {
const _isSpacer = hasConnectNamespace(child, ['Spacer']);
if (_isSpacer) {
const childElement = child;
const _key = childElement.key || `hstack-${index}`;
return (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
isBlock: true,
key: _key,
...childElement.props
});
}
return child;
});
const propsForFlex = {
children: clonedChildren,
direction,
justify: 'center',
...align,
...otherProps,
gap: spacing
};
const flexProps = useFlex(propsForFlex);
return flexProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/h-stack/component.js
/**
* Internal dependencies
*/
function UnconnectedHStack(props, forwardedRef) {
const hStackProps = useHStack(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...hStackProps,
ref: forwardedRef
});
}
/**
* `HStack` (Horizontal Stack) arranges child elements in a horizontal line.
*
* `HStack` can render anything inside.
*
* ```jsx
* import {
* __experimentalHStack as HStack,
* __experimentalText as Text,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <HStack>
* <Text>Code</Text>
* <Text>is</Text>
* <Text>Poetry</Text>
* </HStack>
* );
* }
* ```
*/
const HStack = contextConnect(UnconnectedHStack, 'HStack');
/* harmony default export */ var h_stack_component = (HStack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/number-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const number_control_noop = () => {};
function UnforwardedNumberControl({
__unstableStateReducer: stateReducerProp,
className,
dragDirection = 'n',
hideHTMLArrows = false,
spinControls = 'native',
isDragEnabled = true,
isShiftStepEnabled = true,
label,
max = Infinity,
min = -Infinity,
required = false,
shiftStep = 10,
step = 1,
type: typeProp = 'number',
value: valueProp,
size = 'default',
suffix,
onChange = number_control_noop,
...props
}, forwardedRef) {
if (hideHTMLArrows) {
external_wp_deprecated_default()('wp.components.NumberControl hideHTMLArrows prop ', {
alternative: 'spinControls="none"',
since: '6.2',
version: '6.3'
});
spinControls = 'none';
}
const inputRef = (0,external_wp_element_namespaceObject.useRef)();
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([inputRef, forwardedRef]);
const isStepAny = step === 'any';
const baseStep = isStepAny ? 1 : ensureNumber(step);
const baseValue = roundClamp(0, min, max, baseStep);
const constrainValue = (value, stepOverride) => {
// When step is "any" clamp the value, otherwise round and clamp it.
return isStepAny ? Math.min(max, Math.max(min, ensureNumber(value))) : roundClamp(value, min, max, stepOverride !== null && stepOverride !== void 0 ? stepOverride : baseStep);
};
const autoComplete = typeProp === 'number' ? 'off' : undefined;
const classes = classnames_default()('components-number-control', className);
const cx = useCx();
const spinButtonClasses = cx(size === 'small' && styles.smallSpinButtons);
const spinValue = (value, direction, event) => {
event?.preventDefault();
const shift = event?.shiftKey && isShiftStepEnabled;
const delta = shift ? ensureNumber(shiftStep) * baseStep : baseStep;
let nextValue = isValueEmpty(value) ? baseValue : value;
if (direction === 'up') {
nextValue = add(nextValue, delta);
} else if (direction === 'down') {
nextValue = subtract(nextValue, delta);
}
return constrainValue(nextValue, shift ? delta : undefined);
};
/**
* "Middleware" function that intercepts updates from InputControl.
* This allows us to tap into actions to transform the (next) state for
* InputControl.
*
* @return The updated state to apply to InputControl
*/
const numberControlStateReducer = (state, action) => {
const nextState = { ...state
};
const {
type,
payload
} = action;
const event = payload.event;
const currentValue = nextState.value;
/**
* Handles custom UP and DOWN Keyboard events
*/
if (type === PRESS_UP || type === PRESS_DOWN) {
// @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
nextState.value = spinValue(currentValue, type === PRESS_UP ? 'up' : 'down', event);
}
/**
* Handles drag to update events
*/
if (type === DRAG && isDragEnabled) {
const [x, y] = payload.delta;
const enableShift = payload.shiftKey && isShiftStepEnabled;
const modifier = enableShift ? ensureNumber(shiftStep) * baseStep : baseStep;
let directionModifier;
let delta;
switch (dragDirection) {
case 'n':
delta = y;
directionModifier = -1;
break;
case 'e':
delta = x;
directionModifier = (0,external_wp_i18n_namespaceObject.isRTL)() ? -1 : 1;
break;
case 's':
delta = y;
directionModifier = 1;
break;
case 'w':
delta = x;
directionModifier = (0,external_wp_i18n_namespaceObject.isRTL)() ? 1 : -1;
break;
}
if (delta !== 0) {
delta = Math.ceil(Math.abs(delta)) * Math.sign(delta);
const distance = delta * modifier * directionModifier; // @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
nextState.value = constrainValue( // @ts-expect-error TODO: Investigate if it's ok for currentValue to be undefined
add(currentValue, distance), enableShift ? modifier : undefined);
}
}
/**
* Handles commit (ENTER key press or blur)
*/
if (type === PRESS_ENTER || type === COMMIT) {
const applyEmptyValue = required === false && currentValue === ''; // @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
nextState.value = applyEmptyValue ? currentValue : // @ts-expect-error TODO: Investigate if it's ok for currentValue to be undefined
constrainValue(currentValue);
}
return nextState;
};
const buildSpinButtonClickHandler = direction => event => onChange(String(spinValue(valueProp, direction, event)), {
// Set event.target to the <input> so that consumers can use
// e.g. event.target.validity.
event: { ...event,
target: inputRef.current
}
});
return (0,external_wp_element_namespaceObject.createElement)(number_control_styles_Input, {
autoComplete: autoComplete,
inputMode: "numeric",
...props,
className: classes,
dragDirection: dragDirection,
hideHTMLArrows: spinControls !== 'native',
isDragEnabled: isDragEnabled,
label: label,
max: max,
min: min,
ref: mergedRef,
required: required,
step: step,
type: typeProp // @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
,
value: valueProp,
__unstableStateReducer: (state, action) => {
var _stateReducerProp;
const baseState = numberControlStateReducer(state, action);
return (_stateReducerProp = stateReducerProp?.(baseState, action)) !== null && _stateReducerProp !== void 0 ? _stateReducerProp : baseState;
},
size: size,
suffix: spinControls === 'custom' ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, suffix, (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: 0,
marginRight: 2
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
spacing: 1
}, (0,external_wp_element_namespaceObject.createElement)(SpinButton, {
className: spinButtonClasses,
icon: library_plus,
isSmall: true,
"aria-hidden": "true",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Increment'),
tabIndex: -1,
onClick: buildSpinButtonClickHandler('up')
}), (0,external_wp_element_namespaceObject.createElement)(SpinButton, {
className: spinButtonClasses,
icon: library_reset,
isSmall: true,
"aria-hidden": "true",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Decrement'),
tabIndex: -1,
onClick: buildSpinButtonClickHandler('down')
})))) : suffix,
onChange: onChange
});
}
const NumberControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedNumberControl);
/* harmony default export */ var number_control = (NumberControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/angle-picker-control/styles/angle-picker-control-styles.js
function angle_picker_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const CIRCLE_SIZE = 32;
const INNER_CIRCLE_SIZE = 6;
const deprecatedBottomMargin = ({
__nextHasNoMarginBottom
}) => {
return !__nextHasNoMarginBottom ? /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(2), ";" + ( true ? "" : 0), true ? "" : 0) : '';
};
const angle_picker_control_styles_Root = /*#__PURE__*/createStyled(flex_component, true ? {
target: "eln3bjz4"
} : 0)(deprecatedBottomMargin, ";" + ( true ? "" : 0));
const CircleRoot = createStyled("div", true ? {
target: "eln3bjz3"
} : 0)("border-radius:50%;border:", config_values.borderWidth, " solid ", COLORS.ui.border, ";box-sizing:border-box;cursor:grab;height:", CIRCLE_SIZE, "px;overflow:hidden;width:", CIRCLE_SIZE, "px;:active{cursor:grabbing;}" + ( true ? "" : 0));
const CircleIndicatorWrapper = createStyled("div", true ? {
target: "eln3bjz2"
} : 0)( true ? {
name: "1r307gh",
styles: "box-sizing:border-box;position:relative;width:100%;height:100%;:focus-visible{outline:none;}"
} : 0);
const CircleIndicator = createStyled("div", true ? {
target: "eln3bjz1"
} : 0)("background:", COLORS.ui.theme, ";border-radius:50%;box-sizing:border-box;display:block;left:50%;top:4px;transform:translateX( -50% );position:absolute;width:", INNER_CIRCLE_SIZE, "px;height:", INNER_CIRCLE_SIZE, "px;" + ( true ? "" : 0));
const UnitText = /*#__PURE__*/createStyled(text_component, true ? {
target: "eln3bjz0"
} : 0)("color:", COLORS.ui.theme, ";margin-right:", space(3), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/angle-picker-control/angle-circle.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function AngleCircle({
value,
onChange,
...props
}) {
const angleCircleRef = (0,external_wp_element_namespaceObject.useRef)(null);
const angleCircleCenter = (0,external_wp_element_namespaceObject.useRef)();
const previousCursorValue = (0,external_wp_element_namespaceObject.useRef)();
const setAngleCircleCenter = () => {
if (angleCircleRef.current === null) {
return;
}
const rect = angleCircleRef.current.getBoundingClientRect();
angleCircleCenter.current = {
x: rect.x + rect.width / 2,
y: rect.y + rect.height / 2
};
};
const changeAngleToPosition = event => {
if (event === undefined) {
return;
} // Prevent (drag) mouse events from selecting and accidentally
// triggering actions from other elements.
event.preventDefault(); // Input control needs to lose focus and by preventDefault above, it doesn't.
event.target?.focus();
if (angleCircleCenter.current !== undefined && onChange !== undefined) {
const {
x: centerX,
y: centerY
} = angleCircleCenter.current;
onChange(getAngle(centerX, centerY, event.clientX, event.clientY));
}
};
const {
startDrag,
isDragging
} = (0,external_wp_compose_namespaceObject.__experimentalUseDragging)({
onDragStart: event => {
setAngleCircleCenter();
changeAngleToPosition(event);
},
onDragMove: changeAngleToPosition,
onDragEnd: changeAngleToPosition
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isDragging) {
if (previousCursorValue.current === undefined) {
previousCursorValue.current = document.body.style.cursor;
}
document.body.style.cursor = 'grabbing';
} else {
document.body.style.cursor = previousCursorValue.current || '';
previousCursorValue.current = undefined;
}
}, [isDragging]);
return (0,external_wp_element_namespaceObject.createElement)(CircleRoot, {
ref: angleCircleRef,
onMouseDown: startDrag,
className: "components-angle-picker-control__angle-circle",
...props
}, (0,external_wp_element_namespaceObject.createElement)(CircleIndicatorWrapper, {
style: value ? {
transform: `rotate(${value}deg)`
} : undefined,
className: "components-angle-picker-control__angle-circle-indicator-wrapper",
tabIndex: -1
}, (0,external_wp_element_namespaceObject.createElement)(CircleIndicator, {
className: "components-angle-picker-control__angle-circle-indicator"
})));
}
function getAngle(centerX, centerY, pointX, pointY) {
const y = pointY - centerY;
const x = pointX - centerX;
const angleInRadians = Math.atan2(y, x);
const angleInDeg = Math.round(angleInRadians * (180 / Math.PI)) + 90;
if (angleInDeg < 0) {
return 360 + angleInDeg;
}
return angleInDeg;
}
/* harmony default export */ var angle_circle = (AngleCircle);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/angle-picker-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedAnglePickerControl(props, ref) {
const {
__nextHasNoMarginBottom = false,
className,
label = (0,external_wp_i18n_namespaceObject.__)('Angle'),
onChange,
value,
...restProps
} = props;
if (!__nextHasNoMarginBottom) {
external_wp_deprecated_default()('Bottom margin styles for wp.components.AnglePickerControl', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version.'
});
}
const handleOnNumberChange = unprocessedValue => {
if (onChange === undefined) {
return;
}
const inputValue = unprocessedValue !== undefined && unprocessedValue !== '' ? parseInt(unprocessedValue, 10) : 0;
onChange(inputValue);
};
const classes = classnames_default()('components-angle-picker-control', className);
const unitText = (0,external_wp_element_namespaceObject.createElement)(UnitText, null, "\xB0");
const [prefixedUnitText, suffixedUnitText] = (0,external_wp_i18n_namespaceObject.isRTL)() ? [unitText, null] : [null, unitText];
return (0,external_wp_element_namespaceObject.createElement)(angle_picker_control_styles_Root, { ...restProps,
ref: ref,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: classes,
gap: 2
}, (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(number_control, {
label: label,
className: "components-angle-picker-control__input-field",
max: 360,
min: 0,
onChange: handleOnNumberChange,
size: "__unstable-large",
step: "1",
value: value,
spinControls: "none",
prefix: prefixedUnitText,
suffix: suffixedUnitText
})), (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: "1",
marginTop: "auto"
}, (0,external_wp_element_namespaceObject.createElement)(angle_circle, {
"aria-hidden": "true",
value: value,
onChange: onChange
})));
}
/**
* `AnglePickerControl` is a React component to render a UI that allows users to
* pick an angle. Users can choose an angle in a visual UI with the mouse by
* dragging an angle indicator inside a circle or by directly inserting the
* desired angle in a text field.
*
* ```jsx
* import { useState } from '@wordpress/element';
* import { AnglePickerControl } from '@wordpress/components';
*
* function Example() {
* const [ angle, setAngle ] = useState( 0 );
* return (
* <AnglePickerControl
* value={ angle }
* onChange={ setAngle }
* __nextHasNoMarginBottom
* </>
* );
* }
* ```
*/
const AnglePickerControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedAnglePickerControl);
/* harmony default export */ var angle_picker_control = (AnglePickerControl);
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(4793);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// CONCATENATED MODULE: external ["wp","richText"]
var external_wp_richText_namespaceObject = window["wp"]["richText"];
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/strings.js
/**
* External dependencies
*/
const ALL_UNICODE_DASH_CHARACTERS = new RegExp(`[${[// - (hyphen-minus)
'\u002d', // ~ (tilde)
'\u007e', // ­ (soft hyphen)
'\u00ad', // ֊ (armenian hyphen)
'\u058a', // ־ (hebrew punctuation maqaf)
'\u05be', // (canadian syllabics hyphen)
'\u1400', // ᠆ (mongolian todo soft hyphen)
'\u1806', // (hyphen)
'\u2010', // non-breaking hyphen)
'\u2011', // (figure dash)
'\u2012', // (en dash)
'\u2013', // — (em dash)
'\u2014', // ― (horizontal bar)
'\u2015', // (swung dash)
'\u2053', // superscript minus)
'\u207b', // subscript minus)
'\u208b', // (minus sign)
'\u2212', // ⸗ (double oblique hyphen)
'\u2e17', // ⸺ (two-em dash)
'\u2e3a', // ⸻ (three-em dash)
'\u2e3b', // 〜 (wave dash)
'\u301c', // 〰 (wavy dash)
'\u3030', // (katakana-hiragana double hyphen)
'\u30a0', // ︱ (presentation form for vertical em dash)
'\ufe31', // ︲ (presentation form for vertical en dash)
'\ufe32', // (small em dash)
'\ufe58', // ﹣ (small hyphen-minus)
'\ufe63', // (fullwidth hyphen-minus)
'\uff0d'].join('')}]`, 'g');
const normalizeTextString = value => {
return remove_accents_default()(value).toLocaleLowerCase().replace(ALL_UNICODE_DASH_CHARACTERS, '-');
};
/**
* Escapes the RegExp special characters.
*
* @param {string} string Input string.
*
* @return {string} Regex-escaped string.
*/
function escapeRegExp(string) {
return string.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/get-default-use-items.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function filterOptions(search, options = [], maxResults = 10) {
const filtered = [];
for (let i = 0; i < options.length; i++) {
const option = options[i]; // Merge label into keywords.
let {
keywords = []
} = option;
if ('string' === typeof option.label) {
keywords = [...keywords, option.label];
}
const isMatch = keywords.some(keyword => search.test(remove_accents_default()(keyword)));
if (!isMatch) {
continue;
}
filtered.push(option); // Abort early if max reached.
if (filtered.length === maxResults) {
break;
}
}
return filtered;
}
function getDefaultUseItems(autocompleter) {
return filterValue => {
const [items, setItems] = (0,external_wp_element_namespaceObject.useState)([]);
/*
* We support both synchronous and asynchronous retrieval of completer options
* but internally treat all as async so we maintain a single, consistent code path.
*
* Because networks can be slow, and the internet is wonderfully unpredictable,
* we don't want two promises updating the state at once. This ensures that only
* the most recent promise will act on `optionsData`. This doesn't use the state
* because `setState` is batched, and so there's no guarantee that setting
* `activePromise` in the state would result in it actually being in `this.state`
* before the promise resolves and we check to see if this is the active promise or not.
*/
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const {
options,
isDebounced
} = autocompleter;
const loadOptions = (0,external_wp_compose_namespaceObject.debounce)(() => {
const promise = Promise.resolve(typeof options === 'function' ? options(filterValue) : options).then(optionsData => {
if (promise.canceled) {
return;
}
const keyedOptions = optionsData.map((optionData, optionIndex) => ({
key: `${autocompleter.name}-${optionIndex}`,
value: optionData,
label: autocompleter.getOptionLabel(optionData),
keywords: autocompleter.getOptionKeywords ? autocompleter.getOptionKeywords(optionData) : [],
isDisabled: autocompleter.isOptionDisabled ? autocompleter.isOptionDisabled(optionData) : false
})); // Create a regular expression to filter the options.
const search = new RegExp('(?:\\b|\\s|^)' + escapeRegExp(filterValue), 'i');
setItems(filterOptions(search, keyedOptions));
});
return promise;
}, isDebounced ? 250 : 0);
const promise = loadOptions();
return () => {
loadOptions.cancel();
if (promise) {
promise.canceled = true;
}
};
}, [filterValue]);
return [items];
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/autocompleter-ui.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getAutoCompleterUI(autocompleter) {
const useItems = autocompleter.useItems ? autocompleter.useItems : getDefaultUseItems(autocompleter);
function AutocompleterUI({
filterValue,
instanceId,
listBoxId,
className,
selectedIndex,
onChangeOptions,
onSelect,
onReset,
reset,
contentRef
}) {
const [items] = useItems(filterValue);
const popoverAnchor = (0,external_wp_richText_namespaceObject.useAnchor)({
editableContentElement: contentRef.current
});
const [needsA11yCompat, setNeedsA11yCompat] = (0,external_wp_element_namespaceObject.useState)(false);
const popoverRef = (0,external_wp_element_namespaceObject.useRef)(null);
const popoverRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([popoverRef, (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!contentRef.current) return; // If the popover is rendered in a different document than
// the content, we need to duplicate the options list in the
// content document so that it's available to the screen
// readers, which check the DOM ID based aira-* attributes.
setNeedsA11yCompat(node.ownerDocument !== contentRef.current.ownerDocument);
}, [contentRef])]);
useOnClickOutside(popoverRef, reset);
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
function announce(options) {
if (!debouncedSpeak) {
return;
}
if (!!options.length) {
if (filterValue) {
debouncedSpeak((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', options.length), options.length), 'assertive');
} else {
debouncedSpeak((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('Initial %d result loaded. Type to filter all available results. Use up and down arrow keys to navigate.', 'Initial %d results loaded. Type to filter all available results. Use up and down arrow keys to navigate.', options.length), options.length), 'assertive');
}
} else {
debouncedSpeak((0,external_wp_i18n_namespaceObject.__)('No results.'), 'assertive');
}
}
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
onChangeOptions(items);
announce(items); // Temporarily disabling exhaustive-deps to avoid introducing unexpected side effecst.
// See https://github.com/WordPress/gutenberg/pull/41820
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items]);
if (items.length === 0) {
return null;
}
const ListBox = ({
Component = 'div'
}) => (0,external_wp_element_namespaceObject.createElement)(Component, {
id: listBoxId,
role: "listbox",
className: "components-autocomplete__results"
}, items.map((option, index) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: option.key,
id: `components-autocomplete-item-${instanceId}-${option.key}`,
role: "option",
"aria-selected": index === selectedIndex,
disabled: option.isDisabled,
className: classnames_default()('components-autocomplete__result', className, {
'is-selected': index === selectedIndex
}),
onClick: () => onSelect(option)
}, option.label)));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(popover, {
focusOnMount: false,
onClose: onReset,
placement: "top-start",
className: "components-autocomplete__popover",
anchor: popoverAnchor,
ref: popoverRefs
}, (0,external_wp_element_namespaceObject.createElement)(ListBox, null)), contentRef.current && needsA11yCompat && (0,external_ReactDOM_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)(ListBox, {
Component: visually_hidden_component
}), contentRef.current.ownerDocument.body));
}
return AutocompleterUI;
}
function useOnClickOutside(ref, handler) {
(0,external_wp_element_namespaceObject.useEffect)(() => {
const listener = event => {
// Do nothing if clicking ref's element or descendent elements, or if the ref is not referencing an element
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
}; // Disable reason: `ref` is a ref object and should not be included in a
// hook's dependency list.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [handler]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const EMPTY_FILTERED_OPTIONS = [];
function useAutocomplete({
record,
onChange,
onReplace,
completers,
contentRef
}) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(useAutocomplete);
const [selectedIndex, setSelectedIndex] = (0,external_wp_element_namespaceObject.useState)(0);
const [filteredOptions, setFilteredOptions] = (0,external_wp_element_namespaceObject.useState)(EMPTY_FILTERED_OPTIONS);
const [filterValue, setFilterValue] = (0,external_wp_element_namespaceObject.useState)('');
const [autocompleter, setAutocompleter] = (0,external_wp_element_namespaceObject.useState)(null);
const [AutocompleterUI, setAutocompleterUI] = (0,external_wp_element_namespaceObject.useState)(null);
const backspacing = (0,external_wp_element_namespaceObject.useRef)(false);
function insertCompletion(replacement) {
if (autocompleter === null) {
return;
}
const end = record.start;
const start = end - autocompleter.triggerPrefix.length - filterValue.length;
const toInsert = (0,external_wp_richText_namespaceObject.create)({
html: (0,external_wp_element_namespaceObject.renderToString)(replacement)
});
onChange((0,external_wp_richText_namespaceObject.insert)(record, toInsert, start, end));
}
function select(option) {
const {
getOptionCompletion
} = autocompleter || {};
if (option.isDisabled) {
return;
}
if (getOptionCompletion) {
const completion = getOptionCompletion(option.value, filterValue);
const isCompletionObject = obj => {
return obj !== null && typeof obj === 'object' && 'action' in obj && obj.action !== undefined && 'value' in obj && obj.value !== undefined;
};
const completionObject = isCompletionObject(completion) ? completion : {
action: 'insert-at-caret',
value: completion
};
if ('replace' === completionObject.action) {
onReplace([completionObject.value]); // When replacing, the component will unmount, so don't reset
// state (below) on an unmounted component.
return;
} else if ('insert-at-caret' === completionObject.action) {
insertCompletion(completionObject.value);
}
} // Reset autocomplete state after insertion rather than before
// so insertion events don't cause the completion menu to redisplay.
reset();
}
function reset() {
setSelectedIndex(0);
setFilteredOptions(EMPTY_FILTERED_OPTIONS);
setFilterValue('');
setAutocompleter(null);
setAutocompleterUI(null);
}
/**
* Load options for an autocompleter.
*
* @param {Array} options
*/
function onChangeOptions(options) {
setSelectedIndex(options.length === filteredOptions.length ? selectedIndex : 0);
setFilteredOptions(options);
}
function handleKeyDown(event) {
backspacing.current = event.key === 'Backspace';
if (!autocompleter) {
return;
}
if (filteredOptions.length === 0) {
return;
}
if (event.defaultPrevented || // Ignore keydowns from IMEs
event.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
switch (event.key) {
case 'ArrowUp':
setSelectedIndex((selectedIndex === 0 ? filteredOptions.length : selectedIndex) - 1);
break;
case 'ArrowDown':
setSelectedIndex((selectedIndex + 1) % filteredOptions.length);
break;
case 'Escape':
setAutocompleter(null);
setAutocompleterUI(null);
event.preventDefault();
break;
case 'Enter':
select(filteredOptions[selectedIndex]);
break;
case 'ArrowLeft':
case 'ArrowRight':
reset();
return;
default:
return;
} // Any handled key should prevent original behavior. This relies on
// the early return in the default case.
event.preventDefault();
} // textContent is a primitive (string), memoizing is not strictly necessary
// but this is a preemptive performance improvement, since the autocompleter
// is a potential bottleneck for the editor type metric.
const textContent = (0,external_wp_element_namespaceObject.useMemo)(() => {
if ((0,external_wp_richText_namespaceObject.isCollapsed)(record)) {
return (0,external_wp_richText_namespaceObject.getTextContent)((0,external_wp_richText_namespaceObject.slice)(record, 0));
}
return '';
}, [record]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!textContent) {
if (autocompleter) reset();
return;
}
const completer = completers?.find(({
triggerPrefix,
allowContext
}) => {
const index = textContent.lastIndexOf(triggerPrefix);
if (index === -1) {
return false;
}
const textWithoutTrigger = textContent.slice(index + triggerPrefix.length);
const tooDistantFromTrigger = textWithoutTrigger.length > 50; // 50 chars seems to be a good limit.
// This is a final barrier to prevent the effect from completing with
// an extremely long string, which causes the editor to slow-down
// significantly. This could happen, for example, if `matchingWhileBackspacing`
// is true and one of the "words" end up being too long. If that's the case,
// it will be caught by this guard.
if (tooDistantFromTrigger) return false;
const mismatch = filteredOptions.length === 0;
const wordsFromTrigger = textWithoutTrigger.split(/\s/); // We need to allow the effect to run when not backspacing and if there
// was a mismatch. i.e when typing a trigger + the match string or when
// clicking in an existing trigger word on the page. We do that if we
// detect that we have one word from trigger in the current textual context.
//
// Ex.: "Some text @a" <-- "@a" will be detected as the trigger word and
// allow the effect to run. It will run until there's a mismatch.
const hasOneTriggerWord = wordsFromTrigger.length === 1; // This is used to allow the effect to run when backspacing and if
// "touching" a word that "belongs" to a trigger. We consider a "trigger
// word" any word up to the limit of 3 from the trigger character.
// Anything beyond that is ignored if there's a mismatch. This allows
// us to "escape" a mismatch when backspacing, but still imposing some
// sane limits.
//
// Ex: "Some text @marcelo sekkkk" <--- "kkkk" caused a mismatch, but
// if the user presses backspace here, it will show the completion popup again.
const matchingWhileBackspacing = backspacing.current && textWithoutTrigger.split(/\s/).length <= 3;
if (mismatch && !(matchingWhileBackspacing || hasOneTriggerWord)) {
return false;
}
const textAfterSelection = (0,external_wp_richText_namespaceObject.getTextContent)((0,external_wp_richText_namespaceObject.slice)(record, undefined, (0,external_wp_richText_namespaceObject.getTextContent)(record).length));
if (allowContext && !allowContext(textContent.slice(0, index), textAfterSelection)) {
return false;
}
if (/^\s/.test(textWithoutTrigger) || /\s\s+$/.test(textWithoutTrigger)) {
return false;
}
return /[\u0000-\uFFFF]*$/.test(textWithoutTrigger);
});
if (!completer) {
if (autocompleter) reset();
return;
}
const safeTrigger = escapeRegExp(completer.triggerPrefix);
const text = remove_accents_default()(textContent);
const match = text.slice(text.lastIndexOf(completer.triggerPrefix)).match(new RegExp(`${safeTrigger}([\u0000-\uFFFF]*)$`));
const query = match && match[1];
setAutocompleter(completer);
setAutocompleterUI(() => completer !== autocompleter ? getAutoCompleterUI(completer) : AutocompleterUI);
setFilterValue(query === null ? '' : query); // Temporarily disabling exhaustive-deps to avoid introducing unexpected side effecst.
// See https://github.com/WordPress/gutenberg/pull/41820
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [textContent]);
const {
key: selectedKey = ''
} = filteredOptions[selectedIndex] || {};
const {
className
} = autocompleter || {};
const isExpanded = !!autocompleter && filteredOptions.length > 0;
const listBoxId = isExpanded ? `components-autocomplete-listbox-${instanceId}` : undefined;
const activeId = isExpanded ? `components-autocomplete-item-${instanceId}-${selectedKey}` : null;
const hasSelection = record.start !== undefined;
return {
listBoxId,
activeId,
onKeyDown: handleKeyDown,
popover: hasSelection && AutocompleterUI && (0,external_wp_element_namespaceObject.createElement)(AutocompleterUI, {
className: className,
filterValue: filterValue,
instanceId: instanceId,
listBoxId: listBoxId,
selectedIndex: selectedIndex,
onChangeOptions: onChangeOptions,
onSelect: select,
value: record,
contentRef: contentRef,
reset: reset
})
};
}
function useLastDifferentValue(value) {
const history = (0,external_wp_element_namespaceObject.useRef)(new Set());
history.current.add(value); // Keep the history size to 2.
if (history.current.size > 2) {
history.current.delete(Array.from(history.current)[0]);
}
return Array.from(history.current)[0];
}
function useAutocompleteProps(options) {
const ref = (0,external_wp_element_namespaceObject.useRef)(null);
const onKeyDownRef = (0,external_wp_element_namespaceObject.useRef)();
const {
record
} = options;
const previousRecord = useLastDifferentValue(record);
const {
popover,
listBoxId,
activeId,
onKeyDown
} = useAutocomplete({ ...options,
contentRef: ref
});
onKeyDownRef.current = onKeyDown;
const mergedRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function _onKeyDown(event) {
onKeyDownRef.current?.(event);
}
element.addEventListener('keydown', _onKeyDown);
return () => {
element.removeEventListener('keydown', _onKeyDown);
};
}, [])]); // We only want to show the popover if the user has typed something.
const didUserInput = record.text !== previousRecord?.text;
if (!didUserInput) {
return {
ref: mergedRefs
};
}
return {
ref: mergedRefs,
children: popover,
'aria-autocomplete': listBoxId ? 'list' : undefined,
'aria-owns': listBoxId,
'aria-activedescendant': activeId
};
}
function Autocomplete({
children,
isSelected,
...options
}) {
const {
popover,
...props
} = useAutocomplete(options);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children(props), isSelected && popover);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/base-control/hooks.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Generate props for the `BaseControl` and the inner control itself.
*
* Namely, it takes care of generating a unique `id`, properly associating it with the `label` and `help` elements.
*
* @param props
*/
function useBaseControlProps(props) {
const {
help,
id: preferredId,
...restProps
} = props;
const uniqueId = (0,external_wp_compose_namespaceObject.useInstanceId)(base_control, 'wp-components-base-control', preferredId); // ARIA descriptions can only contain plain text, so fall back to aria-details if not.
const helpPropName = typeof help === 'string' ? 'aria-describedby' : 'aria-details';
return {
baseControlProps: {
id: uniqueId,
help,
...restProps
},
controlProps: {
id: uniqueId,
...(!!help ? {
[helpPropName]: `${uniqueId}__help`
} : {})
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link.js
/**
* WordPress dependencies
*/
const link_link = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M10 17.389H8.444A5.194 5.194 0 1 1 8.444 7H10v1.5H8.444a3.694 3.694 0 0 0 0 7.389H10v1.5ZM14 7h1.556a5.194 5.194 0 0 1 0 10.39H14v-1.5h1.556a3.694 3.694 0 0 0 0-7.39H14V7Zm-4.5 6h5v-1.5h-5V13Z"
}));
/* harmony default export */ var library_link = (link_link);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link-off.js
/**
* WordPress dependencies
*/
const linkOff = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17.031 4.703 15.576 4l-1.56 3H14v.03l-2.324 4.47H9.5V13h1.396l-1.502 2.889h-.95a3.694 3.694 0 0 1 0-7.389H10V7H8.444a5.194 5.194 0 1 0 0 10.389h.17L7.5 19.53l1.416.719L15.049 8.5h.507a3.694 3.694 0 0 1 0 7.39H14v1.5h1.556a5.194 5.194 0 0 0 .273-10.383l1.202-2.304Z"
}));
/* harmony default export */ var link_off = (linkOff);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/styles.js
function border_box_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const borderBoxControl = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const linkedBorderControl = () => /*#__PURE__*/emotion_react_browser_esm_css("flex:1;", rtl({
marginRight: '24px'
})(), ";" + ( true ? "" : 0), true ? "" : 0);
const wrapper = true ? {
name: "bjn8wh",
styles: "position:relative"
} : 0;
const borderBoxControlLinkedButton = size => {
return /*#__PURE__*/emotion_react_browser_esm_css("position:absolute;top:", size === '__unstable-large' ? '8px' : '3px', ";", rtl({
right: 0
})(), " line-height:0;" + ( true ? "" : 0), true ? "" : 0);
};
const borderBoxStyleWithFallback = border => {
const {
color = COLORS.gray[200],
style = 'solid',
width = config_values.borderWidth
} = border || {};
const clampedWidth = width !== config_values.borderWidth ? `clamp(1px, ${width}, 10px)` : width;
const hasVisibleBorder = !!width && width !== '0' || !!color;
const borderStyle = hasVisibleBorder ? style || 'solid' : style;
return `${color} ${borderStyle} ${clampedWidth}`;
};
const borderBoxControlVisualizer = (borders, size) => {
return /*#__PURE__*/emotion_react_browser_esm_css("position:absolute;top:", size === '__unstable-large' ? '20px' : '15px', ";right:", size === '__unstable-large' ? '39px' : '29px', ";bottom:", size === '__unstable-large' ? '20px' : '15px', ";left:", size === '__unstable-large' ? '39px' : '29px', ";border-top:", borderBoxStyleWithFallback(borders?.top), ";border-bottom:", borderBoxStyleWithFallback(borders?.bottom), ";", rtl({
borderLeft: borderBoxStyleWithFallback(borders?.left)
})(), " ", rtl({
borderRight: borderBoxStyleWithFallback(borders?.right)
})(), ";" + ( true ? "" : 0), true ? "" : 0);
};
const borderBoxControlSplitControls = size => /*#__PURE__*/emotion_react_browser_esm_css("position:relative;flex:1;width:", size === '__unstable-large' ? undefined : '80%', ";" + ( true ? "" : 0), true ? "" : 0);
const centeredBorderControl = true ? {
name: "1nwbfnf",
styles: "grid-column:span 2;margin:0 auto"
} : 0;
const rightBorderControl = () => /*#__PURE__*/emotion_react_browser_esm_css(rtl({
marginLeft: 'auto'
})(), ";" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-linked-button/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControlLinkedButton(props) {
const {
className,
size = 'default',
...otherProps
} = useContextSystem(props, 'BorderBoxControlLinkedButton'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControlLinkedButton(size), className);
}, [className, cx, size]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-linked-button/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderBoxControlLinkedButton = (props, forwardedRef) => {
const {
className,
isLinked,
...buttonProps
} = useBorderBoxControlLinkedButton(props);
const label = isLinked ? (0,external_wp_i18n_namespaceObject.__)('Unlink sides') : (0,external_wp_i18n_namespaceObject.__)('Link sides');
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)(component, {
className: className
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, { ...buttonProps,
isSmall: true,
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label,
ref: forwardedRef
})));
};
const ConnectedBorderBoxControlLinkedButton = contextConnect(BorderBoxControlLinkedButton, 'BorderBoxControlLinkedButton');
/* harmony default export */ var border_box_control_linked_button_component = (ConnectedBorderBoxControlLinkedButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-visualizer/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControlVisualizer(props) {
const {
className,
value,
size = 'default',
...otherProps
} = useContextSystem(props, 'BorderBoxControlVisualizer'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControlVisualizer(value, size), className);
}, [cx, className, value, size]);
return { ...otherProps,
className: classes,
value
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-visualizer/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderBoxControlVisualizer = (props, forwardedRef) => {
const {
value,
...otherProps
} = useBorderBoxControlVisualizer(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
});
};
const ConnectedBorderBoxControlVisualizer = contextConnect(BorderBoxControlVisualizer, 'BorderBoxControlVisualizer');
/* harmony default export */ var border_box_control_visualizer_component = (ConnectedBorderBoxControlVisualizer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-solid.js
/**
* WordPress dependencies
*/
const lineSolid = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M5 11.25h14v1.5H5z"
}));
/* harmony default export */ var line_solid = (lineSolid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-dashed.js
/**
* WordPress dependencies
*/
const lineDashed = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
fillRule: "evenodd",
d: "M5 11.25h3v1.5H5v-1.5zm5.5 0h3v1.5h-3v-1.5zm8.5 0h-3v1.5h3v-1.5z",
clipRule: "evenodd"
}));
/* harmony default export */ var line_dashed = (lineDashed);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-dotted.js
/**
* WordPress dependencies
*/
const lineDotted = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
fillRule: "evenodd",
d: "M5.25 11.25h1.5v1.5h-1.5v-1.5zm3 0h1.5v1.5h-1.5v-1.5zm4.5 0h-1.5v1.5h1.5v-1.5zm1.5 0h1.5v1.5h-1.5v-1.5zm4.5 0h-1.5v1.5h1.5v-1.5z",
clipRule: "evenodd"
}));
/* harmony default export */ var line_dotted = (lineDotted);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/styles/unit-control-styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// Using `selectSize` instead of `size` to avoid a type conflict with the
// `size` HTML attribute of the `select` element.
// TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const ValueInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "e1bagdl32"
} : 0)("&&&{input{display:block;width:100%;}", BackdropUI, "{transition:box-shadow 0.1s linear;}}" + ( true ? "" : 0));
const baseUnitLabelStyles = ({
selectSize
}) => {
const sizes = {
default: /*#__PURE__*/emotion_react_browser_esm_css("box-sizing:border-box;padding:2px 1px;width:20px;color:", COLORS.gray[800], ";font-size:8px;line-height:1;letter-spacing:-0.5px;text-transform:uppercase;text-align-last:center;" + ( true ? "" : 0), true ? "" : 0),
large: /*#__PURE__*/emotion_react_browser_esm_css("box-sizing:border-box;min-width:24px;max-width:48px;height:24px;margin-inline-end:", space(2), ";padding:", space(1), ";color:", COLORS.ui.theme, ";font-size:13px;line-height:1;text-align-last:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" + ( true ? "" : 0), true ? "" : 0)
};
return selectSize === '__unstable-large' ? sizes.large : sizes.default;
};
const UnitLabel = createStyled("div", true ? {
target: "e1bagdl31"
} : 0)("&&&{pointer-events:none;", baseUnitLabelStyles, ";color:", COLORS.gray[900], ";}" + ( true ? "" : 0));
const unitSelectSizes = ({
selectSize = 'default'
}) => {
const sizes = {
default: /*#__PURE__*/emotion_react_browser_esm_css("height:100%;border:1px solid transparent;transition:box-shadow 0.1s linear,border 0.1s linear;", rtl({
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0
})(), " &:not(:disabled):hover{background-color:", COLORS.gray[100], ";}&:focus{border:1px solid ", COLORS.ui.borderFocus, ";box-shadow:inset 0 0 0 ", config_values.borderWidth + ' ' + COLORS.ui.borderFocus, ";outline-offset:0;outline:2px solid transparent;z-index:1;}" + ( true ? "" : 0), true ? "" : 0),
large: /*#__PURE__*/emotion_react_browser_esm_css("display:flex;justify-content:center;align-items:center;&:hover{color:", COLORS.ui.borderFocus, ";box-shadow:inset 0 0 0 ", config_values.borderWidth + ' ' + COLORS.ui.borderFocus, ";outline:", config_values.borderWidth, " solid transparent;}&:focus{box-shadow:0 0 0 ", config_values.borderWidthFocus + ' ' + COLORS.ui.borderFocus, ";outline:", config_values.borderWidthFocus, " solid transparent;}" + ( true ? "" : 0), true ? "" : 0)
};
return selectSize === '__unstable-large' ? sizes.large : sizes.default;
};
const UnitSelect = createStyled("select", true ? {
target: "e1bagdl30"
} : 0)("&&&{appearance:none;background:transparent;border-radius:2px;border:none;display:block;outline:none;margin:0;min-height:auto;font-family:inherit;", baseUnitLabelStyles, ";", unitSelectSizes, ";&:not( :disabled ){cursor:pointer;}}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/styles.js
function border_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const styles_labelStyles = true ? {
name: "f3vz0n",
styles: "font-weight:500"
} : 0;
const focusBoxShadow = /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:inset 0 0 0 ", config_values.borderWidth, " ", COLORS.ui.borderFocus, ";" + ( true ? "" : 0), true ? "" : 0);
const borderControl = /*#__PURE__*/emotion_react_browser_esm_css("border:0;padding:0;margin:0;", boxSizingReset, ";" + ( true ? "" : 0), true ? "" : 0);
const innerWrapper = () => /*#__PURE__*/emotion_react_browser_esm_css(ValueInput, "{flex:1 1 40%;}&& ", UnitSelect, "{min-height:0;}" + ( true ? "" : 0), true ? "" : 0);
/*
* This style is only applied to the UnitControl wrapper when the border width
* field should be a set width. Omitting this allows the UnitControl &
* RangeControl to share the available width in a 40/60 split respectively.
*/
const styles_wrapperWidth = /*#__PURE__*/emotion_react_browser_esm_css(ValueInput, "{flex:0 0 auto;}" + ( true ? "" : 0), true ? "" : 0);
const wrapperHeight = size => {
return /*#__PURE__*/emotion_react_browser_esm_css("height:", size === '__unstable-large' ? '40px' : '30px', ";" + ( true ? "" : 0), true ? "" : 0);
};
const borderControlDropdown = size => /*#__PURE__*/emotion_react_browser_esm_css("background:#fff;&&>button{height:", size === '__unstable-large' ? '40px' : '30px', ";width:", size === '__unstable-large' ? '40px' : '30px', ";padding:0;display:flex;align-items:center;justify-content:center;", rtl({
borderRadius: `2px 0 0 2px`
}, {
borderRadius: `0 2px 2px 0`
})(), " border:", config_values.borderWidth, " solid ", COLORS.ui.border, ";&:focus,&:hover:not( :disabled ){", focusBoxShadow, " border-color:", COLORS.ui.borderFocus, ";z-index:1;position:relative;}}" + ( true ? "" : 0), true ? "" : 0);
const colorIndicatorBorder = border => {
const {
color,
style
} = border || {};
const fallbackColor = !!style && style !== 'none' ? COLORS.gray[300] : undefined;
return /*#__PURE__*/emotion_react_browser_esm_css("border-style:", style === 'none' ? 'solid' : style, ";border-color:", color || fallbackColor, ";" + ( true ? "" : 0), true ? "" : 0);
};
const colorIndicatorWrapper = (border, size) => {
const {
style
} = border || {};
return /*#__PURE__*/emotion_react_browser_esm_css("border-radius:9999px;border:2px solid transparent;", style ? colorIndicatorBorder(border) : undefined, " width:", size === '__unstable-large' ? '24px' : '22px', ";height:", size === '__unstable-large' ? '24px' : '22px', ";padding:", size === '__unstable-large' ? '2px' : '1px', ";&>span{height:", space(4), ";width:", space(4), ";background:linear-gradient(\n\t\t\t\t-45deg,\n\t\t\t\ttransparent 48%,\n\t\t\t\trgb( 0 0 0 / 20% ) 48%,\n\t\t\t\trgb( 0 0 0 / 20% ) 52%,\n\t\t\t\ttransparent 52%\n\t\t\t);}" + ( true ? "" : 0), true ? "" : 0);
}; // Must equal $color-palette-circle-size from:
// @wordpress/components/src/circular-option-picker/style.scss
const swatchSize = 28;
const swatchGap = 12;
const borderControlPopoverControls = /*#__PURE__*/emotion_react_browser_esm_css("width:", swatchSize * 6 + swatchGap * 5, "px;>div:first-of-type>", StyledLabel, "{margin-bottom:0;", styles_labelStyles, ";}&& ", StyledLabel, "+button:not( .has-text ){min-width:24px;padding:0;}" + ( true ? "" : 0), true ? "" : 0);
const borderControlPopoverContent = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const borderColorIndicator = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const resetButton = /*#__PURE__*/emotion_react_browser_esm_css("justify-content:center;width:100%;&&{border-top:", config_values.borderWidth, " solid ", COLORS.gray[200], ";border-top-left-radius:0;border-top-right-radius:0;height:46px;}" + ( true ? "" : 0), true ? "" : 0);
const borderControlStylePicker = /*#__PURE__*/emotion_react_browser_esm_css(StyledLabel, "{", styles_labelStyles, ";}" + ( true ? "" : 0), true ? "" : 0);
const borderStyleButton = true ? {
name: "1486260",
styles: "&&&&&{min-width:30px;width:30px;height:30px;padding:3px;}"
} : 0;
const borderSlider = () => /*#__PURE__*/emotion_react_browser_esm_css("flex:1 1 60%;", rtl({
marginRight: space(3)
})(), ";" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-style-picker/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderControlStylePicker(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'BorderControlStylePicker'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlStylePicker, className);
}, [className, cx]);
const buttonClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderStyleButton);
}, [cx]);
return { ...otherProps,
className: classes,
buttonClassName
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-style-picker/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BORDER_STYLES = [{
label: (0,external_wp_i18n_namespaceObject.__)('Solid'),
icon: line_solid,
value: 'solid'
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Dashed'),
icon: line_dashed,
value: 'dashed'
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Dotted'),
icon: line_dotted,
value: 'dotted'
}];
const component_Label = props => {
const {
label,
hideLabelFromVision
} = props;
if (!label) {
return null;
}
return hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label"
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, null, label);
};
const BorderControlStylePicker = (props, forwardedRef) => {
const {
buttonClassName,
hideLabelFromVision,
label,
onChange,
value,
...otherProps
} = useBorderControlStylePicker(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(component_Label, {
label: label,
hideLabelFromVision: hideLabelFromVision
}), (0,external_wp_element_namespaceObject.createElement)(flex_component, {
justify: "flex-start",
gap: 1
}, BORDER_STYLES.map(borderStyle => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: borderStyle.value,
className: buttonClassName,
icon: borderStyle.icon,
isSmall: true,
isPressed: borderStyle.value === value,
onClick: () => onChange(borderStyle.value === value ? undefined : borderStyle.value),
"aria-label": borderStyle.label,
label: borderStyle.label,
showTooltip: true
}))));
};
const ConnectedBorderControlStylePicker = contextConnect(BorderControlStylePicker, 'BorderControlStylePicker');
/* harmony default export */ var border_control_style_picker_component = (ConnectedBorderControlStylePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-indicator/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedColorIndicator(props, forwardedRef) {
const {
className,
colorValue,
...additionalProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: classnames_default()('component-color-indicator', className),
style: {
background: colorValue
},
ref: forwardedRef,
...additionalProps
});
}
/**
* ColorIndicator is a React component that renders a specific color in a
* circle. It's often used to summarize a collection of used colors in a child
* component.
*
* ```jsx
* import { ColorIndicator } from '@wordpress/components';
*
* const MyColorIndicator = () => <ColorIndicator colorValue="#0073aa" />;
* ```
*/
const ColorIndicator = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedColorIndicator);
/* harmony default export */ var color_indicator = (ColorIndicator);
;// CONCATENATED MODULE: ./node_modules/colord/plugins/a11y.mjs
var a11y_o=function(o){var t=o/255;return t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},a11y_t=function(t){return.2126*a11y_o(t.r)+.7152*a11y_o(t.g)+.0722*a11y_o(t.b)};/* harmony default export */ function a11y(o){o.prototype.luminance=function(){return o=a11y_t(this.rgba),void 0===(r=2)&&(r=0),void 0===n&&(n=Math.pow(10,r)),Math.round(n*o)/n+0;var o,r,n},o.prototype.contrast=function(r){void 0===r&&(r="#FFF");var n,a,i,e,v,u,d,c=r instanceof o?r:new o(r);return e=this.rgba,v=c.toRgb(),u=a11y_t(e),d=a11y_t(v),n=u>d?(u+.05)/(d+.05):(d+.05)/(u+.05),void 0===(a=2)&&(a=0),void 0===i&&(i=Math.pow(10,a)),Math.floor(i*n)/i+0},o.prototype.isReadable=function(o,t){return void 0===o&&(o="#FFF"),void 0===t&&(t={}),this.contrast(o)>=(e=void 0===(i=(r=t).size)?"normal":i,"AAA"===(a=void 0===(n=r.level)?"AA":n)&&"normal"===e?7:"AA"===a&&"large"===e?3:4.5);var r,n,a,i,e}}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useObservableState(initialState, onStateChange) {
const [state, setState] = (0,external_wp_element_namespaceObject.useState)(initialState);
return [state, value => {
setState(value);
if (onStateChange) {
onStateChange(value);
}
}];
}
const UnconnectedDropdown = (props, forwardedRef) => {
const {
renderContent,
renderToggle,
className,
contentClassName,
expandOnMobile,
headerTitle,
focusOnMount,
popoverProps,
onClose,
onToggle,
style,
// Deprecated props
position,
// From context system
variant
} = useContextSystem(props, 'Dropdown');
if (position !== undefined) {
external_wp_deprecated_default()('`position` prop in wp.components.Dropdown', {
since: '6.2',
alternative: '`popoverProps.placement` prop',
hint: 'Note that the `position` prop will override any values passed through the `popoverProps.placement` prop.'
});
} // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [fallbackPopoverAnchor, setFallbackPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null);
const containerRef = (0,external_wp_element_namespaceObject.useRef)();
const [isOpen, setIsOpen] = useObservableState(false, onToggle);
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
if (onToggle && isOpen) {
onToggle(false);
}
}, [onToggle, isOpen]);
function toggle() {
setIsOpen(!isOpen);
}
/**
* Closes the popover when focus leaves it unless the toggle was pressed or
* focus has moved to a separate dialog. The former is to let the toggle
* handle closing the popover and the latter is to preserve presence in
* case a dialog has opened, allowing focus to return when it's dismissed.
*/
function closeIfFocusOutside() {
if (!containerRef.current) {
return;
}
const {
ownerDocument
} = containerRef.current;
const dialog = ownerDocument?.activeElement?.closest('[role="dialog"]');
if (!containerRef.current.contains(ownerDocument.activeElement) && (!dialog || dialog.contains(containerRef.current))) {
close();
}
}
function close() {
if (onClose) {
onClose();
}
setIsOpen(false);
}
const args = {
isOpen,
onToggle: toggle,
onClose: close
};
const popoverPropsHaveAnchor = !!popoverProps?.anchor || // Note: `anchorRef`, `getAnchorRect` and `anchorRect` are deprecated and
// be removed from `Popover` from WordPress 6.3
!!popoverProps?.anchorRef || !!popoverProps?.getAnchorRect || !!popoverProps?.anchorRect;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([containerRef, forwardedRef, setFallbackPopoverAnchor]) // Some UAs focus the closest focusable parent when the toggle is
// clicked. Making this div focusable ensures such UAs will focus
// it and `closeIfFocusOutside` can tell if the toggle was clicked.
,
tabIndex: -1,
style: style
}, renderToggle(args), isOpen && (0,external_wp_element_namespaceObject.createElement)(popover, {
position: position,
onClose: close,
onFocusOutside: closeIfFocusOutside,
expandOnMobile: expandOnMobile,
headerTitle: headerTitle,
focusOnMount: focusOnMount // This value is used to ensure that the dropdowns
// align with the editor header by default.
,
offset: 13,
anchor: !popoverPropsHaveAnchor ? fallbackPopoverAnchor : undefined,
variant: variant,
...popoverProps,
className: classnames_default()('components-dropdown__content', popoverProps?.className, contentClassName)
}, renderContent(args)));
};
/**
* Renders a button that opens a floating content modal when clicked.
*
* ```jsx
* import { Button, Dropdown } from '@wordpress/components';
*
* const MyDropdown = () => (
* <Dropdown
* className="my-container-class-name"
* contentClassName="my-dropdown-content-classname"
* popoverProps={ { placement: 'bottom-start' } }
* renderToggle={ ( { isOpen, onToggle } ) => (
* <Button
* variant="primary"
* onClick={ onToggle }
* aria-expanded={ isOpen }
* >
* Toggle Dropdown!
* </Button>
* ) }
* renderContent={ () => <div>This is the content of the dropdown.</div> }
* />
* );
* ```
*/
const Dropdown = contextConnect(UnconnectedDropdown, 'Dropdown');
/* harmony default export */ var dropdown = (Dropdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-suffix-wrapper.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedInputControlSuffixWrapper(props, forwardedRef) {
const derivedProps = useContextSystem(props, 'InputControlSuffixWrapper');
return (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: 0,
...derivedProps,
ref: forwardedRef
});
}
/**
* A convenience wrapper for the `suffix` when you want to apply
* standard padding in accordance with the size variant.
*
* ```jsx
* import {
* __experimentalInputControl as InputControl,
* __experimentalInputControlSuffixWrapper as InputControlSuffixWrapper,
* } from '@wordpress/components';
*
* <InputControl
* suffix={<InputControlSuffixWrapper>%</InputControlSuffixWrapper>}
* />
* ```
*/
const InputControlSuffixWrapper = contextConnect(UnconnectedInputControlSuffixWrapper, 'InputControlSuffixWrapper');
/* harmony default export */ var input_suffix_wrapper = (InputControlSuffixWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/styles/select-control-styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const select_control_styles_disabledStyles = ({
disabled
}) => {
if (!disabled) return '';
return /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.ui.textDisabled
}, true ? "" : 0, true ? "" : 0);
};
const select_control_styles_fontSizeStyles = ({
selectSize = 'default'
}) => {
const sizes = {
default: '13px',
small: '11px',
'__unstable-large': '13px'
};
const fontSize = sizes[selectSize];
const fontSizeMobile = '16px';
if (!fontSize) return '';
return /*#__PURE__*/emotion_react_browser_esm_css("font-size:", fontSizeMobile, ";@media ( min-width: 600px ){font-size:", fontSize, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const select_control_styles_sizeStyles = ({
__next36pxDefaultSize,
multiple,
selectSize = 'default'
}) => {
if (multiple) {
// When `multiple`, just use the native browser styles
// without setting explicit height.
return;
}
const sizes = {
default: {
height: 36,
minHeight: 36,
paddingTop: 0,
paddingBottom: 0
},
small: {
height: 24,
minHeight: 24,
paddingTop: 0,
paddingBottom: 0
},
'__unstable-large': {
height: 40,
minHeight: 40,
paddingTop: 0,
paddingBottom: 0
}
};
if (!__next36pxDefaultSize) {
sizes.default = {
height: 30,
minHeight: 30,
paddingTop: 0,
paddingBottom: 0
};
}
const style = sizes[selectSize] || sizes.default;
return /*#__PURE__*/emotion_react_browser_esm_css(style, true ? "" : 0, true ? "" : 0);
};
const chevronIconSize = 18;
const sizePaddings = ({
__next36pxDefaultSize,
multiple,
selectSize = 'default'
}) => {
const padding = {
default: 16,
small: 8,
'__unstable-large': 16
};
if (!__next36pxDefaultSize) {
padding.default = 8;
}
const selectedPadding = padding[selectSize] || padding.default;
return rtl({
paddingLeft: selectedPadding,
paddingRight: selectedPadding + chevronIconSize,
...(multiple ? {
paddingTop: selectedPadding,
paddingBottom: selectedPadding
} : {})
});
};
const overflowStyles = ({
multiple
}) => {
return {
overflow: multiple ? 'auto' : 'hidden'
};
}; // TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const Select = createStyled("select", true ? {
target: "e1mv6sxx2"
} : 0)("&&&{appearance:none;background:transparent;box-sizing:border-box;border:none;box-shadow:none!important;color:", COLORS.gray[900], ";display:block;font-family:inherit;margin:0;width:100%;max-width:none;cursor:pointer;white-space:nowrap;text-overflow:ellipsis;", select_control_styles_disabledStyles, ";", select_control_styles_fontSizeStyles, ";", select_control_styles_sizeStyles, ";", sizePaddings, ";", overflowStyles, ";}" + ( true ? "" : 0));
const DownArrowWrapper = createStyled("div", true ? {
target: "e1mv6sxx1"
} : 0)("margin-inline-end:", space(-1), ";line-height:0;" + ( true ? "" : 0));
const InputControlSuffixWrapperWithClickThrough = /*#__PURE__*/createStyled(input_suffix_wrapper, true ? {
target: "e1mv6sxx0"
} : 0)("position:absolute;pointer-events:none;", rtl({
right: 0
}), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/icon/index.js
/**
* WordPress dependencies
*/
/** @typedef {{icon: JSX.Element, size?: number} & import('@wordpress/primitives').SVGProps} IconProps */
/**
* Return an SVG icon.
*
* @param {IconProps} props icon is the SVG component to render
* size is a number specifiying the icon size in pixels
* Other props will be passed to wrapped SVG component
*
* @return {JSX.Element} Icon component
*/
function icon_Icon({
icon,
size = 24,
...props
}) {
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
width: size,
height: size,
...props
});
}
/* harmony default export */ var icons_build_module_icon = (icon_Icon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-down.js
/**
* WordPress dependencies
*/
const chevronDown = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"
}));
/* harmony default export */ var chevron_down = (chevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/chevron-down.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SelectControlChevronDown = () => {
return (0,external_wp_element_namespaceObject.createElement)(InputControlSuffixWrapperWithClickThrough, null, (0,external_wp_element_namespaceObject.createElement)(DownArrowWrapper, null, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: chevron_down,
size: chevronIconSize
})));
};
/* harmony default export */ var select_control_chevron_down = (SelectControlChevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const select_control_noop = () => {};
function select_control_useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(SelectControl);
const id = `inspector-select-control-${instanceId}`;
return idProp || id;
}
function UnforwardedSelectControl(props, ref) {
const {
className,
disabled = false,
help,
hideLabelFromVision,
id: idProp,
label,
multiple = false,
onBlur = select_control_noop,
onChange,
onFocus = select_control_noop,
options = [],
size = 'default',
value: valueProp,
labelPosition = 'top',
children,
prefix,
suffix,
__next36pxDefaultSize = false,
__nextHasNoMarginBottom = false,
...restProps
} = props;
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const id = select_control_useUniqueId(idProp);
const helpId = help ? `${id}__help` : undefined; // Disable reason: A select with an onchange throws a warning.
if (!options?.length && !children) return null;
const handleOnBlur = event => {
onBlur(event);
setIsFocused(false);
};
const handleOnFocus = event => {
onFocus(event);
setIsFocused(true);
};
const handleOnChange = event => {
if (props.multiple) {
const selectedOptions = Array.from(event.target.options).filter(({
selected
}) => selected);
const newValues = selectedOptions.map(({
value
}) => value);
props.onChange?.(newValues, {
event
});
return;
}
props.onChange?.(event.target.value, {
event
});
};
const classes = classnames_default()('components-select-control', className);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
help: help,
id: id,
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, (0,external_wp_element_namespaceObject.createElement)(input_base, {
className: classes,
disabled: disabled,
hideLabelFromVision: hideLabelFromVision,
id: id,
isFocused: isFocused,
label: label,
size: size,
suffix: suffix || !multiple && (0,external_wp_element_namespaceObject.createElement)(select_control_chevron_down, null),
prefix: prefix,
labelPosition: labelPosition,
__next36pxDefaultSize: __next36pxDefaultSize
}, (0,external_wp_element_namespaceObject.createElement)(Select, { ...restProps,
__next36pxDefaultSize: __next36pxDefaultSize,
"aria-describedby": helpId,
className: "components-select-control__input",
disabled: disabled,
id: id,
multiple: multiple,
onBlur: handleOnBlur,
onChange: handleOnChange,
onFocus: handleOnFocus,
ref: ref,
selectSize: size,
value: valueProp
}, children || options.map((option, index) => {
const key = option.id || `${option.label}-${option.value}-${index}`;
return (0,external_wp_element_namespaceObject.createElement)("option", {
key: key,
value: option.value,
disabled: option.disabled,
hidden: option.hidden
}, option.label);
}))));
}
/**
* `SelectControl` allows users to select from a single or multiple option menu.
* It functions as a wrapper around the browser's native `<select>` element.
*
* @example
* import { SelectControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MySelectControl = () => {
* const [ size, setSize ] = useState( '50%' );
*
* return (
* <SelectControl
* label="Size"
* value={ size }
* options={ [
* { label: 'Big', value: '100%' },
* { label: 'Medium', value: '50%' },
* { label: 'Small', value: '25%' },
* ] }
* onChange={ setSize }
* />
* );
* };
*/
const SelectControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSelectControl);
/* harmony default export */ var select_control = (SelectControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-controlled-state.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @template T
* @typedef Options
* @property {T} [initial] Initial value
* @property {T | ""} fallback Fallback value
*/
/** @type {Readonly<{ initial: undefined, fallback: '' }>} */
const defaultOptions = {
initial: undefined,
/**
* Defaults to empty string, as that is preferred for usage with
* <input />, <textarea />, and <select /> form elements.
*/
fallback: ''
};
/**
* Custom hooks for "controlled" components to track and consolidate internal
* state and incoming values. This is useful for components that render
* `input`, `textarea`, or `select` HTML elements.
*
* https://reactjs.org/docs/forms.html#controlled-components
*
* At first, a component using useControlledState receives an initial prop
* value, which is used as initial internal state.
*
* This internal state can be maintained and updated without
* relying on new incoming prop values.
*
* Unlike the basic useState hook, useControlledState's state can
* be updated if a new incoming prop value is changed.
*
* @template T
*
* @param {T | undefined} currentState The current value.
* @param {Options<T>} [options=defaultOptions] Additional options for the hook.
*
* @return {[T | "", (nextState: T) => void]} The controlled value and the value setter.
*/
function useControlledState(currentState, options = defaultOptions) {
const {
initial,
fallback
} = { ...defaultOptions,
...options
};
const [internalState, setInternalState] = (0,external_wp_element_namespaceObject.useState)(currentState);
const hasCurrentState = isValueDefined(currentState);
/*
* Resets internal state if value every changes from uncontrolled <-> controlled.
*/
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasCurrentState && internalState) {
setInternalState(undefined);
}
}, [hasCurrentState, internalState]);
const state = getDefinedValue([currentState, internalState, initial], fallback);
/* eslint-disable jsdoc/no-undefined-types */
/** @type {(nextState: T) => void} */
const setState = (0,external_wp_element_namespaceObject.useCallback)(nextState => {
if (!hasCurrentState) {
setInternalState(nextState);
}
}, [hasCurrentState]);
/* eslint-enable jsdoc/no-undefined-types */
return [state, setState];
}
/* harmony default export */ var use_controlled_state = (useControlledState);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A float supported clamp function for a specific value.
*
* @param value The value to clamp.
* @param min The minimum value.
* @param max The maximum value.
*
* @return A (float) number
*/
function floatClamp(value, min, max) {
if (typeof value !== 'number') {
return null;
}
return parseFloat(`${math_clamp(value, min, max)}`);
}
/**
* Hook to store a clamped value, derived from props.
*
* @param settings
* @return The controlled value and the value setter.
*/
function useControlledRangeValue(settings) {
const {
min,
max,
value: valueProp,
initial
} = settings;
const [state, setInternalState] = use_controlled_state(floatClamp(valueProp, min, max), {
initial: floatClamp(initial !== null && initial !== void 0 ? initial : null, min, max),
fallback: null
});
const setState = (0,external_wp_element_namespaceObject.useCallback)(nextValue => {
if (nextValue === null) {
setInternalState(null);
} else {
setInternalState(floatClamp(nextValue, min, max));
}
}, [min, max, setInternalState]); // `state` can't be an empty string because we specified a fallback value of
// `null` in `useControlledState`
return [state, setState];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/styles/range-control-styles.js
function range_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const rangeHeightValue = 30;
const railHeight = 4;
const rangeHeight = () => /*#__PURE__*/emotion_react_browser_esm_css({
height: rangeHeightValue,
minHeight: rangeHeightValue
}, true ? "" : 0, true ? "" : 0);
const thumbSize = 12;
const range_control_styles_Root = createStyled("div", true ? {
target: "e1epgpqk14"
} : 0)( true ? {
name: "1se47kl",
styles: "-webkit-tap-highlight-color:transparent;align-items:flex-start;display:flex;justify-content:flex-start;padding:0;position:relative;touch-action:none;width:100%"
} : 0);
const wrapperColor = ({
color = COLORS.ui.borderFocus
}) => /*#__PURE__*/emotion_react_browser_esm_css({
color
}, true ? "" : 0, true ? "" : 0);
const wrapperMargin = ({
marks,
__nextHasNoMarginBottom
}) => {
if (!__nextHasNoMarginBottom) {
return /*#__PURE__*/emotion_react_browser_esm_css({
marginBottom: marks ? 16 : undefined
}, true ? "" : 0, true ? "" : 0);
}
return '';
};
const range_control_styles_Wrapper = createStyled("div", true ? {
target: "e1epgpqk13"
} : 0)("display:block;flex:1;position:relative;width:100%;", wrapperColor, ";", rangeHeight, ";", wrapperMargin, ";" + ( true ? "" : 0));
const BeforeIconWrapper = createStyled("span", true ? {
target: "e1epgpqk12"
} : 0)("display:flex;margin-top:", railHeight, "px;", rtl({
marginRight: 6
}), ";" + ( true ? "" : 0));
const AfterIconWrapper = createStyled("span", true ? {
target: "e1epgpqk11"
} : 0)("display:flex;margin-top:", railHeight, "px;", rtl({
marginLeft: 6
}), ";" + ( true ? "" : 0));
const railBackgroundColor = ({
disabled,
railColor
}) => {
let background = railColor || '';
if (disabled) {
background = COLORS.ui.backgroundDisabled;
}
return /*#__PURE__*/emotion_react_browser_esm_css({
background
}, true ? "" : 0, true ? "" : 0);
};
const Rail = createStyled("span", true ? {
target: "e1epgpqk10"
} : 0)("background-color:", COLORS.gray[300], ";left:0;pointer-events:none;right:0;display:block;height:", railHeight, "px;position:absolute;margin-top:", (rangeHeightValue - railHeight) / 2, "px;top:0;border-radius:", railHeight, "px;", railBackgroundColor, ";" + ( true ? "" : 0));
const trackBackgroundColor = ({
disabled,
trackColor
}) => {
let background = trackColor || 'currentColor';
if (disabled) {
background = COLORS.gray[400];
}
return /*#__PURE__*/emotion_react_browser_esm_css({
background
}, true ? "" : 0, true ? "" : 0);
};
const Track = createStyled("span", true ? {
target: "e1epgpqk9"
} : 0)("background-color:currentColor;border-radius:", railHeight, "px;height:", railHeight, "px;pointer-events:none;display:block;position:absolute;margin-top:", (rangeHeightValue - railHeight) / 2, "px;top:0;", trackBackgroundColor, ";" + ( true ? "" : 0));
const MarksWrapper = createStyled("span", true ? {
target: "e1epgpqk8"
} : 0)( true ? {
name: "l7tjj5",
styles: "display:block;pointer-events:none;position:relative;width:100%;user-select:none"
} : 0);
const markFill = ({
disabled,
isFilled
}) => {
let backgroundColor = isFilled ? 'currentColor' : COLORS.gray[300];
if (disabled) {
backgroundColor = COLORS.gray[400];
}
return /*#__PURE__*/emotion_react_browser_esm_css({
backgroundColor
}, true ? "" : 0, true ? "" : 0);
};
const Mark = createStyled("span", true ? {
target: "e1epgpqk7"
} : 0)("height:", thumbSize, "px;left:0;position:absolute;top:-4px;width:1px;", markFill, ";" + ( true ? "" : 0));
const markLabelFill = ({
isFilled
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css({
color: isFilled ? COLORS.gray[700] : COLORS.gray[300]
}, true ? "" : 0, true ? "" : 0);
};
const MarkLabel = createStyled("span", true ? {
target: "e1epgpqk6"
} : 0)("color:", COLORS.gray[300], ";left:0;font-size:11px;position:absolute;top:12px;transform:translateX( -50% );white-space:nowrap;", markLabelFill, ";" + ( true ? "" : 0));
const thumbColor = ({
disabled
}) => disabled ? /*#__PURE__*/emotion_react_browser_esm_css("background-color:", COLORS.gray[400], ";" + ( true ? "" : 0), true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css("background-color:", COLORS.ui.theme, ";" + ( true ? "" : 0), true ? "" : 0);
const ThumbWrapper = createStyled("span", true ? {
target: "e1epgpqk5"
} : 0)("align-items:center;display:flex;height:", thumbSize, "px;justify-content:center;margin-top:", (rangeHeightValue - thumbSize) / 2, "px;outline:0;pointer-events:none;position:absolute;top:0;user-select:none;width:", thumbSize, "px;border-radius:50%;", thumbColor, ";", rtl({
marginLeft: -10
}), ";", rtl({
transform: 'translateX( 4.5px )'
}, {
transform: 'translateX( -4.5px )'
}), ";" + ( true ? "" : 0));
const thumbFocus = ({
isFocused
}) => {
return isFocused ? /*#__PURE__*/emotion_react_browser_esm_css("&::before{content:' ';position:absolute;background-color:", COLORS.ui.theme, ";opacity:0.4;border-radius:50%;height:", thumbSize + 8, "px;width:", thumbSize + 8, "px;top:-4px;left:-4px;}" + ( true ? "" : 0), true ? "" : 0) : '';
};
const Thumb = createStyled("span", true ? {
target: "e1epgpqk4"
} : 0)("align-items:center;border-radius:50%;height:100%;outline:0;position:absolute;user-select:none;width:100%;", thumbColor, ";", thumbFocus, ";" + ( true ? "" : 0));
const InputRange = createStyled("input", true ? {
target: "e1epgpqk3"
} : 0)("box-sizing:border-box;cursor:pointer;display:block;height:100%;left:0;margin:0 -", thumbSize / 2, "px;opacity:0;outline:none;position:absolute;right:0;top:0;width:calc( 100% + ", thumbSize, "px );" + ( true ? "" : 0));
const tooltipShow = ({
show
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css({
opacity: show ? 1 : 0
}, true ? "" : 0, true ? "" : 0);
};
var range_control_styles_ref = true ? {
name: "1cypxip",
styles: "top:-80%"
} : 0;
var range_control_styles_ref2 = true ? {
name: "1lr98c4",
styles: "bottom:-80%"
} : 0;
const tooltipPosition = ({
position
}) => {
const isBottom = position === 'bottom';
if (isBottom) {
return range_control_styles_ref2;
}
return range_control_styles_ref;
};
const range_control_styles_Tooltip = createStyled("span", true ? {
target: "e1epgpqk2"
} : 0)("background:rgba( 0, 0, 0, 0.8 );border-radius:2px;color:white;display:inline-block;font-size:12px;min-width:32px;opacity:0;padding:4px 8px;pointer-events:none;position:absolute;text-align:center;transition:opacity 120ms ease;user-select:none;line-height:1.4;", tooltipShow, ";", tooltipPosition, ";", reduceMotion('transition'), ";", rtl({
transform: 'translateX(-50%)'
}, {
transform: 'translateX(50%)'
}), ";" + ( true ? "" : 0)); // @todo: Refactor RangeControl with latest HStack configuration
// @wordpress/components/ui/hstack.
const InputNumber = /*#__PURE__*/createStyled(number_control, true ? {
target: "e1epgpqk1"
} : 0)("display:inline-block;font-size:13px;margin-top:0;width:", space(16), "!important;input[type='number']&{", rangeHeight, ";}", rtl({
marginLeft: `${space(4)} !important`
}), ";" + ( true ? "" : 0));
const ActionRightWrapper = createStyled("span", true ? {
target: "e1epgpqk0"
} : 0)("display:block;margin-top:0;button,button.is-small{margin-left:0;", rangeHeight, ";}", rtl({
marginLeft: 8
}), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/input-range.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function input_range_InputRange(props, ref) {
const {
describedBy,
label,
value,
...otherProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(InputRange, { ...otherProps,
"aria-describedby": describedBy,
"aria-label": label,
"aria-hidden": false,
ref: ref,
tabIndex: 0,
type: "range",
value: value
});
}
const input_range_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(input_range_InputRange);
/* harmony default export */ var input_range = (input_range_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/mark.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function RangeMark(props) {
const {
className,
isFilled = false,
label,
style = {},
...otherProps
} = props;
const classes = classnames_default()('components-range-control__mark', isFilled && 'is-filled', className);
const labelClasses = classnames_default()('components-range-control__mark-label', isFilled && 'is-filled');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(Mark, { ...otherProps,
"aria-hidden": "true",
className: classes,
isFilled: isFilled,
style: style
}), label && (0,external_wp_element_namespaceObject.createElement)(MarkLabel, {
"aria-hidden": "true",
className: labelClasses,
isFilled: isFilled,
style: style
}, label));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/rail.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function RangeRail(props) {
const {
disabled = false,
marks = false,
min = 0,
max = 100,
step = 1,
value = 0,
...restProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(Rail, {
disabled: disabled,
...restProps
}), marks && (0,external_wp_element_namespaceObject.createElement)(Marks, {
disabled: disabled,
marks: marks,
min: min,
max: max,
step: step,
value: value
}));
}
function Marks(props) {
const {
disabled = false,
marks = false,
min = 0,
max = 100,
step: stepProp = 1,
value = 0
} = props;
const step = stepProp === 'any' ? 1 : stepProp;
const marksData = useMarks({
marks,
min,
max,
step,
value
});
return (0,external_wp_element_namespaceObject.createElement)(MarksWrapper, {
"aria-hidden": "true",
className: "components-range-control__marks"
}, marksData.map(mark => (0,external_wp_element_namespaceObject.createElement)(RangeMark, { ...mark,
key: mark.key,
"aria-hidden": "true",
disabled: disabled
})));
}
function useMarks({
marks,
min = 0,
max = 100,
step = 1,
value = 0
}) {
if (!marks) {
return [];
}
const range = max - min;
if (!Array.isArray(marks)) {
marks = [];
const count = 1 + Math.round(range / step);
while (count > marks.push({
value: step * marks.length + min
}));
}
const placedMarks = [];
marks.forEach((mark, index) => {
if (mark.value < min || mark.value > max) {
return;
}
const key = `mark-${index}`;
const isFilled = mark.value <= value;
const offset = `${(mark.value - min) / range * 100}%`;
const offsetStyle = {
[(0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left']: offset
};
placedMarks.push({ ...mark,
isFilled,
key,
style: offsetStyle
});
});
return placedMarks;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/tooltip.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function SimpleTooltip(props) {
const {
className,
inputRef,
tooltipPosition,
show = false,
style = {},
value = 0,
renderTooltipContent = v => v,
zIndex = 100,
...restProps
} = props;
const position = useTooltipPosition({
inputRef,
tooltipPosition
});
const classes = classnames_default()('components-simple-tooltip', className);
const styles = { ...style,
zIndex
};
return (0,external_wp_element_namespaceObject.createElement)(range_control_styles_Tooltip, { ...restProps,
"aria-hidden": show,
className: classes,
position: position,
show: show,
role: "tooltip",
style: styles
}, renderTooltipContent(value));
}
function useTooltipPosition({
inputRef,
tooltipPosition
}) {
const [position, setPosition] = (0,external_wp_element_namespaceObject.useState)();
const setTooltipPosition = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (inputRef && inputRef.current) {
setPosition(tooltipPosition);
}
}, [tooltipPosition, inputRef]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
setTooltipPosition();
}, [setTooltipPosition]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
window.addEventListener('resize', setTooltipPosition);
return () => {
window.removeEventListener('resize', setTooltipPosition);
};
});
return position;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const range_control_noop = () => {};
function UnforwardedRangeControl(props, forwardedRef) {
const {
__nextHasNoMarginBottom = false,
afterIcon,
allowReset = false,
beforeIcon,
className,
color: colorProp = COLORS.ui.theme,
currentInput,
disabled = false,
help,
hideLabelFromVision = false,
initialPosition,
isShiftStepEnabled = true,
label,
marks = false,
max = 100,
min = 0,
onBlur = range_control_noop,
onChange = range_control_noop,
onFocus = range_control_noop,
onMouseLeave = range_control_noop,
onMouseMove = range_control_noop,
railColor,
renderTooltipContent = v => v,
resetFallbackValue,
shiftStep = 10,
showTooltip: showTooltipProp,
step = 1,
trackColor,
value: valueProp,
withInputField = true,
...otherProps
} = props;
const [value, setValue] = useControlledRangeValue({
min,
max,
value: valueProp !== null && valueProp !== void 0 ? valueProp : null,
initial: initialPosition
});
const isResetPendent = (0,external_wp_element_namespaceObject.useRef)(false);
let hasTooltip = showTooltipProp;
let hasInputField = withInputField;
if (step === 'any') {
// The tooltip and number input field are hidden when the step is "any"
// because the decimals get too lengthy to fit well.
hasTooltip = false;
hasInputField = false;
}
const [showTooltip, setShowTooltip] = (0,external_wp_element_namespaceObject.useState)(hasTooltip);
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const inputRef = (0,external_wp_element_namespaceObject.useRef)();
const isCurrentlyFocused = inputRef.current?.matches(':focus');
const isThumbFocused = !disabled && isFocused;
const isValueReset = value === null;
const currentValue = value !== undefined ? value : currentInput;
const inputSliderValue = isValueReset ? '' : currentValue;
const rangeFillValue = isValueReset ? (max - min) / 2 + min : value;
const fillValue = isValueReset ? 50 : (value - min) / (max - min) * 100;
const fillValueOffset = `${math_clamp(fillValue, 0, 100)}%`;
const classes = classnames_default()('components-range-control', className);
const wrapperClasses = classnames_default()('components-range-control__wrapper', !!marks && 'is-marked');
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(UnforwardedRangeControl, 'inspector-range-control');
const describedBy = !!help ? `${id}__help` : undefined;
const enableTooltip = hasTooltip !== false && Number.isFinite(value);
const handleOnRangeChange = event => {
const nextValue = parseFloat(event.target.value);
setValue(nextValue);
onChange(nextValue);
};
const handleOnChange = next => {
// @ts-expect-error TODO: Investigate if it's problematic for setValue() to
// potentially receive a NaN when next is undefined.
let nextValue = parseFloat(next);
setValue(nextValue);
/*
* Calls onChange only when nextValue is numeric
* otherwise may queue a reset for the blur event.
*/
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 = () => {
let resetValue = parseFloat(`${resetFallbackValue}`);
let onChangeResetValue = resetValue;
if (isNaN(resetValue)) {
resetValue = null;
onChangeResetValue = undefined;
}
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(onChangeResetValue);
};
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 = {
[(0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left']: fillValueOffset
};
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: classes,
label: label,
hideLabelFromVision: hideLabelFromVision,
id: `${id}`,
help: help
}, (0,external_wp_element_namespaceObject.createElement)(range_control_styles_Root, {
className: "components-range-control__root"
}, beforeIcon && (0,external_wp_element_namespaceObject.createElement)(BeforeIconWrapper, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: beforeIcon
})), (0,external_wp_element_namespaceObject.createElement)(range_control_styles_Wrapper, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: wrapperClasses,
color: colorProp,
marks: !!marks
}, (0,external_wp_element_namespaceObject.createElement)(input_range, { ...otherProps,
className: "components-range-control__slider",
describedBy: describedBy,
disabled: disabled,
id: `${id}`,
label: label,
max: max,
min: min,
onBlur: handleOnBlur,
onChange: handleOnRangeChange,
onFocus: handleOnFocus,
onMouseMove: onMouseMove,
onMouseLeave: onMouseLeave,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([inputRef, forwardedRef]),
step: step,
value: inputSliderValue !== null && inputSliderValue !== void 0 ? inputSliderValue : undefined
}), (0,external_wp_element_namespaceObject.createElement)(RangeRail, {
"aria-hidden": true,
disabled: disabled,
marks: marks,
max: max,
min: min,
railColor: railColor,
step: step,
value: rangeFillValue
}), (0,external_wp_element_namespaceObject.createElement)(Track, {
"aria-hidden": true,
className: "components-range-control__track",
disabled: disabled,
style: {
width: fillValueOffset
},
trackColor: trackColor
}), (0,external_wp_element_namespaceObject.createElement)(ThumbWrapper, {
className: "components-range-control__thumb-wrapper",
style: offsetStyle,
disabled: disabled
}, (0,external_wp_element_namespaceObject.createElement)(Thumb, {
"aria-hidden": true,
isFocused: isThumbFocused,
disabled: disabled
})), enableTooltip && (0,external_wp_element_namespaceObject.createElement)(SimpleTooltip, {
className: "components-range-control__tooltip",
inputRef: inputRef,
tooltipPosition: "bottom",
renderTooltipContent: renderTooltipContent,
show: isCurrentlyFocused || showTooltip,
style: offsetStyle,
value: value
})), afterIcon && (0,external_wp_element_namespaceObject.createElement)(AfterIconWrapper, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: afterIcon
})), hasInputField && (0,external_wp_element_namespaceObject.createElement)(InputNumber, {
"aria-label": label,
className: "components-range-control__number",
disabled: disabled,
inputMode: "decimal",
isShiftStepEnabled: isShiftStepEnabled,
max: max,
min: min,
onBlur: handleOnInputNumberBlur,
onChange: handleOnChange,
shiftStep: shiftStep,
step: step // @ts-expect-error TODO: Investigate if the `null` value is necessary
,
value: inputSliderValue
}), allowReset && (0,external_wp_element_namespaceObject.createElement)(ActionRightWrapper, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-range-control__reset",
disabled: disabled || value === undefined,
variant: "secondary",
isSmall: true,
onClick: handleOnReset
}, (0,external_wp_i18n_namespaceObject.__)('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 [ isChecked, setChecked ] = useState( true );
* return (
* <RangeControl
* help="Please select how transparent you would like this."
* initialPosition={50}
* label="Opacity"
* max={100}
* min={0}
* onChange={() => {}}
* />
* );
* };
* ```
*/
const RangeControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedRangeControl);
/* harmony default export */ var range_control = (RangeControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const NumberControlWrapper = /*#__PURE__*/createStyled(number_control, true ? {
target: "ez9hsf47"
} : 0)(Container, "{width:", space(24), ";}" + ( true ? "" : 0));
const styles_SelectControl = /*#__PURE__*/createStyled(select_control, true ? {
target: "ez9hsf46"
} : 0)("margin-left:", space(-2), ";width:5em;select:not( :focus )~", BackdropUI, BackdropUI, BackdropUI, "{border-color:transparent;}" + ( true ? "" : 0));
const styles_RangeControl = /*#__PURE__*/createStyled(range_control, true ? {
target: "ez9hsf45"
} : 0)("flex:1;margin-right:", space(2), ";" + ( true ? "" : 0)); // Make the Hue circle picker not go out of the bar.
const interactiveHueStyles = `
.react-colorful__interactive {
width: calc( 100% - ${space(2)} );
margin-left: ${space(1)};
}`;
const AuxiliaryColorArtefactWrapper = createStyled("div", true ? {
target: "ez9hsf44"
} : 0)("padding-top:", space(2), ";padding-right:0;padding-left:0;padding-bottom:0;" + ( true ? "" : 0));
const AuxiliaryColorArtefactHStackHeader = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "ez9hsf43"
} : 0)("padding-left:", space(4), ";padding-right:", space(4), ";" + ( true ? "" : 0));
const ColorInputWrapper = /*#__PURE__*/createStyled(flex_component, true ? {
target: "ez9hsf42"
} : 0)("padding-top:", space(4), ";padding-left:", space(4), ";padding-right:", space(3), ";padding-bottom:", space(5), ";" + ( true ? "" : 0));
const ColorfulWrapper = createStyled("div", true ? {
target: "ez9hsf41"
} : 0)(boxSizingReset, ";width:216px;.react-colorful{display:flex;flex-direction:column;align-items:center;width:216px;height:auto;overflow:hidden;}.react-colorful__saturation{width:100%;border-radius:0;height:216px;margin-bottom:", space(4), ";border-bottom:none;}.react-colorful__hue,.react-colorful__alpha{width:184px;height:16px;border-radius:16px;margin-bottom:", space(2), ";}.react-colorful__pointer{height:16px;width:16px;border:none;box-shadow:0 0 2px 0 rgba( 0, 0, 0, 0.25 );outline:2px solid transparent;}.react-colorful__pointer-fill{box-shadow:inset 0 0 0 ", config_values.borderWidthFocus, " #fff;}", interactiveHueStyles, ";" + ( true ? "" : 0));
const CopyButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "ez9hsf40"
} : 0)("&&&&&{min-width:", space(6), ";padding:0;>svg{margin-right:0;}}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/copy.js
/**
* WordPress dependencies
*/
const copy_copy = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M20.2 8v11c0 .7-.6 1.2-1.2 1.2H6v1.5h13c1.5 0 2.7-1.2 2.7-2.8V8zM18 16.4V4.6c0-.9-.7-1.6-1.6-1.6H4.6C3.7 3 3 3.7 3 4.6v11.8c0 .9.7 1.6 1.6 1.6h11.8c.9 0 1.6-.7 1.6-1.6zm-13.5 0V4.6c0-.1.1-.1.1-.1h11.8c.1 0 .1.1.1.1v11.8c0 .1-.1.1-.1.1H4.6l-.1-.1z"
}));
/* harmony default export */ var library_copy = (copy_copy);
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow_getWindow(node) {
if (node == null) {
return window;
}
if (node.toString() !== '[object Window]') {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
function isElement(node) {
var OwnElement = getWindow_getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement(node) {
var OwnElement = getWindow_getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
// IE 11 has no ShadowRoot
if (typeof ShadowRoot === 'undefined') {
return false;
}
var OwnElement = getWindow_getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/math.js
var math_max = Math.max;
var math_min = Math.min;
var round = Math.round;
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/userAgent.js
function getUAString() {
var uaData = navigator.userAgentData;
if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
return uaData.brands.map(function (item) {
return item.brand + "/" + item.version;
}).join(' ');
}
return navigator.userAgent;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js
function isLayoutViewport() {
return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
function getBoundingClientRect(element, includeScale, isFixedStrategy) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
var clientRect = element.getBoundingClientRect();
var scaleX = 1;
var scaleY = 1;
if (includeScale && isHTMLElement(element)) {
scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
}
var _ref = isElement(element) ? getWindow_getWindow(element) : window,
visualViewport = _ref.visualViewport;
var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
var width = clientRect.width / scaleX;
var height = clientRect.height / scaleY;
return {
width: width,
height: height,
top: y,
right: x + width,
bottom: y + height,
left: x,
x: x,
y: y
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
function getWindowScroll(node) {
var win = getWindow_getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
function getNodeScroll(node) {
if (node === getWindow_getWindow(node) || !isHTMLElement(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName(element) {
return element ? (element.nodeName || '').toLowerCase() : null;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
function getDocumentElement(element) {
// $FlowFixMe[incompatible-return]: assume body is always available
return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
element.document) || window.document).documentElement;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
function getWindowScrollBarX(element) {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
function getComputedStyle_getComputedStyle(element) {
return getWindow_getWindow(element).getComputedStyle(element);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js
function isScrollParent(element) {
// Firefox wants us to check `-x` and `-y` variations as well
var _getComputedStyle = getComputedStyle_getComputedStyle(element),
overflow = _getComputedStyle.overflow,
overflowX = _getComputedStyle.overflowX,
overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
function isElementScaled(element) {
var rect = element.getBoundingClientRect();
var scaleX = round(rect.width) / element.offsetWidth || 1;
var scaleY = round(rect.height) / element.offsetHeight || 1;
return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var isOffsetParentAnElement = isHTMLElement(offsetParent);
var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
var documentElement = getDocumentElement(offsetParent);
var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement(offsetParent)) {
offsets = getBoundingClientRect(offsetParent, true);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
// Returns the layout rect of an element relative to its offsetParent. Layout
// means it doesn't take into account transforms.
function getLayoutRect(element) {
var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
// Fixes https://github.com/popperjs/popper-core/issues/1223
var width = element.offsetWidth;
var height = element.offsetHeight;
if (Math.abs(clientRect.width - width) <= 1) {
width = clientRect.width;
}
if (Math.abs(clientRect.height - height) <= 1) {
height = clientRect.height;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: width,
height: height
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
function getParentNode(element) {
if (getNodeName(element) === 'html') {
return element;
}
return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
// $FlowFixMe[incompatible-return]
// $FlowFixMe[prop-missing]
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || ( // DOM Element detected
isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
// $FlowFixMe[incompatible-call]: HTMLElement is a Node
getDocumentElement(element) // fallback
);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
function getScrollParent(node) {
if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
// $FlowFixMe[incompatible-return]: assume body is always available
return node.ownerDocument.body;
}
if (isHTMLElement(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/
function listScrollParents(element, list) {
var _element$ownerDocumen;
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
var win = getWindow_getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)));
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js
function isTableElement(element) {
return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
function getTrueOffsetParent(element) {
if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
getComputedStyle_getComputedStyle(element).position === 'fixed') {
return null;
}
return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getContainingBlock(element) {
var isFirefox = /firefox/i.test(getUAString());
var isIE = /Trident/i.test(getUAString());
if (isIE && isHTMLElement(element)) {
// In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
var elementCss = getComputedStyle_getComputedStyle(element);
if (elementCss.position === 'fixed') {
return null;
}
}
var currentNode = getParentNode(element);
if (isShadowRoot(currentNode)) {
currentNode = currentNode.host;
}
while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
var css = getComputedStyle_getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
function getOffsetParent(element) {
var window = getWindow_getWindow(element);
var offsetParent = getTrueOffsetParent(element);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle_getComputedStyle(offsetParent).position === 'static') {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle_getComputedStyle(offsetParent).position === 'static')) {
return window;
}
return offsetParent || getContainingBlock(element) || window;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/enums.js
var enums_top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var enums_auto = 'auto';
var basePlacements = [enums_top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var enums_placements = /*#__PURE__*/[].concat(basePlacements, [enums_auto]).reduce(function (acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM
var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers
var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/orderModifiers.js
// source: https://stackoverflow.com/questions/49875255
function order(modifiers) {
var map = new Map();
var visited = new Set();
var result = [];
modifiers.forEach(function (modifier) {
map.set(modifier.name, modifier);
}); // On visiting object, check for its dependencies and visit them recursively
function sort(modifier) {
visited.add(modifier.name);
var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
requires.forEach(function (dep) {
if (!visited.has(dep)) {
var depModifier = map.get(dep);
if (depModifier) {
sort(depModifier);
}
}
});
result.push(modifier);
}
modifiers.forEach(function (modifier) {
if (!visited.has(modifier.name)) {
// check for visited object
sort(modifier);
}
});
return result;
}
function orderModifiers(modifiers) {
// order based on dependencies
var orderedModifiers = order(modifiers); // order based on phase
return modifierPhases.reduce(function (acc, phase) {
return acc.concat(orderedModifiers.filter(function (modifier) {
return modifier.phase === phase;
}));
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/debounce.js
function debounce(fn) {
var pending;
return function () {
if (!pending) {
pending = new Promise(function (resolve) {
Promise.resolve().then(function () {
pending = undefined;
resolve(fn());
});
});
}
return pending;
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName(modifiers) {
var merged = modifiers.reduce(function (merged, current) {
var existing = merged[current.name];
merged[current.name] = existing ? Object.assign({}, existing, current, {
options: Object.assign({}, existing.options, current.options),
data: Object.assign({}, existing.data, current.data)
}) : current;
return merged;
}, {}); // IE11 does not support Object.values
return Object.keys(merged).map(function (key) {
return merged[key];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/createPopper.js
var DEFAULT_OPTIONS = {
placement: 'bottom',
modifiers: [],
strategy: 'absolute'
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function (element) {
return !(element && typeof element.getBoundingClientRect === 'function');
});
}
function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions,
_generatorOptions$def = _generatorOptions.defaultModifiers,
defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
_generatorOptions$def2 = _generatorOptions.defaultOptions,
defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper(reference, popper, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: 'bottom',
orderedModifiers: [],
options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
modifiersData: {},
elements: {
reference: reference,
popper: popper
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state: state,
setOptions: function setOptions(setOptionsAction) {
var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
cleanupModifierEffects();
state.options = Object.assign({}, defaultOptions, state.options, options);
state.scrollParents = {
reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
popper: listScrollParents(popper)
}; // Orders the modifiers based on their dependencies and `phase`
// properties
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
state.orderedModifiers = orderedModifiers.filter(function (m) {
return m.enabled;
});
runModifierEffects();
return instance.update();
},
// Sync update it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements,
reference = _state$elements.reference,
popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
// anymore
if (!areValidElements(reference, popper)) {
return;
} // Store the reference and popper rects to be read by modifiers
state.rects = {
reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
popper: getLayoutRect(popper)
}; // Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset = false;
state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(function (modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
for (var index = 0; index < state.orderedModifiers.length; index++) {
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index],
fn = _state$orderedModifie.fn,
_state$orderedModifie2 = _state$orderedModifie.options,
_options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
name = _state$orderedModifie.name;
if (typeof fn === 'function') {
state = fn({
state: state,
options: _options,
name: name,
instance: instance
}) || state;
}
}
},
// Async and optimistically optimized update it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce(function () {
return new Promise(function (resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference, popper)) {
return instance;
}
instance.setOptions(options).then(function (state) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state);
}
}); // Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects() {
state.orderedModifiers.forEach(function (_ref) {
var name = _ref.name,
_ref$options = _ref.options,
options = _ref$options === void 0 ? {} : _ref$options,
effect = _ref.effect;
if (typeof effect === 'function') {
var cleanupFn = effect({
state: state,
name: name,
instance: instance,
options: options
});
var noopFn = function noopFn() {};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function (fn) {
return fn();
});
effectCleanupFns = [];
}
return instance;
};
}
var createPopper = /*#__PURE__*/(/* unused pure expression or super */ null && (popperGenerator())); // eslint-disable-next-line import/no-unused-modules
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/eventListeners.js
// eslint-disable-next-line import/no-unused-modules
var passive = {
passive: true
};
function effect(_ref) {
var state = _ref.state,
instance = _ref.instance,
options = _ref.options;
var _options$scroll = options.scroll,
scroll = _options$scroll === void 0 ? true : _options$scroll,
_options$resize = options.resize,
resize = _options$resize === void 0 ? true : _options$resize;
var window = getWindow_getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.addEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.addEventListener('resize', instance.update, passive);
}
return function () {
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.removeEventListener('resize', instance.update, passive);
}
};
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var eventListeners = ({
name: 'eventListeners',
enabled: true,
phase: 'write',
fn: function fn() {},
effect: effect,
data: {}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getBasePlacement.js
function getBasePlacement(placement) {
return placement.split('-')[0];
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation(placement) {
return placement.split('-')[1];
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
function getMainAxisFromPlacement_getMainAxisFromPlacement(placement) {
return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/computeOffsets.js
function computeOffsets(_ref) {
var reference = _ref.reference,
element = _ref.element,
placement = _ref.placement;
var basePlacement = placement ? getBasePlacement(placement) : null;
var variation = placement ? getVariation(placement) : null;
var commonX = reference.x + reference.width / 2 - element.width / 2;
var commonY = reference.y + reference.height / 2 - element.height / 2;
var offsets;
switch (basePlacement) {
case enums_top:
offsets = {
x: commonX,
y: reference.y - element.height
};
break;
case bottom:
offsets = {
x: commonX,
y: reference.y + reference.height
};
break;
case right:
offsets = {
x: reference.x + reference.width,
y: commonY
};
break;
case left:
offsets = {
x: reference.x - element.width,
y: commonY
};
break;
default:
offsets = {
x: reference.x,
y: reference.y
};
}
var mainAxis = basePlacement ? getMainAxisFromPlacement_getMainAxisFromPlacement(basePlacement) : null;
if (mainAxis != null) {
var len = mainAxis === 'y' ? 'height' : 'width';
switch (variation) {
case start:
offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
break;
case end:
offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
break;
default:
}
}
return offsets;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
function popperOffsets(_ref) {
var state = _ref.state,
name = _ref.name;
// Offsets are the actual position the popper needs to have to be
// properly positioned near its reference element
// This is the most basic placement, and will be adjusted by
// the modifiers in the next step
state.modifiersData[name] = computeOffsets({
reference: state.rects.reference,
element: state.rects.popper,
strategy: 'absolute',
placement: state.placement
});
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_popperOffsets = ({
name: 'popperOffsets',
enabled: true,
phase: 'read',
fn: popperOffsets,
data: {}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/computeStyles.js
// eslint-disable-next-line import/no-unused-modules
var unsetSides = {
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsetsByDPR(_ref, win) {
var x = _ref.x,
y = _ref.y;
var dpr = win.devicePixelRatio || 1;
return {
x: round(x * dpr) / dpr || 0,
y: round(y * dpr) / dpr || 0
};
}
function mapToStyles(_ref2) {
var _Object$assign2;
var popper = _ref2.popper,
popperRect = _ref2.popperRect,
placement = _ref2.placement,
variation = _ref2.variation,
offsets = _ref2.offsets,
position = _ref2.position,
gpuAcceleration = _ref2.gpuAcceleration,
adaptive = _ref2.adaptive,
roundOffsets = _ref2.roundOffsets,
isFixed = _ref2.isFixed;
var _offsets$x = offsets.x,
x = _offsets$x === void 0 ? 0 : _offsets$x,
_offsets$y = offsets.y,
y = _offsets$y === void 0 ? 0 : _offsets$y;
var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
x: x,
y: y
}) : {
x: x,
y: y
};
x = _ref3.x;
y = _ref3.y;
var hasX = offsets.hasOwnProperty('x');
var hasY = offsets.hasOwnProperty('y');
var sideX = left;
var sideY = enums_top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent(popper);
var heightProp = 'clientHeight';
var widthProp = 'clientWidth';
if (offsetParent === getWindow_getWindow(popper)) {
offsetParent = getDocumentElement(popper);
if (getComputedStyle_getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {
heightProp = 'scrollHeight';
widthProp = 'scrollWidth';
}
} // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
offsetParent = offsetParent;
if (placement === enums_top || (placement === left || placement === right) && variation === end) {
sideY = bottom;
var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]
offsetParent[heightProp];
y -= offsetY - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left || (placement === enums_top || placement === bottom) && variation === end) {
sideX = right;
var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]
offsetParent[widthProp];
x -= offsetX - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position: position
}, adaptive && unsetSides);
var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
x: x,
y: y
}, getWindow_getWindow(popper)) : {
x: x,
y: y
};
x = _ref4.x;
y = _ref4.y;
if (gpuAcceleration) {
var _Object$assign;
return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref5) {
var state = _ref5.state,
options = _ref5.options;
var _options$gpuAccelerat = options.gpuAcceleration,
gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
_options$adaptive = options.adaptive,
adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
_options$roundOffsets = options.roundOffsets,
roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
var commonStyles = {
placement: getBasePlacement(state.placement),
variation: getVariation(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration: gpuAcceleration,
isFixed: state.options.strategy === 'fixed'
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive: adaptive,
roundOffsets: roundOffsets
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.arrow,
position: 'absolute',
adaptive: false,
roundOffsets: roundOffsets
})));
}
state.attributes.popper = Object.assign({}, state.attributes.popper, {
'data-popper-placement': state.placement
});
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_computeStyles = ({
name: 'computeStyles',
enabled: true,
phase: 'beforeWrite',
fn: computeStyles,
data: {}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/applyStyles.js
// This modifier takes the styles prepared by the `computeStyles` modifier
// and applies them to the HTMLElements such as popper and arrow
function applyStyles(_ref) {
var state = _ref.state;
Object.keys(state.elements).forEach(function (name) {
var style = state.styles[name] || {};
var attributes = state.attributes[name] || {};
var element = state.elements[name]; // arrow is optional + virtual elements
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
} // Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe[cannot-write]
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (name) {
var value = attributes[name];
if (value === false) {
element.removeAttribute(name);
} else {
element.setAttribute(name, value === true ? '' : value);
}
});
});
}
function applyStyles_effect(_ref2) {
var state = _ref2.state;
var initialStyles = {
popper: {
position: state.options.strategy,
left: '0',
top: '0',
margin: '0'
},
arrow: {
position: 'absolute'
},
reference: {}
};
Object.assign(state.elements.popper.style, initialStyles.popper);
state.styles = initialStyles;
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return function () {
Object.keys(state.elements).forEach(function (name) {
var element = state.elements[name];
var attributes = state.attributes[name] || {};
var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
var style = styleProperties.reduce(function (style, property) {
style[property] = '';
return style;
}, {}); // arrow is optional + virtual elements
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (attribute) {
element.removeAttribute(attribute);
});
});
};
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_applyStyles = ({
name: 'applyStyles',
enabled: true,
phase: 'write',
fn: applyStyles,
effect: applyStyles_effect,
requires: ['computeStyles']
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/offset.js
// eslint-disable-next-line import/no-unused-modules
function distanceAndSkiddingToXY(placement, rects, offset) {
var basePlacement = getBasePlacement(placement);
var invertDistance = [left, enums_top].indexOf(basePlacement) >= 0 ? -1 : 1;
var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
placement: placement
})) : offset,
skidding = _ref[0],
distance = _ref[1];
skidding = skidding || 0;
distance = (distance || 0) * invertDistance;
return [left, right].indexOf(basePlacement) >= 0 ? {
x: distance,
y: skidding
} : {
x: skidding,
y: distance
};
}
function offset(_ref2) {
var state = _ref2.state,
options = _ref2.options,
name = _ref2.name;
var _options$offset = options.offset,
offset = _options$offset === void 0 ? [0, 0] : _options$offset;
var data = enums_placements.reduce(function (acc, placement) {
acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
return acc;
}, {});
var _data$state$placement = data[state.placement],
x = _data$state$placement.x,
y = _data$state$placement.y;
if (state.modifiersData.popperOffsets != null) {
state.modifiersData.popperOffsets.x += x;
state.modifiersData.popperOffsets.y += y;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_offset = ({
name: 'offset',
enabled: true,
phase: 'main',
requires: ['popperOffsets'],
fn: offset
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js
var getOppositePlacement_hash = {
left: 'right',
right: 'left',
bottom: 'top',
top: 'bottom'
};
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, function (matched) {
return getOppositePlacement_hash[matched];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js
var getOppositeVariationPlacement_hash = {
start: 'end',
end: 'start'
};
function getOppositeVariationPlacement(placement) {
return placement.replace(/start|end/g, function (matched) {
return getOppositeVariationPlacement_hash[matched];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
function getViewportRect(element, strategy) {
var win = getWindow_getWindow(element);
var html = getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
var layoutViewport = isLayoutViewport();
if (layoutViewport || !layoutViewport && strategy === 'fixed') {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width: width,
height: height,
x: x + getWindowScrollBarX(element),
y: y
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js
// Gets the entire size of the scrollable document area, even extending outside
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
function getDocumentRect(element) {
var _element$ownerDocumen;
var html = getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
var width = math_max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = math_max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle_getComputedStyle(body || html).direction === 'rtl') {
x += math_max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width: width,
height: height,
x: x,
y: y
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/contains.js
function contains_contains(parent, child) {
var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
if (parent.contains(child)) {
return true;
} // then fallback to custom implementation with Shadow DOM support
else if (rootNode && isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
} // $FlowFixMe[prop-missing]: need a better way to handle this...
next = next.parentNode || next.host;
} while (next);
} // Give up, the result is false
return false;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/rectToClientRect.js
function rectToClientRect(rect) {
return Object.assign({}, rect, {
left: rect.x,
top: rect.y,
right: rect.x + rect.width,
bottom: rect.y + rect.height
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
function getInnerBoundingClientRect(element, strategy) {
var rect = getBoundingClientRect(element, false, strategy === 'fixed');
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element) {
var clippingParents = listScrollParents(getParentNode(element));
var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle_getComputedStyle(element).position) >= 0;
var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
if (!isElement(clipperElement)) {
return [];
} // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(function (clippingParent) {
return isElement(clippingParent) && contains_contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
});
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents
function getClippingRect(element, boundary, rootBoundary, strategy) {
var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents[0];
var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent, strategy);
accRect.top = math_max(rect.top, accRect.top);
accRect.right = math_min(rect.right, accRect.right);
accRect.bottom = math_min(rect.bottom, accRect.bottom);
accRect.left = math_max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent, strategy));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js
function getFreshSideObject() {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
function mergePaddingObject(paddingObject) {
return Object.assign({}, getFreshSideObject(), paddingObject);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/expandToHashMap.js
function expandToHashMap(value, keys) {
return keys.reduce(function (hashMap, key) {
hashMap[key] = value;
return hashMap;
}, {});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/detectOverflow.js
// eslint-disable-next-line import/no-unused-modules
function detectOverflow(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
_options$placement = _options.placement,
placement = _options$placement === void 0 ? state.placement : _options$placement,
_options$strategy = _options.strategy,
strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
_options$boundary = _options.boundary,
boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
_options$rootBoundary = _options.rootBoundary,
rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
_options$elementConte = _options.elementContext,
elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
_options$altBoundary = _options.altBoundary,
altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
_options$padding = _options.padding,
padding = _options$padding === void 0 ? 0 : _options$padding;
var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
var altContext = elementContext === popper ? reference : popper;
var popperRect = state.rects.popper;
var element = state.elements[altBoundary ? altContext : elementContext];
var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
var referenceClientRect = getBoundingClientRect(state.elements.reference);
var popperOffsets = computeOffsets({
reference: referenceClientRect,
element: popperRect,
strategy: 'absolute',
placement: placement
});
var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
// 0 or negative = within the clipping rect
var overflowOffsets = {
top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
right: elementClientRect.right - clippingClientRect.right + paddingObject.right
};
var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
if (elementContext === popper && offsetData) {
var offset = offsetData[placement];
Object.keys(overflowOffsets).forEach(function (key) {
var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
var axis = [enums_top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
overflowOffsets[key] += offset[axis] * multiply;
});
}
return overflowOffsets;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js
function computeAutoPlacement(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
placement = _options.placement,
boundary = _options.boundary,
rootBoundary = _options.rootBoundary,
padding = _options.padding,
flipVariations = _options.flipVariations,
_options$allowedAutoP = _options.allowedAutoPlacements,
allowedAutoPlacements = _options$allowedAutoP === void 0 ? enums_placements : _options$allowedAutoP;
var variation = getVariation(placement);
var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
return getVariation(placement) === variation;
}) : basePlacements;
var allowedPlacements = placements.filter(function (placement) {
return allowedAutoPlacements.indexOf(placement) >= 0;
});
if (allowedPlacements.length === 0) {
allowedPlacements = placements;
} // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
var overflows = allowedPlacements.reduce(function (acc, placement) {
acc[placement] = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding
})[getBasePlacement(placement)];
return acc;
}, {});
return Object.keys(overflows).sort(function (a, b) {
return overflows[a] - overflows[b];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/flip.js
// eslint-disable-next-line import/no-unused-modules
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === enums_auto) {
return [];
}
var oppositePlacement = getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
specifiedFallbackPlacements = options.fallbackPlacements,
padding = options.padding,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
_options$flipVariatio = options.flipVariations,
flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
return acc.concat(getBasePlacement(placement) === enums_auto ? computeAutoPlacement(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
flipVariations: flipVariations,
allowedAutoPlacements: allowedAutoPlacements
}) : placement);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements[0];
for (var i = 0; i < placements.length; i++) {
var placement = placements[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [enums_top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? 'width' : 'height';
var overflow = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
altBoundary: altBoundary,
padding: padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : enums_top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function (check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
// `2` may be desired in some cases research later
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop(_i) {
var fittingPlacement = placements.find(function (placement) {
var checks = checksMap.get(placement);
if (checks) {
return checks.slice(0, _i).every(function (check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break") break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_flip = ({
name: 'flip',
enabled: true,
phase: 'main',
fn: flip,
requiresIfExists: ['offset'],
data: {
_skip: false
}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getAltAxis.js
function getAltAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/within.js
function within(min, value, max) {
return math_max(min, math_min(value, max));
}
function withinMaxClamp(min, value, max) {
var v = within(min, value, max);
return v > max ? max : v;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js
function preventOverflow(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
padding = options.padding,
_options$tether = options.tether,
tether = _options$tether === void 0 ? true : _options$tether,
_options$tetherOffset = options.tetherOffset,
tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
var overflow = detectOverflow(state, {
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
altBoundary: altBoundary
});
var basePlacement = getBasePlacement(state.placement);
var variation = getVariation(state.placement);
var isBasePlacement = !variation;
var mainAxis = getMainAxisFromPlacement_getMainAxisFromPlacement(basePlacement);
var altAxis = getAltAxis(mainAxis);
var popperOffsets = state.modifiersData.popperOffsets;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
placement: state.placement
})) : tetherOffset;
var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
mainAxis: tetherOffsetValue,
altAxis: tetherOffsetValue
} : Object.assign({
mainAxis: 0,
altAxis: 0
}, tetherOffsetValue);
var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
var data = {
x: 0,
y: 0
};
if (!popperOffsets) {
return;
}
if (checkMainAxis) {
var _offsetModifierState$;
var mainSide = mainAxis === 'y' ? enums_top : left;
var altSide = mainAxis === 'y' ? bottom : right;
var len = mainAxis === 'y' ? 'height' : 'width';
var offset = popperOffsets[mainAxis];
var min = offset + overflow[mainSide];
var max = offset - overflow[altSide];
var additive = tether ? -popperRect[len] / 2 : 0;
var minLen = variation === start ? referenceRect[len] : popperRect[len];
var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
// outside the reference bounds
var arrowElement = state.elements.arrow;
var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
width: 0,
height: 0
};
var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
var arrowPaddingMin = arrowPaddingObject[mainSide];
var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
// to include its full size in the calculation. If the reference is small
// and near the edge of a boundary, the popper can overflow even if the
// reference is not overflowing as well (e.g. virtual elements with no
// width or height)
var arrowLen = within(0, referenceRect[len], arrowRect[len]);
var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
var tetherMax = offset + maxOffset - offsetModifierValue;
var preventedOffset = within(tether ? math_min(min, tetherMin) : min, offset, tether ? math_max(max, tetherMax) : max);
popperOffsets[mainAxis] = preventedOffset;
data[mainAxis] = preventedOffset - offset;
}
if (checkAltAxis) {
var _offsetModifierState$2;
var _mainSide = mainAxis === 'x' ? enums_top : left;
var _altSide = mainAxis === 'x' ? bottom : right;
var _offset = popperOffsets[altAxis];
var _len = altAxis === 'y' ? 'height' : 'width';
var _min = _offset + overflow[_mainSide];
var _max = _offset - overflow[_altSide];
var isOriginSide = [enums_top, left].indexOf(basePlacement) !== -1;
var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
popperOffsets[altAxis] = _preventedOffset;
data[altAxis] = _preventedOffset - _offset;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_preventOverflow = ({
name: 'preventOverflow',
enabled: true,
phase: 'main',
fn: preventOverflow,
requiresIfExists: ['offset']
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/arrow.js
// eslint-disable-next-line import/no-unused-modules
var toPaddingObject = function toPaddingObject(padding, state) {
padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
placement: state.placement
})) : padding;
return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};
function arrow_arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state,
name = _ref.name,
options = _ref.options;
var arrowElement = state.elements.arrow;
var popperOffsets = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement_getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? 'height' : 'width';
if (!arrowElement || !popperOffsets) {
return;
}
var paddingObject = toPaddingObject(options.padding, state);
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === 'y' ? enums_top : left;
var maxProp = axis === 'y' ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
var startDiff = popperOffsets[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
var min = paddingObject[minProp];
var max = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset = within(min, center, max); // Prevents breaking syntax highlighting...
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function arrow_effect(_ref2) {
var state = _ref2.state,
options = _ref2.options;
var _options$element = options.element,
arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
if (arrowElement == null) {
return;
} // CSS selector
if (typeof arrowElement === 'string') {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (!contains_contains(state.elements.popper, arrowElement)) {
return;
}
state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_arrow = ({
name: 'arrow',
enabled: true,
phase: 'main',
fn: arrow_arrow,
effect: arrow_effect,
requires: ['popperOffsets'],
requiresIfExists: ['preventOverflow']
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/hide.js
function getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function isAnySideFullyClipped(overflow) {
return [enums_top, right, bottom, left].some(function (side) {
return overflow[side] >= 0;
});
}
function hide(_ref) {
var state = _ref.state,
name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow(state, {
elementContext: 'reference'
});
var popperAltOverflow = detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets: referenceClippingOffsets,
popperEscapeOffsets: popperEscapeOffsets,
isReferenceHidden: isReferenceHidden,
hasPopperEscaped: hasPopperEscaped
};
state.attributes.popper = Object.assign({}, state.attributes.popper, {
'data-popper-reference-hidden': isReferenceHidden,
'data-popper-escaped': hasPopperEscaped
});
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_hide = ({
name: 'hide',
enabled: true,
phase: 'main',
requiresIfExists: ['preventOverflow'],
fn: hide
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/popper.js
var defaultModifiers = [eventListeners, modifiers_popperOffsets, modifiers_computeStyles, modifiers_applyStyles, modifiers_offset, modifiers_flip, modifiers_preventOverflow, modifiers_arrow, modifiers_hide];
var popper_createPopper = /*#__PURE__*/popperGenerator({
defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules
// eslint-disable-next-line import/no-unused-modules
// eslint-disable-next-line import/no-unused-modules
;// CONCATENATED MODULE: ./node_modules/reakit/es/Disclosure/DisclosureState.js
function useLastValue(value) {
var lastValue = (0,external_React_.useRef)(null);
useIsomorphicEffect(function () {
lastValue.current = value;
}, [value]);
return lastValue;
}
function useDisclosureState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$visib = _useSealedState.visible,
initialVisible = _useSealedState$visib === void 0 ? false : _useSealedState$visib,
_useSealedState$anima = _useSealedState.animated,
initialAnimated = _useSealedState$anima === void 0 ? false : _useSealedState$anima,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["visible", "animated"]);
var id = unstable_useIdState(sealed);
var _React$useState = (0,external_React_.useState)(initialVisible),
visible = _React$useState[0],
setVisible = _React$useState[1];
var _React$useState2 = (0,external_React_.useState)(initialAnimated),
animated = _React$useState2[0],
setAnimated = _React$useState2[1];
var _React$useState3 = (0,external_React_.useState)(false),
animating = _React$useState3[0],
setAnimating = _React$useState3[1];
var lastVisible = useLastValue(visible);
var visibleHasChanged = lastVisible.current != null && lastVisible.current !== visible;
if (animated && !animating && visibleHasChanged) {
// Sets animating to true when when visible is updated
setAnimating(true);
}
(0,external_React_.useEffect)(function () {
if (typeof animated === "number" && animating) {
var timeout = setTimeout(function () {
return setAnimating(false);
}, animated);
return function () {
clearTimeout(timeout);
};
}
if (animated && animating && "production" === "development") { var _timeout; }
return function () {};
}, [animated, animating]);
var show = (0,external_React_.useCallback)(function () {
return setVisible(true);
}, []);
var hide = (0,external_React_.useCallback)(function () {
return setVisible(false);
}, []);
var toggle = (0,external_React_.useCallback)(function () {
return setVisible(function (v) {
return !v;
});
}, []);
var stopAnimation = (0,external_React_.useCallback)(function () {
return setAnimating(false);
}, []);
return _objectSpread2(_objectSpread2({}, id), {}, {
visible: visible,
animated: animated,
animating: animating,
show: show,
hide: hide,
toggle: toggle,
setVisible: setVisible,
setAnimated: setAnimated,
stopAnimation: stopAnimation
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Dialog/DialogState.js
function useDialogState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$modal = _useSealedState.modal,
initialModal = _useSealedState$modal === void 0 ? true : _useSealedState$modal,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["modal"]);
var disclosure = useDisclosureState(sealed);
var _React$useState = (0,external_React_.useState)(initialModal),
modal = _React$useState[0],
setModal = _React$useState[1];
var disclosureRef = (0,external_React_.useRef)(null);
return _objectSpread2(_objectSpread2({}, disclosure), {}, {
modal: modal,
setModal: setModal,
unstable_disclosureRef: disclosureRef
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Popover/PopoverState.js
var isSafari = isUA("Mac") && !isUA("Chrome") && isUA("Safari");
function PopoverState_applyStyles(styles) {
return function (prevStyles) {
if (styles && !shallowEqual(prevStyles, styles)) {
return styles;
}
return prevStyles;
};
}
function usePopoverState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$gutte = _useSealedState.gutter,
gutter = _useSealedState$gutte === void 0 ? 12 : _useSealedState$gutte,
_useSealedState$place = _useSealedState.placement,
sealedPlacement = _useSealedState$place === void 0 ? "bottom" : _useSealedState$place,
_useSealedState$unsta = _useSealedState.unstable_flip,
flip = _useSealedState$unsta === void 0 ? true : _useSealedState$unsta,
sealedOffset = _useSealedState.unstable_offset,
_useSealedState$unsta2 = _useSealedState.unstable_preventOverflow,
preventOverflow = _useSealedState$unsta2 === void 0 ? true : _useSealedState$unsta2,
_useSealedState$unsta3 = _useSealedState.unstable_fixed,
fixed = _useSealedState$unsta3 === void 0 ? false : _useSealedState$unsta3,
_useSealedState$modal = _useSealedState.modal,
modal = _useSealedState$modal === void 0 ? false : _useSealedState$modal,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["gutter", "placement", "unstable_flip", "unstable_offset", "unstable_preventOverflow", "unstable_fixed", "modal"]);
var popper = (0,external_React_.useRef)(null);
var referenceRef = (0,external_React_.useRef)(null);
var popoverRef = (0,external_React_.useRef)(null);
var arrowRef = (0,external_React_.useRef)(null);
var _React$useState = (0,external_React_.useState)(sealedPlacement),
originalPlacement = _React$useState[0],
place = _React$useState[1];
var _React$useState2 = (0,external_React_.useState)(sealedPlacement),
placement = _React$useState2[0],
setPlacement = _React$useState2[1];
var _React$useState3 = (0,external_React_.useState)(sealedOffset || [0, gutter]),
offset = _React$useState3[0];
var _React$useState4 = (0,external_React_.useState)({
position: "fixed",
left: "100%",
top: "100%"
}),
popoverStyles = _React$useState4[0],
setPopoverStyles = _React$useState4[1];
var _React$useState5 = (0,external_React_.useState)({}),
arrowStyles = _React$useState5[0],
setArrowStyles = _React$useState5[1];
var dialog = useDialogState(_objectSpread2({
modal: modal
}, sealed));
var update = (0,external_React_.useCallback)(function () {
if (popper.current) {
popper.current.forceUpdate();
return true;
}
return false;
}, []);
var updateState = (0,external_React_.useCallback)(function (state) {
if (state.placement) {
setPlacement(state.placement);
}
if (state.styles) {
setPopoverStyles(PopoverState_applyStyles(state.styles.popper));
if (arrowRef.current) {
setArrowStyles(PopoverState_applyStyles(state.styles.arrow));
}
}
}, []);
useIsomorphicEffect(function () {
if (referenceRef.current && popoverRef.current) {
popper.current = popper_createPopper(referenceRef.current, popoverRef.current, {
// https://popper.js.org/docs/v2/constructors/#options
placement: originalPlacement,
strategy: fixed ? "fixed" : "absolute",
// Safari needs styles to be applied in the first render, otherwise
// hovering over the popover when it gets visible for the first time
// will change its dimensions unexpectedly.
onFirstUpdate: isSafari ? updateState : undefined,
modifiers: [{
// https://popper.js.org/docs/v2/modifiers/event-listeners/
name: "eventListeners",
enabled: dialog.visible
}, {
// https://popper.js.org/docs/v2/modifiers/apply-styles/
name: "applyStyles",
enabled: false
}, {
// https://popper.js.org/docs/v2/modifiers/flip/
name: "flip",
enabled: flip,
options: {
padding: 8
}
}, {
// https://popper.js.org/docs/v2/modifiers/offset/
name: "offset",
options: {
offset: offset
}
}, {
// https://popper.js.org/docs/v2/modifiers/prevent-overflow/
name: "preventOverflow",
enabled: preventOverflow,
options: {
tetherOffset: function tetherOffset() {
var _arrowRef$current;
return ((_arrowRef$current = arrowRef.current) === null || _arrowRef$current === void 0 ? void 0 : _arrowRef$current.clientWidth) || 0;
}
}
}, {
// https://popper.js.org/docs/v2/modifiers/arrow/
name: "arrow",
enabled: !!arrowRef.current,
options: {
element: arrowRef.current
}
}, {
// https://popper.js.org/docs/v2/modifiers/#custom-modifiers
name: "updateState",
phase: "write",
requires: ["computeStyles"],
enabled: dialog.visible && "production" !== "test",
fn: function fn(_ref) {
var state = _ref.state;
return updateState(state);
}
}]
});
}
return function () {
if (popper.current) {
popper.current.destroy();
popper.current = null;
}
};
}, [originalPlacement, fixed, dialog.visible, flip, offset, preventOverflow]); // Ensure that the popover will be correctly positioned with an additional
// update.
(0,external_React_.useEffect)(function () {
if (!dialog.visible) return undefined;
var id = window.requestAnimationFrame(function () {
var _popper$current;
(_popper$current = popper.current) === null || _popper$current === void 0 ? void 0 : _popper$current.forceUpdate();
});
return function () {
window.cancelAnimationFrame(id);
};
}, [dialog.visible]);
return _objectSpread2(_objectSpread2({}, dialog), {}, {
unstable_referenceRef: referenceRef,
unstable_popoverRef: popoverRef,
unstable_arrowRef: arrowRef,
unstable_popoverStyles: popoverStyles,
unstable_arrowStyles: arrowStyles,
unstable_update: update,
unstable_originalPlacement: originalPlacement,
placement: placement,
place: place
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__globalState-300469f0.js
var globalState = {
currentTooltipId: null,
listeners: new Set(),
subscribe: function subscribe(listener) {
var _this = this;
this.listeners.add(listener);
return function () {
_this.listeners.delete(listener);
};
},
show: function show(id) {
this.currentTooltipId = id;
this.listeners.forEach(function (listener) {
return listener(id);
});
},
hide: function hide(id) {
if (this.currentTooltipId === id) {
this.currentTooltipId = null;
this.listeners.forEach(function (listener) {
return listener(null);
});
}
}
};
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tooltip/TooltipState.js
function useTooltipState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$place = _useSealedState.placement,
placement = _useSealedState$place === void 0 ? "top" : _useSealedState$place,
_useSealedState$unsta = _useSealedState.unstable_timeout,
initialTimeout = _useSealedState$unsta === void 0 ? 0 : _useSealedState$unsta,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["placement", "unstable_timeout"]);
var _React$useState = (0,external_React_.useState)(initialTimeout),
timeout = _React$useState[0],
setTimeout = _React$useState[1];
var showTimeout = (0,external_React_.useRef)(null);
var hideTimeout = (0,external_React_.useRef)(null);
var _usePopoverState = usePopoverState(_objectSpread2(_objectSpread2({}, sealed), {}, {
placement: placement
})),
modal = _usePopoverState.modal,
setModal = _usePopoverState.setModal,
popover = _objectWithoutPropertiesLoose(_usePopoverState, ["modal", "setModal"]);
var clearTimeouts = (0,external_React_.useCallback)(function () {
if (showTimeout.current !== null) {
window.clearTimeout(showTimeout.current);
}
if (hideTimeout.current !== null) {
window.clearTimeout(hideTimeout.current);
}
}, []);
var hide = (0,external_React_.useCallback)(function () {
clearTimeouts();
popover.hide(); // Let's give some time so people can move from a reference to another
// and still show tooltips immediately
hideTimeout.current = window.setTimeout(function () {
globalState.hide(popover.baseId);
}, timeout);
}, [clearTimeouts, popover.hide, timeout, popover.baseId]);
var show = (0,external_React_.useCallback)(function () {
clearTimeouts();
if (!timeout || globalState.currentTooltipId) {
// If there's no timeout or a tooltip visible already, we can show this
// immediately
globalState.show(popover.baseId);
popover.show();
} else {
// There may be a reference with focus whose tooltip is still not visible
// In this case, we want to update it before it gets shown.
globalState.show(null); // Otherwise, wait a little bit to show the tooltip
showTimeout.current = window.setTimeout(function () {
globalState.show(popover.baseId);
popover.show();
}, timeout);
}
}, [clearTimeouts, timeout, popover.show, popover.baseId]);
(0,external_React_.useEffect)(function () {
return globalState.subscribe(function (id) {
if (id !== popover.baseId) {
clearTimeouts();
if (popover.visible) {
// Make sure there will be only one tooltip visible
popover.hide();
}
}
});
}, [popover.baseId, clearTimeouts, popover.visible, popover.hide]);
(0,external_React_.useEffect)(function () {
return function () {
clearTimeouts();
globalState.hide(popover.baseId);
};
}, [clearTimeouts, popover.baseId]);
return _objectSpread2(_objectSpread2({}, popover), {}, {
hide: hide,
show: show,
unstable_timeout: timeout,
unstable_setTimeout: setTimeout
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-d101cb3b.js
// Automatically generated
var TOOLTIP_STATE_KEYS = ["baseId", "unstable_idCountRef", "visible", "animated", "animating", "setBaseId", "show", "hide", "toggle", "setVisible", "setAnimated", "stopAnimation", "unstable_disclosureRef", "unstable_referenceRef", "unstable_popoverRef", "unstable_arrowRef", "unstable_popoverStyles", "unstable_arrowStyles", "unstable_originalPlacement", "unstable_update", "placement", "place", "unstable_timeout", "unstable_setTimeout"];
var TOOLTIP_KEYS = [].concat(TOOLTIP_STATE_KEYS, ["unstable_portal"]);
var TOOLTIP_ARROW_KEYS = TOOLTIP_STATE_KEYS;
var TOOLTIP_REFERENCE_KEYS = TOOLTIP_ARROW_KEYS;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tooltip/TooltipReference.js
var useTooltipReference = createHook({
name: "TooltipReference",
compose: useRole,
keys: TOOLTIP_REFERENCE_KEYS,
useProps: function useProps(options, _ref) {
var htmlRef = _ref.ref,
htmlOnFocus = _ref.onFocus,
htmlOnBlur = _ref.onBlur,
htmlOnMouseEnter = _ref.onMouseEnter,
htmlOnMouseLeave = _ref.onMouseLeave,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref", "onFocus", "onBlur", "onMouseEnter", "onMouseLeave"]);
var onFocusRef = useLiveRef(htmlOnFocus);
var onBlurRef = useLiveRef(htmlOnBlur);
var onMouseEnterRef = useLiveRef(htmlOnMouseEnter);
var onMouseLeaveRef = useLiveRef(htmlOnMouseLeave);
var onFocus = (0,external_React_.useCallback)(function (event) {
var _onFocusRef$current, _options$show;
(_onFocusRef$current = onFocusRef.current) === null || _onFocusRef$current === void 0 ? void 0 : _onFocusRef$current.call(onFocusRef, event);
if (event.defaultPrevented) return;
(_options$show = options.show) === null || _options$show === void 0 ? void 0 : _options$show.call(options);
}, [options.show]);
var onBlur = (0,external_React_.useCallback)(function (event) {
var _onBlurRef$current, _options$hide;
(_onBlurRef$current = onBlurRef.current) === null || _onBlurRef$current === void 0 ? void 0 : _onBlurRef$current.call(onBlurRef, event);
if (event.defaultPrevented) return;
(_options$hide = options.hide) === null || _options$hide === void 0 ? void 0 : _options$hide.call(options);
}, [options.hide]);
var onMouseEnter = (0,external_React_.useCallback)(function (event) {
var _onMouseEnterRef$curr, _options$show2;
(_onMouseEnterRef$curr = onMouseEnterRef.current) === null || _onMouseEnterRef$curr === void 0 ? void 0 : _onMouseEnterRef$curr.call(onMouseEnterRef, event);
if (event.defaultPrevented) return;
(_options$show2 = options.show) === null || _options$show2 === void 0 ? void 0 : _options$show2.call(options);
}, [options.show]);
var onMouseLeave = (0,external_React_.useCallback)(function (event) {
var _onMouseLeaveRef$curr, _options$hide2;
(_onMouseLeaveRef$curr = onMouseLeaveRef.current) === null || _onMouseLeaveRef$curr === void 0 ? void 0 : _onMouseLeaveRef$curr.call(onMouseLeaveRef, event);
if (event.defaultPrevented) return;
(_options$hide2 = options.hide) === null || _options$hide2 === void 0 ? void 0 : _options$hide2.call(options);
}, [options.hide]);
return _objectSpread2({
ref: useForkRef(options.unstable_referenceRef, htmlRef),
tabIndex: 0,
onFocus: onFocus,
onBlur: onBlur,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
"aria-describedby": options.baseId
}, htmlProps);
}
});
var TooltipReference = createComponent({
as: "div",
useHook: useTooltipReference
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/context.js
/**
* WordPress dependencies
*/
/**
* @type {import('react').Context<{ tooltip?: import('reakit').TooltipState }>}
*/
const TooltipContext = (0,external_wp_element_namespaceObject.createContext)({});
const useTooltipContext = () => (0,external_wp_element_namespaceObject.useContext)(TooltipContext);
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-e6a5cfbe.js
// Automatically generated
var DISCLOSURE_STATE_KEYS = ["baseId", "unstable_idCountRef", "visible", "animated", "animating", "setBaseId", "show", "hide", "toggle", "setVisible", "setAnimated", "stopAnimation"];
var DISCLOSURE_KEYS = DISCLOSURE_STATE_KEYS;
var DISCLOSURE_CONTENT_KEYS = DISCLOSURE_KEYS;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Disclosure/DisclosureContent.js
var useDisclosureContent = createHook({
name: "DisclosureContent",
compose: useRole,
keys: DISCLOSURE_CONTENT_KEYS,
useProps: function useProps(options, _ref) {
var htmlOnTransitionEnd = _ref.onTransitionEnd,
htmlOnAnimationEnd = _ref.onAnimationEnd,
htmlStyle = _ref.style,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["onTransitionEnd", "onAnimationEnd", "style"]);
var animating = options.animated && options.animating;
var _React$useState = (0,external_React_.useState)(null),
transition = _React$useState[0],
setTransition = _React$useState[1];
var hidden = !options.visible && !animating;
var style = hidden ? _objectSpread2({
display: "none"
}, htmlStyle) : htmlStyle;
var onTransitionEndRef = useLiveRef(htmlOnTransitionEnd);
var onAnimationEndRef = useLiveRef(htmlOnAnimationEnd);
var raf = (0,external_React_.useRef)(0);
(0,external_React_.useEffect)(function () {
if (!options.animated) return undefined; // Double RAF is needed so the browser has enough time to paint the
// default styles before processing the `data-enter` attribute. Otherwise
// it wouldn't be considered a transition.
// See https://github.com/reakit/reakit/issues/643
raf.current = window.requestAnimationFrame(function () {
raf.current = window.requestAnimationFrame(function () {
if (options.visible) {
setTransition("enter");
} else if (animating) {
setTransition("leave");
} else {
setTransition(null);
}
});
});
return function () {
return window.cancelAnimationFrame(raf.current);
};
}, [options.animated, options.visible, animating]);
var onEnd = (0,external_React_.useCallback)(function (event) {
if (!isSelfTarget(event)) return;
if (!animating) return; // Ignores number animated
if (options.animated === true) {
var _options$stopAnimatio;
(_options$stopAnimatio = options.stopAnimation) === null || _options$stopAnimatio === void 0 ? void 0 : _options$stopAnimatio.call(options);
}
}, [options.animated, animating, options.stopAnimation]);
var onTransitionEnd = (0,external_React_.useCallback)(function (event) {
var _onTransitionEndRef$c;
(_onTransitionEndRef$c = onTransitionEndRef.current) === null || _onTransitionEndRef$c === void 0 ? void 0 : _onTransitionEndRef$c.call(onTransitionEndRef, event);
onEnd(event);
}, [onEnd]);
var onAnimationEnd = (0,external_React_.useCallback)(function (event) {
var _onAnimationEndRef$cu;
(_onAnimationEndRef$cu = onAnimationEndRef.current) === null || _onAnimationEndRef$cu === void 0 ? void 0 : _onAnimationEndRef$cu.call(onAnimationEndRef, event);
onEnd(event);
}, [onEnd]);
return _objectSpread2({
id: options.baseId,
"data-enter": transition === "enter" ? "" : undefined,
"data-leave": transition === "leave" ? "" : undefined,
onTransitionEnd: onTransitionEnd,
onAnimationEnd: onAnimationEnd,
hidden: hidden,
style: style
}, htmlProps);
}
});
var DisclosureContent = createComponent({
as: "div",
useHook: useDisclosureContent
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Portal/Portal.js
function getBodyElement() {
return canUseDOM_canUseDOM ? document.body : null;
}
var PortalContext = /*#__PURE__*/(0,external_React_.createContext)(getBodyElement());
function Portal(_ref) {
var children = _ref.children;
// if it's a nested portal, context is the parent portal
// otherwise it's document.body
// https://github.com/reakit/reakit/issues/513
var context = (0,external_React_.useContext)(PortalContext) || getBodyElement();
var _React$useState = (0,external_React_.useState)(function () {
if (canUseDOM_canUseDOM) {
var element = document.createElement("div");
element.className = Portal.__className;
return element;
} // ssr
return null;
}),
hostNode = _React$useState[0];
useIsomorphicEffect(function () {
if (!hostNode || !context) return undefined;
context.appendChild(hostNode);
return function () {
context.removeChild(hostNode);
};
}, [hostNode, context]);
if (hostNode) {
return /*#__PURE__*/(0,external_ReactDOM_namespaceObject.createPortal)( /*#__PURE__*/(0,external_React_.createElement)(PortalContext.Provider, {
value: hostNode
}, children), hostNode);
} // ssr
return null;
}
Portal.__className = "__reakit-portal";
Portal.__selector = "." + Portal.__className;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tooltip/Tooltip.js
function globallyHideTooltipOnEscape(event) {
if (event.defaultPrevented) return;
if (event.key === "Escape") {
globalState.show(null);
}
}
var useTooltip = createHook({
name: "Tooltip",
compose: useDisclosureContent,
keys: TOOLTIP_KEYS,
useOptions: function useOptions(_ref) {
var _ref$unstable_portal = _ref.unstable_portal,
unstable_portal = _ref$unstable_portal === void 0 ? true : _ref$unstable_portal,
options = _objectWithoutPropertiesLoose(_ref, ["unstable_portal"]);
return _objectSpread2({
unstable_portal: unstable_portal
}, options);
},
useProps: function useProps(options, _ref2) {
var htmlRef = _ref2.ref,
htmlStyle = _ref2.style,
htmlWrapElement = _ref2.wrapElement,
htmlProps = _objectWithoutPropertiesLoose(_ref2, ["ref", "style", "wrapElement"]);
(0,external_React_.useEffect)(function () {
var _options$unstable_pop;
var document = getDocument_getDocument((_options$unstable_pop = options.unstable_popoverRef) === null || _options$unstable_pop === void 0 ? void 0 : _options$unstable_pop.current);
document.addEventListener("keydown", globallyHideTooltipOnEscape);
}, []);
var wrapElement = (0,external_React_.useCallback)(function (element) {
if (options.unstable_portal) {
element = /*#__PURE__*/(0,external_React_.createElement)(Portal, null, element);
}
if (htmlWrapElement) {
return htmlWrapElement(element);
}
return element;
}, [options.unstable_portal, htmlWrapElement]);
return _objectSpread2({
ref: useForkRef(options.unstable_popoverRef, htmlRef),
role: "tooltip",
style: _objectSpread2(_objectSpread2({}, options.unstable_popoverStyles), {}, {
pointerEvents: "none"
}, htmlStyle),
wrapElement: wrapElement
}, htmlProps);
}
});
var Tooltip_Tooltip = createComponent({
as: "div",
memo: true,
useHook: useTooltip
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/shortcut/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function component_Shortcut(props, forwardedRef) {
const {
as: asProp = 'span',
shortcut,
className,
...otherProps
} = useContextSystem(props, 'Shortcut');
if (!shortcut) {
return null;
}
let displayText;
let ariaLabel;
if (typeof shortcut === 'string') {
displayText = shortcut;
} else {
displayText = shortcut.display;
ariaLabel = shortcut.ariaLabel;
}
return (0,external_wp_element_namespaceObject.createElement)(component, {
as: asProp,
className: className,
"aria-label": ariaLabel,
ref: forwardedRef,
...otherProps
}, displayText);
}
const ConnectedShortcut = contextConnect(component_Shortcut, 'Shortcut');
/* harmony default export */ var shortcut_component = (ConnectedShortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/z-index.js
const Flyout = 10000;
const z_index_Tooltip = 1000002;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/styles.js
function tooltip_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const TooltipContent = /*#__PURE__*/emotion_react_browser_esm_css("z-index:", z_index_Tooltip, ";box-sizing:border-box;opacity:0;outline:none;transform-origin:top center;transition:opacity ", config_values.transitionDurationFastest, " ease;font-size:", config_values.fontSize, ";&[data-enter]{opacity:1;}" + ( true ? "" : 0), true ? "" : 0);
const TooltipPopoverView = createStyled("div", true ? {
target: "e7tfjmw1"
} : 0)("background:rgba( 0, 0, 0, 0.8 );border-radius:2px;box-shadow:0 0 0 1px rgba( 255, 255, 255, 0.04 );color:", COLORS.white, ";padding:4px 8px;" + ( true ? "" : 0));
const noOutline = true ? {
name: "12mkfdx",
styles: "outline:none"
} : 0;
const TooltipShortcut = /*#__PURE__*/createStyled(shortcut_component, true ? {
target: "e7tfjmw0"
} : 0)("display:inline-block;margin-left:", space(1), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/content.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* Internal dependencies
*/
const {
TooltipPopoverView: content_TooltipPopoverView
} = tooltip_styles_namespaceObject;
/**
*
* @param {import('../context').WordPressComponentProps<import('./types').ContentProps, 'div'>} props
* @param {import('react').ForwardedRef<any>} forwardedRef
*/
function content_TooltipContent(props, forwardedRef) {
const {
children,
className,
...otherProps
} = useContextSystem(props, 'TooltipContent');
const {
tooltip
} = useTooltipContext();
const cx = useCx();
const classes = cx(TooltipContent, className);
return (0,external_wp_element_namespaceObject.createElement)(Tooltip_Tooltip, {
as: component,
...otherProps,
...tooltip,
className: classes,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(content_TooltipPopoverView, null, children));
}
/* harmony default export */ var tooltip_content = (contextConnect(content_TooltipContent, 'TooltipContent'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/component.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @param {import('../context').WordPressComponentProps<import('./types').Props, 'div'>} props
* @param {import('react').ForwardedRef<any>} forwardedRef
*/
function component_Tooltip(props, forwardedRef) {
const {
animated = true,
animationDuration = 160,
baseId,
children,
content,
focusable = true,
gutter = 4,
id,
modal = true,
placement,
visible = false,
shortcut,
...otherProps
} = useContextSystem(props, 'Tooltip');
const tooltip = useTooltipState({
animated: animated ? animationDuration : undefined,
baseId: baseId || id,
gutter,
placement,
visible,
...otherProps
});
const contextProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
tooltip
}), [tooltip]);
return (0,external_wp_element_namespaceObject.createElement)(TooltipContext.Provider, {
value: contextProps
}, content && (0,external_wp_element_namespaceObject.createElement)(tooltip_content, {
unstable_portal: modal,
ref: forwardedRef
}, content, shortcut && (0,external_wp_element_namespaceObject.createElement)(TooltipShortcut, {
shortcut: shortcut
})), children && (0,external_wp_element_namespaceObject.createElement)(TooltipReference, { ...tooltip,
...children.props,
// @ts-ignore If ref doesn't exist that's fine with us, it'll just be undefined, but it can exist on ReactElement and there's no reason to try to scope this (it'll just overcomplicate things)
ref: children?.ref
}, referenceProps => {
if (!focusable) {
referenceProps.tabIndex = undefined;
}
return (0,external_wp_element_namespaceObject.cloneElement)(children, referenceProps);
}));
}
/**
* `Tooltip` is a component that provides context for a user interface element.
*
* @example
* ```jsx
* import { Tooltip, Text } from `@wordpress/components/ui`;
*
* function Example() {
* return (
* <Tooltip content="Code is Poetry">
* <Text>WordPress.org</Text>
* </Tooltip>
* )
* }
* ```
*/
const ConnectedTooltip = contextConnect(component_Tooltip, 'Tooltip');
/* harmony default export */ var tooltip_component = (ConnectedTooltip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/color-copy-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ColorCopyButton = props => {
const {
color,
colorType
} = props;
const [copiedColor, setCopiedColor] = (0,external_wp_element_namespaceObject.useState)(null);
const copyTimer = (0,external_wp_element_namespaceObject.useRef)();
const copyRef = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(() => {
switch (colorType) {
case 'hsl':
{
return color.toHslString();
}
case 'rgb':
{
return color.toRgbString();
}
default:
case 'hex':
{
return color.toHex();
}
}
}, () => {
if (copyTimer.current) {
clearTimeout(copyTimer.current);
}
setCopiedColor(color.toHex());
copyTimer.current = setTimeout(() => {
setCopiedColor(null);
copyTimer.current = undefined;
}, 3000);
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Clear copyTimer on component unmount.
return () => {
if (copyTimer.current) {
clearTimeout(copyTimer.current);
}
};
}, []);
return (0,external_wp_element_namespaceObject.createElement)(tooltip_component, {
content: (0,external_wp_element_namespaceObject.createElement)(text_component, {
color: "white"
}, copiedColor === color.toHex() ? (0,external_wp_i18n_namespaceObject.__)('Copied!') : (0,external_wp_i18n_namespaceObject.__)('Copy')),
placement: "bottom"
}, (0,external_wp_element_namespaceObject.createElement)(CopyButton, {
isSmall: true,
ref: copyRef,
icon: library_copy,
showTooltip: false
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/input-with-slider.js
/**
* Internal dependencies
*/
const InputWithSlider = ({
min,
max,
label,
abbreviation,
onChange,
value
}) => {
const onNumberControlChange = newValue => {
if (!newValue) {
onChange(0);
return;
}
if (typeof newValue === 'string') {
onChange(parseInt(newValue, 10));
return;
}
onChange(newValue);
};
return (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
spacing: 4
}, (0,external_wp_element_namespaceObject.createElement)(NumberControlWrapper, {
min: min,
max: max,
label: label,
hideLabelFromVision: true,
value: value,
onChange: onNumberControlChange,
prefix: (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
as: text_component,
paddingLeft: space(4),
color: COLORS.ui.theme,
lineHeight: 1
}, abbreviation),
spinControls: "none",
size: "__unstable-large"
}), (0,external_wp_element_namespaceObject.createElement)(styles_RangeControl, {
__nextHasNoMarginBottom: true,
label: label,
hideLabelFromVision: true,
min: min,
max: max,
value: value // @ts-expect-error
// See: https://github.com/WordPress/gutenberg/pull/40535#issuecomment-1172418185
,
onChange: onChange,
withInputField: false
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/rgb-input.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const RgbInput = ({
color,
onChange,
enableAlpha
}) => {
const {
r,
g,
b,
a
} = color.toRgb();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 255,
label: "Red",
abbreviation: "R",
value: r,
onChange: nextR => onChange(colord_w({
r: nextR,
g,
b,
a
}))
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 255,
label: "Green",
abbreviation: "G",
value: g,
onChange: nextG => onChange(colord_w({
r,
g: nextG,
b,
a
}))
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 255,
label: "Blue",
abbreviation: "B",
value: b,
onChange: nextB => onChange(colord_w({
r,
g,
b: nextB,
a
}))
}), enableAlpha && (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Alpha",
abbreviation: "A",
value: Math.trunc(a * 100),
onChange: nextA => onChange(colord_w({
r,
g,
b,
a: nextA / 100
}))
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/hsl-input.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const HslInput = ({
color,
onChange,
enableAlpha
}) => {
const {
h,
s,
l,
a
} = color.toHsl();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 359,
label: "Hue",
abbreviation: "H",
value: h,
onChange: nextH => {
onChange(colord_w({
h: nextH,
s,
l,
a
}));
}
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Saturation",
abbreviation: "S",
value: s,
onChange: nextS => {
onChange(colord_w({
h,
s: nextS,
l,
a
}));
}
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Lightness",
abbreviation: "L",
value: l,
onChange: nextL => {
onChange(colord_w({
h,
s,
l: nextL,
a
}));
}
}), enableAlpha && (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Alpha",
abbreviation: "A",
value: Math.trunc(100 * a),
onChange: nextA => {
onChange(colord_w({
h,
s,
l,
a: nextA / 100
}));
}
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/hex-input.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const HexInput = ({
color,
onChange,
enableAlpha
}) => {
const handleChange = nextValue => {
if (!nextValue) return;
const hexValue = nextValue.startsWith('#') ? nextValue : '#' + nextValue;
onChange(colord_w(hexValue));
};
const stateReducer = (state, action) => {
const nativeEvent = action.payload?.event?.nativeEvent;
if ('insertFromPaste' !== nativeEvent?.inputType) {
return { ...state
};
}
const value = state.value?.startsWith('#') ? state.value.slice(1).toUpperCase() : state.value?.toUpperCase();
return { ...state,
value
};
};
return (0,external_wp_element_namespaceObject.createElement)(InputControl, {
prefix: (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
as: text_component,
marginLeft: space(4),
color: COLORS.ui.theme,
lineHeight: 1
}, "#"),
value: color.toHex().slice(1).toUpperCase(),
onChange: handleChange,
maxLength: enableAlpha ? 9 : 7,
label: (0,external_wp_i18n_namespaceObject.__)('Hex color'),
hideLabelFromVision: true,
size: "__unstable-large",
__unstableStateReducer: stateReducer,
__unstableInputWidth: "9em"
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/color-input.js
/**
* Internal dependencies
*/
const ColorInput = ({
colorType,
color,
onChange,
enableAlpha
}) => {
const props = {
color,
onChange,
enableAlpha
};
switch (colorType) {
case 'hsl':
return (0,external_wp_element_namespaceObject.createElement)(HslInput, { ...props
});
case 'rgb':
return (0,external_wp_element_namespaceObject.createElement)(RgbInput, { ...props
});
default:
case 'hex':
return (0,external_wp_element_namespaceObject.createElement)(HexInput, { ...props
});
}
};
;// CONCATENATED MODULE: ./node_modules/react-colorful/dist/index.mjs
function dist_u(){return(dist_u=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function dist_c(e,r){if(null==e)return{};var t,n,o={},a=Object.keys(e);for(n=0;n<a.length;n++)r.indexOf(t=a[n])>=0||(o[t]=e[t]);return o}function dist_i(e){var t=(0,external_React_.useRef)(e),n=(0,external_React_.useRef)(function(e){t.current&&t.current(e)});return t.current=e,n.current}var dist_s=function(e,r,t){return void 0===r&&(r=0),void 0===t&&(t=1),e>t?t:e<r?r:e},dist_f=function(e){return"touches"in e},dist_v=function(e){return e&&e.ownerDocument.defaultView||self},dist_d=function(e,r,t){var n=e.getBoundingClientRect(),o=dist_f(r)?function(e,r){for(var t=0;t<e.length;t++)if(e[t].identifier===r)return e[t];return e[0]}(r.touches,t):r;return{left:dist_s((o.pageX-(n.left+dist_v(e).pageXOffset))/n.width),top:dist_s((o.pageY-(n.top+dist_v(e).pageYOffset))/n.height)}},dist_h=function(e){!dist_f(e)&&e.preventDefault()},dist_m=external_React_.memo(function(o){var a=o.onMove,l=o.onKey,s=dist_c(o,["onMove","onKey"]),m=(0,external_React_.useRef)(null),g=dist_i(a),p=dist_i(l),b=(0,external_React_.useRef)(null),_=(0,external_React_.useRef)(!1),x=(0,external_React_.useMemo)(function(){var e=function(e){dist_h(e),(dist_f(e)?e.touches.length>0:e.buttons>0)&&m.current?g(dist_d(m.current,e,b.current)):t(!1)},r=function(){return t(!1)};function t(t){var n=_.current,o=dist_v(m.current),a=t?o.addEventListener:o.removeEventListener;a(n?"touchmove":"mousemove",e),a(n?"touchend":"mouseup",r)}return[function(e){var r=e.nativeEvent,n=m.current;if(n&&(dist_h(r),!function(e,r){return r&&!dist_f(e)}(r,_.current)&&n)){if(dist_f(r)){_.current=!0;var o=r.changedTouches||[];o.length&&(b.current=o[0].identifier)}n.focus(),g(dist_d(n,r,b.current)),t(!0)}},function(e){var r=e.which||e.keyCode;r<37||r>40||(e.preventDefault(),p({left:39===r?.05:37===r?-.05:0,top:40===r?.05:38===r?-.05:0}))},t]},[p,g]),C=x[0],E=x[1],H=x[2];return (0,external_React_.useEffect)(function(){return H},[H]),external_React_.createElement("div",dist_u({},s,{onTouchStart:C,onMouseDown:C,className:"react-colorful__interactive",ref:m,onKeyDown:E,tabIndex:0,role:"slider"}))}),dist_g=function(e){return e.filter(Boolean).join(" ")},dist_p=function(r){var t=r.color,n=r.left,o=r.top,a=void 0===o?.5:o,l=dist_g(["react-colorful__pointer",r.className]);return external_React_.createElement("div",{className:l,style:{top:100*a+"%",left:100*n+"%"}},external_React_.createElement("div",{className:"react-colorful__pointer-fill",style:{backgroundColor:t}}))},dist_b=function(e,r,t){return void 0===r&&(r=0),void 0===t&&(t=Math.pow(10,r)),Math.round(t*e)/t},_={grad:.9,turn:360,rad:360/(2*Math.PI)},dist_x=function(e){return dist_L(dist_C(e))},dist_C=function(e){return"#"===e[0]&&(e=e.substring(1)),e.length<6?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:4===e.length?dist_b(parseInt(e[3]+e[3],16)/255,2):1}:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:8===e.length?dist_b(parseInt(e.substring(6,8),16)/255,2):1}},dist_E=function(e,r){return void 0===r&&(r="deg"),Number(e)*(_[r]||1)},dist_H=function(e){var r=/hsla?\(?\s*(-?\d*\.?\d+)(deg|rad|grad|turn)?[,\s]+(-?\d*\.?\d+)%?[,\s]+(-?\d*\.?\d+)%?,?\s*[/\s]*(-?\d*\.?\d+)?(%)?\s*\)?/i.exec(e);return r?dist_N({h:dist_E(r[1],r[2]),s:Number(r[3]),l:Number(r[4]),a:void 0===r[5]?1:Number(r[5])/(r[6]?100:1)}):{h:0,s:0,v:0,a:1}},dist_M=dist_H,dist_N=function(e){var r=e.s,t=e.l;return{h:e.h,s:(r*=(t<50?t:100-t)/100)>0?2*r/(t+r)*100:0,v:t+r,a:e.a}},dist_w=function(e){return K(dist_I(e))},dist_y=function(e){var r=e.s,t=e.v,n=e.a,o=(200-r)*t/100;return{h:dist_b(e.h),s:dist_b(o>0&&o<200?r*t/100/(o<=100?o:200-o)*100:0),l:dist_b(o/2),a:dist_b(n,2)}},q=function(e){var r=dist_y(e);return"hsl("+r.h+", "+r.s+"%, "+r.l+"%)"},dist_k=function(e){var r=dist_y(e);return"hsla("+r.h+", "+r.s+"%, "+r.l+"%, "+r.a+")"},dist_I=function(e){var r=e.h,t=e.s,n=e.v,o=e.a;r=r/360*6,t/=100,n/=100;var a=Math.floor(r),l=n*(1-t),u=n*(1-(r-a)*t),c=n*(1-(1-r+a)*t),i=a%6;return{r:dist_b(255*[n,u,l,l,c,n][i]),g:dist_b(255*[c,n,n,u,l,l][i]),b:dist_b(255*[l,l,c,n,n,u][i]),a:dist_b(o,2)}},dist_O=function(e){var r=/hsva?\(?\s*(-?\d*\.?\d+)(deg|rad|grad|turn)?[,\s]+(-?\d*\.?\d+)%?[,\s]+(-?\d*\.?\d+)%?,?\s*[/\s]*(-?\d*\.?\d+)?(%)?\s*\)?/i.exec(e);return r?dist_A({h:dist_E(r[1],r[2]),s:Number(r[3]),v:Number(r[4]),a:void 0===r[5]?1:Number(r[5])/(r[6]?100:1)}):{h:0,s:0,v:0,a:1}},dist_j=dist_O,dist_z=function(e){var r=/rgba?\(?\s*(-?\d*\.?\d+)(%)?[,\s]+(-?\d*\.?\d+)(%)?[,\s]+(-?\d*\.?\d+)(%)?,?\s*[/\s]*(-?\d*\.?\d+)?(%)?\s*\)?/i.exec(e);return r?dist_L({r:Number(r[1])/(r[2]?100/255:1),g:Number(r[3])/(r[4]?100/255:1),b:Number(r[5])/(r[6]?100/255:1),a:void 0===r[7]?1:Number(r[7])/(r[8]?100:1)}):{h:0,s:0,v:0,a:1}},dist_B=dist_z,dist_D=function(e){var r=e.toString(16);return r.length<2?"0"+r:r},K=function(e){var r=e.r,t=e.g,n=e.b,o=e.a,a=o<1?dist_D(dist_b(255*o)):"";return"#"+dist_D(r)+dist_D(t)+dist_D(n)+a},dist_L=function(e){var r=e.r,t=e.g,n=e.b,o=e.a,a=Math.max(r,t,n),l=a-Math.min(r,t,n),u=l?a===r?(t-n)/l:a===t?2+(n-r)/l:4+(r-t)/l:0;return{h:dist_b(60*(u<0?u+6:u)),s:dist_b(a?l/a*100:0),v:dist_b(a/255*100),a:o}},dist_A=function(e){return{h:dist_b(e.h),s:dist_b(e.s),v:dist_b(e.v),a:dist_b(e.a,2)}},dist_S=external_React_.memo(function(r){var t=r.hue,n=r.onChange,o=dist_g(["react-colorful__hue",r.className]);return external_React_.createElement("div",{className:o},external_React_.createElement(dist_m,{onMove:function(e){n({h:360*e.left})},onKey:function(e){n({h:dist_s(t+360*e.left,0,360)})},"aria-label":"Hue","aria-valuenow":dist_b(t),"aria-valuemax":"360","aria-valuemin":"0"},external_React_.createElement(dist_p,{className:"react-colorful__hue-pointer",left:t/360,color:q({h:t,s:100,v:100,a:1})})))}),dist_T=external_React_.memo(function(r){var t=r.hsva,n=r.onChange,o={backgroundColor:q({h:t.h,s:100,v:100,a:1})};return external_React_.createElement("div",{className:"react-colorful__saturation",style:o},external_React_.createElement(dist_m,{onMove:function(e){n({s:100*e.left,v:100-100*e.top})},onKey:function(e){n({s:dist_s(t.s+100*e.left,0,100),v:dist_s(t.v-100*e.top,0,100)})},"aria-label":"Color","aria-valuetext":"Saturation "+dist_b(t.s)+"%, Brightness "+dist_b(t.v)+"%"},external_React_.createElement(dist_p,{className:"react-colorful__saturation-pointer",top:1-t.v/100,left:t.s/100,color:q(t)})))}),dist_F=function(e,r){if(e===r)return!0;for(var t in e)if(e[t]!==r[t])return!1;return!0},dist_P=function(e,r){return e.replace(/\s/g,"")===r.replace(/\s/g,"")},X=function(e,r){return e.toLowerCase()===r.toLowerCase()||dist_F(dist_C(e),dist_C(r))};function Y(e,t,l){var u=dist_i(l),c=(0,external_React_.useState)(function(){return e.toHsva(t)}),s=c[0],f=c[1],v=(0,external_React_.useRef)({color:t,hsva:s});(0,external_React_.useEffect)(function(){if(!e.equal(t,v.current.color)){var r=e.toHsva(t);v.current={hsva:r,color:t},f(r)}},[t,e]),(0,external_React_.useEffect)(function(){var r;dist_F(s,v.current.hsva)||e.equal(r=e.fromHsva(s),v.current.color)||(v.current={hsva:s,color:r},u(r))},[s,e,u]);var d=(0,external_React_.useCallback)(function(e){f(function(r){return Object.assign({},r,e)})},[]);return[s,d]}var dist_R,dist_V="undefined"!=typeof window?external_React_.useLayoutEffect:external_React_.useEffect,dist_$=function(){return dist_R||( true?__webpack_require__.nc:0)},G=function(e){dist_R=e},J=new Map,Q=function(e){dist_V(function(){var r=e.current?e.current.ownerDocument:document;if(void 0!==r&&!J.has(r)){var t=r.createElement("style");t.innerHTML='.react-colorful{position:relative;display:flex;flex-direction:column;width:200px;height:200px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.react-colorful__saturation{position:relative;flex-grow:1;border-color:transparent;border-bottom:12px solid #000;border-radius:8px 8px 0 0;background-image:linear-gradient(0deg,#000,transparent),linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.react-colorful__alpha-gradient,.react-colorful__pointer-fill{content:"";position:absolute;left:0;top:0;right:0;bottom:0;pointer-events:none;border-radius:inherit}.react-colorful__alpha-gradient,.react-colorful__saturation{box-shadow:inset 0 0 0 1px rgba(0,0,0,.05)}.react-colorful__alpha,.react-colorful__hue{position:relative;height:24px}.react-colorful__hue{background:linear-gradient(90deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red)}.react-colorful__last-control{border-radius:0 0 8px 8px}.react-colorful__interactive{position:absolute;left:0;top:0;right:0;bottom:0;border-radius:inherit;outline:none;touch-action:none}.react-colorful__pointer{position:absolute;z-index:1;box-sizing:border-box;width:28px;height:28px;transform:translate(-50%,-50%);background-color:#fff;border:2px solid #fff;border-radius:50%;box-shadow:0 2px 4px rgba(0,0,0,.2)}.react-colorful__interactive:focus .react-colorful__pointer{transform:translate(-50%,-50%) scale(1.1)}.react-colorful__alpha,.react-colorful__alpha-pointer{background-color:#fff;background-image:url(\'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill-opacity=".05"><path d="M8 0h8v8H8zM0 8h8v8H0z"/></svg>\')}.react-colorful__saturation-pointer{z-index:3}.react-colorful__hue-pointer{z-index:2}',J.set(r,t);var n=dist_$();n&&t.setAttribute("nonce",n),r.head.appendChild(t)}},[])},U=function(t){var n=t.className,o=t.colorModel,a=t.color,l=void 0===a?o.defaultColor:a,i=t.onChange,s=dist_c(t,["className","colorModel","color","onChange"]),f=(0,external_React_.useRef)(null);Q(f);var v=Y(o,l,i),d=v[0],h=v[1],m=dist_g(["react-colorful",n]);return external_React_.createElement("div",dist_u({},s,{ref:f,className:m}),external_React_.createElement(dist_T,{hsva:d,onChange:h}),external_React_.createElement(dist_S,{hue:d.h,onChange:h,className:"react-colorful__last-control"}))},dist_W={defaultColor:"000",toHsva:dist_x,fromHsva:function(e){return dist_w({h:e.h,s:e.s,v:e.v,a:1})},equal:X},Z=function(r){return e.createElement(U,dist_u({},r,{colorModel:dist_W}))},ee=function(r){var t=r.className,n=r.hsva,o=r.onChange,a={backgroundImage:"linear-gradient(90deg, "+dist_k(Object.assign({},n,{a:0}))+", "+dist_k(Object.assign({},n,{a:1}))+")"},l=dist_g(["react-colorful__alpha",t]),u=dist_b(100*n.a);return external_React_.createElement("div",{className:l},external_React_.createElement("div",{className:"react-colorful__alpha-gradient",style:a}),external_React_.createElement(dist_m,{onMove:function(e){o({a:e.left})},onKey:function(e){o({a:dist_s(n.a+e.left)})},"aria-label":"Alpha","aria-valuetext":u+"%","aria-valuenow":u,"aria-valuemin":"0","aria-valuemax":"100"},external_React_.createElement(dist_p,{className:"react-colorful__alpha-pointer",left:n.a,color:dist_k(n)})))},re=function(t){var n=t.className,o=t.colorModel,a=t.color,l=void 0===a?o.defaultColor:a,i=t.onChange,s=dist_c(t,["className","colorModel","color","onChange"]),f=(0,external_React_.useRef)(null);Q(f);var v=Y(o,l,i),d=v[0],h=v[1],m=dist_g(["react-colorful",n]);return external_React_.createElement("div",dist_u({},s,{ref:f,className:m}),external_React_.createElement(dist_T,{hsva:d,onChange:h}),external_React_.createElement(dist_S,{hue:d.h,onChange:h}),external_React_.createElement(ee,{hsva:d,onChange:h,className:"react-colorful__last-control"}))},te={defaultColor:"0001",toHsva:dist_x,fromHsva:dist_w,equal:X},ne=function(r){return e.createElement(re,dist_u({},r,{colorModel:te}))},oe={defaultColor:{h:0,s:0,l:0,a:1},toHsva:dist_N,fromHsva:dist_y,equal:dist_F},ae=function(r){return e.createElement(re,dist_u({},r,{colorModel:oe}))},le={defaultColor:"hsla(0, 0%, 0%, 1)",toHsva:dist_H,fromHsva:dist_k,equal:dist_P},ue=function(r){return e.createElement(re,dist_u({},r,{colorModel:le}))},ce={defaultColor:{h:0,s:0,l:0},toHsva:function(e){return dist_N({h:e.h,s:e.s,l:e.l,a:1})},fromHsva:function(e){return{h:(r=dist_y(e)).h,s:r.s,l:r.l};var r},equal:dist_F},ie=function(r){return e.createElement(U,dist_u({},r,{colorModel:ce}))},se={defaultColor:"hsl(0, 0%, 0%)",toHsva:dist_M,fromHsva:q,equal:dist_P},fe=function(r){return e.createElement(U,dist_u({},r,{colorModel:se}))},ve={defaultColor:{h:0,s:0,v:0,a:1},toHsva:function(e){return e},fromHsva:dist_A,equal:dist_F},de=function(r){return e.createElement(re,dist_u({},r,{colorModel:ve}))},he={defaultColor:"hsva(0, 0%, 0%, 1)",toHsva:dist_O,fromHsva:function(e){var r=dist_A(e);return"hsva("+r.h+", "+r.s+"%, "+r.v+"%, "+r.a+")"},equal:dist_P},me=function(r){return e.createElement(re,dist_u({},r,{colorModel:he}))},ge={defaultColor:{h:0,s:0,v:0},toHsva:function(e){return{h:e.h,s:e.s,v:e.v,a:1}},fromHsva:function(e){var r=dist_A(e);return{h:r.h,s:r.s,v:r.v}},equal:dist_F},pe=function(r){return e.createElement(U,dist_u({},r,{colorModel:ge}))},be={defaultColor:"hsv(0, 0%, 0%)",toHsva:dist_j,fromHsva:function(e){var r=dist_A(e);return"hsv("+r.h+", "+r.s+"%, "+r.v+"%)"},equal:dist_P},_e=function(r){return e.createElement(U,dist_u({},r,{colorModel:be}))},xe={defaultColor:{r:0,g:0,b:0,a:1},toHsva:dist_L,fromHsva:dist_I,equal:dist_F},Ce=function(r){return e.createElement(re,dist_u({},r,{colorModel:xe}))},Ee={defaultColor:"rgba(0, 0, 0, 1)",toHsva:dist_z,fromHsva:function(e){var r=dist_I(e);return"rgba("+r.r+", "+r.g+", "+r.b+", "+r.a+")"},equal:dist_P},He=function(r){return external_React_.createElement(re,dist_u({},r,{colorModel:Ee}))},Me={defaultColor:{r:0,g:0,b:0},toHsva:function(e){return dist_L({r:e.r,g:e.g,b:e.b,a:1})},fromHsva:function(e){return{r:(r=dist_I(e)).r,g:r.g,b:r.b};var r},equal:dist_F},Ne=function(r){return e.createElement(U,dist_u({},r,{colorModel:Me}))},we={defaultColor:"rgb(0, 0, 0)",toHsva:dist_B,fromHsva:function(e){var r=dist_I(e);return"rgb("+r.r+", "+r.g+", "+r.b+")"},equal:dist_P},ye=function(r){return external_React_.createElement(U,dist_u({},r,{colorModel:we}))},qe=/^#?([0-9A-F]{3,8})$/i,ke=function(r){var t=r.color,l=void 0===t?"":t,s=r.onChange,f=r.onBlur,v=r.escape,d=r.validate,h=r.format,m=r.process,g=dist_c(r,["color","onChange","onBlur","escape","validate","format","process"]),p=o(function(){return v(l)}),b=p[0],_=p[1],x=dist_i(s),C=dist_i(f),E=a(function(e){var r=v(e.target.value);_(r),d(r)&&x(m?m(r):r)},[v,m,d,x]),H=a(function(e){d(e.target.value)||_(v(l)),C(e)},[l,v,d,C]);return n(function(){_(v(l))},[l,v]),e.createElement("input",dist_u({},g,{value:h?h(b):b,spellCheck:"false",onChange:E,onBlur:H}))},Ie=function(e){return"#"+e},Oe=function(r){var t=r.prefixed,n=r.alpha,o=dist_c(r,["prefixed","alpha"]),l=a(function(e){return e.replace(/([^0-9A-F]+)/gi,"").substring(0,n?8:6)},[n]),i=a(function(e){return function(e,r){var t=qe.exec(e),n=t?t[1].length:0;return 3===n||6===n||!!r&&4===n||!!r&&8===n}(e,n)},[n]);return e.createElement(ke,dist_u({},o,{escape:l,format:t?Ie:void 0,process:Ie,validate:i}))};
//# sourceMappingURL=index.module.js.map
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/picker.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const Picker = ({
color,
enableAlpha,
onChange
}) => {
const Component = enableAlpha ? He : ye;
const rgbColor = (0,external_wp_element_namespaceObject.useMemo)(() => color.toRgbString(), [color]);
return (0,external_wp_element_namespaceObject.createElement)(Component, {
color: rgbColor,
onChange: nextColor => {
onChange(colord_w(nextColor));
}
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-controlled-value.js
/**
* WordPress dependencies
*/
/**
* Simplified and improved implementation of useControlledState.
*
* @param props
* @param props.defaultValue
* @param props.value
* @param props.onChange
* @return The controlled value and the value setter.
*/
function useControlledValue({
defaultValue,
onChange,
value: valueProp
}) {
const hasValue = typeof valueProp !== 'undefined';
const initialValue = hasValue ? valueProp : defaultValue;
const [state, setState] = (0,external_wp_element_namespaceObject.useState)(initialValue);
const value = hasValue ? valueProp : state;
let setValue;
if (hasValue && typeof onChange === 'function') {
setValue = onChange;
} else if (!hasValue && typeof onChange === 'function') {
setValue = nextValue => {
onChange(nextValue);
setState(nextValue);
};
} else {
setValue = setState;
}
return [value, setValue];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
colord_k([names]);
const options = [{
label: 'RGB',
value: 'rgb'
}, {
label: 'HSL',
value: 'hsl'
}, {
label: 'Hex',
value: 'hex'
}];
const UnconnectedColorPicker = (props, forwardedRef) => {
const {
enableAlpha = false,
color: colorProp,
onChange,
defaultValue = '#fff',
copyFormat,
...divProps
} = useContextSystem(props, 'ColorPicker'); // Use a safe default value for the color and remove the possibility of `undefined`.
const [color, setColor] = useControlledValue({
onChange,
value: colorProp,
defaultValue
});
const safeColordColor = (0,external_wp_element_namespaceObject.useMemo)(() => {
return colord_w(color || '');
}, [color]);
const debouncedSetColor = (0,external_wp_compose_namespaceObject.useDebounce)(setColor);
const handleChange = (0,external_wp_element_namespaceObject.useCallback)(nextValue => {
debouncedSetColor(nextValue.toHex());
}, [debouncedSetColor]);
const [colorType, setColorType] = (0,external_wp_element_namespaceObject.useState)(copyFormat || 'hex');
return (0,external_wp_element_namespaceObject.createElement)(ColorfulWrapper, {
ref: forwardedRef,
...divProps
}, (0,external_wp_element_namespaceObject.createElement)(Picker, {
onChange: handleChange,
color: safeColordColor,
enableAlpha: enableAlpha
}), (0,external_wp_element_namespaceObject.createElement)(AuxiliaryColorArtefactWrapper, null, (0,external_wp_element_namespaceObject.createElement)(AuxiliaryColorArtefactHStackHeader, {
justify: "space-between"
}, (0,external_wp_element_namespaceObject.createElement)(styles_SelectControl, {
__nextHasNoMarginBottom: true,
options: options,
value: colorType,
onChange: nextColorType => setColorType(nextColorType),
label: (0,external_wp_i18n_namespaceObject.__)('Color format'),
hideLabelFromVision: true
}), (0,external_wp_element_namespaceObject.createElement)(ColorCopyButton, {
color: safeColordColor,
colorType: copyFormat || colorType
})), (0,external_wp_element_namespaceObject.createElement)(ColorInputWrapper, {
direction: "column",
gap: 2
}, (0,external_wp_element_namespaceObject.createElement)(ColorInput, {
colorType: colorType,
color: safeColordColor,
onChange: handleChange,
enableAlpha: enableAlpha
}))));
};
const ColorPicker = contextConnect(UnconnectedColorPicker, 'ColorPicker');
/* harmony default export */ var color_picker_component = (ColorPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/use-deprecated-props.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function isLegacyProps(props) {
return typeof props.onChangeComplete !== 'undefined' || typeof props.disableAlpha !== 'undefined' || typeof props.color?.hex === 'string';
}
function getColorFromLegacyProps(color) {
if (color === undefined) return;
if (typeof color === 'string') return color;
if (color.hex) return color.hex;
return undefined;
}
const transformColorStringToLegacyColor = memize(color => {
const colordColor = colord_w(color);
const hex = colordColor.toHex();
const rgb = colordColor.toRgb();
const hsv = colordColor.toHsv();
const hsl = colordColor.toHsl();
return {
hex,
rgb,
hsv,
hsl,
source: 'hex',
oldHue: hsl.h
};
});
function use_deprecated_props_useDeprecatedProps(props) {
const {
onChangeComplete
} = props;
const legacyChangeHandler = (0,external_wp_element_namespaceObject.useCallback)(color => {
onChangeComplete(transformColorStringToLegacyColor(color));
}, [onChangeComplete]);
if (isLegacyProps(props)) {
return {
color: getColorFromLegacyProps(props.color),
enableAlpha: !props.disableAlpha,
onChange: legacyChangeHandler
};
}
return { ...props,
color: props.color,
enableAlpha: props.enableAlpha,
onChange: props.onChange
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/legacy-adapter.js
/**
* Internal dependencies
*/
const LegacyAdapter = props => {
return (0,external_wp_element_namespaceObject.createElement)(color_picker_component, { ...use_deprecated_props_useDeprecatedProps(props)
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
const check = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"
}));
/* harmony default export */ var library_check = (check);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/circular-option-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Option({
className,
isSelected,
selectedIconProps,
tooltipText,
...additionalProps
}) {
const optionButton = (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isPressed: isSelected,
className: "components-circular-option-picker__option",
...additionalProps
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()(className, 'components-circular-option-picker__option-wrapper')
}, tooltipText ? (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: tooltipText
}, optionButton) : optionButton, isSelected && (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_check,
...(selectedIconProps ? selectedIconProps : {})
}));
}
function DropdownLinkAction({
buttonProps,
className,
dropdownProps,
linkText
}) {
return (0,external_wp_element_namespaceObject.createElement)(dropdown, {
className: classnames_default()('components-circular-option-picker__dropdown-link-action', className),
renderToggle: ({
isOpen,
onToggle
}) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
variant: "link",
...buttonProps
}, linkText),
...dropdownProps
});
}
function ButtonAction({
className,
children,
...additionalProps
}) {
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: classnames_default()('components-circular-option-picker__clear', className),
variant: "tertiary",
...additionalProps
}, children);
}
/**
*`CircularOptionPicker` is a component that displays a set of options as circular buttons.
*
* ```jsx
* import { CircularOptionPicker } from '../circular-option-picker';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ currentColor, setCurrentColor ] = useState();
* const colors = [
* { color: '#f00', name: 'Red' },
* { color: '#0f0', name: 'Green' },
* { color: '#00f', name: 'Blue' },
* ];
* const colorOptions = (
* <>
* { colors.map( ( { color, name }, index ) => {
* return (
* <CircularOptionPicker.Option
* key={ `${ color }-${ index }` }
* tooltipText={ name }
* style={ { backgroundColor: color, color } }
* isSelected={ index === currentColor }
* onClick={ () => setCurrentColor( index ) }
* aria-label={ name }
* />
* );
* } ) }
* </>
* );
* return (
* <CircularOptionPicker
* options={ colorOptions }
* actions={
* <CircularOptionPicker.ButtonAction
* onClick={ () => setCurrentColor( undefined ) }
* >
* { 'Clear' }
* </CircularOptionPicker.ButtonAction>
* }
* />
* );
* };
* ```
*/
function CircularOptionPicker(props) {
const {
actions,
className,
options,
children
} = props;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-circular-option-picker', className)
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-circular-option-picker__swatches"
}, options), children, actions && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-circular-option-picker__custom-clear-wrapper"
}, actions));
}
CircularOptionPicker.Option = Option;
CircularOptionPicker.ButtonAction = ButtonAction;
CircularOptionPicker.DropdownLinkAction = DropdownLinkAction;
/* harmony default export */ var circular_option_picker = (CircularOptionPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/v-stack/hook.js
/**
* Internal dependencies
*/
function useVStack(props) {
const {
expanded = false,
alignment = 'stretch',
...otherProps
} = useContextSystem(props, 'VStack');
const hStackProps = useHStack({
direction: 'column',
expanded,
alignment,
...otherProps
});
return hStackProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/v-stack/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedVStack(props, forwardedRef) {
const vStackProps = useVStack(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...vStackProps,
ref: forwardedRef
});
}
/**
* `VStack` (or Vertical Stack) is a layout component that arranges child
* elements in a vertical line.
*
* `VStack` can render anything inside.
*
* ```jsx
* import {
* __experimentalText as Text,
* __experimentalVStack as VStack,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <VStack>
* <Text>Code</Text>
* <Text>is</Text>
* <Text>Poetry</Text>
* </VStack>
* );
* }
* ```
*/
const VStack = contextConnect(UnconnectedVStack, 'VStack');
/* harmony default export */ var v_stack_component = (VStack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedTruncate(props, forwardedRef) {
const truncateProps = useTruncate(props);
return (0,external_wp_element_namespaceObject.createElement)(component, {
as: "span",
...truncateProps,
ref: forwardedRef
});
}
/**
* `Truncate` is a typography primitive that trims text content.
* For almost all cases, it is recommended that `Text`, `Heading`, or
* `Subheading` is used to render text content. However,`Truncate` is
* available for custom implementations.
*
* ```jsx
* import { __experimentalTruncate as Truncate } from `@wordpress/components`;
*
* function Example() {
* return (
* <Truncate>
* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ex
* neque, vulputate a diam et, luctus convallis lacus. Vestibulum ac
* mollis mi. Morbi id elementum massa.
* </Truncate>
* );
* }
* ```
*/
const component_Truncate = contextConnect(UnconnectedTruncate, 'Truncate');
/* harmony default export */ var truncate_component = (component_Truncate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/heading/hook.js
/**
* Internal dependencies
*/
function useHeading(props) {
const {
as: asProp,
level = 2,
...otherProps
} = useContextSystem(props, 'Heading');
const as = asProp || `h${level}`;
const a11yProps = {};
if (typeof as === 'string' && as[0] !== 'h') {
// If not a semantic `h` element, add a11y props:
a11yProps.role = 'heading';
a11yProps['aria-level'] = typeof level === 'string' ? parseInt(level) : level;
}
const textProps = useText({
color: COLORS.gray[900],
size: getHeadingFontSize(level),
isBlock: true,
weight: config_values.fontWeightHeading,
...otherProps
});
return { ...textProps,
...a11yProps,
as
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/heading/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedHeading(props, forwardedRef) {
const headerProps = useHeading(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...headerProps,
ref: forwardedRef
});
}
/**
* `Heading` renders headings and titles using the library's typography system.
*
* ```jsx
* import { __experimentalHeading as Heading } from "@wordpress/components";
*
* function Example() {
* return <Heading>Code is Poetry</Heading>;
* }
* ```
*/
const Heading = contextConnect(UnconnectedHeading, 'Heading');
/* harmony default export */ var heading_component = (Heading);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-palette/styles.js
function color_palette_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ColorHeading = /*#__PURE__*/createStyled(heading_component, true ? {
target: "ev9wop70"
} : 0)( true ? {
name: "13lxv2o",
styles: "text-transform:uppercase;line-height:24px;font-weight:500;&&&{font-size:11px;margin-bottom:0;}"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const padding = ({
paddingSize = 'small'
}) => {
if (paddingSize === 'none') return;
const paddingValues = {
small: space(2),
medium: space(4)
};
return /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingValues[paddingSize] || paddingValues.small, ";" + ( true ? "" : 0), true ? "" : 0);
};
const DropdownContentWrapperDiv = createStyled("div", true ? {
target: "eovvns30"
} : 0)("margin-left:", space(-2), ";margin-right:", space(-2), ";&:first-of-type{margin-top:", space(-2), ";}&:last-of-type{margin-bottom:", space(-2), ";}", padding, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown/dropdown-content-wrapper.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedDropdownContentWrapper(props, forwardedRef) {
const {
paddingSize = 'small',
...derivedProps
} = useContextSystem(props, 'DropdownContentWrapper');
return (0,external_wp_element_namespaceObject.createElement)(DropdownContentWrapperDiv, { ...derivedProps,
paddingSize: paddingSize,
ref: forwardedRef
});
}
/**
* A convenience wrapper for the `renderContent` when you want to apply
* different padding. (Default is `paddingSize="small"`).
*
* ```jsx
* import {
* Dropdown,
* __experimentalDropdownContentWrapper as DropdownContentWrapper,
* } from '@wordpress/components';
*
* <Dropdown
* renderContent={ () => (
* <DropdownContentWrapper paddingSize="medium">
* My dropdown content
* </DropdownContentWrapper>
* ) }
* />
* ```
*/
const DropdownContentWrapper = contextConnect(UnconnectedDropdownContentWrapper, 'DropdownContentWrapper');
/* harmony default export */ var dropdown_content_wrapper = (DropdownContentWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-palette/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
colord_k([names, a11y]);
const extractColorNameFromCurrentValue = (currentValue, colors = [], showMultiplePalettes = false) => {
if (!currentValue) {
return '';
}
const currentValueIsCssVariable = /^var\(/.test(currentValue);
const normalizedCurrentValue = currentValueIsCssVariable ? currentValue : colord_w(currentValue).toHex(); // Normalize format of `colors` to simplify the following loop
const colorPalettes = showMultiplePalettes ? colors : [{
colors: colors
}];
for (const {
colors: paletteColors
} of colorPalettes) {
for (const {
name: colorName,
color: colorValue
} of paletteColors) {
const normalizedColorValue = currentValueIsCssVariable ? colorValue : colord_w(colorValue).toHex();
if (normalizedCurrentValue === normalizedColorValue) {
return colorName;
}
}
} // translators: shown when the user has picked a custom color (i.e not in the palette of colors).
return (0,external_wp_i18n_namespaceObject.__)('Custom');
};
const showTransparentBackground = currentValue => {
if (typeof currentValue === 'undefined') {
return true;
}
return colord(currentValue).alpha() === 0;
}; // The PaletteObject type has a `colors` property (an array of ColorObject),
// while the ColorObject type has a `color` property (the CSS color value).
const isMultiplePaletteObject = obj => Array.isArray(obj.colors) && !('color' in obj);
const isMultiplePaletteArray = arr => {
return arr.length > 0 && arr.every(colorObj => isMultiplePaletteObject(colorObj));
};
/**
* Transform a CSS variable used as background color into the color value itself.
*
* @param value The color value that may be a CSS variable.
* @param element The element for which to get the computed style.
* @return The background color value computed from a element.
*/
const normalizeColorValue = (value, element) => {
const currentValueIsCssVariable = /^var\(/.test(value !== null && value !== void 0 ? value : '');
if (!currentValueIsCssVariable || element === null) {
return value;
}
const {
ownerDocument
} = element;
const {
defaultView
} = ownerDocument;
const computedBackgroundColor = defaultView?.getComputedStyle(element).backgroundColor;
return computedBackgroundColor ? colord_w(computedBackgroundColor).toHex() : value;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-palette/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
colord_k([names, a11y]);
function SinglePalette({
className,
clearColor,
colors,
onChange,
value,
actions
}) {
const colorOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return colors.map(({
color,
name
}, index) => {
const colordColor = colord_w(color);
const isSelected = value === color;
return (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.Option, {
key: `${color}-${index}`,
isSelected: isSelected,
selectedIconProps: isSelected ? {
fill: colordColor.contrast() > colordColor.contrast('#000') ? '#fff' : '#000'
} : {},
tooltipText: name || // translators: %s: color hex code e.g: "#f00".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Color code: %s'), color),
style: {
backgroundColor: color,
color
},
onClick: isSelected ? clearColor : () => onChange(color, index),
"aria-label": name ? // translators: %s: The name of the color e.g: "vivid red".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Color: %s'), name) : // translators: %s: color hex code e.g: "#f00".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Color code: %s'), color)
});
});
}, [colors, value, onChange, clearColor]);
return (0,external_wp_element_namespaceObject.createElement)(circular_option_picker, {
className: className,
options: colorOptions,
actions: actions
});
}
function MultiplePalettes({
className,
clearColor,
colors,
onChange,
value,
actions,
headingLevel
}) {
if (colors.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3,
className: className
}, colors.map(({
name,
colors: colorPalette
}, index) => {
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 2,
key: index
}, (0,external_wp_element_namespaceObject.createElement)(ColorHeading, {
level: headingLevel
}, name), (0,external_wp_element_namespaceObject.createElement)(SinglePalette, {
clearColor: clearColor,
colors: colorPalette,
onChange: newColor => onChange(newColor, index),
value: value,
actions: colors.length === index + 1 ? actions : null
}));
}));
}
function CustomColorPickerDropdown({
isRenderedInSidebar,
popoverProps: receivedPopoverProps,
...props
}) {
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
shift: true,
...(isRenderedInSidebar ? {
// When in the sidebar: open to the left (stacking),
// leaving the same gap as the parent popover.
placement: 'left-start',
offset: 34
} : {
// Default behavior: open below the anchor
placement: 'bottom',
offset: 8
}),
...receivedPopoverProps
}), [isRenderedInSidebar, receivedPopoverProps]);
return (0,external_wp_element_namespaceObject.createElement)(dropdown, {
contentClassName: "components-color-palette__custom-color-dropdown-content",
popoverProps: popoverProps,
...props
});
}
function UnforwardedColorPalette(props, forwardedRef) {
const {
clearable = true,
colors = [],
disableCustomColors = false,
enableAlpha = false,
onChange,
value,
__experimentalIsRenderedInSidebar = false,
headingLevel = 2,
...otherProps
} = props;
const [normalizedColorValue, setNormalizedColorValue] = (0,external_wp_element_namespaceObject.useState)(value);
const clearColor = (0,external_wp_element_namespaceObject.useCallback)(() => onChange(undefined), [onChange]);
const customColorPaletteCallbackRef = (0,external_wp_element_namespaceObject.useCallback)(node => {
setNormalizedColorValue(normalizeColorValue(value, node));
}, [value]);
const hasMultipleColorOrigins = isMultiplePaletteArray(colors);
const buttonLabelName = (0,external_wp_element_namespaceObject.useMemo)(() => extractColorNameFromCurrentValue(value, colors, hasMultipleColorOrigins), [value, colors, hasMultipleColorOrigins]);
const renderCustomColorPicker = () => (0,external_wp_element_namespaceObject.createElement)(dropdown_content_wrapper, {
paddingSize: "none"
}, (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
color: normalizedColorValue,
onChange: color => onChange(color),
enableAlpha: enableAlpha
}));
const isHex = value?.startsWith('#'); // Leave hex values as-is. Remove the `var()` wrapper from CSS vars.
const displayValue = value?.replace(/^var\((.+)\)$/, '$1');
const customColorAccessibleLabel = !!displayValue ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g: "vivid red". %2$s: The color's hex code, with added hyphens e.g: "#-f-0-0".
(0,external_wp_i18n_namespaceObject.__)('Custom color picker. The currently selected color is called "%1$s" and has a value of "%2$s".'), buttonLabelName, isHex ? displayValue.split('').join('-') : displayValue) : (0,external_wp_i18n_namespaceObject.__)('Custom color picker.');
const paletteCommonProps = {
clearable,
clearColor,
onChange,
value,
actions: !!clearable && (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.ButtonAction, {
onClick: clearColor
}, (0,external_wp_i18n_namespaceObject.__)('Clear')),
headingLevel
};
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3,
ref: forwardedRef,
...otherProps
}, !disableCustomColors && (0,external_wp_element_namespaceObject.createElement)(CustomColorPickerDropdown, {
isRenderedInSidebar: __experimentalIsRenderedInSidebar,
renderContent: renderCustomColorPicker,
renderToggle: ({
isOpen,
onToggle
}) => (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
className: "components-color-palette__custom-color-wrapper",
spacing: 0
}, (0,external_wp_element_namespaceObject.createElement)("button", {
ref: customColorPaletteCallbackRef,
className: "components-color-palette__custom-color-button",
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
"aria-label": customColorAccessibleLabel,
style: {
background: value
}
}), (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
className: "components-color-palette__custom-color-text-wrapper",
spacing: 0.5
}, (0,external_wp_element_namespaceObject.createElement)(truncate_component, {
className: "components-color-palette__custom-color-name"
}, value ? buttonLabelName : 'No color selected'), (0,external_wp_element_namespaceObject.createElement)(truncate_component, {
className: classnames_default()('components-color-palette__custom-color-value', {
'components-color-palette__custom-color-value--is-hex': isHex
})
}, displayValue)))
}), hasMultipleColorOrigins ? (0,external_wp_element_namespaceObject.createElement)(MultiplePalettes, { ...paletteCommonProps,
colors: colors
}) : (0,external_wp_element_namespaceObject.createElement)(SinglePalette, { ...paletteCommonProps,
colors: colors
}));
}
/**
* Allows the user to pick a color from a list of pre-defined color entries.
*
* ```jsx
* import { ColorPalette } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyColorPalette = () => {
* const [ color, setColor ] = useState ( '#f00' )
* const colors = [
* { name: 'red', color: '#f00' },
* { name: 'white', color: '#fff' },
* { name: 'blue', color: '#00f' },
* ];
* return (
* <ColorPalette
* colors={ colors }
* value={ color }
* onChange={ ( color ) => setColor( color ) }
* />
* );
* } );
* ```
*/
const ColorPalette = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedColorPalette);
/* harmony default export */ var color_palette = (ColorPalette);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const isWeb = external_wp_element_namespaceObject.Platform.OS === 'web';
const allUnits = {
px: {
value: 'px',
label: isWeb ? 'px' : (0,external_wp_i18n_namespaceObject.__)('Pixels (px)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Pixels (px)'),
step: 1
},
'%': {
value: '%',
label: isWeb ? '%' : (0,external_wp_i18n_namespaceObject.__)('Percentage (%)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Percent (%)'),
step: 0.1
},
em: {
value: 'em',
label: isWeb ? 'em' : (0,external_wp_i18n_namespaceObject.__)('Relative to parent font size (em)'),
a11yLabel: (0,external_wp_i18n_namespaceObject._x)('ems', 'Relative to parent font size (em)'),
step: 0.01
},
rem: {
value: 'rem',
label: isWeb ? 'rem' : (0,external_wp_i18n_namespaceObject.__)('Relative to root font size (rem)'),
a11yLabel: (0,external_wp_i18n_namespaceObject._x)('rems', 'Relative to root font size (rem)'),
step: 0.01
},
vw: {
value: 'vw',
label: isWeb ? 'vw' : (0,external_wp_i18n_namespaceObject.__)('Viewport width (vw)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport width (vw)'),
step: 0.1
},
vh: {
value: 'vh',
label: isWeb ? 'vh' : (0,external_wp_i18n_namespaceObject.__)('Viewport height (vh)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport height (vh)'),
step: 0.1
},
vmin: {
value: 'vmin',
label: isWeb ? 'vmin' : (0,external_wp_i18n_namespaceObject.__)('Viewport smallest dimension (vmin)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport smallest dimension (vmin)'),
step: 0.1
},
vmax: {
value: 'vmax',
label: isWeb ? 'vmax' : (0,external_wp_i18n_namespaceObject.__)('Viewport largest dimension (vmax)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport largest dimension (vmax)'),
step: 0.1
},
ch: {
value: 'ch',
label: isWeb ? 'ch' : (0,external_wp_i18n_namespaceObject.__)('Width of the zero (0) character (ch)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Width of the zero (0) character (ch)'),
step: 0.01
},
ex: {
value: 'ex',
label: isWeb ? 'ex' : (0,external_wp_i18n_namespaceObject.__)('x-height of the font (ex)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('x-height of the font (ex)'),
step: 0.01
},
cm: {
value: 'cm',
label: isWeb ? 'cm' : (0,external_wp_i18n_namespaceObject.__)('Centimeters (cm)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Centimeters (cm)'),
step: 0.001
},
mm: {
value: 'mm',
label: isWeb ? 'mm' : (0,external_wp_i18n_namespaceObject.__)('Millimeters (mm)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Millimeters (mm)'),
step: 0.1
},
in: {
value: 'in',
label: isWeb ? 'in' : (0,external_wp_i18n_namespaceObject.__)('Inches (in)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Inches (in)'),
step: 0.001
},
pc: {
value: 'pc',
label: isWeb ? 'pc' : (0,external_wp_i18n_namespaceObject.__)('Picas (pc)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Picas (pc)'),
step: 1
},
pt: {
value: 'pt',
label: isWeb ? 'pt' : (0,external_wp_i18n_namespaceObject.__)('Points (pt)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Points (pt)'),
step: 1
}
};
/**
* An array of all available CSS length units.
*/
const ALL_CSS_UNITS = Object.values(allUnits);
/**
* Units of measurements. `a11yLabel` is used by screenreaders.
*/
const CSS_UNITS = [allUnits.px, allUnits['%'], allUnits.em, allUnits.rem, allUnits.vw, allUnits.vh];
const DEFAULT_UNIT = allUnits.px;
/**
* Handles legacy value + unit handling.
* This component use to manage both incoming value and units separately.
*
* Moving forward, ideally the value should be a string that contains both
* the value and unit, example: '10px'
*
* @param rawValue The raw value as a string (may or may not contain the unit)
* @param fallbackUnit The unit used as a fallback, if not unit is detected in the `value`
* @param allowedUnits Units to derive from.
* @return The extracted quantity and unit. The quantity can be `undefined` in case the raw value
* could not be parsed to a number correctly. The unit can be `undefined` in case the unit parse
* from the raw value could not be matched against the list of allowed units.
*/
function getParsedQuantityAndUnit(rawValue, fallbackUnit, allowedUnits) {
const initialValue = fallbackUnit ? `${rawValue !== null && rawValue !== void 0 ? rawValue : ''}${fallbackUnit}` : rawValue;
return parseQuantityAndUnitFromRawValue(initialValue, allowedUnits);
}
/**
* Checks if units are defined.
*
* @param units List of units.
* @return Whether the list actually contains any units.
*/
function hasUnits(units) {
// Although the `isArray` check shouldn't be necessary (given the signature of
// this typed function), it's better to stay on the side of caution, since
// this function may be called from un-typed environments.
return Array.isArray(units) && !!units.length;
}
/**
* Parses a quantity and unit from a raw string value, given a list of allowed
* units and otherwise falling back to the default unit.
*
* @param rawValue The raw value as a string (may or may not contain the unit)
* @param allowedUnits Units to derive from.
* @return The extracted quantity and unit. The quantity can be `undefined` in case the raw value
* could not be parsed to a number correctly. The unit can be `undefined` in case the unit parsed
* from the raw value could not be matched against the list of allowed units.
*/
function parseQuantityAndUnitFromRawValue(rawValue, allowedUnits = ALL_CSS_UNITS) {
let trimmedValue;
let quantityToReturn;
if (typeof rawValue !== 'undefined' || rawValue === null) {
trimmedValue = `${rawValue}`.trim();
const parsedQuantity = parseFloat(trimmedValue);
quantityToReturn = !isFinite(parsedQuantity) ? undefined : parsedQuantity;
}
const unitMatch = trimmedValue?.match(/[\d.\-\+]*\s*(.*)/);
const matchedUnit = unitMatch?.[1]?.toLowerCase();
let unitToReturn;
if (hasUnits(allowedUnits)) {
const match = allowedUnits.find(item => item.value === matchedUnit);
unitToReturn = match?.value;
} else {
unitToReturn = DEFAULT_UNIT.value;
}
return [quantityToReturn, unitToReturn];
}
/**
* Parses quantity and unit from a raw value. Validates parsed value, using fallback
* value if invalid.
*
* @param rawValue The next value.
* @param allowedUnits Units to derive from.
* @param fallbackQuantity The fallback quantity, used in case it's not possible to parse a valid quantity from the raw value.
* @param fallbackUnit The fallback unit, used in case it's not possible to parse a valid unit from the raw value.
* @return The extracted quantity and unit. The quantity can be `undefined` in case the raw value
* could not be parsed to a number correctly, and the `fallbackQuantity` was also `undefined`. The
* unit can be `undefined` only if the unit parsed from the raw value could not be matched against
* the list of allowed units, the `fallbackQuantity` is also `undefined` and the list of
* `allowedUnits` is passed empty.
*/
function getValidParsedQuantityAndUnit(rawValue, allowedUnits, fallbackQuantity, fallbackUnit) {
const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(rawValue, allowedUnits); // The parsed value from `parseQuantityAndUnitFromRawValue` should now be
// either a real number or undefined. If undefined, use the fallback value.
const quantityToReturn = parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : fallbackQuantity; // If no unit is parsed from the raw value, or if the fallback unit is not
// defined, use the first value from the list of allowed units as fallback.
let unitToReturn = parsedUnit || fallbackUnit;
if (!unitToReturn && hasUnits(allowedUnits)) {
unitToReturn = allowedUnits[0].value;
}
return [quantityToReturn, unitToReturn];
}
/**
* Takes a unit value and finds the matching accessibility label for the
* unit abbreviation.
*
* @param unit Unit value (example: `px`)
* @return a11y label for the unit abbreviation
*/
function getAccessibleLabelForUnit(unit) {
const match = ALL_CSS_UNITS.find(item => item.value === unit);
return match?.a11yLabel ? match?.a11yLabel : match?.value;
}
/**
* Filters available units based on values defined a list of allowed unit values.
*
* @param allowedUnitValues Collection of allowed unit value strings.
* @param availableUnits Collection of available unit objects.
* @return Filtered units.
*/
function filterUnitsWithSettings(allowedUnitValues = [], availableUnits) {
// Although the `isArray` check shouldn't be necessary (given the signature of
// this typed function), it's better to stay on the side of caution, since
// this function may be called from un-typed environments.
return Array.isArray(availableUnits) ? availableUnits.filter(unit => allowedUnitValues.includes(unit.value)) : [];
}
/**
* Custom hook to retrieve and consolidate units setting from add_theme_support().
* TODO: ideally this hook shouldn't be needed
* https://github.com/WordPress/gutenberg/pull/31822#discussion_r633280823
*
* @param args An object containing units, settingPath & defaultUnits.
* @param args.units Collection of all potentially available units.
* @param args.availableUnits Collection of unit value strings for filtering available units.
* @param args.defaultValues Collection of default values for defined units. Example: `{ px: 350, em: 15 }`.
*
* @return Filtered list of units, with their default values updated following the `defaultValues`
* argument's property.
*/
const useCustomUnits = ({
units = ALL_CSS_UNITS,
availableUnits = [],
defaultValues
}) => {
const customUnitsToReturn = filterUnitsWithSettings(availableUnits, units);
if (defaultValues) {
customUnitsToReturn.forEach((unit, i) => {
if (defaultValues[unit.value]) {
const [parsedDefaultValue] = parseQuantityAndUnitFromRawValue(defaultValues[unit.value]);
customUnitsToReturn[i].default = parsedDefaultValue;
}
});
}
return customUnitsToReturn;
};
/**
* Get available units with the unit for the currently selected value
* prepended if it is not available in the list of units.
*
* This is useful to ensure that the current value's unit is always
* accurately displayed in the UI, even if the intention is to hide
* the availability of that unit.
*
* @param rawValue Selected value to parse.
* @param legacyUnit Legacy unit value, if rawValue needs it appended.
* @param units List of available units.
*
* @return A collection of units containing the unit for the current value.
*/
function getUnitsWithCurrentUnit(rawValue, legacyUnit, units = ALL_CSS_UNITS) {
const unitsToReturn = Array.isArray(units) ? [...units] : [];
const [, currentUnit] = getParsedQuantityAndUnit(rawValue, legacyUnit, ALL_CSS_UNITS);
if (currentUnit && !unitsToReturn.some(unit => unit.value === currentUnit)) {
if (allUnits[currentUnit]) {
unitsToReturn.unshift(allUnits[currentUnit]);
}
}
return unitsToReturn;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-dropdown/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderControlDropdown(props) {
const {
border,
className,
colors = [],
enableAlpha = false,
enableStyle = true,
onChange,
previousStyleSelection,
size = 'default',
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderControlDropdown');
const [widthValue] = parseQuantityAndUnitFromRawValue(border?.width);
const hasZeroWidth = widthValue === 0;
const onColorChange = color => {
const style = border?.style === 'none' ? previousStyleSelection : border?.style;
const width = hasZeroWidth && !!color ? '1px' : border?.width;
onChange({
color,
style,
width
});
};
const onStyleChange = style => {
const width = hasZeroWidth && !!style ? '1px' : border?.width;
onChange({ ...border,
style,
width
});
};
const onReset = () => {
onChange({ ...border,
color: undefined,
style: undefined
});
}; // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlDropdown(size), className);
}, [className, cx, size]);
const indicatorClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderColorIndicator);
}, [cx]);
const indicatorWrapperClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(colorIndicatorWrapper(border, size));
}, [border, cx, size]);
const popoverControlsClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlPopoverControls);
}, [cx]);
const popoverContentClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlPopoverContent);
}, [cx]);
const resetButtonClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(resetButton);
}, [cx]);
return { ...otherProps,
border,
className: classes,
colors,
enableAlpha,
enableStyle,
indicatorClassName,
indicatorWrapperClassName,
onColorChange,
onStyleChange,
onReset,
popoverContentClassName,
popoverControlsClassName,
resetButtonClassName,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-dropdown/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getAriaLabelColorValue = colorValue => {
const isHex = colorValue.startsWith('#'); // Leave hex values as-is. Remove the `var()` wrapper from CSS vars.
const displayValue = colorValue.replace(/^var\((.+)\)$/, '$1');
return isHex ? displayValue.split('').join('-') : displayValue;
};
const getColorObject = (colorValue, colors) => {
if (!colorValue || !colors) {
return;
}
if (isMultiplePaletteArray(colors)) {
// Multiple origins
let matchedColor;
colors.some(origin => origin.colors.some(color => {
if (color.color === colorValue) {
matchedColor = color;
return true;
}
return false;
}));
return matchedColor;
} // Single origin
return colors.find(color => color.color === colorValue);
};
const getToggleAriaLabel = (colorValue, colorObject, style, isStyleEnabled) => {
if (isStyleEnabled) {
if (colorObject) {
const ariaLabelValue = getAriaLabelColorValue(colorObject.color);
return style ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g. "vivid red". %2$s: The color's hex code, with added hyphens e.g: "#-f-0-0". %3$s: The current border style selection e.g. "solid".
'Border color and style picker. The currently selected color is called "%1$s" and has a value of "%2$s". The currently selected style is "%3$s".', colorObject.name, ariaLabelValue, style) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g. "vivid red". %2$s: The color's hex code, with added hyphens e.g: "#-f-0-0".
'Border color and style picker. The currently selected color is called "%1$s" and has a value of "%2$s".', colorObject.name, ariaLabelValue);
}
if (colorValue) {
const ariaLabelValue = getAriaLabelColorValue(colorValue);
return style ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The color's hex code, with added hyphens e.g: "#-f-0-0". %2$s: The current border style selection e.g. "solid".
'Border color and style picker. The currently selected color has a value of "%1$s". The currently selected style is "%2$s".', ariaLabelValue, style) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The color's hex code, with added hyphens e.g: "#-f-0-0".
'Border color and style picker. The currently selected color has a value of "%1$s".', ariaLabelValue);
}
return (0,external_wp_i18n_namespaceObject.__)('Border color and style picker.');
}
if (colorObject) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g. "vivid red". %2$s: The color's hex code, with added hyphens e.g: "#-f-0-0".
'Border color picker. The currently selected color is called "%1$s" and has a value of "%2$s".', colorObject.name, getAriaLabelColorValue(colorObject.color));
}
if (colorValue) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The color's hex code, with added hyphens e.g: "#-f-0-0".
'Border color picker. The currently selected color has a value of "%1$s".', getAriaLabelColorValue(colorValue));
}
return (0,external_wp_i18n_namespaceObject.__)('Border color picker.');
};
const BorderControlDropdown = (props, forwardedRef) => {
const {
__experimentalIsRenderedInSidebar,
border,
colors,
disableCustomColors,
enableAlpha,
enableStyle,
indicatorClassName,
indicatorWrapperClassName,
onReset,
onColorChange,
onStyleChange,
popoverContentClassName,
popoverControlsClassName,
resetButtonClassName,
showDropdownHeader,
__unstablePopoverProps,
...otherProps
} = useBorderControlDropdown(props);
const {
color,
style
} = border || {};
const colorObject = getColorObject(color, colors);
const toggleAriaLabel = getToggleAriaLabel(color, colorObject, style, enableStyle);
const showResetButton = color || style && style !== 'none';
const dropdownPosition = __experimentalIsRenderedInSidebar ? 'bottom left' : undefined;
const renderToggle = ({
onToggle
}) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: onToggle,
variant: "tertiary",
"aria-label": toggleAriaLabel,
tooltipPosition: dropdownPosition,
label: (0,external_wp_i18n_namespaceObject.__)('Border color and style picker'),
showTooltip: true
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: indicatorWrapperClassName
}, (0,external_wp_element_namespaceObject.createElement)(color_indicator, {
className: indicatorClassName,
colorValue: color
})));
const renderContent = ({
onClose
}) => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(dropdown_content_wrapper, {
paddingSize: "medium"
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
className: popoverControlsClassName,
spacing: 6
}, showDropdownHeader ? (0,external_wp_element_namespaceObject.createElement)(h_stack_component, null, (0,external_wp_element_namespaceObject.createElement)(StyledLabel, null, (0,external_wp_i18n_namespaceObject.__)('Border color')), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isSmall: true,
label: (0,external_wp_i18n_namespaceObject.__)('Close border color'),
icon: close_small,
onClick: onClose
})) : undefined, (0,external_wp_element_namespaceObject.createElement)(color_palette, {
className: popoverContentClassName,
value: color,
onChange: onColorChange,
colors,
disableCustomColors,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
clearable: false,
enableAlpha: enableAlpha
}), enableStyle && (0,external_wp_element_namespaceObject.createElement)(border_control_style_picker_component, {
label: (0,external_wp_i18n_namespaceObject.__)('Style'),
value: style,
onChange: onStyleChange
}))), showResetButton && (0,external_wp_element_namespaceObject.createElement)(dropdown_content_wrapper, {
paddingSize: "none"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: resetButtonClassName,
variant: "tertiary",
onClick: () => {
onReset();
onClose();
}
}, (0,external_wp_i18n_namespaceObject.__)('Reset to default'))));
return (0,external_wp_element_namespaceObject.createElement)(dropdown, {
renderToggle: renderToggle,
renderContent: renderContent,
popoverProps: { ...__unstablePopoverProps
},
...otherProps,
ref: forwardedRef
});
};
const ConnectedBorderControlDropdown = contextConnect(BorderControlDropdown, 'BorderControlDropdown');
/* harmony default export */ var border_control_dropdown_component = (ConnectedBorderControlDropdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/unit-select-control.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnitSelectControl({
className,
isUnitSelectTabbable: isTabbable = true,
onChange,
size = 'default',
unit = 'px',
units = CSS_UNITS,
...props
}, ref) {
if (!hasUnits(units) || units?.length === 1) {
return (0,external_wp_element_namespaceObject.createElement)(UnitLabel, {
className: "components-unit-control__unit-label",
selectSize: size
}, unit);
}
const handleOnChange = event => {
const {
value: unitValue
} = event.target;
const data = units.find(option => option.value === unitValue);
onChange?.(unitValue, {
event,
data
});
};
const classes = classnames_default()('components-unit-control__select', className);
return (0,external_wp_element_namespaceObject.createElement)(UnitSelect, {
ref: ref,
className: classes,
onChange: handleOnChange,
selectSize: size,
tabIndex: isTabbable ? undefined : -1,
value: unit,
...props
}, units.map(option => (0,external_wp_element_namespaceObject.createElement)("option", {
value: option.value,
key: option.value
}, option.label)));
}
/* harmony default export */ var unit_select_control = ((0,external_wp_element_namespaceObject.forwardRef)(UnitSelectControl));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedUnitControl(unitControlProps, forwardedRef) {
const {
__unstableStateReducer,
autoComplete = 'off',
// @ts-expect-error Ensure that children is omitted from restProps
children,
className,
disabled = false,
disableUnits = false,
isPressEnterToChange = false,
isResetValueOnUnitChange = false,
isUnitSelectTabbable = true,
label,
onChange: onChangeProp,
onUnitChange,
size = 'default',
unit: unitProp,
units: unitsProp = CSS_UNITS,
value: valueProp,
onFocus: onFocusProp,
...props
} = unitControlProps;
if ('unit' in unitControlProps) {
external_wp_deprecated_default()('UnitControl unit prop', {
since: '5.6',
hint: 'The unit should be provided within the `value` prop.',
version: '6.2'
});
} // The `value` prop, in theory, should not be `null`, but the following line
// ensures it fallback to `undefined` in case a consumer of `UnitControl`
// still passes `null` as a `value`.
const nonNullValueProp = valueProp !== null && valueProp !== void 0 ? valueProp : undefined;
const [units, reFirstCharacterOfUnits] = (0,external_wp_element_namespaceObject.useMemo)(() => {
const list = getUnitsWithCurrentUnit(nonNullValueProp, unitProp, unitsProp);
const [{
value: firstUnitValue = ''
} = {}, ...rest] = list;
const firstCharacters = rest.reduce((carry, {
value
}) => {
const first = escapeRegExp(value?.substring(0, 1) || '');
return carry.includes(first) ? carry : `${carry}|${first}`;
}, escapeRegExp(firstUnitValue.substring(0, 1)));
return [list, new RegExp(`^(?:${firstCharacters})$`, 'i')];
}, [nonNullValueProp, unitProp, unitsProp]);
const [parsedQuantity, parsedUnit] = getParsedQuantityAndUnit(nonNullValueProp, unitProp, units);
const [unit, setUnit] = use_controlled_state(units.length === 1 ? units[0].value : unitProp, {
initial: parsedUnit,
fallback: ''
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (parsedUnit !== undefined) {
setUnit(parsedUnit);
}
}, [parsedUnit, setUnit]);
const classes = classnames_default()('components-unit-control', // This class is added for legacy purposes to maintain it on the outer
// wrapper. See: https://github.com/WordPress/gutenberg/pull/45139
'components-unit-control-wrapper', className);
const handleOnQuantityChange = (nextQuantityValue, changeProps) => {
if (nextQuantityValue === '' || typeof nextQuantityValue === 'undefined' || nextQuantityValue === null) {
onChangeProp?.('', changeProps);
return;
}
/*
* Customizing the onChange callback.
* This allows as to broadcast a combined value+unit to onChange.
*/
const onChangeValue = getValidParsedQuantityAndUnit(nextQuantityValue, units, parsedQuantity, unit).join('');
onChangeProp?.(onChangeValue, changeProps);
};
const handleOnUnitChange = (nextUnitValue, changeProps) => {
const {
data
} = changeProps;
let nextValue = `${parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : ''}${nextUnitValue}`;
if (isResetValueOnUnitChange && data?.default !== undefined) {
nextValue = `${data.default}${nextUnitValue}`;
}
onChangeProp?.(nextValue, changeProps);
onUnitChange?.(nextUnitValue, changeProps);
setUnit(nextUnitValue);
};
let handleOnKeyDown;
if (!disableUnits && isUnitSelectTabbable && units.length) {
handleOnKeyDown = event => {
props.onKeyDown?.(event); // Unless the meta key was pressed (to avoid interfering with
// shortcuts, e.g. pastes), moves focus to the unit select if a key
// matches the first character of a unit.
if (!event.metaKey && reFirstCharacterOfUnits.test(event.key)) refInputSuffix.current?.focus();
};
}
const refInputSuffix = (0,external_wp_element_namespaceObject.useRef)(null);
const inputSuffix = !disableUnits ? (0,external_wp_element_namespaceObject.createElement)(unit_select_control, {
ref: refInputSuffix,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Select unit'),
disabled: disabled,
isUnitSelectTabbable: isUnitSelectTabbable,
onChange: handleOnUnitChange,
size: size,
unit: unit,
units: units,
onFocus: onFocusProp,
onBlur: unitControlProps.onBlur
}) : null;
let step = props.step;
/*
* If no step prop has been passed, lookup the active unit and
* try to get step from `units`, or default to a value of `1`
*/
if (!step && units) {
var _activeUnit$step;
const activeUnit = units.find(option => option.value === unit);
step = (_activeUnit$step = activeUnit?.step) !== null && _activeUnit$step !== void 0 ? _activeUnit$step : 1;
}
return (0,external_wp_element_namespaceObject.createElement)(ValueInput, { ...props,
autoComplete: autoComplete,
className: classes,
disabled: disabled,
spinControls: "none",
isPressEnterToChange: isPressEnterToChange,
label: label,
onKeyDown: handleOnKeyDown,
onChange: handleOnQuantityChange,
ref: forwardedRef,
size: size,
suffix: inputSuffix,
type: isPressEnterToChange ? 'text' : 'number',
value: parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : '',
step: step,
onFocus: onFocusProp,
__unstableStateReducer: __unstableStateReducer
});
}
/**
* `UnitControl` allows the user to set a numeric quantity as well as a unit (e.g. `px`).
*
*
* @example
* ```jsx
* import { __experimentalUnitControl as UnitControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ value, setValue ] = useState( '10px' );
*
* return <UnitControl onChange={ setValue } value={ value } />;
* };
* ```
*/
const UnitControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedUnitControl);
/* harmony default export */ var unit_control = (UnitControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const sanitizeBorder = border => {
const hasNoWidth = border?.width === undefined || border.width === '';
const hasNoColor = border?.color === undefined; // If width and color are undefined, unset any style selection as well.
if (hasNoWidth && hasNoColor) {
return undefined;
}
return border;
};
function useBorderControl(props) {
const {
className,
colors = [],
isCompact,
onChange,
enableAlpha = true,
enableStyle = true,
shouldSanitizeBorder = true,
size = 'default',
value: border,
width,
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderControl');
const [widthValue, originalWidthUnit] = parseQuantityAndUnitFromRawValue(border?.width);
const widthUnit = originalWidthUnit || 'px';
const hadPreviousZeroWidth = widthValue === 0;
const [colorSelection, setColorSelection] = (0,external_wp_element_namespaceObject.useState)();
const [styleSelection, setStyleSelection] = (0,external_wp_element_namespaceObject.useState)();
const onBorderChange = (0,external_wp_element_namespaceObject.useCallback)(newBorder => {
if (shouldSanitizeBorder) {
return onChange(sanitizeBorder(newBorder));
}
onChange(newBorder);
}, [onChange, shouldSanitizeBorder]);
const onWidthChange = (0,external_wp_element_namespaceObject.useCallback)(newWidth => {
const newWidthValue = newWidth === '' ? undefined : newWidth;
const [parsedValue] = parseQuantityAndUnitFromRawValue(newWidth);
const hasZeroWidth = parsedValue === 0;
const updatedBorder = { ...border,
width: newWidthValue
}; // Setting the border width explicitly to zero will also set the
// border style to `none` and clear the border color.
if (hasZeroWidth && !hadPreviousZeroWidth) {
// Before clearing the color and style selections, keep track of
// the current selections so they can be restored when the width
// changes to a non-zero value.
setColorSelection(border?.color);
setStyleSelection(border?.style); // Clear the color and style border properties.
updatedBorder.color = undefined;
updatedBorder.style = 'none';
} // Selection has changed from zero border width to non-zero width.
if (!hasZeroWidth && hadPreviousZeroWidth) {
// Restore previous border color and style selections if width
// is now not zero.
if (updatedBorder.color === undefined) {
updatedBorder.color = colorSelection;
}
if (updatedBorder.style === 'none') {
updatedBorder.style = styleSelection;
}
}
onBorderChange(updatedBorder);
}, [border, hadPreviousZeroWidth, colorSelection, styleSelection, onBorderChange]);
const onSliderChange = (0,external_wp_element_namespaceObject.useCallback)(value => {
onWidthChange(`${value}${widthUnit}`);
}, [onWidthChange, widthUnit]); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControl, className);
}, [className, cx]);
let wrapperWidth = width;
if (isCompact) {
// Widths below represent the minimum usable width for compact controls.
// Taller controls contain greater internal padding, thus greater width.
wrapperWidth = size === '__unstable-large' ? '116px' : '90px';
}
const innerWrapperClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
const widthStyle = !!wrapperWidth && styles_wrapperWidth;
const heightStyle = wrapperHeight(size);
return cx(innerWrapper(), widthStyle, heightStyle);
}, [wrapperWidth, cx, size]);
const sliderClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderSlider());
}, [cx]);
return { ...otherProps,
className: classes,
colors,
enableAlpha,
enableStyle,
innerWrapperClassName,
inputWidth: wrapperWidth,
onBorderChange,
onSliderChange,
onWidthChange,
previousStyleSelection: styleSelection,
sliderClassName,
value: border,
widthUnit,
widthValue,
size,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderLabel = props => {
const {
label,
hideLabelFromVision
} = props;
if (!label) {
return null;
}
return hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "legend"
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, {
as: "legend"
}, label);
};
const UnconnectedBorderControl = (props, forwardedRef) => {
const {
colors,
disableCustomColors,
disableUnits,
enableAlpha,
enableStyle,
hideLabelFromVision,
innerWrapperClassName,
inputWidth,
label,
onBorderChange,
onSliderChange,
onWidthChange,
placeholder,
__unstablePopoverProps,
previousStyleSelection,
showDropdownHeader,
size,
sliderClassName,
value: border,
widthUnit,
widthValue,
withSlider,
__experimentalIsRenderedInSidebar,
...otherProps
} = useBorderControl(props);
return (0,external_wp_element_namespaceObject.createElement)(component, {
as: "fieldset",
...otherProps,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(BorderLabel, {
label: label,
hideLabelFromVision: hideLabelFromVision
}), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
spacing: 4,
className: innerWrapperClassName
}, (0,external_wp_element_namespaceObject.createElement)(unit_control, {
prefix: (0,external_wp_element_namespaceObject.createElement)(border_control_dropdown_component, {
border: border,
colors: colors,
__unstablePopoverProps: __unstablePopoverProps,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
enableStyle: enableStyle,
onChange: onBorderChange,
previousStyleSelection: previousStyleSelection,
showDropdownHeader: showDropdownHeader,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
size: size
}),
label: (0,external_wp_i18n_namespaceObject.__)('Border width'),
hideLabelFromVision: true,
min: 0,
onChange: onWidthChange,
value: border?.width || '',
placeholder: placeholder,
disableUnits: disableUnits,
__unstableInputWidth: inputWidth,
size: size
}), withSlider && (0,external_wp_element_namespaceObject.createElement)(range_control, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Border width'),
hideLabelFromVision: true,
className: sliderClassName,
initialPosition: 0,
max: 100,
min: 0,
onChange: onSliderChange,
step: ['px', '%'].includes(widthUnit) ? 1 : 0.1,
value: widthValue || undefined,
withInputField: false
})));
};
/**
* The `BorderControl` brings together internal sub-components which allow users to
* set the various properties of a border. The first sub-component, a
* `BorderDropdown` contains options representing border color and style. The
* border width is controlled via a `UnitControl` and an optional `RangeControl`.
*
* Border radius is not covered by this control as it may be desired separate to
* color, style, and width. For example, the border radius may be absorbed under
* a "shape" abstraction.
*
* ```jsx
* import { __experimentalBorderControl as BorderControl } from '@wordpress/components';
* import { __ } from '@wordpress/i18n';
*
* const colors = [
* { name: 'Blue 20', color: '#72aee6' },
* // ...
* ];
*
* const MyBorderControl = () => {
* const [ border, setBorder ] = useState();
* const onChange = ( newBorder ) => setBorder( newBorder );
*
* return (
* <BorderControl
* colors={ colors }
* label={ __( 'Border' ) }
* onChange={ onChange }
* value={ border }
* />
* );
* };
* ```
*/
const BorderControl = contextConnect(UnconnectedBorderControl, 'BorderControl');
/* harmony default export */ var border_control_component = (BorderControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/grid/utils.js
/**
* External dependencies
*/
const utils_ALIGNMENTS = {
bottom: {
alignItems: 'flex-end',
justifyContent: 'center'
},
bottomLeft: {
alignItems: 'flex-start',
justifyContent: 'flex-end'
},
bottomRight: {
alignItems: 'flex-end',
justifyContent: 'flex-end'
},
center: {
alignItems: 'center',
justifyContent: 'center'
},
spaced: {
alignItems: 'center',
justifyContent: 'space-between'
},
left: {
alignItems: 'center',
justifyContent: 'flex-start'
},
right: {
alignItems: 'center',
justifyContent: 'flex-end'
},
stretch: {
alignItems: 'stretch'
},
top: {
alignItems: 'flex-start',
justifyContent: 'center'
},
topLeft: {
alignItems: 'flex-start',
justifyContent: 'flex-start'
},
topRight: {
alignItems: 'flex-start',
justifyContent: 'flex-end'
}
};
function utils_getAlignmentProps(alignment) {
const alignmentProps = alignment ? utils_ALIGNMENTS[alignment] : {};
return alignmentProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/grid/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useGrid(props) {
const {
align,
alignment,
className,
columnGap,
columns = 2,
gap = 3,
isInline = false,
justify,
rowGap,
rows,
templateColumns,
templateRows,
...otherProps
} = useContextSystem(props, 'Grid');
const columnsAsArray = Array.isArray(columns) ? columns : [columns];
const column = useResponsiveValue(columnsAsArray);
const rowsAsArray = Array.isArray(rows) ? rows : [rows];
const row = useResponsiveValue(rowsAsArray);
const gridTemplateColumns = templateColumns || !!columns && `repeat( ${column}, 1fr )`;
const gridTemplateRows = templateRows || !!rows && `repeat( ${row}, 1fr )`;
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const alignmentProps = utils_getAlignmentProps(alignment);
const gridClasses = /*#__PURE__*/emotion_react_browser_esm_css({
alignItems: align,
display: isInline ? 'inline-grid' : 'grid',
gap: `calc( ${config_values.gridBase} * ${gap} )`,
gridTemplateColumns: gridTemplateColumns || undefined,
gridTemplateRows: gridTemplateRows || undefined,
gridRowGap: rowGap,
gridColumnGap: columnGap,
justifyContent: justify,
verticalAlign: isInline ? 'middle' : undefined,
...alignmentProps
}, true ? "" : 0, true ? "" : 0);
return cx(gridClasses, className);
}, [align, alignment, className, columnGap, cx, gap, gridTemplateColumns, gridTemplateRows, isInline, justify, rowGap]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/grid/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedGrid(props, forwardedRef) {
const gridProps = useGrid(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...gridProps,
ref: forwardedRef
});
}
/**
* `Grid` is a primitive layout component that can arrange content in a grid configuration.
*
* ```jsx
* import {
* __experimentalGrid as Grid,
* __experimentalText as Text
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <Grid columns={ 3 }>
* <Text>Code</Text>
* <Text>is</Text>
* <Text>Poetry</Text>
* </Grid>
* );
* }
* ```
*/
const Grid = contextConnect(UnconnectedGrid, 'Grid');
/* harmony default export */ var grid_component = (Grid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-split-controls/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControlSplitControls(props) {
const {
className,
colors = [],
enableAlpha = false,
enableStyle = true,
size = 'default',
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderBoxControlSplitControls'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControlSplitControls(size), className);
}, [cx, className, size]);
const centeredClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(centeredBorderControl, className);
}, [cx, className]);
const rightAlignedClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(rightBorderControl(), className);
}, [cx, className]);
return { ...otherProps,
centeredClassName,
className: classes,
colors,
enableAlpha,
enableStyle,
rightAlignedClassName,
size,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-split-controls/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderBoxControlSplitControls = (props, forwardedRef) => {
const {
centeredClassName,
colors,
disableCustomColors,
enableAlpha,
enableStyle,
onChange,
popoverPlacement,
popoverOffset,
rightAlignedClassName,
size = 'default',
value,
__experimentalIsRenderedInSidebar,
...otherProps
} = useBorderBoxControlSplitControls(props); // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => popoverPlacement ? {
placement: popoverPlacement,
offset: popoverOffset,
anchor: popoverAnchor,
shift: true
} : undefined, [popoverPlacement, popoverOffset, popoverAnchor]);
const sharedBorderControlProps = {
colors,
disableCustomColors,
enableAlpha,
enableStyle,
isCompact: true,
__experimentalIsRenderedInSidebar,
size
};
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([setPopoverAnchor, forwardedRef]);
return (0,external_wp_element_namespaceObject.createElement)(grid_component, { ...otherProps,
ref: mergedRef,
gap: 4
}, (0,external_wp_element_namespaceObject.createElement)(border_box_control_visualizer_component, {
value: value,
size: size
}), (0,external_wp_element_namespaceObject.createElement)(border_control_component, {
className: centeredClassName,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Top border'),
onChange: newBorder => onChange(newBorder, 'top'),
__unstablePopoverProps: popoverProps,
value: value?.top,
...sharedBorderControlProps
}), (0,external_wp_element_namespaceObject.createElement)(border_control_component, {
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Left border'),
onChange: newBorder => onChange(newBorder, 'left'),
__unstablePopoverProps: popoverProps,
value: value?.left,
...sharedBorderControlProps
}), (0,external_wp_element_namespaceObject.createElement)(border_control_component, {
className: rightAlignedClassName,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Right border'),
onChange: newBorder => onChange(newBorder, 'right'),
__unstablePopoverProps: popoverProps,
value: value?.right,
...sharedBorderControlProps
}), (0,external_wp_element_namespaceObject.createElement)(border_control_component, {
className: centeredClassName,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Bottom border'),
onChange: newBorder => onChange(newBorder, 'bottom'),
__unstablePopoverProps: popoverProps,
value: value?.bottom,
...sharedBorderControlProps
}));
};
const ConnectedBorderBoxControlSplitControls = contextConnect(BorderBoxControlSplitControls, 'BorderBoxControlSplitControls');
/* harmony default export */ var border_box_control_split_controls_component = (ConnectedBorderBoxControlSplitControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/unit-values.js
const UNITED_VALUE_REGEX = /^([\d.\-+]*)\s*(fr|cm|mm|Q|in|pc|pt|px|em|ex|ch|rem|lh|vw|vh|vmin|vmax|%|cap|ic|rlh|vi|vb|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?$/;
/**
* Parses a number and unit from a value.
*
* @param toParse Value to parse
*
* @return The extracted number and unit.
*/
function parseCSSUnitValue(toParse) {
const value = toParse.trim();
const matched = value.match(UNITED_VALUE_REGEX);
if (!matched) {
return [undefined, undefined];
}
const [, num, unit] = matched;
let numParsed = parseFloat(num);
numParsed = Number.isNaN(numParsed) ? undefined : numParsed;
return [numParsed, unit];
}
/**
* Combines a value and a unit into a unit value.
*
* @param value
* @param unit
*
* @return The unit value.
*/
function createCSSUnitValue(value, unit) {
return `${value}${unit}`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const sides = ['top', 'right', 'bottom', 'left'];
const borderProps = ['color', 'style', 'width'];
const isEmptyBorder = border => {
if (!border) {
return true;
}
return !borderProps.some(prop => border[prop] !== undefined);
};
const isDefinedBorder = border => {
// No border, no worries :)
if (!border) {
return false;
} // If we have individual borders per side within the border object we
// need to check whether any of those side borders have been set.
if (hasSplitBorders(border)) {
const allSidesEmpty = sides.every(side => isEmptyBorder(border[side]));
return !allSidesEmpty;
} // If we have a top-level border only, check if that is empty. e.g.
// { color: undefined, style: undefined, width: undefined }
// Border radius can still be set within the border object as it is
// handled separately.
return !isEmptyBorder(border);
};
const isCompleteBorder = border => {
if (!border) {
return false;
}
return borderProps.every(prop => border[prop] !== undefined);
};
const hasSplitBorders = (border = {}) => {
return Object.keys(border).some(side => sides.indexOf(side) !== -1);
};
const hasMixedBorders = borders => {
if (!hasSplitBorders(borders)) {
return false;
}
const shorthandBorders = sides.map(side => getShorthandBorderStyle(borders?.[side]));
return !shorthandBorders.every(border => border === shorthandBorders[0]);
};
const getSplitBorders = border => {
if (!border || isEmptyBorder(border)) {
return undefined;
}
return {
top: border,
right: border,
bottom: border,
left: border
};
};
const getBorderDiff = (original, updated) => {
const diff = {};
if (original.color !== updated.color) {
diff.color = updated.color;
}
if (original.style !== updated.style) {
diff.style = updated.style;
}
if (original.width !== updated.width) {
diff.width = updated.width;
}
return diff;
};
const getCommonBorder = borders => {
if (!borders) {
return undefined;
}
const colors = [];
const styles = [];
const widths = [];
sides.forEach(side => {
colors.push(borders[side]?.color);
styles.push(borders[side]?.style);
widths.push(borders[side]?.width);
});
const allColorsMatch = colors.every(value => value === colors[0]);
const allStylesMatch = styles.every(value => value === styles[0]);
const allWidthsMatch = widths.every(value => value === widths[0]);
return {
color: allColorsMatch ? colors[0] : undefined,
style: allStylesMatch ? styles[0] : undefined,
width: allWidthsMatch ? widths[0] : getMostCommonUnit(widths)
};
};
const getShorthandBorderStyle = (border, fallbackBorder) => {
if (isEmptyBorder(border)) {
return fallbackBorder;
}
const {
color: fallbackColor,
style: fallbackStyle,
width: fallbackWidth
} = fallbackBorder || {};
const {
color = fallbackColor,
style = fallbackStyle,
width = fallbackWidth
} = border;
const hasVisibleBorder = !!width && width !== '0' || !!color;
const borderStyle = hasVisibleBorder ? style || 'solid' : style;
return [width, borderStyle, color].filter(Boolean).join(' ');
};
const getMostCommonUnit = values => {
// Collect all the CSS units.
const units = values.map(value => value === undefined ? undefined : parseCSSUnitValue(`${value}`)[1]); // Return the most common unit out of only the defined CSS units.
const filteredUnits = units.filter(value => value !== undefined);
return mode(filteredUnits);
};
/**
* Finds the mode value out of the array passed favouring the first value
* as a tiebreaker.
*
* @param values Values to determine the mode from.
*
* @return The mode value.
*/
function mode(values) {
if (values.length === 0) {
return undefined;
}
const map = {};
let maxCount = 0;
let currentMode;
values.forEach(value => {
map[value] = map[value] === undefined ? 1 : map[value] + 1;
if (map[value] > maxCount) {
currentMode = value;
maxCount = map[value];
}
});
return currentMode;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControl(props) {
const {
className,
colors = [],
onChange,
enableAlpha = false,
enableStyle = true,
size = 'default',
value,
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderBoxControl');
const mixedBorders = hasMixedBorders(value);
const splitBorders = hasSplitBorders(value);
const linkedValue = splitBorders ? getCommonBorder(value) : value;
const splitValue = splitBorders ? value : getSplitBorders(value); // If no numeric width value is set, the unit select will be disabled.
const hasWidthValue = !isNaN(parseFloat(`${linkedValue?.width}`));
const [isLinked, setIsLinked] = (0,external_wp_element_namespaceObject.useState)(!mixedBorders);
const toggleLinked = () => setIsLinked(!isLinked);
const onLinkedChange = newBorder => {
if (!newBorder) {
return onChange(undefined);
} // If we have all props defined on the new border apply it.
if (!mixedBorders || isCompleteBorder(newBorder)) {
return onChange(isEmptyBorder(newBorder) ? undefined : newBorder);
} // If we had mixed borders we might have had some shared border props
// that we need to maintain. For example; we could have mixed borders
// with all the same color but different widths. Then from the linked
// control we change the color. We should keep the separate widths.
const changes = getBorderDiff(linkedValue, newBorder);
const updatedBorders = {
top: { ...value?.top,
...changes
},
right: { ...value?.right,
...changes
},
bottom: { ...value?.bottom,
...changes
},
left: { ...value?.left,
...changes
}
};
if (hasMixedBorders(updatedBorders)) {
return onChange(updatedBorders);
}
const filteredResult = isEmptyBorder(updatedBorders.top) ? undefined : updatedBorders.top;
onChange(filteredResult);
};
const onSplitChange = (newBorder, side) => {
const updatedBorders = { ...splitValue,
[side]: newBorder
};
if (hasMixedBorders(updatedBorders)) {
onChange(updatedBorders);
} else {
onChange(newBorder);
}
};
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControl, className);
}, [cx, className]);
const linkedControlClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(linkedBorderControl());
}, [cx]);
const wrapperClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(wrapper);
}, [cx]);
return { ...otherProps,
className: classes,
colors,
disableUnits: mixedBorders && !hasWidthValue,
enableAlpha,
enableStyle,
hasMixedBorders: mixedBorders,
isLinked,
linkedControlClassName,
onLinkedChange,
onSplitChange,
toggleLinked,
linkedValue,
size,
splitValue,
wrapperClassName,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const component_BorderLabel = props => {
const {
label,
hideLabelFromVision
} = props;
if (!label) {
return null;
}
return hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label"
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, null, label);
};
const UnconnectedBorderBoxControl = (props, forwardedRef) => {
const {
className,
colors,
disableCustomColors,
disableUnits,
enableAlpha,
enableStyle,
hasMixedBorders,
hideLabelFromVision,
isLinked,
label,
linkedControlClassName,
linkedValue,
onLinkedChange,
onSplitChange,
popoverPlacement,
popoverOffset,
size,
splitValue,
toggleLinked,
wrapperClassName,
__experimentalIsRenderedInSidebar,
...otherProps
} = useBorderBoxControl(props); // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => popoverPlacement ? {
placement: popoverPlacement,
offset: popoverOffset,
anchor: popoverAnchor,
shift: true
} : undefined, [popoverPlacement, popoverOffset, popoverAnchor]);
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([setPopoverAnchor, forwardedRef]);
return (0,external_wp_element_namespaceObject.createElement)(component, {
className: className,
...otherProps,
ref: mergedRef
}, (0,external_wp_element_namespaceObject.createElement)(component_BorderLabel, {
label: label,
hideLabelFromVision: hideLabelFromVision
}), (0,external_wp_element_namespaceObject.createElement)(component, {
className: wrapperClassName
}, isLinked ? (0,external_wp_element_namespaceObject.createElement)(border_control_component, {
className: linkedControlClassName,
colors: colors,
disableUnits: disableUnits,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
enableStyle: enableStyle,
onChange: onLinkedChange,
placeholder: hasMixedBorders ? (0,external_wp_i18n_namespaceObject.__)('Mixed') : undefined,
__unstablePopoverProps: popoverProps,
shouldSanitizeBorder: false // This component will handle that.
,
value: linkedValue,
withSlider: true,
width: size === '__unstable-large' ? '116px' : '110px',
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
size: size
}) : (0,external_wp_element_namespaceObject.createElement)(border_box_control_split_controls_component, {
colors: colors,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
enableStyle: enableStyle,
onChange: onSplitChange,
popoverPlacement: popoverPlacement,
popoverOffset: popoverOffset,
value: splitValue,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
size: size
}), (0,external_wp_element_namespaceObject.createElement)(border_box_control_linked_button_component, {
onClick: toggleLinked,
isLinked: isLinked,
size: size
})));
};
/**
* The `BorderBoxControl` effectively has two view states. The first, a "linked"
* view, allows configuration of a flat border via a single `BorderControl`.
* The second, a "split" view, contains a `BorderControl` for each side
* as well as a visualizer for the currently selected borders. Each view also
* contains a button to toggle between the two.
*
* When switching from the "split" view to "linked", if the individual side
* borders are not consistent, the "linked" view will display any border
* properties selections that are consistent while showing a mixed state for
* those that aren't. For example, if all borders had the same color and style
* but different widths, then the border dropdown in the "linked" view's
* `BorderControl` would show that consistent color and style but the "linked"
* view's width input would show "Mixed" placeholder text.
*
* ```jsx
* import { __experimentalBorderBoxControl as BorderBoxControl } from '@wordpress/components';
* import { __ } from '@wordpress/i18n';
*
* const colors = [
* { name: 'Blue 20', color: '#72aee6' },
* // ...
* ];
*
* const MyBorderBoxControl = () => {
* const defaultBorder = {
* color: '#72aee6',
* style: 'dashed',
* width: '1px',
* };
* const [ borders, setBorders ] = useState( {
* top: defaultBorder,
* right: defaultBorder,
* bottom: defaultBorder,
* left: defaultBorder,
* } );
* const onChange = ( newBorders ) => setBorders( newBorders );
*
* return (
* <BorderBoxControl
* colors={ colors }
* label={ __( 'Borders' ) }
* onChange={ onChange }
* value={ borders }
* />
* );
* };
* ```
*/
const BorderBoxControl = contextConnect(UnconnectedBorderBoxControl, 'BorderBoxControl');
/* harmony default export */ var border_box_control_component = (BorderBoxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/styles/box-control-styles.js
function box_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const box_control_styles_Root = createStyled("div", true ? {
target: "e1jovhle6"
} : 0)( true ? {
name: "14bvcyk",
styles: "box-sizing:border-box;max-width:235px;padding-bottom:12px;width:100%"
} : 0);
const Header = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e1jovhle5"
} : 0)( true ? {
name: "5bhc30",
styles: "margin-bottom:8px"
} : 0);
const HeaderControlWrapper = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e1jovhle4"
} : 0)( true ? {
name: "aujtid",
styles: "min-height:30px;gap:0"
} : 0);
const UnitControlWrapper = createStyled("div", true ? {
target: "e1jovhle3"
} : 0)( true ? {
name: "112jwab",
styles: "box-sizing:border-box;max-width:80px"
} : 0);
const LayoutContainer = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e1jovhle2"
} : 0)( true ? {
name: "xy18ro",
styles: "justify-content:center;padding-top:8px"
} : 0);
const Layout = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e1jovhle1"
} : 0)( true ? {
name: "3tw5wk",
styles: "position:relative;height:100%;width:100%;justify-content:flex-start"
} : 0);
var box_control_styles_ref = true ? {
name: "1ch9yvl",
styles: "border-radius:0"
} : 0;
var box_control_styles_ref2 = true ? {
name: "tg3mx0",
styles: "border-radius:2px"
} : 0;
const unitControlBorderRadiusStyles = ({
isFirst,
isLast,
isOnly
}) => {
if (isFirst) {
return rtl({
borderTopRightRadius: 0,
borderBottomRightRadius: 0
})();
}
if (isLast) {
return rtl({
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0
})();
}
if (isOnly) {
return box_control_styles_ref2;
}
return box_control_styles_ref;
};
const unitControlMarginStyles = ({
isFirst,
isOnly
}) => {
const marginLeft = isFirst || isOnly ? 0 : -1;
return rtl({
marginLeft
})();
};
const box_control_styles_UnitControl = /*#__PURE__*/createStyled(unit_control, true ? {
target: "e1jovhle0"
} : 0)("max-width:60px;", unitControlBorderRadiusStyles, ";", unitControlMarginStyles, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/unit-control.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const unit_control_noop = () => {};
function BoxUnitControl({
isFirst,
isLast,
isOnly,
onHoverOn = unit_control_noop,
onHoverOff = unit_control_noop,
label,
value,
...props
}) {
const bindHoverGesture = useHover(({
event,
...state
}) => {
if (state.hovering) {
onHoverOn(event, state);
} else {
onHoverOff(event, state);
}
});
return (0,external_wp_element_namespaceObject.createElement)(UnitControlWrapper, { ...bindHoverGesture()
}, (0,external_wp_element_namespaceObject.createElement)(unit_control_Tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)(box_control_styles_UnitControl, {
"aria-label": label,
className: "component-box-control__unit-control",
isFirst: isFirst,
isLast: isLast,
isOnly: isOnly,
isPressEnterToChange: true,
isResetValueOnUnitChange: false,
value: value,
...props
})));
}
function unit_control_Tooltip({
children,
text
}) {
if (!text) return children;
/**
* Wrapping the children in a `<div />` as Tooltip as it attempts
* to render the <UnitControl />. Using a plain `<div />` appears to
* resolve this issue.
*
* Originally discovered and referenced here:
* https://github.com/WordPress/gutenberg/pull/24966#issuecomment-685875026
*/
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: text,
position: "top"
}, (0,external_wp_element_namespaceObject.createElement)("div", null, children));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const LABELS = {
all: (0,external_wp_i18n_namespaceObject.__)('All'),
top: (0,external_wp_i18n_namespaceObject.__)('Top'),
bottom: (0,external_wp_i18n_namespaceObject.__)('Bottom'),
left: (0,external_wp_i18n_namespaceObject.__)('Left'),
right: (0,external_wp_i18n_namespaceObject.__)('Right'),
mixed: (0,external_wp_i18n_namespaceObject.__)('Mixed'),
vertical: (0,external_wp_i18n_namespaceObject.__)('Vertical'),
horizontal: (0,external_wp_i18n_namespaceObject.__)('Horizontal')
};
const DEFAULT_VALUES = {
top: undefined,
right: undefined,
bottom: undefined,
left: undefined
};
const ALL_SIDES = ['top', 'right', 'bottom', 'left'];
/**
* Gets an items with the most occurrence within an array
* https://stackoverflow.com/a/20762713
*
* @param arr Array of items to check.
* @return The item with the most occurrences.
*/
function utils_mode(arr) {
return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop();
}
/**
* Gets the 'all' input value and unit from values data.
*
* @param values Box values.
* @param selectedUnits Box units.
* @param availableSides Available box sides to evaluate.
*
* @return A value + unit for the 'all' input.
*/
function getAllValue(values = {}, selectedUnits, availableSides = ALL_SIDES) {
const sides = normalizeSides(availableSides);
const parsedQuantitiesAndUnits = sides.map(side => parseQuantityAndUnitFromRawValue(values[side]));
const allParsedQuantities = parsedQuantitiesAndUnits.map(value => {
var _value$;
return (_value$ = value[0]) !== null && _value$ !== void 0 ? _value$ : '';
});
const allParsedUnits = parsedQuantitiesAndUnits.map(value => value[1]);
const commonQuantity = allParsedQuantities.every(v => v === allParsedQuantities[0]) ? allParsedQuantities[0] : '';
/**
* The typeof === 'number' check is important. On reset actions, the incoming value
* may be null or an empty string.
*
* Also, the value may also be zero (0), which is considered a valid unit value.
*
* typeof === 'number' is more specific for these cases, rather than relying on a
* simple truthy check.
*/
let commonUnit;
if (typeof commonQuantity === 'number') {
commonUnit = utils_mode(allParsedUnits);
} else {
var _getAllUnitFallback;
// Set meaningful unit selection if no commonQuantity and user has previously
// selected units without assigning values while controls were unlinked.
commonUnit = (_getAllUnitFallback = getAllUnitFallback(selectedUnits)) !== null && _getAllUnitFallback !== void 0 ? _getAllUnitFallback : utils_mode(allParsedUnits);
}
return [commonQuantity, commonUnit].join('');
}
/**
* Determine the most common unit selection to use as a fallback option.
*
* @param selectedUnits Current unit selections for individual sides.
* @return Most common unit selection.
*/
function getAllUnitFallback(selectedUnits) {
if (!selectedUnits || typeof selectedUnits !== 'object') {
return undefined;
}
const filteredUnits = Object.values(selectedUnits).filter(Boolean);
return utils_mode(filteredUnits);
}
/**
* Checks to determine if values are mixed.
*
* @param values Box values.
* @param selectedUnits Box units.
* @param sides Available box sides to evaluate.
*
* @return Whether values are mixed.
*/
function isValuesMixed(values = {}, selectedUnits, sides = ALL_SIDES) {
const allValue = getAllValue(values, selectedUnits, sides);
const isMixed = isNaN(parseFloat(allValue));
return isMixed;
}
/**
* Checks to determine if values are defined.
*
* @param values Box values.
*
* @return Whether values are mixed.
*/
function isValuesDefined(values) {
return values !== undefined && Object.values(values).filter( // Switching units when input is empty causes values only
// containing units. This gives false positive on mixed values
// unless filtered.
value => !!value && /\d/.test(value)).length > 0;
}
/**
* Get initial selected side, factoring in whether the sides are linked,
* and whether the vertical / horizontal directions are grouped via splitOnAxis.
*
* @param isLinked Whether the box control's fields are linked.
* @param splitOnAxis Whether splitting by horizontal or vertical axis.
* @return The initial side.
*/
function getInitialSide(isLinked, splitOnAxis) {
let initialSide = 'all';
if (!isLinked) {
initialSide = splitOnAxis ? 'vertical' : 'top';
}
return initialSide;
}
/**
* Normalizes provided sides configuration to an array containing only top,
* right, bottom and left. This essentially just maps `horizontal` or `vertical`
* to their appropriate sides to facilitate correctly determining value for
* all input control.
*
* @param sides Available sides for box control.
* @return Normalized sides configuration.
*/
function normalizeSides(sides) {
const filteredSides = [];
if (!sides?.length) {
return ALL_SIDES;
}
if (sides.includes('vertical')) {
filteredSides.push(...['top', 'bottom']);
} else if (sides.includes('horizontal')) {
filteredSides.push(...['left', 'right']);
} else {
const newSides = ALL_SIDES.filter(side => sides.includes(side));
filteredSides.push(...newSides);
}
return filteredSides;
}
/**
* Applies a value to an object representing top, right, bottom and left sides
* while taking into account any custom side configuration.
*
* @param currentValues The current values for each side.
* @param newValue The value to apply to the sides object.
* @param sides Array defining valid sides.
*
* @return Object containing the updated values for each side.
*/
function applyValueToSides(currentValues, newValue, sides) {
const newValues = { ...currentValues
};
if (sides?.length) {
sides.forEach(side => {
if (side === 'vertical') {
newValues.top = newValue;
newValues.bottom = newValue;
} else if (side === 'horizontal') {
newValues.left = newValue;
newValues.right = newValue;
} else {
newValues[side] = newValue;
}
});
} else {
ALL_SIDES.forEach(side => newValues[side] = newValue);
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/all-input-control.js
/**
* Internal dependencies
*/
const all_input_control_noop = () => {};
function AllInputControl({
onChange = all_input_control_noop,
onFocus = all_input_control_noop,
onHoverOn = all_input_control_noop,
onHoverOff = all_input_control_noop,
values,
sides,
selectedUnits,
setSelectedUnits,
...props
}) {
const allValue = getAllValue(values, selectedUnits, sides);
const hasValues = isValuesDefined(values);
const isMixed = hasValues && isValuesMixed(values, selectedUnits, sides);
const allPlaceholder = isMixed ? LABELS.mixed : undefined;
const handleOnFocus = event => {
onFocus(event, {
side: 'all'
});
};
const handleOnChange = next => {
const isNumeric = next !== undefined && !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
const nextValues = applyValueToSides(values, nextValue, sides);
onChange(nextValues);
}; // Set selected unit so it can be used as fallback by unlinked controls
// when individual sides do not have a value containing a unit.
const handleOnUnitChange = unit => {
const newUnits = applyValueToSides(selectedUnits, unit, sides);
setSelectedUnits(newUnits);
};
const handleOnHoverOn = () => {
onHoverOn({
top: true,
bottom: true,
left: true,
right: true
});
};
const handleOnHoverOff = () => {
onHoverOff({
top: false,
bottom: false,
left: false,
right: false
});
};
return (0,external_wp_element_namespaceObject.createElement)(BoxUnitControl, { ...props,
disableUnits: isMixed,
isOnly: true,
value: allValue,
onChange: handleOnChange,
onUnitChange: handleOnUnitChange,
onFocus: handleOnFocus,
onHoverOn: handleOnHoverOn,
onHoverOff: handleOnHoverOff,
placeholder: allPlaceholder
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/input-controls.js
/**
* Internal dependencies
*/
const input_controls_noop = () => {};
function BoxInputControls({
onChange = input_controls_noop,
onFocus = input_controls_noop,
onHoverOn = input_controls_noop,
onHoverOff = input_controls_noop,
values,
selectedUnits,
setSelectedUnits,
sides,
...props
}) {
const createHandleOnFocus = side => event => {
onFocus(event, {
side
});
};
const createHandleOnHoverOn = side => () => {
onHoverOn({
[side]: true
});
};
const createHandleOnHoverOff = side => () => {
onHoverOff({
[side]: false
});
};
const handleOnChange = nextValues => {
onChange(nextValues);
};
const createHandleOnChange = side => (next, {
event
}) => {
const nextValues = { ...values
};
const isNumeric = next !== undefined && !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
nextValues[side] = nextValue;
/**
* Supports changing pair sides. For example, holding the ALT key
* when changing the TOP will also update BOTTOM.
*/
// @ts-expect-error - TODO: event.altKey is only present when the change event was
// triggered by a keyboard event. Should this feature be implemented differently so
// it also works with drag events?
if (event.altKey) {
switch (side) {
case 'top':
nextValues.bottom = nextValue;
break;
case 'bottom':
nextValues.top = nextValue;
break;
case 'left':
nextValues.right = nextValue;
break;
case 'right':
nextValues.left = nextValue;
break;
}
}
handleOnChange(nextValues);
};
const createHandleOnUnitChange = side => next => {
const newUnits = { ...selectedUnits
};
newUnits[side] = next;
setSelectedUnits(newUnits);
}; // Filter sides if custom configuration provided, maintaining default order.
const filteredSides = sides?.length ? ALL_SIDES.filter(side => sides.includes(side)) : ALL_SIDES;
const first = filteredSides[0];
const last = filteredSides[filteredSides.length - 1];
const only = first === last && first;
return (0,external_wp_element_namespaceObject.createElement)(LayoutContainer, {
className: "component-box-control__input-controls-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(Layout, {
gap: 0,
align: "top",
className: "component-box-control__input-controls"
}, filteredSides.map(side => {
const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(values[side]);
const computedUnit = values[side] ? parsedUnit : selectedUnits[side];
return (0,external_wp_element_namespaceObject.createElement)(BoxUnitControl, { ...props,
isFirst: first === side,
isLast: last === side,
isOnly: only === side,
value: [parsedQuantity, computedUnit].join(''),
onChange: createHandleOnChange(side),
onUnitChange: createHandleOnUnitChange(side),
onFocus: createHandleOnFocus(side),
onHoverOn: createHandleOnHoverOn(side),
onHoverOff: createHandleOnHoverOff(side),
label: LABELS[side],
key: `box-control-${side}`
});
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/axial-input-controls.js
/**
* Internal dependencies
*/
const groupedSides = ['vertical', 'horizontal'];
function AxialInputControls({
onChange,
onFocus,
onHoverOn,
onHoverOff,
values,
selectedUnits,
setSelectedUnits,
sides,
...props
}) {
const createHandleOnFocus = side => event => {
if (!onFocus) {
return;
}
onFocus(event, {
side
});
};
const createHandleOnHoverOn = side => () => {
if (!onHoverOn) {
return;
}
if (side === 'vertical') {
onHoverOn({
top: true,
bottom: true
});
}
if (side === 'horizontal') {
onHoverOn({
left: true,
right: true
});
}
};
const createHandleOnHoverOff = side => () => {
if (!onHoverOff) {
return;
}
if (side === 'vertical') {
onHoverOff({
top: false,
bottom: false
});
}
if (side === 'horizontal') {
onHoverOff({
left: false,
right: false
});
}
};
const createHandleOnChange = side => next => {
if (!onChange) {
return;
}
const nextValues = { ...values
};
const isNumeric = next !== undefined && !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
if (side === 'vertical') {
nextValues.top = nextValue;
nextValues.bottom = nextValue;
}
if (side === 'horizontal') {
nextValues.left = nextValue;
nextValues.right = nextValue;
}
onChange(nextValues);
};
const createHandleOnUnitChange = side => next => {
const newUnits = { ...selectedUnits
};
if (side === 'vertical') {
newUnits.top = next;
newUnits.bottom = next;
}
if (side === 'horizontal') {
newUnits.left = next;
newUnits.right = next;
}
setSelectedUnits(newUnits);
}; // Filter sides if custom configuration provided, maintaining default order.
const filteredSides = sides?.length ? groupedSides.filter(side => sides.includes(side)) : groupedSides;
const first = filteredSides[0];
const last = filteredSides[filteredSides.length - 1];
const only = first === last && first;
return (0,external_wp_element_namespaceObject.createElement)(Layout, {
gap: 0,
align: "top",
className: "component-box-control__vertical-horizontal-input-controls"
}, filteredSides.map(side => {
const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(side === 'vertical' ? values.top : values.left);
const selectedUnit = side === 'vertical' ? selectedUnits.top : selectedUnits.left;
return (0,external_wp_element_namespaceObject.createElement)(BoxUnitControl, { ...props,
isFirst: first === side,
isLast: last === side,
isOnly: only === side,
value: [parsedQuantity, selectedUnit !== null && selectedUnit !== void 0 ? selectedUnit : parsedUnit].join(''),
onChange: createHandleOnChange(side),
onUnitChange: createHandleOnUnitChange(side),
onFocus: createHandleOnFocus(side),
onHoverOn: createHandleOnHoverOn(side),
onHoverOff: createHandleOnHoverOff(side),
label: LABELS[side],
key: side
});
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/styles/box-control-icon-styles.js
function box_control_icon_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const box_control_icon_styles_Root = createStyled("span", true ? {
target: "e1j5nr4z8"
} : 0)( true ? {
name: "1w884gc",
styles: "box-sizing:border-box;display:block;width:24px;height:24px;position:relative;padding:4px"
} : 0);
const Viewbox = createStyled("span", true ? {
target: "e1j5nr4z7"
} : 0)( true ? {
name: "i6vjox",
styles: "box-sizing:border-box;display:block;position:relative;width:100%;height:100%"
} : 0);
const strokeFocus = ({
isFocused
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css({
backgroundColor: 'currentColor',
opacity: isFocused ? 1 : 0.3
}, true ? "" : 0, true ? "" : 0);
};
const Stroke = createStyled("span", true ? {
target: "e1j5nr4z6"
} : 0)("box-sizing:border-box;display:block;pointer-events:none;position:absolute;", strokeFocus, ";" + ( true ? "" : 0));
const VerticalStroke = /*#__PURE__*/createStyled(Stroke, true ? {
target: "e1j5nr4z5"
} : 0)( true ? {
name: "1k2w39q",
styles: "bottom:3px;top:3px;width:2px"
} : 0);
const HorizontalStroke = /*#__PURE__*/createStyled(Stroke, true ? {
target: "e1j5nr4z4"
} : 0)( true ? {
name: "1q9b07k",
styles: "height:2px;left:3px;right:3px"
} : 0);
const TopStroke = /*#__PURE__*/createStyled(HorizontalStroke, true ? {
target: "e1j5nr4z3"
} : 0)( true ? {
name: "abcix4",
styles: "top:0"
} : 0);
const RightStroke = /*#__PURE__*/createStyled(VerticalStroke, true ? {
target: "e1j5nr4z2"
} : 0)( true ? {
name: "1wf8jf",
styles: "right:0"
} : 0);
const BottomStroke = /*#__PURE__*/createStyled(HorizontalStroke, true ? {
target: "e1j5nr4z1"
} : 0)( true ? {
name: "8tapst",
styles: "bottom:0"
} : 0);
const LeftStroke = /*#__PURE__*/createStyled(VerticalStroke, true ? {
target: "e1j5nr4z0"
} : 0)( true ? {
name: "1ode3cm",
styles: "left:0"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/icon.js
/**
* Internal dependencies
*/
const BASE_ICON_SIZE = 24;
function BoxControlIcon({
size = 24,
side = 'all',
sides,
...props
}) {
const isSideDisabled = value => sides?.length && !sides.includes(value);
const hasSide = value => {
if (isSideDisabled(value)) {
return false;
}
return side === 'all' || side === value;
};
const top = hasSide('top') || hasSide('vertical');
const right = hasSide('right') || hasSide('horizontal');
const bottom = hasSide('bottom') || hasSide('vertical');
const left = hasSide('left') || hasSide('horizontal'); // Simulates SVG Icon scaling.
const scale = size / BASE_ICON_SIZE;
return (0,external_wp_element_namespaceObject.createElement)(box_control_icon_styles_Root, {
style: {
transform: `scale(${scale})`
},
...props
}, (0,external_wp_element_namespaceObject.createElement)(Viewbox, null, (0,external_wp_element_namespaceObject.createElement)(TopStroke, {
isFocused: top
}), (0,external_wp_element_namespaceObject.createElement)(RightStroke, {
isFocused: right
}), (0,external_wp_element_namespaceObject.createElement)(BottomStroke, {
isFocused: bottom
}), (0,external_wp_element_namespaceObject.createElement)(LeftStroke, {
isFocused: left
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/linked-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function LinkedButton({
isLinked,
...props
}) {
const label = isLinked ? (0,external_wp_i18n_namespaceObject.__)('Unlink sides') : (0,external_wp_i18n_namespaceObject.__)('Link sides');
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, { ...props,
className: "component-box-control__linked-button",
isSmall: true,
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const defaultInputProps = {
min: 0
};
const box_control_noop = () => {};
function box_control_useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(BoxControl, 'inspector-box-control');
return idProp || instanceId;
}
/**
* BoxControl components let users set values for Top, Right, Bottom, and Left.
* This can be used as an input control for values like `padding` or `margin`.
*
* ```jsx
* import { __experimentalBoxControl as BoxControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ values, setValues ] = useState( {
* top: '50px',
* left: '10%',
* right: '10%',
* bottom: '50px',
* } );
*
* return (
* <BoxControl
* values={ values }
* onChange={ ( nextValues ) => setValues( nextValues ) }
* />
* );
* };
* ```
*/
function BoxControl({
id: idProp,
inputProps = defaultInputProps,
onChange = box_control_noop,
label = (0,external_wp_i18n_namespaceObject.__)('Box Control'),
values: valuesProp,
units,
sides,
splitOnAxis = false,
allowReset = true,
resetValues = DEFAULT_VALUES,
onMouseOver,
onMouseOut
}) {
const [values, setValues] = use_controlled_state(valuesProp, {
fallback: DEFAULT_VALUES
});
const inputValues = values || DEFAULT_VALUES;
const hasInitialValue = isValuesDefined(valuesProp);
const hasOneSide = sides?.length === 1;
const [isDirty, setIsDirty] = (0,external_wp_element_namespaceObject.useState)(hasInitialValue);
const [isLinked, setIsLinked] = (0,external_wp_element_namespaceObject.useState)(!hasInitialValue || !isValuesMixed(inputValues) || hasOneSide);
const [side, setSide] = (0,external_wp_element_namespaceObject.useState)(getInitialSide(isLinked, splitOnAxis)); // Tracking selected units via internal state allows filtering of CSS unit
// only values from being saved while maintaining preexisting unit selection
// behaviour. Filtering CSS only values prevents invalid style values.
const [selectedUnits, setSelectedUnits] = (0,external_wp_element_namespaceObject.useState)({
top: parseQuantityAndUnitFromRawValue(valuesProp?.top)[1],
right: parseQuantityAndUnitFromRawValue(valuesProp?.right)[1],
bottom: parseQuantityAndUnitFromRawValue(valuesProp?.bottom)[1],
left: parseQuantityAndUnitFromRawValue(valuesProp?.left)[1]
});
const id = box_control_useUniqueId(idProp);
const headingId = `${id}-heading`;
const toggleLinked = () => {
setIsLinked(!isLinked);
setSide(getInitialSide(!isLinked, splitOnAxis));
};
const handleOnFocus = (_event, {
side: nextSide
}) => {
setSide(nextSide);
};
const handleOnChange = nextValues => {
onChange(nextValues);
setValues(nextValues);
setIsDirty(true);
};
const handleOnReset = () => {
onChange(resetValues);
setValues(resetValues);
setSelectedUnits(resetValues);
setIsDirty(false);
};
const inputControlProps = { ...inputProps,
onChange: handleOnChange,
onFocus: handleOnFocus,
isLinked,
units,
selectedUnits,
setSelectedUnits,
sides,
values: inputValues,
onMouseOver,
onMouseOut
};
return (0,external_wp_element_namespaceObject.createElement)(box_control_styles_Root, {
id: id,
role: "group",
"aria-labelledby": headingId
}, (0,external_wp_element_namespaceObject.createElement)(Header, {
className: "component-box-control__header"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(BaseControl.VisualLabel, {
id: headingId
}, label)), allowReset && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "component-box-control__reset-button",
variant: "secondary",
isSmall: true,
onClick: handleOnReset,
disabled: !isDirty
}, (0,external_wp_i18n_namespaceObject.__)('Reset')))), (0,external_wp_element_namespaceObject.createElement)(HeaderControlWrapper, {
className: "component-box-control__header-control-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(BoxControlIcon, {
side: side,
sides: sides
})), isLinked && (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(AllInputControl, {
"aria-label": label,
...inputControlProps
})), !isLinked && splitOnAxis && (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(AxialInputControls, { ...inputControlProps
})), !hasOneSide && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(LinkedButton, {
onClick: toggleLinked,
isLinked: isLinked
}))), !isLinked && !splitOnAxis && (0,external_wp_element_namespaceObject.createElement)(BoxInputControls, { ...inputControlProps
}));
}
/* harmony default export */ var box_control = (BoxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button-group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedButtonGroup(props, ref) {
const {
className,
...restProps
} = props;
const classes = classnames_default()('components-button-group', className);
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
role: "group",
className: classes,
...restProps
});
}
/**
* ButtonGroup can be used to group any related buttons together. To emphasize
* related buttons, a group should share a common container.
*
* ```jsx
* import { Button, ButtonGroup } from '@wordpress/components';
*
* const MyButtonGroup = () => (
* <ButtonGroup>
* <Button variant="primary">Button 1</Button>
* <Button variant="primary">Button 2</Button>
* </ButtonGroup>
* );
* ```
*/
const ButtonGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedButtonGroup);
/* harmony default export */ var button_group = (ButtonGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/elevation/styles.js
function elevation_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const Elevation = true ? {
name: "12ip69d",
styles: "background:transparent;display:block;margin:0!important;pointer-events:none;position:absolute;will-change:box-shadow"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/elevation/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getBoxShadow(value) {
const boxShadowColor = `rgba(0, 0, 0, ${value / 20})`;
const boxShadow = `0 ${value}px ${value * 2}px 0
${boxShadowColor}`;
return boxShadow;
}
function useElevation(props) {
const {
active,
borderRadius = 'inherit',
className,
focus,
hover,
isInteractive = false,
offset = 0,
value = 0,
...otherProps
} = useContextSystem(props, 'Elevation');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
let hoverValue = isValueDefined(hover) ? hover : value * 2;
let activeValue = isValueDefined(active) ? active : value / 2;
if (!isInteractive) {
hoverValue = isValueDefined(hover) ? hover : undefined;
activeValue = isValueDefined(active) ? active : undefined;
}
const transition = `box-shadow ${config_values.transitionDuration} ${config_values.transitionTimingFunction}`;
const sx = {};
sx.Base = /*#__PURE__*/emotion_react_browser_esm_css({
borderRadius,
bottom: offset,
boxShadow: getBoxShadow(value),
opacity: config_values.elevationIntensity,
left: offset,
right: offset,
top: offset,
transition
}, reduceMotion('transition'), true ? "" : 0, true ? "" : 0);
if (isValueDefined(hoverValue)) {
sx.hover = /*#__PURE__*/emotion_react_browser_esm_css("*:hover>&{box-shadow:", getBoxShadow(hoverValue), ";}" + ( true ? "" : 0), true ? "" : 0);
}
if (isValueDefined(activeValue)) {
sx.active = /*#__PURE__*/emotion_react_browser_esm_css("*:active>&{box-shadow:", getBoxShadow(activeValue), ";}" + ( true ? "" : 0), true ? "" : 0);
}
if (isValueDefined(focus)) {
sx.focus = /*#__PURE__*/emotion_react_browser_esm_css("*:focus>&{box-shadow:", getBoxShadow(focus), ";}" + ( true ? "" : 0), true ? "" : 0);
}
return cx(Elevation, sx.Base, sx.hover, sx.focus, sx.active, className);
}, [active, borderRadius, className, cx, focus, hover, isInteractive, offset, value]);
return { ...otherProps,
className: classes,
'aria-hidden': true
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/elevation/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedElevation(props, forwardedRef) {
const elevationProps = useElevation(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...elevationProps,
ref: forwardedRef
});
}
/**
* `Elevation` is a core component that renders shadow, using the component
* system's shadow system.
*
* The shadow effect is generated using the `value` prop.
*
* ```jsx
* import {
* __experimentalElevation as Elevation,
* __experimentalSurface as Surface,
* __experimentalText as Text,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <Surface>
* <Text>Code is Poetry</Text>
* <Elevation value={ 5 } />
* </Surface>
* );
* }
* ```
*/
const component_Elevation = contextConnect(UnconnectedElevation, 'Elevation');
/* harmony default export */ var elevation_component = (component_Elevation);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/styles.js
function card_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// Since the border for `Card` is rendered via the `box-shadow` property
// (as opposed to the `border` property), the value of the border radius needs
// to be adjusted by removing 1px (this is because the `box-shadow` renders
// as an "outer radius").
const adjustedBorderRadius = `calc(${config_values.cardBorderRadius} - 1px)`;
const Card = /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:0 0 0 1px ", config_values.surfaceBorderColor, ";outline:none;" + ( true ? "" : 0), true ? "" : 0);
const styles_Header = true ? {
name: "1showjb",
styles: "border-bottom:1px solid;box-sizing:border-box;&:last-child{border-bottom:none;}"
} : 0;
const Footer = true ? {
name: "14n5oej",
styles: "border-top:1px solid;box-sizing:border-box;&:first-of-type{border-top:none;}"
} : 0;
const Content = true ? {
name: "13udsys",
styles: "height:100%"
} : 0;
const Body = true ? {
name: "6ywzd",
styles: "box-sizing:border-box;height:auto;max-height:100%"
} : 0;
const Media = true ? {
name: "dq805e",
styles: "box-sizing:border-box;overflow:hidden;&>img,&>iframe{display:block;height:auto;max-width:100%;width:100%;}"
} : 0;
const Divider = true ? {
name: "c990dr",
styles: "box-sizing:border-box;display:block;width:100%"
} : 0;
const borderRadius = /*#__PURE__*/emotion_react_browser_esm_css("&:first-of-type{border-top-left-radius:", adjustedBorderRadius, ";border-top-right-radius:", adjustedBorderRadius, ";}&:last-of-type{border-bottom-left-radius:", adjustedBorderRadius, ";border-bottom-right-radius:", adjustedBorderRadius, ";}" + ( true ? "" : 0), true ? "" : 0);
const borderColor = /*#__PURE__*/emotion_react_browser_esm_css("border-color:", config_values.colorDivider, ";" + ( true ? "" : 0), true ? "" : 0);
const boxShadowless = true ? {
name: "1t90u8d",
styles: "box-shadow:none"
} : 0;
const borderless = true ? {
name: "1e1ncky",
styles: "border:none"
} : 0;
const rounded = /*#__PURE__*/emotion_react_browser_esm_css("border-radius:", adjustedBorderRadius, ";" + ( true ? "" : 0), true ? "" : 0);
const xSmallCardPadding = /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingXSmall, ";" + ( true ? "" : 0), true ? "" : 0);
const cardPaddings = {
large: /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingLarge, ";" + ( true ? "" : 0), true ? "" : 0),
medium: /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingMedium, ";" + ( true ? "" : 0), true ? "" : 0),
small: /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingSmall, ";" + ( true ? "" : 0), true ? "" : 0),
xSmall: xSmallCardPadding,
// The `extraSmall` size is not officially documented, but the following styles
// are kept for legacy reasons to support older values of the `size` prop.
extraSmall: xSmallCardPadding
};
const shady = /*#__PURE__*/emotion_react_browser_esm_css("background-color:", COLORS.ui.backgroundDisabled, ";" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/surface/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const Surface = /*#__PURE__*/emotion_react_browser_esm_css("background-color:", config_values.surfaceColor, ";color:", COLORS.gray[900], ";position:relative;" + ( true ? "" : 0), true ? "" : 0);
const background = /*#__PURE__*/emotion_react_browser_esm_css("background-color:", config_values.surfaceBackgroundColor, ";" + ( true ? "" : 0), true ? "" : 0);
function getBorders({
borderBottom,
borderLeft,
borderRight,
borderTop
}) {
const borderStyle = `1px solid ${config_values.surfaceBorderColor}`;
return /*#__PURE__*/emotion_react_browser_esm_css({
borderBottom: borderBottom ? borderStyle : undefined,
borderLeft: borderLeft ? borderStyle : undefined,
borderRight: borderRight ? borderStyle : undefined,
borderTop: borderTop ? borderStyle : undefined
}, true ? "" : 0, true ? "" : 0);
}
const primary = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const secondary = /*#__PURE__*/emotion_react_browser_esm_css("background:", config_values.surfaceBackgroundTintColor, ";" + ( true ? "" : 0), true ? "" : 0);
const tertiary = /*#__PURE__*/emotion_react_browser_esm_css("background:", config_values.surfaceBackgroundTertiaryColor, ";" + ( true ? "" : 0), true ? "" : 0);
const customBackgroundSize = surfaceBackgroundSize => [surfaceBackgroundSize, surfaceBackgroundSize].join(' ');
const dottedBackground1 = surfaceBackgroundSizeDotted => ['90deg', [config_values.surfaceBackgroundColor, surfaceBackgroundSizeDotted].join(' '), 'transparent 1%'].join(',');
const dottedBackground2 = surfaceBackgroundSizeDotted => [[config_values.surfaceBackgroundColor, surfaceBackgroundSizeDotted].join(' '), 'transparent 1%'].join(',');
const dottedBackgroundCombined = surfaceBackgroundSizeDotted => [`linear-gradient( ${dottedBackground1(surfaceBackgroundSizeDotted)} ) center`, `linear-gradient( ${dottedBackground2(surfaceBackgroundSizeDotted)} ) center`, config_values.surfaceBorderBoldColor].join(',');
const getDotted = (surfaceBackgroundSize, surfaceBackgroundSizeDotted) => /*#__PURE__*/emotion_react_browser_esm_css("background:", dottedBackgroundCombined(surfaceBackgroundSizeDotted), ";background-size:", customBackgroundSize(surfaceBackgroundSize), ";" + ( true ? "" : 0), true ? "" : 0);
const gridBackground1 = [`${config_values.surfaceBorderSubtleColor} 1px`, 'transparent 1px'].join(',');
const gridBackground2 = ['90deg', `${config_values.surfaceBorderSubtleColor} 1px`, 'transparent 1px'].join(',');
const gridBackgroundCombined = [`linear-gradient( ${gridBackground1} )`, `linear-gradient( ${gridBackground2} )`].join(',');
const getGrid = surfaceBackgroundSize => {
return /*#__PURE__*/emotion_react_browser_esm_css("background:", config_values.surfaceBackgroundColor, ";background-image:", gridBackgroundCombined, ";background-size:", customBackgroundSize(surfaceBackgroundSize), ";" + ( true ? "" : 0), true ? "" : 0);
};
const getVariant = (variant, surfaceBackgroundSize, surfaceBackgroundSizeDotted) => {
switch (variant) {
case 'dotted':
{
return getDotted(surfaceBackgroundSize, surfaceBackgroundSizeDotted);
}
case 'grid':
{
return getGrid(surfaceBackgroundSize);
}
case 'primary':
{
return primary;
}
case 'secondary':
{
return secondary;
}
case 'tertiary':
{
return tertiary;
}
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/surface/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSurface(props) {
const {
backgroundSize = 12,
borderBottom = false,
borderLeft = false,
borderRight = false,
borderTop = false,
className,
variant = 'primary',
...otherProps
} = useContextSystem(props, 'Surface');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const sx = {
borders: getBorders({
borderBottom,
borderLeft,
borderRight,
borderTop
})
};
return cx(Surface, sx.borders, getVariant(variant, `${backgroundSize}px`, `${backgroundSize - 1}px`), className);
}, [backgroundSize, borderBottom, borderLeft, borderRight, borderTop, className, cx, variant]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function card_hook_useDeprecatedProps({
elevation,
isElevated,
...otherProps
}) {
const propsToReturn = { ...otherProps
};
let computedElevation = elevation;
if (isElevated) {
var _computedElevation;
external_wp_deprecated_default()('Card isElevated prop', {
since: '5.9',
alternative: 'elevation'
});
(_computedElevation = computedElevation) !== null && _computedElevation !== void 0 ? _computedElevation : computedElevation = 2;
} // The `elevation` prop should only be passed when it's not `undefined`,
// otherwise it will override the value that gets derived from `useContextSystem`.
if (typeof computedElevation !== 'undefined') {
propsToReturn.elevation = computedElevation;
}
return propsToReturn;
}
function useCard(props) {
const {
className,
elevation = 0,
isBorderless = false,
isRounded = true,
size = 'medium',
...otherProps
} = useContextSystem(card_hook_useDeprecatedProps(props), 'Card');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(Card, isBorderless && boxShadowless, isRounded && rounded, className);
}, [className, cx, isBorderless, isRounded]);
const surfaceProps = useSurface({ ...otherProps,
className: classes
});
return { ...surfaceProps,
elevation,
isBorderless,
isRounded,
size
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCard(props, forwardedRef) {
const {
children,
elevation,
isBorderless,
isRounded,
size,
...otherProps
} = useCard(props);
const elevationBorderRadius = isRounded ? config_values.cardBorderRadius : 0;
const cx = useCx();
const elevationClassName = (0,external_wp_element_namespaceObject.useMemo)(() => cx( /*#__PURE__*/emotion_react_browser_esm_css({
borderRadius: elevationBorderRadius
}, true ? "" : 0, true ? "" : 0)), [cx, elevationBorderRadius]);
const contextProviderValue = (0,external_wp_element_namespaceObject.useMemo)(() => {
const contextProps = {
size,
isBorderless
};
return {
CardBody: contextProps,
CardHeader: contextProps,
CardFooter: contextProps
};
}, [isBorderless, size]);
return (0,external_wp_element_namespaceObject.createElement)(ContextSystemProvider, {
value: contextProviderValue
}, (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(component, {
className: cx(Content)
}, children), (0,external_wp_element_namespaceObject.createElement)(elevation_component, {
className: elevationClassName,
isInteractive: false,
value: elevation ? 1 : 0
}), (0,external_wp_element_namespaceObject.createElement)(elevation_component, {
className: elevationClassName,
isInteractive: false,
value: elevation
})));
}
/**
* `Card` provides a flexible and extensible content container.
* `Card` also provides a convenient set of sub-components such as `CardBody`,
* `CardHeader`, `CardFooter`, and more.
*
* ```jsx
* import {
* Card,
* CardHeader,
* CardBody,
* CardFooter,
* Text,
* Heading,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <Card>
* <CardHeader>
* <Heading size={ 4 }>Card Title</Heading>
* </CardHeader>
* <CardBody>
* <Text>Card Content</Text>
* </CardBody>
* <CardFooter>
* <Text>Card Footer</Text>
* </CardFooter>
* </Card>
* );
* }
* ```
*/
const component_Card = contextConnect(UnconnectedCard, 'Card');
/* harmony default export */ var card_component = (component_Card);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scrollable/styles.js
function scrollable_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const scrollableScrollbar = /*#__PURE__*/emotion_react_browser_esm_css("@media only screen and ( min-device-width: 40em ){&::-webkit-scrollbar{height:12px;width:12px;}&::-webkit-scrollbar-track{background-color:transparent;}&::-webkit-scrollbar-track{background:", config_values.colorScrollbarTrack, ";border-radius:8px;}&::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:", config_values.colorScrollbarThumb, ";border:2px solid rgba( 0, 0, 0, 0 );border-radius:7px;}&:hover::-webkit-scrollbar-thumb{background-color:", config_values.colorScrollbarThumbHover, ";}}" + ( true ? "" : 0), true ? "" : 0);
const Scrollable = true ? {
name: "13udsys",
styles: "height:100%"
} : 0;
const styles_Content = true ? {
name: "bjn8wh",
styles: "position:relative"
} : 0;
const styles_smoothScroll = true ? {
name: "7zq9w",
styles: "scroll-behavior:smooth"
} : 0;
const scrollX = true ? {
name: "q33xhg",
styles: "overflow-x:auto;overflow-y:hidden"
} : 0;
const scrollY = true ? {
name: "103x71s",
styles: "overflow-x:hidden;overflow-y:auto"
} : 0;
const scrollAuto = true ? {
name: "umwchj",
styles: "overflow-y:auto"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scrollable/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useScrollable(props) {
const {
className,
scrollDirection = 'y',
smoothScroll = false,
...otherProps
} = useContextSystem(props, 'Scrollable');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Scrollable, scrollableScrollbar, smoothScroll && styles_smoothScroll, scrollDirection === 'x' && scrollX, scrollDirection === 'y' && scrollY, scrollDirection === 'auto' && scrollAuto, className), [className, cx, scrollDirection, smoothScroll]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scrollable/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedScrollable(props, forwardedRef) {
const scrollableProps = useScrollable(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...scrollableProps,
ref: forwardedRef
});
}
/**
* `Scrollable` is a layout component that content in a scrollable container.
*
* ```jsx
* import { __experimentalScrollable as Scrollable } from `@wordpress/components`;
*
* function Example() {
* return (
* <Scrollable style={ { maxHeight: 200 } }>
* <div style={ { height: 500 } }>...</div>
* </Scrollable>
* );
* }
* ```
*/
const component_Scrollable = contextConnect(UnconnectedScrollable, 'Scrollable');
/* harmony default export */ var scrollable_component = (component_Scrollable);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-body/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardBody(props) {
const {
className,
isScrollable = false,
isShady = false,
size = 'medium',
...otherProps
} = useContextSystem(props, 'CardBody');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Body, borderRadius, cardPaddings[size], isShady && shady, // This classname is added for legacy compatibility reasons.
'components-card__body', className), [className, cx, isShady, size]);
return { ...otherProps,
className: classes,
isScrollable
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-body/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardBody(props, forwardedRef) {
const {
isScrollable,
...otherProps
} = useCardBody(props);
if (isScrollable) {
return (0,external_wp_element_namespaceObject.createElement)(scrollable_component, { ...otherProps,
ref: forwardedRef
});
}
return (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
});
}
/**
* `CardBody` renders an optional content area for a `Card`.
* Multiple `CardBody` components can be used within `Card` if needed.
*
* ```jsx
* import { Card, CardBody } from `@wordpress/components`;
*
* <Card>
* <CardBody>
* ...
* </CardBody>
* </Card>
* ```
*/
const CardBody = contextConnect(UnconnectedCardBody, 'CardBody');
/* harmony default export */ var card_body_component = (CardBody);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Separator/Separator.js
// Automatically generated
var SEPARATOR_KEYS = ["orientation"];
var useSeparator = createHook({
name: "Separator",
compose: useRole,
keys: SEPARATOR_KEYS,
useOptions: function useOptions(_ref) {
var _ref$orientation = _ref.orientation,
orientation = _ref$orientation === void 0 ? "horizontal" : _ref$orientation,
options = _objectWithoutPropertiesLoose(_ref, ["orientation"]);
return _objectSpread2({
orientation: orientation
}, options);
},
useProps: function useProps(options, htmlProps) {
return _objectSpread2({
role: "separator",
"aria-orientation": options.orientation
}, htmlProps);
}
});
var Separator = createComponent({
as: "hr",
memo: true,
useHook: useSeparator
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/divider/styles.js
function divider_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const MARGIN_DIRECTIONS = {
vertical: {
start: 'marginLeft',
end: 'marginRight'
},
horizontal: {
start: 'marginTop',
end: 'marginBottom'
}
}; // Renders the correct margins given the Divider's `orientation` and the writing direction.
// When both the generic `margin` and the specific `marginStart|marginEnd` props are defined,
// the latter will take priority.
const renderMargin = ({
'aria-orientation': orientation = 'horizontal',
margin,
marginStart,
marginEnd
}) => /*#__PURE__*/emotion_react_browser_esm_css(rtl({
[MARGIN_DIRECTIONS[orientation].start]: space(marginStart !== null && marginStart !== void 0 ? marginStart : margin),
[MARGIN_DIRECTIONS[orientation].end]: space(marginEnd !== null && marginEnd !== void 0 ? marginEnd : margin)
})(), true ? "" : 0, true ? "" : 0);
var styles_ref = true ? {
name: "1u4hpl4",
styles: "display:inline"
} : 0;
const renderDisplay = ({
'aria-orientation': orientation = 'horizontal'
}) => {
return orientation === 'vertical' ? styles_ref : undefined;
};
const renderBorder = ({
'aria-orientation': orientation = 'horizontal'
}) => {
return /*#__PURE__*/emotion_react_browser_esm_css({
[orientation === 'vertical' ? 'borderRight' : 'borderBottom']: '1px solid currentColor'
}, true ? "" : 0, true ? "" : 0);
};
const renderSize = ({
'aria-orientation': orientation = 'horizontal'
}) => /*#__PURE__*/emotion_react_browser_esm_css({
height: orientation === 'vertical' ? 'auto' : 0,
width: orientation === 'vertical' ? 0 : 'auto'
}, true ? "" : 0, true ? "" : 0);
const DividerView = createStyled("hr", true ? {
target: "e19on6iw0"
} : 0)("border:0;margin:0;", renderDisplay, " ", renderBorder, " ", renderSize, " ", renderMargin, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/divider/component.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* Internal dependencies
*/
function UnconnectedDivider(props, forwardedRef) {
const contextProps = useContextSystem(props, 'Divider');
return (0,external_wp_element_namespaceObject.createElement)(Separator, {
as: DividerView,
...contextProps,
ref: forwardedRef
});
}
/**
* `Divider` is a layout component that separates groups of related content.
*
* ```js
* import {
* __experimentalDivider as Divider,
* __experimentalText as Text,
* __experimentalVStack as VStack,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <VStack spacing={4}>
* <Text>Some text here</Text>
* <Divider />
* <Text>Some more text here</Text>
* </VStack>
* );
* }
* ```
*/
const component_Divider = contextConnect(UnconnectedDivider, 'Divider');
/* harmony default export */ var divider_component = (component_Divider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-divider/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardDivider(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'CardDivider');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Divider, borderColor, // This classname is added for legacy compatibility reasons.
'components-card__divider', className), [className, cx]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-divider/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardDivider(props, forwardedRef) {
const dividerProps = useCardDivider(props);
return (0,external_wp_element_namespaceObject.createElement)(divider_component, { ...dividerProps,
ref: forwardedRef
});
}
/**
* `CardDivider` renders an optional divider within a `Card`.
* It is typically used to divide multiple `CardBody` components from each other.
*
* ```jsx
* import { Card, CardBody, CardDivider } from `@wordpress/components`;
*
* <Card>
* <CardBody>...</CardBody>
* <CardDivider />
* <CardBody>...</CardBody>
* </Card>
* ```
*/
const CardDivider = contextConnect(UnconnectedCardDivider, 'CardDivider');
/* harmony default export */ var card_divider_component = (CardDivider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-footer/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardFooter(props) {
const {
className,
justify,
isBorderless = false,
isShady = false,
size = 'medium',
...otherProps
} = useContextSystem(props, 'CardFooter');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Footer, borderRadius, borderColor, cardPaddings[size], isBorderless && borderless, isShady && shady, // This classname is added for legacy compatibility reasons.
'components-card__footer', className), [className, cx, isBorderless, isShady, size]);
return { ...otherProps,
className: classes,
justify
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-footer/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardFooter(props, forwardedRef) {
const footerProps = useCardFooter(props);
return (0,external_wp_element_namespaceObject.createElement)(flex_component, { ...footerProps,
ref: forwardedRef
});
}
/**
* `CardFooter` renders an optional footer within a `Card`.
*
* ```jsx
* import { Card, CardBody, CardFooter } from `@wordpress/components`;
*
* <Card>
* <CardBody>...</CardBody>
* <CardFooter>...</CardFooter>
* </Card>
* ```
*/
const CardFooter = contextConnect(UnconnectedCardFooter, 'CardFooter');
/* harmony default export */ var card_footer_component = (CardFooter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-header/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardHeader(props) {
const {
className,
isBorderless = false,
isShady = false,
size = 'medium',
...otherProps
} = useContextSystem(props, 'CardHeader');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(styles_Header, borderRadius, borderColor, cardPaddings[size], isBorderless && borderless, isShady && shady, // This classname is added for legacy compatibility reasons.
'components-card__header', className), [className, cx, isBorderless, isShady, size]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-header/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardHeader(props, forwardedRef) {
const headerProps = useCardHeader(props);
return (0,external_wp_element_namespaceObject.createElement)(flex_component, { ...headerProps,
ref: forwardedRef
});
}
/**
* `CardHeader` renders an optional header within a `Card`.
*
* ```jsx
* import { Card, CardBody, CardHeader } from `@wordpress/components`;
*
* <Card>
* <CardHeader>...</CardHeader>
* <CardBody>...</CardBody>
* </Card>
* ```
*/
const CardHeader = contextConnect(UnconnectedCardHeader, 'CardHeader');
/* harmony default export */ var card_header_component = (CardHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-media/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardMedia(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'CardMedia');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Media, borderRadius, // This classname is added for legacy compatibility reasons.
'components-card__media', className), [className, cx]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-media/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardMedia(props, forwardedRef) {
const cardMediaProps = useCardMedia(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...cardMediaProps,
ref: forwardedRef
});
}
/**
* `CardMedia` provides a container for full-bleed content within a `Card`,
* such as images, video, or even just a background color.
*
* @example
* ```jsx
* import { Card, CardBody, CardMedia } from '@wordpress/components';
*
* const Example = () => (
* <Card>
* <CardMedia>
* <img src="..." />
* </CardMedia>
* <CardBody>...</CardBody>
* </Card>
* );
* ```
*/
const CardMedia = contextConnect(UnconnectedCardMedia, 'CardMedia');
/* harmony default export */ var card_media_component = (CardMedia);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/checkbox-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Checkboxes allow the user to select one or more items from a set.
*
* ```jsx
* import { CheckboxControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyCheckboxControl = () => {
* const [ isChecked, setChecked ] = useState( true );
* return (
* <CheckboxControl
* label="Is author"
* help="Is the user a author or not?"
* checked={ isChecked }
* onChange={ setChecked }
* />
* );
* };
* ```
*/
function CheckboxControl(props) {
const {
__nextHasNoMarginBottom,
label,
className,
heading,
checked,
indeterminate,
help,
id: idProp,
onChange,
...additionalProps
} = props;
if (heading) {
external_wp_deprecated_default()('`heading` prop in `CheckboxControl`', {
alternative: 'a separate element to implement a heading',
since: '5.8'
});
}
const [showCheckedIcon, setShowCheckedIcon] = (0,external_wp_element_namespaceObject.useState)(false);
const [showIndeterminateIcon, setShowIndeterminateIcon] = (0,external_wp_element_namespaceObject.useState)(false); // Run the following callback every time the `ref` (and the additional
// dependencies) change.
const ref = (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!node) {
return;
} // It cannot be set using an HTML attribute.
node.indeterminate = !!indeterminate;
setShowCheckedIcon(node.matches(':checked'));
setShowIndeterminateIcon(node.matches(':indeterminate'));
}, [checked, indeterminate]);
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(CheckboxControl, 'inspector-checkbox-control', idProp);
const onChangeValue = event => onChange(event.target.checked);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: heading,
id: id,
help: help,
className: classnames_default()('components-checkbox-control', className)
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-checkbox-control__input-container"
}, (0,external_wp_element_namespaceObject.createElement)("input", {
ref: ref,
id: id,
className: "components-checkbox-control__input",
type: "checkbox",
value: "1",
onChange: onChangeValue,
checked: checked,
"aria-describedby": !!help ? id + '__help' : undefined,
...additionalProps
}), showIndeterminateIcon ? (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_reset,
className: "components-checkbox-control__indeterminate",
role: "presentation"
}) : null, showCheckedIcon ? (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_check,
className: "components-checkbox-control__checked",
role: "presentation"
}) : null), (0,external_wp_element_namespaceObject.createElement)("label", {
className: "components-checkbox-control__label",
htmlFor: id
}, label));
}
/* harmony default export */ var checkbox_control = (CheckboxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/clipboard-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TIMEOUT = 4000;
function ClipboardButton({
className,
children,
onCopy,
onFinishCopy,
text,
...buttonProps
}) {
external_wp_deprecated_default()('wp.components.ClipboardButton', {
since: '5.8',
alternative: 'wp.compose.useCopyToClipboard'
});
const timeoutId = (0,external_wp_element_namespaceObject.useRef)();
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text, () => {
onCopy();
if (timeoutId.current) {
clearTimeout(timeoutId.current);
}
if (onFinishCopy) {
timeoutId.current = setTimeout(() => onFinishCopy(), TIMEOUT);
}
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (timeoutId.current) {
clearTimeout(timeoutId.current);
}
}, []);
const classes = classnames_default()('components-clipboard-button', className); // Workaround for inconsistent behavior in Safari, where <textarea> is not
// the document.activeElement at the moment when the copy event fires.
// This causes documentHasSelection() in the copy-handler component to
// mistakenly override the ClipboardButton, and copy a serialized string
// of the current block instead.
const focusOnCopyEventTarget = event => {
// @ts-expect-error: Should be currentTarget, but not changing because this component is deprecated.
event.target.focus();
};
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, { ...buttonProps,
className: classes,
ref: ref,
onCopy: focusOnCopyEventTarget
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-vertical.js
/**
* WordPress dependencies
*/
const moreVertical = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"
}));
/* harmony default export */ var more_vertical = (moreVertical);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/styles.js
function item_group_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const unstyledButton = /*#__PURE__*/emotion_react_browser_esm_css("appearance:none;border:1px solid transparent;cursor:pointer;background:none;text-align:start;svg,path{fill:currentColor;}&:hover{color:", COLORS.ui.theme, ";}&:focus-visible{box-shadow:0 0 0 var( --wp-admin-border-width-focus ) var(\n\t\t\t\t--wp-components-color-accent,\n\t\t\t\tvar( --wp-admin-theme-color, ", COLORS.ui.theme, " )\n\t\t\t);outline:2px solid transparent;}" + ( true ? "" : 0), true ? "" : 0);
const itemWrapper = true ? {
name: "1bcj5ek",
styles: "width:100%;display:block"
} : 0;
const item = true ? {
name: "150ruhm",
styles: "box-sizing:border-box;width:100%;display:block;margin:0;color:inherit"
} : 0;
const bordered = /*#__PURE__*/emotion_react_browser_esm_css("border:1px solid ", config_values.surfaceBorderColor, ";" + ( true ? "" : 0), true ? "" : 0);
const separated = /*#__PURE__*/emotion_react_browser_esm_css(">*:not( marquee )>*{border-bottom:1px solid ", config_values.surfaceBorderColor, ";}>*:last-of-type>*:not( :focus ){border-bottom-color:transparent;}" + ( true ? "" : 0), true ? "" : 0);
const styles_borderRadius = config_values.controlBorderRadius;
const styles_spacedAround = /*#__PURE__*/emotion_react_browser_esm_css("border-radius:", styles_borderRadius, ";" + ( true ? "" : 0), true ? "" : 0);
const styles_rounded = /*#__PURE__*/emotion_react_browser_esm_css("border-radius:", styles_borderRadius, ";>*:first-of-type>*{border-top-left-radius:", styles_borderRadius, ";border-top-right-radius:", styles_borderRadius, ";}>*:last-of-type>*{border-bottom-left-radius:", styles_borderRadius, ";border-bottom-right-radius:", styles_borderRadius, ";}" + ( true ? "" : 0), true ? "" : 0);
const baseFontHeight = `calc(${config_values.fontSize} * ${config_values.fontLineHeightBase})`;
/*
* Math:
* - Use the desired height as the base value
* - Subtract the computed height of (default) text
* - Subtract the effects of border
* - Divide the calculated number by 2, in order to get an individual top/bottom padding
*/
const paddingY = `calc((${config_values.controlHeight} - ${baseFontHeight} - 2px) / 2)`;
const paddingYSmall = `calc((${config_values.controlHeightSmall} - ${baseFontHeight} - 2px) / 2)`;
const paddingYLarge = `calc((${config_values.controlHeightLarge} - ${baseFontHeight} - 2px) / 2)`;
const itemSizes = {
small: /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingYSmall, " ", config_values.controlPaddingXSmall, ";" + ( true ? "" : 0), true ? "" : 0),
medium: /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingY, " ", config_values.controlPaddingX, ";" + ( true ? "" : 0), true ? "" : 0),
large: /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingYLarge, " ", config_values.controlPaddingXLarge, ";" + ( true ? "" : 0), true ? "" : 0)
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item-group/hook.js
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
function useItemGroup(props) {
const {
className,
isBordered = false,
isRounded = true,
isSeparated = false,
role = 'list',
...otherProps
} = useContextSystem(props, 'ItemGroup');
const cx = useCx();
const classes = cx(isBordered && bordered, isSeparated && separated, isRounded && styles_rounded, className);
return {
isBordered,
className: classes,
role,
isSeparated,
...otherProps
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ItemGroupContext = (0,external_wp_element_namespaceObject.createContext)({
size: 'medium'
});
const useItemGroupContext = () => (0,external_wp_element_namespaceObject.useContext)(ItemGroupContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item-group/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedItemGroup(props, forwardedRef) {
const {
isBordered,
isSeparated,
size: sizeProp,
...otherProps
} = useItemGroup(props);
const {
size: contextSize
} = useItemGroupContext();
const spacedAround = !isBordered && !isSeparated;
const size = sizeProp || contextSize;
const contextValue = {
spacedAround,
size
};
return (0,external_wp_element_namespaceObject.createElement)(ItemGroupContext.Provider, {
value: contextValue
}, (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
}));
}
/**
* `ItemGroup` displays a list of `Item`s grouped and styled together.
*
* @example
* ```jsx
* import {
* __experimentalItemGroup as ItemGroup,
* __experimentalItem as Item,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ItemGroup>
* <Item>Code</Item>
* <Item>is</Item>
* <Item>Poetry</Item>
* </ItemGroup>
* );
* }
* ```
*/
const ItemGroup = contextConnect(UnconnectedItemGroup, 'ItemGroup');
/* harmony default export */ var item_group_component = (ItemGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/constants.js
const GRADIENT_MARKERS_WIDTH = 16;
const INSERT_POINT_WIDTH = 16;
const MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT = 10;
const MINIMUM_DISTANCE_BETWEEN_POINTS = 0;
const MINIMUM_SIGNIFICANT_MOVE = 5;
const KEYBOARD_CONTROL_POINT_VARIATION = MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT;
const MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_MARKER = (INSERT_POINT_WIDTH + GRADIENT_MARKERS_WIDTH) / 2;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/utils.js
/**
* Internal dependencies
*/
/**
* Clamps a number between 0 and 100.
*
* @param value Value to clamp.
*
* @return Value clamped between 0 and 100.
*/
function clampPercent(value) {
return Math.max(0, Math.min(100, value));
}
/**
* Check if a control point is overlapping with another.
*
* @param value Array of control points.
* @param initialIndex Index of the position to test.
* @param newPosition New position of the control point.
* @param minDistance Distance considered to be overlapping.
*
* @return True if the point is overlapping.
*/
function isOverlapping(value, initialIndex, newPosition, minDistance = MINIMUM_DISTANCE_BETWEEN_POINTS) {
const initialPosition = value[initialIndex].position;
const minPosition = Math.min(initialPosition, newPosition);
const maxPosition = Math.max(initialPosition, newPosition);
return value.some(({
position
}, index) => {
return index !== initialIndex && (Math.abs(position - newPosition) < minDistance || minPosition < position && position < maxPosition);
});
}
/**
* Adds a control point from an array and returns the new array.
*
* @param points Array of control points.
* @param position Position to insert the new point.
* @param color Color to update the control point at index.
*
* @return New array of control points.
*/
function addControlPoint(points, position, color) {
const nextIndex = points.findIndex(point => point.position > position);
const newPoint = {
color,
position
};
const newPoints = points.slice();
newPoints.splice(nextIndex - 1, 0, newPoint);
return newPoints;
}
/**
* Removes a control point from an array and returns the new array.
*
* @param points Array of control points.
* @param index Index to remove.
*
* @return New array of control points.
*/
function removeControlPoint(points, index) {
return points.filter((_point, pointIndex) => {
return pointIndex !== index;
});
}
/**
* Updates a control point from an array and returns the new array.
*
* @param points Array of control points.
* @param index Index to update.
* @param newPoint New control point to replace the index.
*
* @return New array of control points.
*/
function updateControlPoint(points, index, newPoint) {
const newValue = points.slice();
newValue[index] = newPoint;
return newValue;
}
/**
* Updates the position of a control point from an array and returns the new array.
*
* @param points Array of control points.
* @param index Index to update.
* @param newPosition Position to move the control point at index.
*
* @return New array of control points.
*/
function updateControlPointPosition(points, index, newPosition) {
if (isOverlapping(points, index, newPosition)) {
return points;
}
const newPoint = { ...points[index],
position: newPosition
};
return updateControlPoint(points, index, newPoint);
}
/**
* Updates the position of a control point from an array and returns the new array.
*
* @param points Array of control points.
* @param index Index to update.
* @param newColor Color to update the control point at index.
*
* @return New array of control points.
*/
function updateControlPointColor(points, index, newColor) {
const newPoint = { ...points[index],
color: newColor
};
return updateControlPoint(points, index, newPoint);
}
/**
* Updates the position of a control point from an array and returns the new array.
*
* @param points Array of control points.
* @param position Position of the color stop.
* @param newColor Color to update the control point at index.
*
* @return New array of control points.
*/
function updateControlPointColorByPosition(points, position, newColor) {
const index = points.findIndex(point => point.position === position);
return updateControlPointColor(points, index, newColor);
}
/**
* Gets the horizontal coordinate when dragging a control point with the mouse.
*
* @param mouseXcoordinate Horizontal coordinate of the mouse position.
* @param containerElement Container for the gradient picker.
*
* @return Whole number percentage from the left.
*/
function getHorizontalRelativeGradientPosition(mouseXCoordinate, containerElement) {
if (!containerElement) {
return;
}
const {
x,
width
} = containerElement.getBoundingClientRect();
const absolutePositionValue = mouseXCoordinate - x;
return Math.round(clampPercent(absolutePositionValue * 100 / width));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/control-points.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ControlPointButton({
isOpen,
position,
color,
...additionalProps
}) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ControlPointButton);
const descriptionId = `components-custom-gradient-picker__control-point-button-description-${instanceId}`;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: gradient position e.g: 70, %2$s: gradient color code e.g: rgb(52,121,151).
(0,external_wp_i18n_namespaceObject.__)('Gradient control point at position %1$s%% with color code %2$s.'), position, color),
"aria-describedby": descriptionId,
"aria-haspopup": "true",
"aria-expanded": isOpen,
className: classnames_default()('components-custom-gradient-picker__control-point-button', {
'is-active': isOpen
}),
...additionalProps
}), (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
id: descriptionId
}, (0,external_wp_i18n_namespaceObject.__)('Use your left or right arrow keys or drag and drop with the mouse to change the gradient position. Press the button to change the color or remove the control point.')));
}
function GradientColorPickerDropdown({
isRenderedInSidebar,
className,
...props
}) {
// Open the popover below the gradient control/insertion point
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
placement: 'bottom',
offset: 8
}), []);
const mergedClassName = classnames_default()('components-custom-gradient-picker__control-point-dropdown', className);
return (0,external_wp_element_namespaceObject.createElement)(CustomColorPickerDropdown, {
isRenderedInSidebar: isRenderedInSidebar,
popoverProps: popoverProps,
className: mergedClassName,
...props
});
}
function ControlPoints({
disableRemove,
disableAlpha,
gradientPickerDomRef,
ignoreMarkerPosition,
value: controlPoints,
onChange,
onStartControlPointChange,
onStopControlPointChange,
__experimentalIsRenderedInSidebar
}) {
const controlPointMoveState = (0,external_wp_element_namespaceObject.useRef)();
const onMouseMove = event => {
if (controlPointMoveState.current === undefined || gradientPickerDomRef.current === null) {
return;
}
const relativePosition = getHorizontalRelativeGradientPosition(event.clientX, gradientPickerDomRef.current);
const {
initialPosition,
index,
significantMoveHappened
} = controlPointMoveState.current;
if (!significantMoveHappened && Math.abs(initialPosition - relativePosition) >= MINIMUM_SIGNIFICANT_MOVE) {
controlPointMoveState.current.significantMoveHappened = true;
}
onChange(updateControlPointPosition(controlPoints, index, relativePosition));
};
const cleanEventListeners = () => {
if (window && window.removeEventListener && controlPointMoveState.current && controlPointMoveState.current.listenersActivated) {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', cleanEventListeners);
onStopControlPointChange();
controlPointMoveState.current.listenersActivated = false;
}
}; // Adding `cleanEventListeners` to the dependency array below requires the function itself to be wrapped in a `useCallback`
// This memoization would prevent the event listeners from being properly cleaned.
// Instead, we'll pass a ref to the function in our `useEffect` so `cleanEventListeners` itself is no longer a dependency.
const cleanEventListenersRef = (0,external_wp_element_namespaceObject.useRef)();
cleanEventListenersRef.current = cleanEventListeners;
(0,external_wp_element_namespaceObject.useEffect)(() => {
return () => {
cleanEventListenersRef.current?.();
};
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, controlPoints.map((point, index) => {
const initialPosition = point?.position;
return ignoreMarkerPosition !== initialPosition && (0,external_wp_element_namespaceObject.createElement)(GradientColorPickerDropdown, {
isRenderedInSidebar: __experimentalIsRenderedInSidebar,
key: index,
onClose: onStopControlPointChange,
renderToggle: ({
isOpen,
onToggle
}) => (0,external_wp_element_namespaceObject.createElement)(ControlPointButton, {
key: index,
onClick: () => {
if (controlPointMoveState.current && controlPointMoveState.current.significantMoveHappened) {
return;
}
if (isOpen) {
onStopControlPointChange();
} else {
onStartControlPointChange();
}
onToggle();
},
onMouseDown: () => {
if (window && window.addEventListener) {
controlPointMoveState.current = {
initialPosition,
index,
significantMoveHappened: false,
listenersActivated: true
};
onStartControlPointChange();
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', cleanEventListeners);
}
},
onKeyDown: event => {
if (event.code === 'ArrowLeft') {
// Stop propagation of the key press event to avoid focus moving
// to another editor area.
event.stopPropagation();
onChange(updateControlPointPosition(controlPoints, index, clampPercent(point.position - KEYBOARD_CONTROL_POINT_VARIATION)));
} else if (event.code === 'ArrowRight') {
// Stop propagation of the key press event to avoid focus moving
// to another editor area.
event.stopPropagation();
onChange(updateControlPointPosition(controlPoints, index, clampPercent(point.position + KEYBOARD_CONTROL_POINT_VARIATION)));
}
},
isOpen: isOpen,
position: point.position,
color: point.color
}),
renderContent: ({
onClose
}) => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
enableAlpha: !disableAlpha,
color: point.color,
onChange: color => {
onChange(updateControlPointColor(controlPoints, index, colord_w(color).toRgbString()));
}
}), !disableRemove && controlPoints.length > 2 && (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-custom-gradient-picker__remove-control-point-wrapper",
alignment: "center"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: () => {
onChange(removeControlPoint(controlPoints, index));
onClose();
},
variant: "link"
}, (0,external_wp_i18n_namespaceObject.__)('Remove Control Point')))),
style: {
left: `${point.position}%`,
transform: 'translateX( -50% )'
}
});
}));
}
function InsertPoint({
value: controlPoints,
onChange,
onOpenInserter,
onCloseInserter,
insertPosition,
disableAlpha,
__experimentalIsRenderedInSidebar
}) {
const [alreadyInsertedPoint, setAlreadyInsertedPoint] = (0,external_wp_element_namespaceObject.useState)(false);
return (0,external_wp_element_namespaceObject.createElement)(GradientColorPickerDropdown, {
isRenderedInSidebar: __experimentalIsRenderedInSidebar,
className: "components-custom-gradient-picker__inserter",
onClose: () => {
onCloseInserter();
},
renderToggle: ({
isOpen,
onToggle
}) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: () => {
if (isOpen) {
onCloseInserter();
} else {
setAlreadyInsertedPoint(false);
onOpenInserter();
}
onToggle();
},
className: "components-custom-gradient-picker__insert-point-dropdown",
icon: library_plus
}),
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
enableAlpha: !disableAlpha,
onChange: color => {
if (!alreadyInsertedPoint) {
onChange(addControlPoint(controlPoints, insertPosition, colord_w(color).toRgbString()));
setAlreadyInsertedPoint(true);
} else {
onChange(updateControlPointColorByPosition(controlPoints, insertPosition, colord_w(color).toRgbString()));
}
}
}),
style: insertPosition !== null ? {
left: `${insertPosition}%`,
transform: 'translateX( -50% )'
} : undefined
});
}
ControlPoints.InsertPoint = InsertPoint;
/* harmony default export */ var control_points = (ControlPoints);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const customGradientBarReducer = (state, action) => {
switch (action.type) {
case 'MOVE_INSERTER':
if (state.id === 'IDLE' || state.id === 'MOVING_INSERTER') {
return {
id: 'MOVING_INSERTER',
insertPosition: action.insertPosition
};
}
break;
case 'STOP_INSERTER_MOVE':
if (state.id === 'MOVING_INSERTER') {
return {
id: 'IDLE'
};
}
break;
case 'OPEN_INSERTER':
if (state.id === 'MOVING_INSERTER') {
return {
id: 'INSERTING_CONTROL_POINT',
insertPosition: state.insertPosition
};
}
break;
case 'CLOSE_INSERTER':
if (state.id === 'INSERTING_CONTROL_POINT') {
return {
id: 'IDLE'
};
}
break;
case 'START_CONTROL_CHANGE':
if (state.id === 'IDLE') {
return {
id: 'MOVING_CONTROL_POINT'
};
}
break;
case 'STOP_CONTROL_CHANGE':
if (state.id === 'MOVING_CONTROL_POINT') {
return {
id: 'IDLE'
};
}
break;
}
return state;
};
const customGradientBarReducerInitialState = {
id: 'IDLE'
};
function CustomGradientBar({
background,
hasGradient,
value: controlPoints,
onChange,
disableInserter = false,
disableAlpha = false,
__experimentalIsRenderedInSidebar = false
}) {
const gradientMarkersContainerDomRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [gradientBarState, gradientBarStateDispatch] = (0,external_wp_element_namespaceObject.useReducer)(customGradientBarReducer, customGradientBarReducerInitialState);
const onMouseEnterAndMove = event => {
if (!gradientMarkersContainerDomRef.current) {
return;
}
const insertPosition = getHorizontalRelativeGradientPosition(event.clientX, gradientMarkersContainerDomRef.current); // If the insert point is close to an existing control point don't show it.
if (controlPoints.some(({
position
}) => {
return Math.abs(insertPosition - position) < MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT;
})) {
if (gradientBarState.id === 'MOVING_INSERTER') {
gradientBarStateDispatch({
type: 'STOP_INSERTER_MOVE'
});
}
return;
}
gradientBarStateDispatch({
type: 'MOVE_INSERTER',
insertPosition
});
};
const onMouseLeave = () => {
gradientBarStateDispatch({
type: 'STOP_INSERTER_MOVE'
});
};
const isMovingInserter = gradientBarState.id === 'MOVING_INSERTER';
const isInsertingControlPoint = gradientBarState.id === 'INSERTING_CONTROL_POINT';
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-custom-gradient-picker__gradient-bar', {
'has-gradient': hasGradient
}),
onMouseEnter: onMouseEnterAndMove,
onMouseMove: onMouseEnterAndMove,
onMouseLeave: onMouseLeave
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-custom-gradient-picker__gradient-bar-background",
style: {
background,
opacity: hasGradient ? 1 : 0.4
}
}), (0,external_wp_element_namespaceObject.createElement)("div", {
ref: gradientMarkersContainerDomRef,
className: "components-custom-gradient-picker__markers-container"
}, !disableInserter && (isMovingInserter || isInsertingControlPoint) && (0,external_wp_element_namespaceObject.createElement)(control_points.InsertPoint, {
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
disableAlpha: disableAlpha,
insertPosition: gradientBarState.insertPosition,
value: controlPoints,
onChange: onChange,
onOpenInserter: () => {
gradientBarStateDispatch({
type: 'OPEN_INSERTER'
});
},
onCloseInserter: () => {
gradientBarStateDispatch({
type: 'CLOSE_INSERTER'
});
}
}), (0,external_wp_element_namespaceObject.createElement)(control_points, {
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
disableAlpha: disableAlpha,
disableRemove: disableInserter,
gradientPickerDomRef: gradientMarkersContainerDomRef,
ignoreMarkerPosition: isInsertingControlPoint ? gradientBarState.insertPosition : undefined,
value: controlPoints,
onChange: onChange,
onStartControlPointChange: () => {
gradientBarStateDispatch({
type: 'START_CONTROL_CHANGE'
});
},
onStopControlPointChange: () => {
gradientBarStateDispatch({
type: 'STOP_CONTROL_CHANGE'
});
}
})));
}
// EXTERNAL MODULE: ./node_modules/gradient-parser/build/node.js
var build_node = __webpack_require__(7115);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/constants.js
/**
* WordPress dependencies
*/
const DEFAULT_GRADIENT = 'linear-gradient(135deg, rgba(6, 147, 227, 1) 0%, rgb(155, 81, 224) 100%)';
const DEFAULT_LINEAR_GRADIENT_ANGLE = 180;
const HORIZONTAL_GRADIENT_ORIENTATION = {
type: 'angular',
value: '90'
};
const GRADIENT_OPTIONS = [{
value: 'linear-gradient',
label: (0,external_wp_i18n_namespaceObject.__)('Linear')
}, {
value: 'radial-gradient',
label: (0,external_wp_i18n_namespaceObject.__)('Radial')
}];
const DIRECTIONAL_ORIENTATION_ANGLE_MAP = {
top: 0,
'top right': 45,
'right top': 45,
right: 90,
'right bottom': 135,
'bottom right': 135,
bottom: 180,
'bottom left': 225,
'left bottom': 225,
left: 270,
'top left': 315,
'left top': 315
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/serializer.js
/**
* External dependencies
*/
function serializeGradientColor({
type,
value
}) {
if (type === 'literal') {
return value;
}
if (type === 'hex') {
return `#${value}`;
}
return `${type}(${value.join(',')})`;
}
function serializeGradientPosition(position) {
if (!position) {
return '';
}
const {
value,
type
} = position;
return `${value}${type}`;
}
function serializeGradientColorStop({
type,
value,
length
}) {
return `${serializeGradientColor({
type,
value
})} ${serializeGradientPosition(length)}`;
}
function serializeGradientOrientation(orientation) {
if (Array.isArray(orientation) || !orientation || orientation.type !== 'angular') {
return;
}
return `${orientation.value}deg`;
}
function serializeGradient({
type,
orientation,
colorStops
}) {
const serializedOrientation = serializeGradientOrientation(orientation);
const serializedColorStops = colorStops.sort((colorStop1, colorStop2) => {
const getNumericStopValue = colorStop => {
return colorStop?.length?.value === undefined ? 0 : parseInt(colorStop.length.value);
};
return getNumericStopValue(colorStop1) - getNumericStopValue(colorStop2);
}).map(serializeGradientColorStop);
return `${type}(${[serializedOrientation, ...serializedColorStops].filter(Boolean).join(',')})`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
colord_k([names]);
function getLinearGradientRepresentation(gradientAST) {
return serializeGradient({
type: 'linear-gradient',
orientation: HORIZONTAL_GRADIENT_ORIENTATION,
colorStops: gradientAST.colorStops
});
}
function hasUnsupportedLength(item) {
return item.length === undefined || item.length.type !== '%';
}
function getGradientAstWithDefault(value) {
// gradientAST will contain the gradient AST as parsed by gradient-parser npm module.
// More information of its structure available at https://www.npmjs.com/package/gradient-parser#ast.
let gradientAST;
let hasGradient = !!value;
const valueToParse = value !== null && value !== void 0 ? value : DEFAULT_GRADIENT;
try {
gradientAST = build_node.parse(valueToParse)[0];
} catch (error) {
// eslint-disable-next-line no-console
console.warn('wp.components.CustomGradientPicker failed to parse the gradient with error', error);
gradientAST = build_node.parse(DEFAULT_GRADIENT)[0];
hasGradient = false;
}
if (!Array.isArray(gradientAST.orientation) && gradientAST.orientation?.type === 'directional') {
gradientAST.orientation = {
type: 'angular',
value: DIRECTIONAL_ORIENTATION_ANGLE_MAP[gradientAST.orientation.value].toString()
};
}
if (gradientAST.colorStops.some(hasUnsupportedLength)) {
const {
colorStops
} = gradientAST;
const step = 100 / (colorStops.length - 1);
colorStops.forEach((stop, index) => {
stop.length = {
value: `${step * index}`,
type: '%'
};
});
}
return {
gradientAST,
hasGradient
};
}
function getGradientAstWithControlPoints(gradientAST, newControlPoints) {
return { ...gradientAST,
colorStops: newControlPoints.map(({
position,
color
}) => {
const {
r,
g,
b,
a
} = colord_w(color).toRgb();
return {
length: {
type: '%',
value: position?.toString()
},
type: a < 1 ? 'rgba' : 'rgb',
value: a < 1 ? [`${r}`, `${g}`, `${b}`, `${a}`] : [`${r}`, `${g}`, `${b}`]
};
})
};
}
function getStopCssColor(colorStop) {
switch (colorStop.type) {
case 'hex':
return `#${colorStop.value}`;
case 'literal':
return colorStop.value;
case 'rgb':
case 'rgba':
return `${colorStop.type}(${colorStop.value.join(',')})`;
default:
// Should be unreachable if passing an AST from gradient-parser.
// See https://github.com/rafaelcaricio/gradient-parser#ast.
return 'transparent';
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/styles/custom-gradient-picker-styles.js
function custom_gradient_picker_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const SelectWrapper = /*#__PURE__*/createStyled(flex_block_component, true ? {
target: "e10bzpgi1"
} : 0)( true ? {
name: "1gvx10y",
styles: "flex-grow:5"
} : 0);
const AccessoryWrapper = /*#__PURE__*/createStyled(flex_block_component, true ? {
target: "e10bzpgi0"
} : 0)( true ? {
name: "1gvx10y",
styles: "flex-grow:5"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const GradientAnglePicker = ({
gradientAST,
hasGradient,
onChange
}) => {
var _gradientAST$orientat;
const angle = (_gradientAST$orientat = gradientAST?.orientation?.value) !== null && _gradientAST$orientat !== void 0 ? _gradientAST$orientat : DEFAULT_LINEAR_GRADIENT_ANGLE;
const onAngleChange = newAngle => {
onChange(serializeGradient({ ...gradientAST,
orientation: {
type: 'angular',
value: `${newAngle}`
}
}));
};
return (0,external_wp_element_namespaceObject.createElement)(angle_picker_control, {
__nextHasNoMarginBottom: true,
onChange: onAngleChange,
value: hasGradient ? angle : ''
});
};
const GradientTypePicker = ({
gradientAST,
hasGradient,
onChange
}) => {
const {
type
} = gradientAST;
const onSetLinearGradient = () => {
onChange(serializeGradient({ ...gradientAST,
orientation: gradientAST.orientation ? undefined : HORIZONTAL_GRADIENT_ORIENTATION,
type: 'linear-gradient'
}));
};
const onSetRadialGradient = () => {
const {
orientation,
...restGradientAST
} = gradientAST;
onChange(serializeGradient({ ...restGradientAST,
type: 'radial-gradient'
}));
};
const handleOnChange = next => {
if (next === 'linear-gradient') {
onSetLinearGradient();
}
if (next === 'radial-gradient') {
onSetRadialGradient();
}
};
return (0,external_wp_element_namespaceObject.createElement)(select_control, {
__nextHasNoMarginBottom: true,
className: "components-custom-gradient-picker__type-picker",
label: (0,external_wp_i18n_namespaceObject.__)('Type'),
labelPosition: "top",
onChange: handleOnChange,
options: GRADIENT_OPTIONS,
size: "__unstable-large",
value: hasGradient ? type : undefined
});
};
/**
* CustomGradientPicker is a React component that renders a UI for specifying
* linear or radial gradients. Radial gradients are displayed in the picker as
* a slice of the gradient from the center to the outside.
*
* ```jsx
* import { CustomGradientPicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyCustomGradientPicker = () => {
* const [ gradient, setGradient ] = useState();
*
* return (
* <CustomGradientPicker
* value={ gradient }
* onChange={ setGradient }
* />
* );
* };
* ```
*/
function CustomGradientPicker({
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMargin = false,
value,
onChange,
__experimentalIsRenderedInSidebar = false
}) {
const {
gradientAST,
hasGradient
} = getGradientAstWithDefault(value); // On radial gradients the bar should display a linear gradient.
// On radial gradients the bar represents a slice of the gradient from the center until the outside.
// On liner gradients the bar represents the color stops from left to right independently of the angle.
const background = getLinearGradientRepresentation(gradientAST); // Control points color option may be hex from presets, custom colors will be rgb.
// The position should always be a percentage.
const controlPoints = gradientAST.colorStops.map(colorStop => {
return {
color: getStopCssColor(colorStop),
// Although it's already been checked by `hasUnsupportedLength` in `getGradientAstWithDefault`,
// TypeScript doesn't know that `colorStop.length` is not undefined here.
// @ts-expect-error
position: parseInt(colorStop.length.value)
};
});
if (!__nextHasNoMargin) {
external_wp_deprecated_default()('Outer margin styles for wp.components.CustomGradientPicker', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMargin` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 4,
className: classnames_default()('components-custom-gradient-picker', {
'is-next-has-no-margin': __nextHasNoMargin
})
}, (0,external_wp_element_namespaceObject.createElement)(CustomGradientBar, {
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
background: background,
hasGradient: hasGradient,
value: controlPoints,
onChange: newControlPoints => {
onChange(serializeGradient(getGradientAstWithControlPoints(gradientAST, newControlPoints)));
}
}), (0,external_wp_element_namespaceObject.createElement)(flex_component, {
gap: 3,
className: "components-custom-gradient-picker__ui-line"
}, (0,external_wp_element_namespaceObject.createElement)(SelectWrapper, null, (0,external_wp_element_namespaceObject.createElement)(GradientTypePicker, {
gradientAST: gradientAST,
hasGradient: hasGradient,
onChange: onChange
})), (0,external_wp_element_namespaceObject.createElement)(AccessoryWrapper, null, gradientAST.type === 'linear-gradient' && (0,external_wp_element_namespaceObject.createElement)(GradientAnglePicker, {
gradientAST: gradientAST,
hasGradient: hasGradient,
onChange: onChange
}))));
}
/* harmony default export */ var custom_gradient_picker = (CustomGradientPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/gradient-picker/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// The Multiple Origin Gradients have a `gradients` property (an array of
// gradient objects), while Single Origin ones have a `gradient` property.
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,
actions
}) {
const gradientOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return gradients.map(({
gradient,
name
}, index) => (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.Option, {
key: gradient,
value: gradient,
isSelected: value === gradient,
tooltipText: name || // translators: %s: gradient code e.g: "linear-gradient(90deg, rgba(98,16,153,1) 0%, rgba(172,110,22,1) 100%);".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Gradient code: %s'), gradient),
style: {
color: 'rgba( 0,0,0,0 )',
background: gradient
},
onClick: value === gradient ? clearGradient : () => onChange(gradient, index),
"aria-label": name ? // translators: %s: The name of the gradient e.g: "Angular red to blue".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Gradient: %s'), name) : // translators: %s: gradient code e.g: "linear-gradient(90deg, rgba(98,16,153,1) 0%, rgba(172,110,22,1) 100%);".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Gradient code: %s'), gradient)
}));
}, [gradients, value, onChange, clearGradient]);
return (0,external_wp_element_namespaceObject.createElement)(circular_option_picker, {
className: className,
options: gradientOptions,
actions: actions
});
}
function MultipleOrigin({
className,
clearGradient,
gradients,
onChange,
value,
actions,
headingLevel
}) {
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3,
className: className
}, gradients.map(({
name,
gradients: gradientSet
}, index) => {
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 2,
key: index
}, (0,external_wp_element_namespaceObject.createElement)(ColorHeading, {
level: headingLevel
}, name), (0,external_wp_element_namespaceObject.createElement)(SingleOrigin, {
clearGradient: clearGradient,
gradients: gradientSet,
onChange: gradient => onChange(gradient, index),
value: value,
...(gradients.length === index + 1 ? {
actions
} : {})
}));
}));
}
function Component(props) {
if (isMultipleOriginArray(props.gradients)) {
return (0,external_wp_element_namespaceObject.createElement)(MultipleOrigin, { ...props
});
}
return (0,external_wp_element_namespaceObject.createElement)(SingleOrigin, { ...props
});
}
/**
* 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 { GradientPicker } from '@wordpress/components';
*import { useState } from '@wordpress/element';
*
*const myGradientPicker = () => {
* const [ gradient, setGradient ] = useState( null );
*
* return (
* <GradientPicker
* __nextHasNoMargin
* 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({
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMargin = false,
className,
gradients = [],
onChange,
value,
clearable = true,
disableCustomGradients = false,
__experimentalIsRenderedInSidebar,
headingLevel = 2
}) {
const clearGradient = (0,external_wp_element_namespaceObject.useCallback)(() => onChange(undefined), [onChange]);
if (!__nextHasNoMargin) {
external_wp_deprecated_default()('Outer margin styles for wp.components.GradientPicker', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMargin` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
const deprecatedMarginSpacerProps = !__nextHasNoMargin ? {
marginTop: !gradients.length ? 3 : undefined,
marginBottom: !clearable ? 6 : 0
} : {};
return (// Outmost Spacer wrapper can be removed when deprecation period is over
(0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: 0,
...deprecatedMarginSpacerProps
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: gradients.length ? 4 : 0
}, !disableCustomGradients && (0,external_wp_element_namespaceObject.createElement)(custom_gradient_picker, {
__nextHasNoMargin: true,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
value: value,
onChange: onChange
}), (gradients.length || clearable) && (0,external_wp_element_namespaceObject.createElement)(Component, {
className: className,
clearGradient: clearGradient,
gradients: gradients,
onChange: onChange,
value: value,
actions: clearable && !disableCustomGradients && (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.ButtonAction, {
onClick: clearGradient
}, (0,external_wp_i18n_namespaceObject.__)('Clear')),
headingLevel: headingLevel
})))
);
}
/* harmony default export */ var gradient_picker = (GradientPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/menu.js
/**
* WordPress dependencies
*/
const menu = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M5 5v1.5h14V5H5zm0 7.8h14v-1.5H5v1.5zM5 19h14v-1.5H5V19z"
}));
/* harmony default export */ var library_menu = (menu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigable-container/container.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const container_noop = () => {};
const MENU_ITEM_ROLES = ['menuitem', 'menuitemradio', 'menuitemcheckbox'];
function cycleValue(value, total, offset) {
const nextValue = value + offset;
if (nextValue < 0) {
return total + nextValue;
} else if (nextValue >= total) {
return nextValue - total;
}
return nextValue;
}
class NavigableContainer extends external_wp_element_namespaceObject.Component {
constructor(args) {
super(args);
this.onKeyDown = this.onKeyDown.bind(this);
this.bindContainer = this.bindContainer.bind(this);
this.getFocusableContext = this.getFocusableContext.bind(this);
this.getFocusableIndex = this.getFocusableIndex.bind(this);
}
componentDidMount() {
if (!this.container) {
return;
} // We use DOM event listeners instead of React event listeners
// because we want to catch events from the underlying DOM tree
// The React Tree can be different from the DOM tree when using
// portals. Block Toolbars for instance are rendered in a separate
// React Trees.
this.container.addEventListener('keydown', this.onKeyDown);
}
componentWillUnmount() {
if (!this.container) {
return;
}
this.container.removeEventListener('keydown', this.onKeyDown);
}
bindContainer(ref) {
const {
forwardedRef
} = this.props;
this.container = ref;
if (typeof forwardedRef === 'function') {
forwardedRef(ref);
} else if (forwardedRef && 'current' in forwardedRef) {
forwardedRef.current = ref;
}
}
getFocusableContext(target) {
if (!this.container) {
return null;
}
const {
onlyBrowserTabstops
} = this.props;
const finder = onlyBrowserTabstops ? external_wp_dom_namespaceObject.focus.tabbable : external_wp_dom_namespaceObject.focus.focusable;
const focusables = finder.find(this.container);
const index = this.getFocusableIndex(focusables, target);
if (index > -1 && target) {
return {
index,
target,
focusables
};
}
return null;
}
getFocusableIndex(focusables, target) {
return focusables.indexOf(target);
}
onKeyDown(event) {
if (this.props.onKeyDown) {
this.props.onKeyDown(event);
}
const {
getFocusableContext
} = this;
const {
cycle = true,
eventToOffset,
onNavigate = container_noop,
stopNavigationEvents
} = this.props;
const offset = eventToOffset(event); // eventToOffset returns undefined if the event is not handled by the component.
if (offset !== undefined && stopNavigationEvents) {
// Prevents arrow key handlers bound to the document directly interfering.
event.stopImmediatePropagation(); // When navigating a collection of items, prevent scroll containers
// from scrolling. The preventDefault also prevents Voiceover from
// 'handling' the event, as voiceover will try to use arrow keys
// for highlighting text.
const targetRole = event.target?.getAttribute('role');
const targetHasMenuItemRole = !!targetRole && MENU_ITEM_ROLES.includes(targetRole);
if (targetHasMenuItemRole) {
event.preventDefault();
}
}
if (!offset) {
return;
}
const activeElement = event.target?.ownerDocument?.activeElement;
if (!activeElement) {
return;
}
const context = getFocusableContext(activeElement);
if (!context) {
return;
}
const {
index,
focusables
} = context;
const nextIndex = cycle ? cycleValue(index, focusables.length, offset) : index + offset;
if (nextIndex >= 0 && nextIndex < focusables.length) {
focusables[nextIndex].focus();
onNavigate(nextIndex, focusables[nextIndex]); // `preventDefault()` on tab to avoid having the browser move the focus
// after this component has already moved it.
if (event.code === 'Tab') {
event.preventDefault();
}
}
}
render() {
const {
children,
stopNavigationEvents,
eventToOffset,
onNavigate,
onKeyDown,
cycle,
onlyBrowserTabstops,
forwardedRef,
...restProps
} = this.props;
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: this.bindContainer,
...restProps
}, children);
}
}
const forwardedNavigableContainer = (props, ref) => {
return (0,external_wp_element_namespaceObject.createElement)(NavigableContainer, { ...props,
forwardedRef: ref
});
};
forwardedNavigableContainer.displayName = 'NavigableContainer';
/* harmony default export */ var container = ((0,external_wp_element_namespaceObject.forwardRef)(forwardedNavigableContainer));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigable-container/menu.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedNavigableMenu({
role = 'menu',
orientation = 'vertical',
...rest
}, ref) {
const eventToOffset = evt => {
const {
code
} = evt;
let next = ['ArrowDown'];
let previous = ['ArrowUp'];
if (orientation === 'horizontal') {
next = ['ArrowRight'];
previous = ['ArrowLeft'];
}
if (orientation === 'both') {
next = ['ArrowRight', 'ArrowDown'];
previous = ['ArrowLeft', 'ArrowUp'];
}
if (next.includes(code)) {
return 1;
} else if (previous.includes(code)) {
return -1;
} else if (['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight'].includes(code)) {
// Key press should be handled, e.g. have event propagation and
// default behavior handled by NavigableContainer but not result
// in an offset.
return 0;
}
return undefined;
};
return (0,external_wp_element_namespaceObject.createElement)(container, {
ref: ref,
stopNavigationEvents: true,
onlyBrowserTabstops: false,
role: role,
"aria-orientation": role !== 'presentation' && (orientation === 'vertical' || orientation === 'horizontal') ? orientation : undefined,
eventToOffset: eventToOffset,
...rest
});
}
/**
* A container for a navigable menu.
*
* ```jsx
* import {
* NavigableMenu,
* Button,
* } from '@wordpress/components';
*
* function onNavigate( index, target ) {
* console.log( `Navigates to ${ index }`, target );
* }
*
* const MyNavigableContainer = () => (
* <div>
* <span>Navigable Menu:</span>
* <NavigableMenu onNavigate={ onNavigate } orientation="horizontal">
* <Button variant="secondary">Item 1</Button>
* <Button variant="secondary">Item 2</Button>
* <Button variant="secondary">Item 3</Button>
* </NavigableMenu>
* </div>
* );
* ```
*/
const NavigableMenu = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedNavigableMenu);
/* harmony default export */ var navigable_container_menu = (NavigableMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown-menu/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function mergeProps(defaultProps = {}, props = {}) {
const mergedProps = { ...defaultProps,
...props
};
if (props.className && defaultProps.className) {
mergedProps.className = classnames_default()(props.className, defaultProps.className);
}
return mergedProps;
}
function dropdown_menu_isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
function UnconnectedDropdownMenu(dropdownMenuProps) {
const {
children,
className,
controls,
icon = library_menu,
label,
popoverProps,
toggleProps,
menuProps,
disableOpenOnArrowDown = false,
text,
noIcons,
// Context
variant
} = useContextSystem(dropdownMenuProps, 'DropdownMenu');
if (!controls?.length && !dropdown_menu_isFunction(children)) {
return null;
} // Normalize controls to nested array of objects (sets of controls)
let controlSets;
if (controls?.length) {
// @ts-expect-error The check below is needed because `DropdownMenus`
// rendered by `ToolBarGroup` receive controls as a nested array.
controlSets = controls;
if (!Array.isArray(controlSets[0])) {
// This is not ideal, but at this point we know that `controls` is
// not a nested array, even if TypeScript doesn't.
controlSets = [controls];
}
}
const mergedPopoverProps = mergeProps({
className: 'components-dropdown-menu__popover',
variant
}, popoverProps);
return (0,external_wp_element_namespaceObject.createElement)(dropdown, {
className: className,
popoverProps: mergedPopoverProps,
renderToggle: ({
isOpen,
onToggle
}) => {
var _toggleProps$showTool;
const openOnArrowDown = event => {
if (disableOpenOnArrowDown) {
return;
}
if (!isOpen && event.code === 'ArrowDown') {
event.preventDefault();
onToggle();
}
};
const {
as: Toggle = build_module_button,
...restToggleProps
} = toggleProps !== null && toggleProps !== void 0 ? toggleProps : {};
const mergedToggleProps = mergeProps({
className: classnames_default()('components-dropdown-menu__toggle', {
'is-opened': isOpen
})
}, restToggleProps);
return (0,external_wp_element_namespaceObject.createElement)(Toggle, { ...mergedToggleProps,
icon: icon,
onClick: event => {
onToggle();
if (mergedToggleProps.onClick) {
mergedToggleProps.onClick(event);
}
},
onKeyDown: event => {
openOnArrowDown(event);
if (mergedToggleProps.onKeyDown) {
mergedToggleProps.onKeyDown(event);
}
},
"aria-haspopup": "true",
"aria-expanded": isOpen,
label: label,
text: text,
showTooltip: (_toggleProps$showTool = toggleProps?.showTooltip) !== null && _toggleProps$showTool !== void 0 ? _toggleProps$showTool : true
}, mergedToggleProps.children);
},
renderContent: props => {
const mergedMenuProps = mergeProps({
'aria-label': label,
className: classnames_default()('components-dropdown-menu__menu', {
'no-icons': noIcons
})
}, menuProps);
return (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, { ...mergedMenuProps,
role: "menu"
}, dropdown_menu_isFunction(children) ? children(props) : null, controlSets?.flatMap((controlSet, indexOfSet) => controlSet.map((control, indexOfControl) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: [indexOfSet, indexOfControl].join(),
onClick: event => {
event.stopPropagation();
props.onClose();
if (control.onClick) {
control.onClick();
}
},
className: classnames_default()('components-dropdown-menu__menu-item', {
'has-separator': indexOfSet > 0 && indexOfControl === 0,
'is-active': control.isActive,
'is-icon-only': !control.title
}),
icon: control.icon,
label: control.label,
"aria-checked": control.role === 'menuitemcheckbox' || control.role === 'menuitemradio' ? control.isActive : undefined,
role: control.role === 'menuitemcheckbox' || control.role === 'menuitemradio' ? control.role : 'menuitem',
disabled: control.isDisabled
}, control.title))));
}
});
}
/**
*
* The DropdownMenu displays a list of actions (each contained in a MenuItem,
* MenuItemsChoice, or MenuGroup) in a compact way. It appears in a Popover
* after the user has interacted with an element (a button or icon) or when
* they perform a specific action.
*
* Render a Dropdown Menu with a set of controls:
*
* ```jsx
* import { DropdownMenu } from '@wordpress/components';
* import {
* more,
* arrowLeft,
* arrowRight,
* arrowUp,
* arrowDown,
* } from '@wordpress/icons';
*
* const MyDropdownMenu = () => (
* <DropdownMenu
* icon={ more }
* label="Select a direction"
* controls={ [
* {
* title: 'Up',
* icon: arrowUp,
* onClick: () => console.log( 'up' ),
* },
* {
* title: 'Right',
* icon: arrowRight,
* onClick: () => console.log( 'right' ),
* },
* {
* title: 'Down',
* icon: arrowDown,
* onClick: () => console.log( 'down' ),
* },
* {
* title: 'Left',
* icon: arrowLeft,
* onClick: () => console.log( 'left' ),
* },
* ] }
* />
* );
* ```
*
* Alternatively, specify a `children` function which returns elements valid for
* use in a DropdownMenu: `MenuItem`, `MenuItemsChoice`, or `MenuGroup`.
*
* ```jsx
* import { DropdownMenu, MenuGroup, MenuItem } from '@wordpress/components';
* import { more, arrowUp, arrowDown, trash } from '@wordpress/icons';
*
* const MyDropdownMenu = () => (
* <DropdownMenu icon={ more } label="Select a direction">
* { ( { onClose } ) => (
* <>
* <MenuGroup>
* <MenuItem icon={ arrowUp } onClick={ onClose }>
* Move Up
* </MenuItem>
* <MenuItem icon={ arrowDown } onClick={ onClose }>
* Move Down
* </MenuItem>
* </MenuGroup>
* <MenuGroup>
* <MenuItem icon={ trash } onClick={ onClose }>
* Remove
* </MenuItem>
* </MenuGroup>
* </>
* ) }
* </DropdownMenu>
* );
* ```
*
*/
const DropdownMenu = contextConnectWithoutRef(UnconnectedDropdownMenu, 'DropdownMenu');
/* harmony default export */ var dropdown_menu = (DropdownMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/palette-edit/styles.js
function palette_edit_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const IndicatorStyled = /*#__PURE__*/createStyled(circular_option_picker.Option, true ? {
target: "e5bw3229"
} : 0)("width:", space(6), ";height:", space(6), ";pointer-events:none;" + ( true ? "" : 0));
const NameInputControl = /*#__PURE__*/createStyled(input_control, true ? {
target: "e5bw3228"
} : 0)(Container, "{background:", COLORS.gray[100], ";border-radius:", config_values.controlBorderRadius, ";", Input, Input, Input, Input, "{height:", space(8), ";}", BackdropUI, BackdropUI, BackdropUI, "{border-color:transparent;box-shadow:none;}}" + ( true ? "" : 0));
const PaletteItem = /*#__PURE__*/createStyled(component, true ? {
target: "e5bw3227"
} : 0)("padding:3px 0 3px ", space(3), ";height:calc( 40px - ", config_values.borderWidth, " );border:1px solid ", config_values.surfaceBorderColor, ";border-bottom-color:transparent;&:first-of-type{border-top-left-radius:", config_values.controlBorderRadius, ";border-top-right-radius:", config_values.controlBorderRadius, ";}&:last-of-type{border-bottom-left-radius:", config_values.controlBorderRadius, ";border-bottom-right-radius:", config_values.controlBorderRadius, ";border-bottom-color:", config_values.surfaceBorderColor, ";}&.is-selected+&{border-top-color:transparent;}&.is-selected{border-color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const NameContainer = createStyled("div", true ? {
target: "e5bw3226"
} : 0)("line-height:", space(8), ";margin-left:", space(2), ";margin-right:", space(2), ";white-space:nowrap;overflow:hidden;", PaletteItem, ":hover &{color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const PaletteHeading = /*#__PURE__*/createStyled(heading_component, true ? {
target: "e5bw3225"
} : 0)("text-transform:uppercase;line-height:", space(6), ";font-weight:500;&&&{font-size:11px;margin-bottom:0;}" + ( true ? "" : 0));
const PaletteActionsContainer = /*#__PURE__*/createStyled(component, true ? {
target: "e5bw3224"
} : 0)("height:", space(6), ";display:flex;" + ( true ? "" : 0));
const PaletteHStackHeader = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "e5bw3223"
} : 0)("margin-bottom:", space(2), ";" + ( true ? "" : 0));
const PaletteEditStyles = /*#__PURE__*/createStyled(component, true ? {
target: "e5bw3222"
} : 0)( true ? {
name: "u6wnko",
styles: "&&&{.components-button.has-icon{min-width:0;padding:0;}}"
} : 0);
const DoneButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "e5bw3221"
} : 0)("&&{color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const RemoveButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "e5bw3220"
} : 0)("&&{margin-top:", space(1), ";}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/palette-edit/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_COLOR = '#000';
function NameInput({
value,
onChange,
label
}) {
return (0,external_wp_element_namespaceObject.createElement)(NameInputControl, {
label: label,
hideLabelFromVision: true,
value: value,
onChange: onChange
});
}
/**
* Returns a temporary name for a palette item in the format "Color + id".
* To ensure there are no duplicate ids, this function checks all slugs for temporary names.
* It expects slugs to be in the format: slugPrefix + color- + number.
* It then sets the id component of the new name based on the incremented id of the highest existing slug id.
*
* @param elements An array of color palette items.
* @param slugPrefix The slug prefix used to match the element slug.
*
* @return A unique name for a palette item.
*/
function getNameForPosition(elements, slugPrefix) {
const temporaryNameRegex = new RegExp(`^${slugPrefix}color-([\\d]+)$`);
const position = elements.reduce((previousValue, currentValue) => {
if (typeof currentValue?.slug === 'string') {
const matches = currentValue?.slug.match(temporaryNameRegex);
if (matches) {
const id = parseInt(matches[1], 10);
if (id >= previousValue) {
return id + 1;
}
}
}
return previousValue;
}, 1);
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: is a temporary id for a custom color */
(0,external_wp_i18n_namespaceObject.__)('Color %s'), position);
}
function ColorPickerPopover({
isGradient,
element,
onChange,
popoverProps: receivedPopoverProps,
onClose = () => {}
}) {
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
shift: true,
offset: 20,
placement: 'left-start',
...receivedPopoverProps,
className: classnames_default()('components-palette-edit__popover', receivedPopoverProps?.className)
}), [receivedPopoverProps]);
return (0,external_wp_element_namespaceObject.createElement)(popover, { ...popoverProps,
onClose: onClose
}, !isGradient && (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
color: element.color,
enableAlpha: true,
onChange: newColor => {
onChange({ ...element,
color: newColor
});
}
}), isGradient && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-palette-edit__popover-gradient-picker"
}, (0,external_wp_element_namespaceObject.createElement)(custom_gradient_picker, {
__nextHasNoMargin: true,
__experimentalIsRenderedInSidebar: true,
value: element.gradient,
onChange: newGradient => {
onChange({ ...element,
gradient: newGradient
});
}
})));
}
function palette_edit_Option({
canOnlyChangeValues,
element,
onChange,
isEditing,
onStartEditing,
onRemove,
onStopEditing,
popoverProps: receivedPopoverProps,
slugPrefix,
isGradient
}) {
const focusOutsideProps = (0,external_wp_compose_namespaceObject.__experimentalUseFocusOutside)(onStopEditing);
const value = isGradient ? element.gradient : element.color; // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null);
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({ ...receivedPopoverProps,
// Use the custom palette color item as the popover anchor.
anchor: popoverAnchor
}), [popoverAnchor, receivedPopoverProps]);
return (0,external_wp_element_namespaceObject.createElement)(PaletteItem, {
className: isEditing ? 'is-selected' : undefined,
as: "div",
onClick: onStartEditing,
ref: setPopoverAnchor,
...(isEditing ? { ...focusOutsideProps
} : {
style: {
cursor: 'pointer'
}
})
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
justify: "flex-start"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(IndicatorStyled, {
style: {
background: value,
color: 'transparent'
}
})), (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, isEditing && !canOnlyChangeValues ? (0,external_wp_element_namespaceObject.createElement)(NameInput, {
label: isGradient ? (0,external_wp_i18n_namespaceObject.__)('Gradient name') : (0,external_wp_i18n_namespaceObject.__)('Color name'),
value: element.name,
onChange: nextName => onChange({ ...element,
name: nextName,
slug: slugPrefix + paramCase(nextName !== null && nextName !== void 0 ? nextName : '')
})
}) : (0,external_wp_element_namespaceObject.createElement)(NameContainer, null, element.name)), isEditing && !canOnlyChangeValues && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(RemoveButton, {
isSmall: true,
icon: line_solid,
label: (0,external_wp_i18n_namespaceObject.__)('Remove color'),
onClick: onRemove
}))), isEditing && (0,external_wp_element_namespaceObject.createElement)(ColorPickerPopover, {
isGradient: isGradient,
onChange: onChange,
element: element,
popoverProps: popoverProps
}));
}
function isTemporaryElement(slugPrefix, {
slug,
color,
gradient
}) {
const regex = new RegExp(`^${slugPrefix}color-([\\d]+)$`);
return regex.test(slug) && (!!color && color === DEFAULT_COLOR || !!gradient && gradient === DEFAULT_GRADIENT);
}
function PaletteEditListView({
elements,
onChange,
editingElement,
setEditingElement,
canOnlyChangeValues,
slugPrefix,
isGradient,
popoverProps
}) {
// When unmounting the component if there are empty elements (the user did not complete the insertion) clean them.
const elementsReference = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
elementsReference.current = elements;
}, [elements]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
return () => {
if (elementsReference.current?.some(element => isTemporaryElement(slugPrefix, element))) {
const newElements = elementsReference.current.filter(element => !isTemporaryElement(slugPrefix, element));
onChange(newElements.length ? newElements : undefined);
}
}; // Disable reason: adding the missing dependency here would cause breaking changes that will require
// a heavier refactor to avoid. See https://github.com/WordPress/gutenberg/pull/43911
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const debounceOnChange = (0,external_wp_compose_namespaceObject.useDebounce)(onChange, 100);
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3
}, (0,external_wp_element_namespaceObject.createElement)(item_group_component, {
isRounded: true
}, elements.map((element, index) => (0,external_wp_element_namespaceObject.createElement)(palette_edit_Option, {
isGradient: isGradient,
canOnlyChangeValues: canOnlyChangeValues,
key: index,
element: element,
onStartEditing: () => {
if (editingElement !== index) {
setEditingElement(index);
}
},
onChange: newElement => {
debounceOnChange(elements.map((currentElement, currentIndex) => {
if (currentIndex === index) {
return newElement;
}
return currentElement;
}));
},
onRemove: () => {
setEditingElement(null);
const newElements = elements.filter((_currentElement, currentIndex) => {
if (currentIndex === index) {
return false;
}
return true;
});
onChange(newElements.length ? newElements : undefined);
},
isEditing: index === editingElement,
onStopEditing: () => {
if (index === editingElement) {
setEditingElement(null);
}
},
slugPrefix: slugPrefix,
popoverProps: popoverProps
}))));
}
const EMPTY_ARRAY = [];
/**
* Allows editing a palette of colors or gradients.
*
* ```jsx
* import { PaletteEdit } from '@wordpress/components';
* const MyPaletteEdit = () => {
* const [ controlledColors, setControlledColors ] = useState( colors );
*
* return (
* <PaletteEdit
* colors={ controlledColors }
* onChange={ ( newColors?: Color[] ) => {
* setControlledColors( newColors );
* } }
* paletteLabel="Here is a label"
* />
* );
* };
* ```
*/
function PaletteEdit({
gradients,
colors = EMPTY_ARRAY,
onChange,
paletteLabel,
paletteLabelHeadingLevel = 2,
emptyMessage,
canOnlyChangeValues,
canReset,
slugPrefix = '',
popoverProps
}) {
const isGradient = !!gradients;
const elements = isGradient ? gradients : colors;
const [isEditing, setIsEditing] = (0,external_wp_element_namespaceObject.useState)(false);
const [editingElement, setEditingElement] = (0,external_wp_element_namespaceObject.useState)(null);
const isAdding = isEditing && !!editingElement && elements[editingElement] && !elements[editingElement].slug;
const elementsLength = elements.length;
const hasElements = elementsLength > 0;
const debounceOnChange = (0,external_wp_compose_namespaceObject.useDebounce)(onChange, 100);
const onSelectPaletteItem = (0,external_wp_element_namespaceObject.useCallback)((value, newEditingElementIndex) => {
const selectedElement = newEditingElementIndex === undefined ? undefined : elements[newEditingElementIndex];
const key = isGradient ? 'gradient' : 'color'; // Ensures that the index returned matches a known element value.
if (!!selectedElement && selectedElement[key] === value) {
setEditingElement(newEditingElementIndex);
} else {
setIsEditing(true);
}
}, [isGradient, elements]);
return (0,external_wp_element_namespaceObject.createElement)(PaletteEditStyles, null, (0,external_wp_element_namespaceObject.createElement)(PaletteHStackHeader, null, (0,external_wp_element_namespaceObject.createElement)(PaletteHeading, {
level: paletteLabelHeadingLevel
}, paletteLabel), (0,external_wp_element_namespaceObject.createElement)(PaletteActionsContainer, null, hasElements && isEditing && (0,external_wp_element_namespaceObject.createElement)(DoneButton, {
isSmall: true,
onClick: () => {
setIsEditing(false);
setEditingElement(null);
}
}, (0,external_wp_i18n_namespaceObject.__)('Done')), !canOnlyChangeValues && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isSmall: true,
isPressed: isAdding,
icon: library_plus,
label: isGradient ? (0,external_wp_i18n_namespaceObject.__)('Add gradient') : (0,external_wp_i18n_namespaceObject.__)('Add color'),
onClick: () => {
const tempOptionName = getNameForPosition(elements, slugPrefix);
if (!!gradients) {
onChange([...gradients, {
gradient: DEFAULT_GRADIENT,
name: tempOptionName,
slug: slugPrefix + paramCase(tempOptionName)
}]);
} else {
onChange([...colors, {
color: DEFAULT_COLOR,
name: tempOptionName,
slug: slugPrefix + paramCase(tempOptionName)
}]);
}
setIsEditing(true);
setEditingElement(elements.length);
}
}), hasElements && (!isEditing || !canOnlyChangeValues || canReset) && (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, {
icon: more_vertical,
label: isGradient ? (0,external_wp_i18n_namespaceObject.__)('Gradient options') : (0,external_wp_i18n_namespaceObject.__)('Color options'),
toggleProps: {
isSmall: true
}
}, ({
onClose
}) => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, {
role: "menu"
}, !isEditing && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: () => {
setIsEditing(true);
onClose();
},
className: "components-palette-edit__menu-button"
}, (0,external_wp_i18n_namespaceObject.__)('Show details')), !canOnlyChangeValues && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: () => {
setEditingElement(null);
setIsEditing(false);
onChange();
onClose();
},
className: "components-palette-edit__menu-button"
}, isGradient ? (0,external_wp_i18n_namespaceObject.__)('Remove all gradients') : (0,external_wp_i18n_namespaceObject.__)('Remove all colors')), canReset && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: () => {
setEditingElement(null);
onChange();
onClose();
}
}, isGradient ? (0,external_wp_i18n_namespaceObject.__)('Reset gradient') : (0,external_wp_i18n_namespaceObject.__)('Reset colors'))))))), hasElements && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isEditing && (0,external_wp_element_namespaceObject.createElement)(PaletteEditListView, {
canOnlyChangeValues: canOnlyChangeValues,
elements: elements // @ts-expect-error TODO: Don't know how to resolve
,
onChange: onChange,
editingElement: editingElement,
setEditingElement: setEditingElement,
slugPrefix: slugPrefix,
isGradient: isGradient,
popoverProps: popoverProps
}), !isEditing && editingElement !== null && (0,external_wp_element_namespaceObject.createElement)(ColorPickerPopover, {
isGradient: isGradient,
onClose: () => setEditingElement(null),
onChange: newElement => {
debounceOnChange( // @ts-expect-error TODO: Don't know how to resolve
elements.map((currentElement, currentIndex) => {
if (currentIndex === editingElement) {
return newElement;
}
return currentElement;
}));
},
element: elements[editingElement !== null && editingElement !== void 0 ? editingElement : -1],
popoverProps: popoverProps
}), !isEditing && (isGradient ? (0,external_wp_element_namespaceObject.createElement)(gradient_picker, {
__nextHasNoMargin: true,
gradients: gradients,
onChange: onSelectPaletteItem,
clearable: false,
disableCustomGradients: true
}) : (0,external_wp_element_namespaceObject.createElement)(color_palette, {
colors: colors,
onChange: onSelectPaletteItem,
clearable: false,
disableCustomColors: true
}))), !hasElements && emptyMessage);
}
/* harmony default export */ var palette_edit = (PaletteEdit);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/combobox-control/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const deprecatedDefaultSize = ({
__next40pxDefaultSize
}) => !__next40pxDefaultSize && /*#__PURE__*/emotion_react_browser_esm_css("height:28px;padding-left:", space(1), ";padding-right:", space(1), ";" + ( true ? "" : 0), true ? "" : 0);
const InputWrapperFlex = /*#__PURE__*/createStyled(flex_component, true ? {
target: "evuatpg0"
} : 0)("height:38px;padding-left:", space(2), ";padding-right:", space(2), ";", deprecatedDefaultSize, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/token-input.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnForwardedTokenInput(props, ref) {
const {
value,
isExpanded,
instanceId,
selectedSuggestionIndex,
className,
onChange,
onFocus,
onBlur,
...restProps
} = props;
const [hasFocus, setHasFocus] = (0,external_wp_element_namespaceObject.useState)(false);
const size = value ? value.length + 1 : 0;
const onChangeHandler = event => {
if (onChange) {
onChange({
value: event.target.value
});
}
};
const onFocusHandler = e => {
setHasFocus(true);
onFocus?.(e);
};
const onBlurHandler = e => {
setHasFocus(false);
onBlur?.(e);
};
return (0,external_wp_element_namespaceObject.createElement)("input", {
ref: ref,
id: `components-form-token-input-${instanceId}`,
type: "text",
...restProps,
value: value || '',
onChange: onChangeHandler,
onFocus: onFocusHandler,
onBlur: onBlurHandler,
size: size,
className: classnames_default()(className, 'components-form-token-field__input'),
autoComplete: "off",
role: "combobox",
"aria-expanded": isExpanded,
"aria-autocomplete": "list",
"aria-owns": isExpanded ? `components-form-token-suggestions-${instanceId}` : undefined,
"aria-activedescendant": // Only add the `aria-activedescendant` attribute when:
// - the user is actively interacting with the input (`hasFocus`)
// - there is a selected suggestion (`selectedSuggestionIndex !== -1`)
// - the list of suggestions are rendered in the DOM (`isExpanded`)
hasFocus && selectedSuggestionIndex !== -1 && isExpanded ? `components-form-token-suggestions-${instanceId}-${selectedSuggestionIndex}` : undefined,
"aria-describedby": `components-form-token-suggestions-howto-${instanceId}`
});
}
const TokenInput = (0,external_wp_element_namespaceObject.forwardRef)(UnForwardedTokenInput);
/* harmony default export */ var token_input = (TokenInput);
// EXTERNAL MODULE: ./node_modules/dom-scroll-into-view/lib/index.js
var lib = __webpack_require__(5425);
var lib_default = /*#__PURE__*/__webpack_require__.n(lib);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/suggestions-list.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const handleMouseDown = e => {
// By preventing default here, we will not lose focus of <input> when clicking a suggestion.
e.preventDefault();
};
function SuggestionsList({
selectedIndex,
scrollIntoView,
match,
onHover,
onSelect,
suggestions = [],
displayTransform,
instanceId,
__experimentalRenderItem
}) {
const [scrollingIntoView, setScrollingIntoView] = (0,external_wp_element_namespaceObject.useState)(false);
const listRef = (0,external_wp_compose_namespaceObject.useRefEffect)(listNode => {
// only have to worry about scrolling selected suggestion into view
// when already expanded.
let rafId;
if (selectedIndex > -1 && scrollIntoView && listNode.children[selectedIndex]) {
setScrollingIntoView(true);
lib_default()(listNode.children[selectedIndex], listNode, {
onlyScrollIfNeeded: true
});
rafId = requestAnimationFrame(() => {
setScrollingIntoView(false);
});
}
return () => {
if (rafId !== undefined) {
cancelAnimationFrame(rafId);
}
};
}, [selectedIndex, scrollIntoView]);
const handleHover = suggestion => {
return () => {
if (!scrollingIntoView) {
onHover?.(suggestion);
}
};
};
const handleClick = suggestion => {
return () => {
onSelect?.(suggestion);
};
};
const computeSuggestionMatch = suggestion => {
const matchText = displayTransform(match).toLocaleLowerCase();
if (matchText.length === 0) {
return null;
}
const transformedSuggestion = displayTransform(suggestion);
const indexOfMatch = transformedSuggestion.toLocaleLowerCase().indexOf(matchText);
return {
suggestionBeforeMatch: transformedSuggestion.substring(0, indexOfMatch),
suggestionMatch: transformedSuggestion.substring(indexOfMatch, indexOfMatch + matchText.length),
suggestionAfterMatch: transformedSuggestion.substring(indexOfMatch + matchText.length)
};
};
return (0,external_wp_element_namespaceObject.createElement)("ul", {
ref: listRef,
className: "components-form-token-field__suggestions-list",
id: `components-form-token-suggestions-${instanceId}`,
role: "listbox"
}, suggestions.map((suggestion, index) => {
const matchText = computeSuggestionMatch(suggestion);
const className = classnames_default()('components-form-token-field__suggestion', {
'is-selected': index === selectedIndex
});
let output;
if (typeof __experimentalRenderItem === 'function') {
output = __experimentalRenderItem({
item: suggestion
});
} else if (matchText) {
output = (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-label": displayTransform(suggestion)
}, matchText.suggestionBeforeMatch, (0,external_wp_element_namespaceObject.createElement)("strong", {
className: "components-form-token-field__suggestion-match"
}, matchText.suggestionMatch), matchText.suggestionAfterMatch);
} else {
output = displayTransform(suggestion);
}
/* eslint-disable jsx-a11y/click-events-have-key-events */
return (0,external_wp_element_namespaceObject.createElement)("li", {
id: `components-form-token-suggestions-${instanceId}-${index}`,
role: "option",
className: className,
key: typeof suggestion === 'object' && 'value' in suggestion ? suggestion?.value : displayTransform(suggestion),
onMouseDown: handleMouseDown,
onClick: handleClick(suggestion),
onMouseEnter: handleHover(suggestion),
"aria-selected": index === selectedIndex
}, output);
/* eslint-enable jsx-a11y/click-events-have-key-events */
}));
}
/* harmony default export */ var suggestions_list = (SuggestionsList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-focus-outside/index.js
//@ts-nocheck
/**
* WordPress dependencies
*/
/* harmony default export */ var with_focus_outside = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => props => {
const [handleFocusOutside, setHandleFocusOutside] = (0,external_wp_element_namespaceObject.useState)();
const bindFocusOutsideHandler = (0,external_wp_element_namespaceObject.useCallback)(node => setHandleFocusOutside(() => node?.handleFocusOutside ? node.handleFocusOutside.bind(node) : undefined), []);
return (0,external_wp_element_namespaceObject.createElement)("div", { ...(0,external_wp_compose_namespaceObject.__experimentalUseFocusOutside)(handleFocusOutside)
}, (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, {
ref: bindFocusOutsideHandler,
...props
}));
}, 'withFocusOutside'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/use-deprecated-props.js
/**
* WordPress dependencies
*/
function useDeprecated36pxDefaultSizeProp(props,
/** The component identifier in dot notation, e.g. `wp.components.ComponentName`. */
componentIdentifier) {
const {
__next36pxDefaultSize,
__next40pxDefaultSize,
...otherProps
} = props;
if (typeof __next36pxDefaultSize !== 'undefined') {
external_wp_deprecated_default()('`__next36pxDefaultSize` prop in ' + componentIdentifier, {
alternative: '`__next40pxDefaultSize`',
since: '6.3'
});
}
return { ...otherProps,
__next40pxDefaultSize: __next40pxDefaultSize !== null && __next40pxDefaultSize !== void 0 ? __next40pxDefaultSize : __next36pxDefaultSize
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/combobox-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const combobox_control_noop = () => {};
const DetectOutside = with_focus_outside(class extends external_wp_element_namespaceObject.Component {
// @ts-expect-error - TODO: Should be resolved when `withFocusOutside` is refactored to TypeScript
handleFocusOutside(event) {
// @ts-expect-error - TODO: Should be resolved when `withFocusOutside` is refactored to TypeScript
this.props.onFocusOutside(event);
}
render() {
// @ts-expect-error - TODO: Should be resolved when `withFocusOutside` is refactored to TypeScript
return this.props.children;
}
});
const getIndexOfMatchingSuggestion = (selectedSuggestion, matchingSuggestions) => selectedSuggestion === null ? -1 : matchingSuggestions.indexOf(selectedSuggestion);
/**
* `ComboboxControl` is an enhanced version of a [`SelectControl`](../select-control/README.md) with the addition of
* being able to search for options using a search input.
*
* ```jsx
* import { ComboboxControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const options = [
* {
* value: 'small',
* label: 'Small',
* },
* {
* value: 'normal',
* label: 'Normal',
* },
* {
* value: 'large',
* label: 'Large',
* },
* ];
*
* function MyComboboxControl() {
* const [ fontSize, setFontSize ] = useState();
* const [ filteredOptions, setFilteredOptions ] = useState( options );
* return (
* <ComboboxControl
* label="Font Size"
* value={ fontSize }
* onChange={ setFontSize }
* options={ filteredOptions }
* onFilterValueChange={ ( inputValue ) =>
* setFilteredOptions(
* options.filter( ( option ) =>
* option.label
* .toLowerCase()
* .startsWith( inputValue.toLowerCase() )
* )
* )
* }
* />
* );
* }
* ```
*/
function ComboboxControl(props) {
var _currentOption$label;
const {
__nextHasNoMarginBottom = false,
__next40pxDefaultSize = false,
value: valueProp,
label,
options,
onChange: onChangeProp,
onFilterValueChange = combobox_control_noop,
hideLabelFromVision,
help,
allowReset = true,
className,
messages = {
selected: (0,external_wp_i18n_namespaceObject.__)('Item selected.')
},
__experimentalRenderItem
} = useDeprecated36pxDefaultSizeProp(props, 'wp.components.ComboboxControl');
const [value, setValue] = useControlledValue({
value: valueProp,
onChange: onChangeProp
});
const currentOption = options.find(option => option.value === value);
const currentLabel = (_currentOption$label = currentOption?.label) !== null && _currentOption$label !== void 0 ? _currentOption$label : ''; // Use a custom prefix when generating the `instanceId` to avoid having
// duplicate input IDs when rendering this component and `FormTokenField`
// in the same page (see https://github.com/WordPress/gutenberg/issues/42112).
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ComboboxControl, 'combobox-control');
const [selectedSuggestion, setSelectedSuggestion] = (0,external_wp_element_namespaceObject.useState)(currentOption || null);
const [isExpanded, setIsExpanded] = (0,external_wp_element_namespaceObject.useState)(false);
const [inputHasFocus, setInputHasFocus] = (0,external_wp_element_namespaceObject.useState)(false);
const [inputValue, setInputValue] = (0,external_wp_element_namespaceObject.useState)('');
const inputContainer = (0,external_wp_element_namespaceObject.useRef)(null);
const matchingSuggestions = (0,external_wp_element_namespaceObject.useMemo)(() => {
const startsWithMatch = [];
const containsMatch = [];
const match = normalizeTextString(inputValue);
options.forEach(option => {
const index = normalizeTextString(option.label).indexOf(match);
if (index === 0) {
startsWithMatch.push(option);
} else if (index > 0) {
containsMatch.push(option);
}
});
return startsWithMatch.concat(containsMatch);
}, [inputValue, options]);
const onSuggestionSelected = newSelectedSuggestion => {
setValue(newSelectedSuggestion.value);
(0,external_wp_a11y_namespaceObject.speak)(messages.selected, 'assertive');
setSelectedSuggestion(newSelectedSuggestion);
setInputValue('');
setIsExpanded(false);
};
const handleArrowNavigation = (offset = 1) => {
const index = getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions);
let nextIndex = index + offset;
if (nextIndex < 0) {
nextIndex = matchingSuggestions.length - 1;
} else if (nextIndex >= matchingSuggestions.length) {
nextIndex = 0;
}
setSelectedSuggestion(matchingSuggestions[nextIndex]);
setIsExpanded(true);
};
const onKeyDown = event => {
let preventDefault = false;
if (event.defaultPrevented || // Ignore keydowns from IMEs
event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
switch (event.code) {
case 'Enter':
if (selectedSuggestion) {
onSuggestionSelected(selectedSuggestion);
preventDefault = true;
}
break;
case 'ArrowUp':
handleArrowNavigation(-1);
preventDefault = true;
break;
case 'ArrowDown':
handleArrowNavigation(1);
preventDefault = true;
break;
case 'Escape':
setIsExpanded(false);
setSelectedSuggestion(null);
preventDefault = true;
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
};
const onBlur = () => {
setInputHasFocus(false);
};
const onFocus = () => {
setInputHasFocus(true);
setIsExpanded(true);
onFilterValueChange('');
setInputValue('');
};
const onFocusOutside = () => {
setIsExpanded(false);
};
const onInputChange = event => {
const text = event.value;
setInputValue(text);
onFilterValueChange(text);
if (inputHasFocus) {
setIsExpanded(true);
}
};
const handleOnReset = () => {
setValue(null);
inputContainer.current?.focus();
}; // Update current selections when the filter input changes.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const hasMatchingSuggestions = matchingSuggestions.length > 0;
const hasSelectedMatchingSuggestions = getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions) > 0;
if (hasMatchingSuggestions && !hasSelectedMatchingSuggestions) {
// If the current selection isn't present in the list of suggestions, then automatically select the first item from the list of suggestions.
setSelectedSuggestion(matchingSuggestions[0]);
}
}, [matchingSuggestions, selectedSuggestion]); // Announcements.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const hasMatchingSuggestions = matchingSuggestions.length > 0;
if (isExpanded) {
const message = hasMatchingSuggestions ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', matchingSuggestions.length), matchingSuggestions.length) : (0,external_wp_i18n_namespaceObject.__)('No results.');
(0,external_wp_a11y_namespaceObject.speak)(message, 'polite');
}
}, [matchingSuggestions, isExpanded]); // Disable reason: There is no appropriate role which describes the
// input container intended accessible usability.
// TODO: Refactor click detection to use blur to stop propagation.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)(DetectOutside, {
onFocusOutside: onFocusOutside
}, (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: classnames_default()(className, 'components-combobox-control'),
label: label,
id: `components-form-token-input-${instanceId}`,
hideLabelFromVision: hideLabelFromVision,
help: help
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-combobox-control__suggestions-container",
tabIndex: -1,
onKeyDown: onKeyDown
}, (0,external_wp_element_namespaceObject.createElement)(InputWrapperFlex, {
__next40pxDefaultSize: __next40pxDefaultSize
}, (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(token_input, {
className: "components-combobox-control__input",
instanceId: instanceId,
ref: inputContainer,
value: isExpanded ? inputValue : currentLabel,
onFocus: onFocus,
onBlur: onBlur,
isExpanded: isExpanded,
selectedSuggestionIndex: getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions),
onChange: onInputChange
})), allowReset && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-combobox-control__reset",
icon: close_small,
disabled: !value,
onClick: handleOnReset,
label: (0,external_wp_i18n_namespaceObject.__)('Reset')
}))), isExpanded && (0,external_wp_element_namespaceObject.createElement)(suggestions_list, {
instanceId: instanceId // The empty string for `value` here is not actually used, but is
// just a quick way to satisfy the TypeScript requirements of SuggestionsList.
// See: https://github.com/WordPress/gutenberg/pull/47581/files#r1091089330
,
match: {
label: inputValue,
value: ''
},
displayTransform: suggestion => suggestion.label,
suggestions: matchingSuggestions,
selectedIndex: getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions),
onHover: setSelectedSuggestion,
onSelect: onSuggestionSelected,
scrollIntoView: true,
__experimentalRenderItem: __experimentalRenderItem
}))));
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
/* harmony default export */ var combobox_control = (ComboboxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/modal/aria-helper.js
const LIVE_REGION_ARIA_ROLES = new Set(['alert', 'status', 'log', 'marquee', 'timer']);
let hiddenElements = [],
isHidden = false;
/**
* Hides all elements in the body element from screen-readers except
* the provided element and elements that should not be hidden from
* screen-readers.
*
* The reason we do this is because `aria-modal="true"` currently is bugged
* in Safari, and support is spotty in other browsers overall. In the future
* we should consider removing these helper functions in favor of
* `aria-modal="true"`.
*
* @param {HTMLDivElement} unhiddenElement The element that should not be hidden.
*/
function hideApp(unhiddenElement) {
if (isHidden) {
return;
}
const elements = Array.from(document.body.children);
elements.forEach(element => {
if (element === unhiddenElement) {
return;
}
if (elementShouldBeHidden(element)) {
element.setAttribute('aria-hidden', 'true');
hiddenElements.push(element);
}
});
isHidden = true;
}
/**
* Determines if the passed element should not be hidden from screen readers.
*
* @param {HTMLElement} element The element that should be checked.
*
* @return {boolean} Whether the element should not be hidden from screen-readers.
*/
function elementShouldBeHidden(element) {
const role = element.getAttribute('role');
return !(element.tagName === 'SCRIPT' || element.hasAttribute('aria-hidden') || element.hasAttribute('aria-live') || role && LIVE_REGION_ARIA_ROLES.has(role));
}
/**
* Makes all elements in the body that have been hidden by `hideApp`
* visible again to screen-readers.
*/
function showApp() {
if (!isHidden) {
return;
}
hiddenElements.forEach(element => {
element.removeAttribute('aria-hidden');
});
hiddenElements = [];
isHidden = false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Used to count the number of open modals.
let openModalCount = 0;
function UnforwardedModal(props, forwardedRef) {
const {
bodyOpenClassName = 'modal-open',
role = 'dialog',
title = null,
focusOnMount = true,
shouldCloseOnEsc = true,
shouldCloseOnClickOutside = true,
isDismissible = true,
/* Accessibility. */
aria = {
labelledby: undefined,
describedby: undefined
},
onRequestClose,
icon,
closeButtonLabel,
children,
style,
overlayClassName,
className,
contentLabel,
onKeyDown,
isFullScreen = false,
__experimentalHideHeader = false
} = props;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Modal);
const headingId = title ? `components-modal-header-${instanceId}` : aria.labelledby;
const focusOnMountRef = (0,external_wp_compose_namespaceObject.useFocusOnMount)(focusOnMount);
const constrainedTabbingRef = (0,external_wp_compose_namespaceObject.useConstrainedTabbing)();
const focusReturnRef = (0,external_wp_compose_namespaceObject.useFocusReturn)();
const focusOutsideProps = (0,external_wp_compose_namespaceObject.__experimentalUseFocusOutside)(onRequestClose);
const contentRef = (0,external_wp_element_namespaceObject.useRef)(null);
const childrenContainerRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [hasScrolledContent, setHasScrolledContent] = (0,external_wp_element_namespaceObject.useState)(false);
const [hasScrollableContent, setHasScrollableContent] = (0,external_wp_element_namespaceObject.useState)(false); // Determines whether the Modal content is scrollable and updates the state.
const isContentScrollable = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (!contentRef.current) {
return;
}
const closestScrollContainer = (0,external_wp_dom_namespaceObject.getScrollContainer)(contentRef.current);
if (contentRef.current === closestScrollContainer) {
setHasScrollableContent(true);
} else {
setHasScrollableContent(false);
}
}, [contentRef]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
openModalCount++;
if (openModalCount === 1) {
hideApp(ref.current);
document.body.classList.add(bodyOpenClassName);
}
return () => {
openModalCount--;
if (openModalCount === 0) {
document.body.classList.remove(bodyOpenClassName);
showApp();
}
};
}, [bodyOpenClassName]); // Calls the isContentScrollable callback when the Modal children container resizes.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!window.ResizeObserver || !childrenContainerRef.current) {
return;
}
const resizeObserver = new ResizeObserver(isContentScrollable);
resizeObserver.observe(childrenContainerRef.current);
isContentScrollable();
return () => {
resizeObserver.disconnect();
};
}, [isContentScrollable, childrenContainerRef]);
function handleEscapeKeyDown(event) {
if ( // Ignore keydowns from IMEs
event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
if (shouldCloseOnEsc && event.code === 'Escape' && !event.defaultPrevented) {
event.preventDefault();
if (onRequestClose) {
onRequestClose(event);
}
}
}
const onContentContainerScroll = (0,external_wp_element_namespaceObject.useCallback)(e => {
var _e$currentTarget$scro;
const scrollY = (_e$currentTarget$scro = e?.currentTarget?.scrollTop) !== null && _e$currentTarget$scro !== void 0 ? _e$currentTarget$scro : -1;
if (!hasScrolledContent && scrollY > 0) {
setHasScrolledContent(true);
} else if (hasScrolledContent && scrollY <= 0) {
setHasScrolledContent(false);
}
}, [hasScrolledContent]);
return (0,external_wp_element_namespaceObject.createPortal)( // eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("div", {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, forwardedRef]),
className: classnames_default()('components-modal__screen-overlay', overlayClassName),
onKeyDown: handleEscapeKeyDown
}, (0,external_wp_element_namespaceObject.createElement)(style_provider, {
document: document
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-modal__frame', className, {
'is-full-screen': isFullScreen
}),
style: style,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([constrainedTabbingRef, focusReturnRef, focusOnMountRef]),
role: role,
"aria-label": contentLabel,
"aria-labelledby": contentLabel ? undefined : headingId,
"aria-describedby": aria.describedby,
tabIndex: -1,
...(shouldCloseOnClickOutside ? focusOutsideProps : {}),
onKeyDown: onKeyDown
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-modal__content', {
'hide-header': __experimentalHideHeader,
'is-scrollable': hasScrollableContent,
'has-scrolled-content': hasScrolledContent
}),
role: "document",
onScroll: onContentContainerScroll,
ref: contentRef,
"aria-label": hasScrollableContent ? (0,external_wp_i18n_namespaceObject.__)('Scrollable section') : undefined,
tabIndex: hasScrollableContent ? 0 : undefined
}, !__experimentalHideHeader && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-modal__header"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-modal__header-heading-container"
}, icon && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-modal__icon-container",
"aria-hidden": true
}, icon), title && (0,external_wp_element_namespaceObject.createElement)("h1", {
id: headingId,
className: "components-modal__header-heading"
}, title)), isDismissible && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: onRequestClose,
icon: library_close,
label: closeButtonLabel || (0,external_wp_i18n_namespaceObject.__)('Close')
})), (0,external_wp_element_namespaceObject.createElement)("div", {
ref: childrenContainerRef
}, children))))), document.body);
}
/**
* Modals give users information and choices related to a task theyre trying to
* accomplish. They can contain critical information, require decisions, or
* involve multiple tasks.
*
* ```jsx
* import { Button, Modal } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyModal = () => {
* const [ isOpen, setOpen ] = useState( false );
* const openModal = () => setOpen( true );
* const closeModal = () => setOpen( false );
*
* return (
* <>
* <Button variant="secondary" onClick={ openModal }>
* Open Modal
* </Button>
* { isOpen && (
* <Modal title="This is my modal" onRequestClose={ closeModal }>
* <Button variant="secondary" onClick={ closeModal }>
* My custom close button
* </Button>
* </Modal>
* ) }
* </>
* );
* };
* ```
*/
const Modal = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedModal);
/* harmony default export */ var modal = (Modal);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/confirm-dialog/styles.js
function confirm_dialog_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* The z-index for ConfirmDialog is being set here instead of in
* packages/base-styles/_z-index.scss, because this component uses
* emotion instead of sass.
*
* ConfirmDialog needs this higher z-index to ensure it renders on top of
* any parent Popover component.
*/
const styles_wrapper = true ? {
name: "7g5ii0",
styles: "&&{z-index:1000001;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/confirm-dialog/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ConfirmDialog(props, forwardedRef) {
const {
isOpen: isOpenProp,
onConfirm,
onCancel,
children,
confirmButtonText,
cancelButtonText,
...otherProps
} = useContextSystem(props, 'ConfirmDialog');
const cx = useCx();
const wrapperClassName = cx(styles_wrapper);
const cancelButtonRef = (0,external_wp_element_namespaceObject.useRef)();
const confirmButtonRef = (0,external_wp_element_namespaceObject.useRef)();
const [isOpen, setIsOpen] = (0,external_wp_element_namespaceObject.useState)();
const [shouldSelfClose, setShouldSelfClose] = (0,external_wp_element_namespaceObject.useState)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We only allow the dialog to close itself if `isOpenProp` is *not* set.
// If `isOpenProp` is set, then it (probably) means it's controlled by a
// parent component. In that case, `shouldSelfClose` might do more harm than
// good, so we disable it.
const isIsOpenSet = typeof isOpenProp !== 'undefined';
setIsOpen(isIsOpenSet ? isOpenProp : true);
setShouldSelfClose(!isIsOpenSet);
}, [isOpenProp]);
const handleEvent = (0,external_wp_element_namespaceObject.useCallback)(callback => event => {
callback?.(event);
if (shouldSelfClose) {
setIsOpen(false);
}
}, [shouldSelfClose, setIsOpen]);
const handleEnter = (0,external_wp_element_namespaceObject.useCallback)(event => {
// Avoid triggering the 'confirm' action when a button is focused,
// as this can cause a double submission.
const isConfirmOrCancelButton = event.target === cancelButtonRef.current || event.target === confirmButtonRef.current;
if (!isConfirmOrCancelButton && event.key === 'Enter') {
handleEvent(onConfirm)(event);
}
}, [handleEvent, onConfirm]);
const cancelLabel = cancelButtonText !== null && cancelButtonText !== void 0 ? cancelButtonText : (0,external_wp_i18n_namespaceObject.__)('Cancel');
const confirmLabel = confirmButtonText !== null && confirmButtonText !== void 0 ? confirmButtonText : (0,external_wp_i18n_namespaceObject.__)('OK');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isOpen && (0,external_wp_element_namespaceObject.createElement)(modal, {
onRequestClose: handleEvent(onCancel),
onKeyDown: handleEnter,
closeButtonLabel: cancelLabel,
isDismissible: true,
ref: forwardedRef,
overlayClassName: wrapperClassName,
__experimentalHideHeader: true,
...otherProps
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 8
}, (0,external_wp_element_namespaceObject.createElement)(text_component, null, children), (0,external_wp_element_namespaceObject.createElement)(flex_component, {
direction: "row",
justify: "flex-end"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
ref: cancelButtonRef,
variant: "tertiary",
onClick: handleEvent(onCancel)
}, cancelLabel), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
ref: confirmButtonRef,
variant: "primary",
onClick: handleEvent(onConfirm)
}, confirmLabel)))));
}
/* harmony default export */ var confirm_dialog_component = (contextConnect(ConfirmDialog, 'ConfirmDialog'));
// EXTERNAL MODULE: ./node_modules/prop-types/index.js
var prop_types = __webpack_require__(2652);
var prop_types_default = /*#__PURE__*/__webpack_require__.n(prop_types);
// EXTERNAL MODULE: ./node_modules/downshift/node_modules/react-is/index.js
var react_is = __webpack_require__(2797);
;// CONCATENATED MODULE: ./node_modules/compute-scroll-into-view/dist/index.mjs
function dist_t(t){return"object"==typeof t&&null!=t&&1===t.nodeType}function dist_e(t,e){return(!e||"hidden"!==t)&&"visible"!==t&&"clip"!==t}function dist_n(t,n){if(t.clientHeight<t.scrollHeight||t.clientWidth<t.scrollWidth){var r=getComputedStyle(t,null);return dist_e(r.overflowY,n)||dist_e(r.overflowX,n)||function(t){var e=function(t){if(!t.ownerDocument||!t.ownerDocument.defaultView)return null;try{return t.ownerDocument.defaultView.frameElement}catch(t){return null}}(t);return!!e&&(e.clientHeight<t.scrollHeight||e.clientWidth<t.scrollWidth)}(t)}return!1}function dist_r(t,e,n,r,i,o,l,d){return o<t&&l>e||o>t&&l<e?0:o<=t&&d<=n||l>=e&&d>=n?o-t-r:l>e&&d<n||o<t&&d>n?l-e+i:0}var compute_scroll_into_view_dist_i=function(e,i){var o=window,l=i.scrollMode,d=i.block,f=i.inline,h=i.boundary,u=i.skipOverflowHiddenElements,s="function"==typeof h?h:function(t){return t!==h};if(!dist_t(e))throw new TypeError("Invalid target");for(var a,c,g=document.scrollingElement||document.documentElement,p=[],m=e;dist_t(m)&&s(m);){if((m=null==(c=(a=m).parentElement)?a.getRootNode().host||null:c)===g){p.push(m);break}null!=m&&m===document.body&&dist_n(m)&&!dist_n(document.documentElement)||null!=m&&dist_n(m,u)&&p.push(m)}for(var w=o.visualViewport?o.visualViewport.width:innerWidth,v=o.visualViewport?o.visualViewport.height:innerHeight,W=window.scrollX||pageXOffset,H=window.scrollY||pageYOffset,b=e.getBoundingClientRect(),y=b.height,E=b.width,M=b.top,V=b.right,x=b.bottom,I=b.left,C="start"===d||"nearest"===d?M:"end"===d?x:M+y/2,R="center"===f?I+E/2:"end"===f?V:I,T=[],k=0;k<p.length;k++){var B=p[k],D=B.getBoundingClientRect(),O=D.height,X=D.width,Y=D.top,L=D.right,S=D.bottom,j=D.left;if("if-needed"===l&&M>=0&&I>=0&&x<=v&&V<=w&&M>=Y&&x<=S&&I>=j&&V<=L)return T;var N=getComputedStyle(B),q=parseInt(N.borderLeftWidth,10),z=parseInt(N.borderTopWidth,10),A=parseInt(N.borderRightWidth,10),F=parseInt(N.borderBottomWidth,10),G=0,J=0,K="offsetWidth"in B?B.offsetWidth-B.clientWidth-q-A:0,P="offsetHeight"in B?B.offsetHeight-B.clientHeight-z-F:0,Q="offsetWidth"in B?0===B.offsetWidth?0:X/B.offsetWidth:0,U="offsetHeight"in B?0===B.offsetHeight?0:O/B.offsetHeight:0;if(g===B)G="start"===d?C:"end"===d?C-v:"nearest"===d?dist_r(H,H+v,v,z,F,H+C,H+C+y,y):C-v/2,J="start"===f?R:"center"===f?R-w/2:"end"===f?R-w:dist_r(W,W+w,w,q,A,W+R,W+R+E,E),G=Math.max(0,G+H),J=Math.max(0,J+W);else{G="start"===d?C-Y-z:"end"===d?C-S+F+P:"nearest"===d?dist_r(Y,S,O,z,F+P,C,C+y,y):C-(Y+O/2)+P/2,J="start"===f?R-j-q:"center"===f?R-(j+X/2)+K/2:"end"===f?R-L+A+K:dist_r(j,L,X,q,A+K,R,R+E,E);var Z=B.scrollLeft,$=B.scrollTop;C+=$-(G=Math.max(0,Math.min($+G/U,B.scrollHeight-O/U+P))),R+=Z-(J=Math.max(0,Math.min(Z+J/Q,B.scrollWidth-X/Q+K)))}T.push({el:B,top:G,left:J})}return T};
//# sourceMappingURL=index.mjs.map
;// CONCATENATED MODULE: ./node_modules/downshift/dist/downshift.esm.js
let idCounter = 0;
/**
* Accepts a parameter and returns it if it's a function
* or a noop function if it's not. This allows us to
* accept a callback, but not worry about it if it's not
* passed.
* @param {Function} cb the callback
* @return {Function} a function
*/
function cbToCb(cb) {
return typeof cb === 'function' ? cb : downshift_esm_noop;
}
function downshift_esm_noop() {}
/**
* Scroll node into view if necessary
* @param {HTMLElement} node the element that should scroll into view
* @param {HTMLElement} menuNode the menu element of the component
*/
function scrollIntoView(node, menuNode) {
if (!node) {
return;
}
const actions = compute_scroll_into_view_dist_i(node, {
boundary: menuNode,
block: 'nearest',
scrollMode: 'if-needed'
});
actions.forEach(_ref => {
let {
el,
top,
left
} = _ref;
el.scrollTop = top;
el.scrollLeft = left;
});
}
/**
* @param {HTMLElement} parent the parent node
* @param {HTMLElement} child the child node
* @param {Window} environment The window context where downshift renders.
* @return {Boolean} whether the parent is the child or the child is in the parent
*/
function isOrContainsNode(parent, child, environment) {
const result = parent === child || child instanceof environment.Node && parent.contains && parent.contains(child);
return result;
}
/**
* Simple debounce implementation. Will call the given
* function once after the time given has passed since
* it was last called.
* @param {Function} fn the function to call after the time
* @param {Number} time the time to wait
* @return {Function} the debounced function
*/
function downshift_esm_debounce(fn, time) {
let timeoutId;
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
}
function wrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
cancel();
timeoutId = setTimeout(() => {
timeoutId = null;
fn(...args);
}, time);
}
wrapper.cancel = cancel;
return wrapper;
}
/**
* This is intended to be used to compose event handlers.
* They are executed in order until one of them sets
* `event.preventDownshiftDefault = true`.
* @param {...Function} fns the event handler functions
* @return {Function} the event handler to add to an element
*/
function callAllEventHandlers() {
for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fns[_key2] = arguments[_key2];
}
return function (event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return fns.some(fn => {
if (fn) {
fn(event, ...args);
}
return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault;
});
};
}
function handleRefs() {
for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
refs[_key4] = arguments[_key4];
}
return node => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
ref.current = node;
}
});
};
}
/**
* This generates a unique ID for an instance of Downshift
* @return {String} the unique ID
*/
function generateId() {
return String(idCounter++);
}
/**
* Resets idCounter to 0. Used for SSR.
*/
function resetIdCounter() {
idCounter = 0;
}
/**
* Default implementation for status message. Only added when menu is open.
* Will specify if there are results in the list, and if so, how many,
* and what keys are relevant.
*
* @param {Object} param the downshift state and other relevant properties
* @return {String} the a11y status message
*/
function getA11yStatusMessage$1(_ref2) {
let {
isOpen,
resultCount,
previousResultCount
} = _ref2;
if (!isOpen) {
return '';
}
if (!resultCount) {
return 'No results are available.';
}
if (resultCount !== previousResultCount) {
return `${resultCount} result${resultCount === 1 ? ' is' : 's are'} available, use up and down arrow keys to navigate. Press Enter key to select.`;
}
return '';
}
/**
* Takes an argument and if it's an array, returns the first item in the array
* otherwise returns the argument
* @param {*} arg the maybe-array
* @param {*} defaultValue the value if arg is falsey not defined
* @return {*} the arg or it's first item
*/
function unwrapArray(arg, defaultValue) {
arg = Array.isArray(arg) ?
/* istanbul ignore next (preact) */
arg[0] : arg;
if (!arg && defaultValue) {
return defaultValue;
} else {
return arg;
}
}
/**
* @param {Object} element (P)react element
* @return {Boolean} whether it's a DOM element
*/
function isDOMElement(element) {
return typeof element.type === 'string';
}
/**
* @param {Object} element (P)react element
* @return {Object} the props
*/
function getElementProps(element) {
return element.props;
}
/**
* Throws a helpful error message for required properties. Useful
* to be used as a default in destructuring or object params.
* @param {String} fnName the function name
* @param {String} propName the prop name
*/
function requiredProp(fnName, propName) {
// eslint-disable-next-line no-console
console.error(`The property "${propName}" is required in "${fnName}"`);
}
const stateKeys = ['highlightedIndex', 'inputValue', 'isOpen', 'selectedItem', 'type'];
/**
* @param {Object} state the state object
* @return {Object} state that is relevant to downshift
*/
function pickState(state) {
if (state === void 0) {
state = {};
}
const result = {};
stateKeys.forEach(k => {
if (state.hasOwnProperty(k)) {
result[k] = state[k];
}
});
return result;
}
/**
* This will perform a shallow merge of the given state object
* with the state coming from props
* (for the controlled component scenario)
* This is used in state updater functions so they're referencing
* the right state regardless of where it comes from.
*
* @param {Object} state The state of the component/hook.
* @param {Object} props The props that may contain controlled values.
* @returns {Object} The merged controlled state.
*/
function getState(state, props) {
return Object.keys(state).reduce((prevState, key) => {
prevState[key] = isControlledProp(props, key) ? props[key] : state[key];
return prevState;
}, {});
}
/**
* This determines whether a prop is a "controlled prop" meaning it is
* state which is controlled by the outside of this component rather
* than within this component.
*
* @param {Object} props The props that may contain controlled values.
* @param {String} key the key to check
* @return {Boolean} whether it is a controlled controlled prop
*/
function isControlledProp(props, key) {
return props[key] !== undefined;
}
/**
* Normalizes the 'key' property of a KeyboardEvent in IE/Edge
* @param {Object} event a keyboardEvent object
* @return {String} keyboard key
*/
function normalizeArrowKey(event) {
const {
key,
keyCode
} = event;
/* istanbul ignore next (ie) */
if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) {
return `Arrow${key}`;
}
return key;
}
/**
* Simple check if the value passed is object literal
* @param {*} obj any things
* @return {Boolean} whether it's object literal
*/
function downshift_esm_isPlainObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
* Returns the new index in the list, in a circular way. If next value is out of bonds from the total,
* it will wrap to either 0 or itemCount - 1.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @param {Function} getItemNodeFromIndex Used to check if item is disabled.
* @param {boolean} circular Specify if navigation is circular. Default is true.
* @returns {number} The new index after the move.
*/
function getNextWrappingIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
if (circular === void 0) {
circular = true;
}
if (itemCount === 0) {
return -1;
}
const itemsLastIndex = itemCount - 1;
if (typeof baseIndex !== 'number' || baseIndex < 0 || baseIndex >= itemCount) {
baseIndex = moveAmount > 0 ? -1 : itemsLastIndex + 1;
}
let newIndex = baseIndex + moveAmount;
if (newIndex < 0) {
newIndex = circular ? itemsLastIndex : 0;
} else if (newIndex > itemsLastIndex) {
newIndex = circular ? 0 : itemsLastIndex;
}
const nonDisabledNewIndex = getNextNonDisabledIndex(moveAmount, newIndex, itemCount, getItemNodeFromIndex, circular);
if (nonDisabledNewIndex === -1) {
return baseIndex >= itemCount ? -1 : baseIndex;
}
return nonDisabledNewIndex;
}
/**
* Returns the next index in the list of an item that is not disabled.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @param {Function} getItemNodeFromIndex Used to check if item is disabled.
* @param {boolean} circular Specify if navigation is circular. Default is true.
* @returns {number} The new index. Returns baseIndex if item is not disabled. Returns next non-disabled item otherwise. If no non-disabled found it will return -1.
*/
function getNextNonDisabledIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
const currentElementNode = getItemNodeFromIndex(baseIndex);
if (!currentElementNode || !currentElementNode.hasAttribute('disabled')) {
return baseIndex;
}
if (moveAmount > 0) {
for (let index = baseIndex + 1; index < itemCount; index++) {
if (!getItemNodeFromIndex(index).hasAttribute('disabled')) {
return index;
}
}
} else {
for (let index = baseIndex - 1; index >= 0; index--) {
if (!getItemNodeFromIndex(index).hasAttribute('disabled')) {
return index;
}
}
}
if (circular) {
return moveAmount > 0 ? getNextNonDisabledIndex(1, 0, itemCount, getItemNodeFromIndex, false) : getNextNonDisabledIndex(-1, itemCount - 1, itemCount, getItemNodeFromIndex, false);
}
return -1;
}
/**
* Checks if event target is within the downshift elements.
*
* @param {EventTarget} target Target to check.
* @param {HTMLElement[]} downshiftElements The elements that form downshift (list, toggle button etc).
* @param {Window} environment The window context where downshift renders.
* @param {boolean} checkActiveElement Whether to also check activeElement.
*
* @returns {boolean} Whether or not the target is within downshift elements.
*/
function targetWithinDownshift(target, downshiftElements, environment, checkActiveElement) {
if (checkActiveElement === void 0) {
checkActiveElement = true;
}
return downshiftElements.some(contextNode => contextNode && (isOrContainsNode(contextNode, target, environment) || checkActiveElement && isOrContainsNode(contextNode, environment.document.activeElement, environment)));
} // eslint-disable-next-line import/no-mutable-exports
let validateControlledUnchanged = (/* unused pure expression or super */ null && (downshift_esm_noop));
/* istanbul ignore next */
if (false) {}
const cleanupStatus = downshift_esm_debounce(documentProp => {
getStatusDiv(documentProp).textContent = '';
}, 500);
/**
* @param {String} status the status message
* @param {Object} documentProp document passed by the user.
*/
function setStatus(status, documentProp) {
const div = getStatusDiv(documentProp);
if (!status) {
return;
}
div.textContent = status;
cleanupStatus(documentProp);
}
/**
* Get the status node or create it if it does not already exist.
* @param {Object} documentProp document passed by the user.
* @return {HTMLElement} the status node.
*/
function getStatusDiv(documentProp) {
if (documentProp === void 0) {
documentProp = document;
}
let statusDiv = documentProp.getElementById('a11y-status-message');
if (statusDiv) {
return statusDiv;
}
statusDiv = documentProp.createElement('div');
statusDiv.setAttribute('id', 'a11y-status-message');
statusDiv.setAttribute('role', 'status');
statusDiv.setAttribute('aria-live', 'polite');
statusDiv.setAttribute('aria-relevant', 'additions text');
Object.assign(statusDiv.style, {
border: '0',
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
width: '1px'
});
documentProp.body.appendChild(statusDiv);
return statusDiv;
}
const unknown = false ? 0 : 0;
const mouseUp = false ? 0 : 1;
const itemMouseEnter = false ? 0 : 2;
const keyDownArrowUp = false ? 0 : 3;
const keyDownArrowDown = false ? 0 : 4;
const keyDownEscape = false ? 0 : 5;
const keyDownEnter = false ? 0 : 6;
const keyDownHome = false ? 0 : 7;
const keyDownEnd = false ? 0 : 8;
const clickItem = false ? 0 : 9;
const blurInput = false ? 0 : 10;
const changeInput = false ? 0 : 11;
const keyDownSpaceButton = false ? 0 : 12;
const clickButton = false ? 0 : 13;
const blurButton = false ? 0 : 14;
const controlledPropUpdatedSelectedItem = false ? 0 : 15;
const touchEnd = false ? 0 : 16;
var stateChangeTypes$3 = /*#__PURE__*/Object.freeze({
__proto__: null,
unknown: unknown,
mouseUp: mouseUp,
itemMouseEnter: itemMouseEnter,
keyDownArrowUp: keyDownArrowUp,
keyDownArrowDown: keyDownArrowDown,
keyDownEscape: keyDownEscape,
keyDownEnter: keyDownEnter,
keyDownHome: keyDownHome,
keyDownEnd: keyDownEnd,
clickItem: clickItem,
blurInput: blurInput,
changeInput: changeInput,
keyDownSpaceButton: keyDownSpaceButton,
clickButton: clickButton,
blurButton: blurButton,
controlledPropUpdatedSelectedItem: controlledPropUpdatedSelectedItem,
touchEnd: touchEnd
});
/* eslint camelcase:0 */
const Downshift = /*#__PURE__*/(() => {
class Downshift extends external_React_.Component {
constructor(_props) {
var _this;
super(_props);
_this = this;
this.id = this.props.id || `downshift-${generateId()}`;
this.menuId = this.props.menuId || `${this.id}-menu`;
this.labelId = this.props.labelId || `${this.id}-label`;
this.inputId = this.props.inputId || `${this.id}-input`;
this.getItemId = this.props.getItemId || (index => `${this.id}-item-${index}`);
this.input = null;
this.items = [];
this.itemCount = null;
this.previousResultCount = 0;
this.timeoutIds = [];
this.internalSetTimeout = (fn, time) => {
const id = setTimeout(() => {
this.timeoutIds = this.timeoutIds.filter(i => i !== id);
fn();
}, time);
this.timeoutIds.push(id);
};
this.setItemCount = count => {
this.itemCount = count;
};
this.unsetItemCount = () => {
this.itemCount = null;
};
this.setHighlightedIndex = function (highlightedIndex, otherStateToSet) {
if (highlightedIndex === void 0) {
highlightedIndex = _this.props.defaultHighlightedIndex;
}
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState({
highlightedIndex,
...otherStateToSet
});
};
this.clearSelection = cb => {
this.internalSetState({
selectedItem: null,
inputValue: '',
highlightedIndex: this.props.defaultHighlightedIndex,
isOpen: this.props.defaultIsOpen
}, cb);
};
this.selectItem = (item, otherStateToSet, cb) => {
otherStateToSet = pickState(otherStateToSet);
this.internalSetState({
isOpen: this.props.defaultIsOpen,
highlightedIndex: this.props.defaultHighlightedIndex,
selectedItem: item,
inputValue: this.props.itemToString(item),
...otherStateToSet
}, cb);
};
this.selectItemAtIndex = (itemIndex, otherStateToSet, cb) => {
const item = this.items[itemIndex];
if (item == null) {
return;
}
this.selectItem(item, otherStateToSet, cb);
};
this.selectHighlightedItem = (otherStateToSet, cb) => {
return this.selectItemAtIndex(this.getState().highlightedIndex, otherStateToSet, cb);
};
this.internalSetState = (stateToSet, cb) => {
let isItemSelected, onChangeArg;
const onStateChangeArg = {};
const isStateToSetFunction = typeof stateToSet === 'function'; // we want to call `onInputValueChange` before the `setState` call
// so someone controlling the `inputValue` state gets notified of
// the input change as soon as possible. This avoids issues with
// preserving the cursor position.
// See https://github.com/downshift-js/downshift/issues/217 for more info.
if (!isStateToSetFunction && stateToSet.hasOwnProperty('inputValue')) {
this.props.onInputValueChange(stateToSet.inputValue, { ...this.getStateAndHelpers(),
...stateToSet
});
}
return this.setState(state => {
state = this.getState(state);
let newStateToSet = isStateToSetFunction ? stateToSet(state) : stateToSet; // Your own function that could modify the state that will be set.
newStateToSet = this.props.stateReducer(state, newStateToSet); // checks if an item is selected, regardless of if it's different from
// what was selected before
// used to determine if onSelect and onChange callbacks should be called
isItemSelected = newStateToSet.hasOwnProperty('selectedItem'); // this keeps track of the object we want to call with setState
const nextState = {}; // this is just used to tell whether the state changed
// and we're trying to update that state. OR if the selection has changed and we're
// trying to update the selection
if (isItemSelected && newStateToSet.selectedItem !== state.selectedItem) {
onChangeArg = newStateToSet.selectedItem;
}
newStateToSet.type = newStateToSet.type || unknown;
Object.keys(newStateToSet).forEach(key => {
// onStateChangeArg should only have the state that is
// actually changing
if (state[key] !== newStateToSet[key]) {
onStateChangeArg[key] = newStateToSet[key];
} // the type is useful for the onStateChangeArg
// but we don't actually want to set it in internal state.
// this is an undocumented feature for now... Not all internalSetState
// calls support it and I'm not certain we want them to yet.
// But it enables users controlling the isOpen state to know when
// the isOpen state changes due to mouseup events which is quite handy.
if (key === 'type') {
return;
}
newStateToSet[key]; // if it's coming from props, then we don't care to set it internally
if (!isControlledProp(this.props, key)) {
nextState[key] = newStateToSet[key];
}
}); // if stateToSet is a function, then we weren't able to call onInputValueChange
// earlier, so we'll call it now that we know what the inputValue state will be.
if (isStateToSetFunction && newStateToSet.hasOwnProperty('inputValue')) {
this.props.onInputValueChange(newStateToSet.inputValue, { ...this.getStateAndHelpers(),
...newStateToSet
});
}
return nextState;
}, () => {
// call the provided callback if it's a function
cbToCb(cb)(); // only call the onStateChange and onChange callbacks if
// we have relevant information to pass them.
const hasMoreStateThanType = Object.keys(onStateChangeArg).length > 1;
if (hasMoreStateThanType) {
this.props.onStateChange(onStateChangeArg, this.getStateAndHelpers());
}
if (isItemSelected) {
this.props.onSelect(stateToSet.selectedItem, this.getStateAndHelpers());
}
if (onChangeArg !== undefined) {
this.props.onChange(onChangeArg, this.getStateAndHelpers());
} // this is currently undocumented and therefore subject to change
// We'll try to not break it, but just be warned.
this.props.onUserAction(onStateChangeArg, this.getStateAndHelpers());
});
};
this.rootRef = node => this._rootNode = node;
this.getRootProps = function (_temp, _temp2) {
let {
refKey = 'ref',
ref,
...rest
} = _temp === void 0 ? {} : _temp;
let {
suppressRefError = false
} = _temp2 === void 0 ? {} : _temp2;
// this is used in the render to know whether the user has called getRootProps.
// It uses that to know whether to apply the props automatically
_this.getRootProps.called = true;
_this.getRootProps.refKey = refKey;
_this.getRootProps.suppressRefError = suppressRefError;
const {
isOpen
} = _this.getState();
return {
[refKey]: handleRefs(ref, _this.rootRef),
role: 'combobox',
'aria-expanded': isOpen,
'aria-haspopup': 'listbox',
'aria-owns': isOpen ? _this.menuId : null,
'aria-labelledby': _this.labelId,
...rest
};
};
this.keyDownHandlers = {
ArrowDown(event) {
event.preventDefault();
if (this.getState().isOpen) {
const amount = event.shiftKey ? 5 : 1;
this.moveHighlightedIndex(amount, {
type: keyDownArrowDown
});
} else {
this.internalSetState({
isOpen: true,
type: keyDownArrowDown
}, () => {
const itemCount = this.getItemCount();
if (itemCount > 0) {
const {
highlightedIndex
} = this.getState();
const nextHighlightedIndex = getNextWrappingIndex(1, highlightedIndex, itemCount, index => this.getItemNodeFromIndex(index));
this.setHighlightedIndex(nextHighlightedIndex, {
type: keyDownArrowDown
});
}
});
}
},
ArrowUp(event) {
event.preventDefault();
if (this.getState().isOpen) {
const amount = event.shiftKey ? -5 : -1;
this.moveHighlightedIndex(amount, {
type: keyDownArrowUp
});
} else {
this.internalSetState({
isOpen: true,
type: keyDownArrowUp
}, () => {
const itemCount = this.getItemCount();
if (itemCount > 0) {
const {
highlightedIndex
} = this.getState();
const nextHighlightedIndex = getNextWrappingIndex(-1, highlightedIndex, itemCount, index => this.getItemNodeFromIndex(index));
this.setHighlightedIndex(nextHighlightedIndex, {
type: keyDownArrowUp
});
}
});
}
},
Enter(event) {
if (event.which === 229) {
return;
}
const {
isOpen,
highlightedIndex
} = this.getState();
if (isOpen && highlightedIndex != null) {
event.preventDefault();
const item = this.items[highlightedIndex];
const itemNode = this.getItemNodeFromIndex(highlightedIndex);
if (item == null || itemNode && itemNode.hasAttribute('disabled')) {
return;
}
this.selectHighlightedItem({
type: keyDownEnter
});
}
},
Escape(event) {
event.preventDefault();
this.reset({
type: keyDownEscape,
...(!this.state.isOpen && {
selectedItem: null,
inputValue: ''
})
});
}
};
this.buttonKeyDownHandlers = { ...this.keyDownHandlers,
' '(event) {
event.preventDefault();
this.toggleMenu({
type: keyDownSpaceButton
});
}
};
this.inputKeyDownHandlers = { ...this.keyDownHandlers,
Home(event) {
const {
isOpen
} = this.getState();
if (!isOpen) {
return;
}
event.preventDefault();
const itemCount = this.getItemCount();
if (itemCount <= 0 || !isOpen) {
return;
} // get next non-disabled starting downwards from 0 if that's disabled.
const newHighlightedIndex = getNextNonDisabledIndex(1, 0, itemCount, index => this.getItemNodeFromIndex(index), false);
this.setHighlightedIndex(newHighlightedIndex, {
type: keyDownHome
});
},
End(event) {
const {
isOpen
} = this.getState();
if (!isOpen) {
return;
}
event.preventDefault();
const itemCount = this.getItemCount();
if (itemCount <= 0 || !isOpen) {
return;
} // get next non-disabled starting upwards from last index if that's disabled.
const newHighlightedIndex = getNextNonDisabledIndex(-1, itemCount - 1, itemCount, index => this.getItemNodeFromIndex(index), false);
this.setHighlightedIndex(newHighlightedIndex, {
type: keyDownEnd
});
}
};
this.getToggleButtonProps = function (_temp3) {
let {
onClick,
onPress,
onKeyDown,
onKeyUp,
onBlur,
...rest
} = _temp3 === void 0 ? {} : _temp3;
const {
isOpen
} = _this.getState();
const enabledEventHandlers = {
onClick: callAllEventHandlers(onClick, _this.buttonHandleClick),
onKeyDown: callAllEventHandlers(onKeyDown, _this.buttonHandleKeyDown),
onKeyUp: callAllEventHandlers(onKeyUp, _this.buttonHandleKeyUp),
onBlur: callAllEventHandlers(onBlur, _this.buttonHandleBlur)
};
const eventHandlers = rest.disabled ? {} : enabledEventHandlers;
return {
type: 'button',
role: 'button',
'aria-label': isOpen ? 'close menu' : 'open menu',
'aria-haspopup': true,
'data-toggle': true,
...eventHandlers,
...rest
};
};
this.buttonHandleKeyUp = event => {
// Prevent click event from emitting in Firefox
event.preventDefault();
};
this.buttonHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (this.buttonKeyDownHandlers[key]) {
this.buttonKeyDownHandlers[key].call(this, event);
}
};
this.buttonHandleClick = event => {
event.preventDefault(); // handle odd case for Safari and Firefox which
// don't give the button the focus properly.
/* istanbul ignore if (can't reasonably test this) */
if (this.props.environment.document.activeElement === this.props.environment.document.body) {
event.target.focus();
} // to simplify testing components that use downshift, we'll not wrap this in a setTimeout
// if the NODE_ENV is test. With the proper build system, this should be dead code eliminated
// when building for production and should therefore have no impact on production code.
if (false) {} else {
// Ensure that toggle of menu occurs after the potential blur event in iOS
this.internalSetTimeout(() => this.toggleMenu({
type: clickButton
}));
}
};
this.buttonHandleBlur = event => {
const blurTarget = event.target; // Save blur target for comparison with activeElement later
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not body element
this.internalSetTimeout(() => {
if (!this.isMouseDown && (this.props.environment.document.activeElement == null || this.props.environment.document.activeElement.id !== this.inputId) && this.props.environment.document.activeElement !== blurTarget // Do nothing if we refocus the same element again (to solve issue in Safari on iOS)
) {
this.reset({
type: blurButton
});
}
});
};
this.getLabelProps = props => {
return {
htmlFor: this.inputId,
id: this.labelId,
...props
};
};
this.getInputProps = function (_temp4) {
let {
onKeyDown,
onBlur,
onChange,
onInput,
onChangeText,
...rest
} = _temp4 === void 0 ? {} : _temp4;
let onChangeKey;
let eventHandlers = {};
/* istanbul ignore next (preact) */
{
onChangeKey = 'onChange';
}
const {
inputValue,
isOpen,
highlightedIndex
} = _this.getState();
if (!rest.disabled) {
eventHandlers = {
[onChangeKey]: callAllEventHandlers(onChange, onInput, _this.inputHandleChange),
onKeyDown: callAllEventHandlers(onKeyDown, _this.inputHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, _this.inputHandleBlur)
};
}
return {
'aria-autocomplete': 'list',
'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0 ? _this.getItemId(highlightedIndex) : null,
'aria-controls': isOpen ? _this.menuId : null,
'aria-labelledby': _this.labelId,
// https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
// revert back since autocomplete="nope" is ignored on latest Chrome and Opera
autoComplete: 'off',
value: inputValue,
id: _this.inputId,
...eventHandlers,
...rest
};
};
this.inputHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && this.inputKeyDownHandlers[key]) {
this.inputKeyDownHandlers[key].call(this, event);
}
};
this.inputHandleChange = event => {
this.internalSetState({
type: changeInput,
isOpen: true,
inputValue: event.target.value,
highlightedIndex: this.props.defaultHighlightedIndex
});
};
this.inputHandleBlur = () => {
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not the body element
this.internalSetTimeout(() => {
const downshiftButtonIsActive = this.props.environment.document && !!this.props.environment.document.activeElement && !!this.props.environment.document.activeElement.dataset && this.props.environment.document.activeElement.dataset.toggle && this._rootNode && this._rootNode.contains(this.props.environment.document.activeElement);
if (!this.isMouseDown && !downshiftButtonIsActive) {
this.reset({
type: blurInput
});
}
});
};
this.menuRef = node => {
this._menuNode = node;
};
this.getMenuProps = function (_temp5, _temp6) {
let {
refKey = 'ref',
ref,
...props
} = _temp5 === void 0 ? {} : _temp5;
let {
suppressRefError = false
} = _temp6 === void 0 ? {} : _temp6;
_this.getMenuProps.called = true;
_this.getMenuProps.refKey = refKey;
_this.getMenuProps.suppressRefError = suppressRefError;
return {
[refKey]: handleRefs(ref, _this.menuRef),
role: 'listbox',
'aria-labelledby': props && props['aria-label'] ? null : _this.labelId,
id: _this.menuId,
...props
};
};
this.getItemProps = function (_temp7) {
let {
onMouseMove,
onMouseDown,
onClick,
onPress,
index,
item = true ?
/* istanbul ignore next */
undefined : 0,
...rest
} = _temp7 === void 0 ? {} : _temp7;
if (index === undefined) {
_this.items.push(item);
index = _this.items.indexOf(item);
} else {
_this.items[index] = item;
}
const onSelectKey = 'onClick';
const customClickHandler = onClick;
const enabledEventHandlers = {
// onMouseMove is used over onMouseEnter here. onMouseMove
// is only triggered on actual mouse movement while onMouseEnter
// can fire on DOM changes, interrupting keyboard navigation
onMouseMove: callAllEventHandlers(onMouseMove, () => {
if (index === _this.getState().highlightedIndex) {
return;
}
_this.setHighlightedIndex(index, {
type: itemMouseEnter
}); // We never want to manually scroll when changing state based
// on `onMouseMove` because we will be moving the element out
// from under the user which is currently scrolling/moving the
// cursor
_this.avoidScrolling = true;
_this.internalSetTimeout(() => _this.avoidScrolling = false, 250);
}),
onMouseDown: callAllEventHandlers(onMouseDown, event => {
// This prevents the activeElement from being changed
// to the item so it can remain with the current activeElement
// which is a more common use case.
event.preventDefault();
}),
[onSelectKey]: callAllEventHandlers(customClickHandler, () => {
_this.selectItemAtIndex(index, {
type: clickItem
});
})
}; // Passing down the onMouseDown handler to prevent redirect
// of the activeElement if clicking on disabled items
const eventHandlers = rest.disabled ? {
onMouseDown: enabledEventHandlers.onMouseDown
} : enabledEventHandlers;
return {
id: _this.getItemId(index),
role: 'option',
'aria-selected': _this.getState().highlightedIndex === index,
...eventHandlers,
...rest
};
};
this.clearItems = () => {
this.items = [];
};
this.reset = function (otherStateToSet, cb) {
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(_ref => {
let {
selectedItem
} = _ref;
return {
isOpen: _this.props.defaultIsOpen,
highlightedIndex: _this.props.defaultHighlightedIndex,
inputValue: _this.props.itemToString(selectedItem),
...otherStateToSet
};
}, cb);
};
this.toggleMenu = function (otherStateToSet, cb) {
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(_ref2 => {
let {
isOpen
} = _ref2;
return {
isOpen: !isOpen,
...(isOpen && {
highlightedIndex: _this.props.defaultHighlightedIndex
}),
...otherStateToSet
};
}, () => {
const {
isOpen,
highlightedIndex
} = _this.getState();
if (isOpen) {
if (_this.getItemCount() > 0 && typeof highlightedIndex === 'number') {
_this.setHighlightedIndex(highlightedIndex, otherStateToSet);
}
}
cbToCb(cb)();
});
};
this.openMenu = cb => {
this.internalSetState({
isOpen: true
}, cb);
};
this.closeMenu = cb => {
this.internalSetState({
isOpen: false
}, cb);
};
this.updateStatus = downshift_esm_debounce(() => {
const state = this.getState();
const item = this.items[state.highlightedIndex];
const resultCount = this.getItemCount();
const status = this.props.getA11yStatusMessage({
itemToString: this.props.itemToString,
previousResultCount: this.previousResultCount,
resultCount,
highlightedItem: item,
...state
});
this.previousResultCount = resultCount;
setStatus(status, this.props.environment.document);
}, 200);
// fancy destructuring + defaults + aliases
// this basically says each value of state should either be set to
// the initial value or the default value if the initial value is not provided
const {
defaultHighlightedIndex,
initialHighlightedIndex: _highlightedIndex = defaultHighlightedIndex,
defaultIsOpen,
initialIsOpen: _isOpen = defaultIsOpen,
initialInputValue: _inputValue = '',
initialSelectedItem: _selectedItem = null
} = this.props;
const _state = this.getState({
highlightedIndex: _highlightedIndex,
isOpen: _isOpen,
inputValue: _inputValue,
selectedItem: _selectedItem
});
if (_state.selectedItem != null && this.props.initialInputValue === undefined) {
_state.inputValue = this.props.itemToString(_state.selectedItem);
}
this.state = _state;
}
/**
* Clear all running timeouts
*/
internalClearTimeouts() {
this.timeoutIds.forEach(id => {
clearTimeout(id);
});
this.timeoutIds = [];
}
/**
* Gets the state based on internal state or props
* If a state value is passed via props, then that
* is the value given, otherwise it's retrieved from
* stateToMerge
*
* @param {Object} stateToMerge defaults to this.state
* @return {Object} the state
*/
getState(stateToMerge) {
if (stateToMerge === void 0) {
stateToMerge = this.state;
}
return getState(stateToMerge, this.props);
}
getItemCount() {
// things read better this way. They're in priority order:
// 1. `this.itemCount`
// 2. `this.props.itemCount`
// 3. `this.items.length`
let itemCount = this.items.length;
if (this.itemCount != null) {
itemCount = this.itemCount;
} else if (this.props.itemCount !== undefined) {
itemCount = this.props.itemCount;
}
return itemCount;
}
getItemNodeFromIndex(index) {
return this.props.environment.document.getElementById(this.getItemId(index));
}
scrollHighlightedItemIntoView() {
/* istanbul ignore else (react-native) */
{
const node = this.getItemNodeFromIndex(this.getState().highlightedIndex);
this.props.scrollIntoView(node, this._menuNode);
}
}
moveHighlightedIndex(amount, otherStateToSet) {
const itemCount = this.getItemCount();
const {
highlightedIndex
} = this.getState();
if (itemCount > 0) {
const nextHighlightedIndex = getNextWrappingIndex(amount, highlightedIndex, itemCount, index => this.getItemNodeFromIndex(index));
this.setHighlightedIndex(nextHighlightedIndex, otherStateToSet);
}
}
getStateAndHelpers() {
const {
highlightedIndex,
inputValue,
selectedItem,
isOpen
} = this.getState();
const {
itemToString
} = this.props;
const {
id
} = this;
const {
getRootProps,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getItemProps,
openMenu,
closeMenu,
toggleMenu,
selectItem,
selectItemAtIndex,
selectHighlightedItem,
setHighlightedIndex,
clearSelection,
clearItems,
reset,
setItemCount,
unsetItemCount,
internalSetState: setState
} = this;
return {
// prop getters
getRootProps,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getItemProps,
// actions
reset,
openMenu,
closeMenu,
toggleMenu,
selectItem,
selectItemAtIndex,
selectHighlightedItem,
setHighlightedIndex,
clearSelection,
clearItems,
setItemCount,
unsetItemCount,
setState,
// props
itemToString,
// derived
id,
// state
highlightedIndex,
inputValue,
isOpen,
selectedItem
};
} //////////////////////////// ROOT
componentDidMount() {
/* istanbul ignore if (react-native) */
if (false) {}
/* istanbul ignore if (react-native) */
{
// this.isMouseDown helps us track whether the mouse is currently held down.
// This is useful when the user clicks on an item in the list, but holds the mouse
// down long enough for the list to disappear (because the blur event fires on the input)
// this.isMouseDown is used in the blur handler on the input to determine whether the blur event should
// trigger hiding the menu.
const onMouseDown = () => {
this.isMouseDown = true;
};
const onMouseUp = event => {
this.isMouseDown = false; // if the target element or the activeElement is within a downshift node
// then we don't want to reset downshift
const contextWithinDownshift = targetWithinDownshift(event.target, [this._rootNode, this._menuNode], this.props.environment);
if (!contextWithinDownshift && this.getState().isOpen) {
this.reset({
type: mouseUp
}, () => this.props.onOuterClick(this.getStateAndHelpers()));
}
}; // Touching an element in iOS gives focus and hover states, but touching out of
// the element will remove hover, and persist the focus state, resulting in the
// blur event not being triggered.
// this.isTouchMove helps us track whether the user is tapping or swiping on a touch screen.
// If the user taps outside of Downshift, the component should be reset,
// but not if the user is swiping
const onTouchStart = () => {
this.isTouchMove = false;
};
const onTouchMove = () => {
this.isTouchMove = true;
};
const onTouchEnd = event => {
const contextWithinDownshift = targetWithinDownshift(event.target, [this._rootNode, this._menuNode], this.props.environment, false);
if (!this.isTouchMove && !contextWithinDownshift && this.getState().isOpen) {
this.reset({
type: touchEnd
}, () => this.props.onOuterClick(this.getStateAndHelpers()));
}
};
const {
environment
} = this.props;
environment.addEventListener('mousedown', onMouseDown);
environment.addEventListener('mouseup', onMouseUp);
environment.addEventListener('touchstart', onTouchStart);
environment.addEventListener('touchmove', onTouchMove);
environment.addEventListener('touchend', onTouchEnd);
this.cleanup = () => {
this.internalClearTimeouts();
this.updateStatus.cancel();
environment.removeEventListener('mousedown', onMouseDown);
environment.removeEventListener('mouseup', onMouseUp);
environment.removeEventListener('touchstart', onTouchStart);
environment.removeEventListener('touchmove', onTouchMove);
environment.removeEventListener('touchend', onTouchEnd);
};
}
}
shouldScroll(prevState, prevProps) {
const {
highlightedIndex: currentHighlightedIndex
} = this.props.highlightedIndex === undefined ? this.getState() : this.props;
const {
highlightedIndex: prevHighlightedIndex
} = prevProps.highlightedIndex === undefined ? prevState : prevProps;
const scrollWhenOpen = currentHighlightedIndex && this.getState().isOpen && !prevState.isOpen;
const scrollWhenNavigating = currentHighlightedIndex !== prevHighlightedIndex;
return scrollWhenOpen || scrollWhenNavigating;
}
componentDidUpdate(prevProps, prevState) {
if (false) {}
if (isControlledProp(this.props, 'selectedItem') && this.props.selectedItemChanged(prevProps.selectedItem, this.props.selectedItem)) {
this.internalSetState({
type: controlledPropUpdatedSelectedItem,
inputValue: this.props.itemToString(this.props.selectedItem)
});
}
if (!this.avoidScrolling && this.shouldScroll(prevState, prevProps)) {
this.scrollHighlightedItemIntoView();
}
/* istanbul ignore else (react-native) */
{
this.updateStatus();
}
}
componentWillUnmount() {
this.cleanup(); // avoids memory leak
}
render() {
const children = unwrapArray(this.props.children, downshift_esm_noop); // because the items are rerendered every time we call the children
// we clear this out each render and it will be populated again as
// getItemProps is called.
this.clearItems(); // we reset this so we know whether the user calls getRootProps during
// this render. If they do then we don't need to do anything,
// if they don't then we need to clone the element they return and
// apply the props for them.
this.getRootProps.called = false;
this.getRootProps.refKey = undefined;
this.getRootProps.suppressRefError = undefined; // we do something similar for getMenuProps
this.getMenuProps.called = false;
this.getMenuProps.refKey = undefined;
this.getMenuProps.suppressRefError = undefined; // we do something similar for getLabelProps
this.getLabelProps.called = false; // and something similar for getInputProps
this.getInputProps.called = false;
const element = unwrapArray(children(this.getStateAndHelpers()));
if (!element) {
return null;
}
if (this.getRootProps.called || this.props.suppressRefError) {
if (false) {}
return element;
} else if (isDOMElement(element)) {
// they didn't apply the root props, but we can clone
// this and apply the props ourselves
return /*#__PURE__*/(0,external_React_.cloneElement)(element, this.getRootProps(getElementProps(element)));
}
/* istanbul ignore else */
if (false) {}
/* istanbul ignore next */
return undefined;
}
}
Downshift.defaultProps = {
defaultHighlightedIndex: null,
defaultIsOpen: false,
getA11yStatusMessage: getA11yStatusMessage$1,
itemToString: i => {
if (i == null) {
return '';
}
if (false) {}
return String(i);
},
onStateChange: downshift_esm_noop,
onInputValueChange: downshift_esm_noop,
onUserAction: downshift_esm_noop,
onChange: downshift_esm_noop,
onSelect: downshift_esm_noop,
onOuterClick: downshift_esm_noop,
selectedItemChanged: (prevItem, item) => prevItem !== item,
environment:
/* istanbul ignore next (ssr) */
typeof window === 'undefined' ? {} : window,
stateReducer: (state, stateToSet) => stateToSet,
suppressRefError: false,
scrollIntoView
};
Downshift.stateChangeTypes = stateChangeTypes$3;
return Downshift;
})();
false ? 0 : void 0;
var Downshift$1 = Downshift;
function validateGetMenuPropsCalledCorrectly(node, _ref3) {
let {
refKey
} = _ref3;
if (!node) {
// eslint-disable-next-line no-console
console.error(`downshift: The ref prop "${refKey}" from getMenuProps was not applied correctly on your menu element.`);
}
}
function validateGetRootPropsCalledCorrectly(element, _ref4) {
let {
refKey
} = _ref4;
const refKeySpecified = refKey !== 'ref';
const isComposite = !isDOMElement(element);
if (isComposite && !refKeySpecified && !isForwardRef(element)) {
// eslint-disable-next-line no-console
console.error('downshift: You returned a non-DOM element. You must specify a refKey in getRootProps');
} else if (!isComposite && refKeySpecified) {
// eslint-disable-next-line no-console
console.error(`downshift: You returned a DOM element. You should not specify a refKey in getRootProps. You specified "${refKey}"`);
}
if (!isForwardRef(element) && !getElementProps(element)[refKey]) {
// eslint-disable-next-line no-console
console.error(`downshift: You must apply the ref prop "${refKey}" from getRootProps onto your root element.`);
}
}
const dropdownDefaultStateValues = {
highlightedIndex: -1,
isOpen: false,
selectedItem: null,
inputValue: ''
};
function callOnChangeProps(action, state, newState) {
const {
props,
type
} = action;
const changes = {};
Object.keys(state).forEach(key => {
invokeOnChangeHandler(key, action, state, newState);
if (newState[key] !== state[key]) {
changes[key] = newState[key];
}
});
if (props.onStateChange && Object.keys(changes).length) {
props.onStateChange({
type,
...changes
});
}
}
function invokeOnChangeHandler(key, action, state, newState) {
const {
props,
type
} = action;
const handler = `on${capitalizeString(key)}Change`;
if (props[handler] && newState[key] !== undefined && newState[key] !== state[key]) {
props[handler]({
type,
...newState
});
}
}
/**
* Default state reducer that returns the changes.
*
* @param {Object} s state.
* @param {Object} a action with changes.
* @returns {Object} changes.
*/
function stateReducer(s, a) {
return a.changes;
}
/**
* Returns a message to be added to aria-live region when item is selected.
*
* @param {Object} selectionParameters Parameters required to build the message.
* @returns {string} The a11y message.
*/
function getA11ySelectionMessage(selectionParameters) {
const {
selectedItem,
itemToString: itemToStringLocal
} = selectionParameters;
return selectedItem ? `${itemToStringLocal(selectedItem)} has been selected.` : '';
}
/**
* Debounced call for updating the a11y message.
*/
const updateA11yStatus = downshift_esm_debounce((getA11yMessage, document) => {
setStatus(getA11yMessage(), document);
}, 200); // istanbul ignore next
const downshift_esm_useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? external_React_.useLayoutEffect : external_React_.useEffect;
function useElementIds(_ref) {
let {
id = `downshift-${generateId()}`,
labelId,
menuId,
getItemId,
toggleButtonId,
inputId
} = _ref;
const elementIdsRef = (0,external_React_.useRef)({
labelId: labelId || `${id}-label`,
menuId: menuId || `${id}-menu`,
getItemId: getItemId || (index => `${id}-item-${index}`),
toggleButtonId: toggleButtonId || `${id}-toggle-button`,
inputId: inputId || `${id}-input`
});
return elementIdsRef.current;
}
function getItemIndex(index, item, items) {
if (index !== undefined) {
return index;
}
if (items.length === 0) {
return -1;
}
return items.indexOf(item);
}
function itemToString(item) {
return item ? String(item) : '';
}
function isAcceptedCharacterKey(key) {
return /^\S{1}$/.test(key);
}
function capitalizeString(string) {
return `${string.slice(0, 1).toUpperCase()}${string.slice(1)}`;
}
function downshift_esm_useLatestRef(val) {
const ref = (0,external_React_.useRef)(val); // technically this is not "concurrent mode safe" because we're manipulating
// the value during render (so it's not idempotent). However, the places this
// hook is used is to support memoizing callbacks which will be called
// *during* render, so we need the latest values *during* render.
// If not for this, then we'd probably want to use useLayoutEffect instead.
ref.current = val;
return ref;
}
/**
* Computes the controlled state using a the previous state, props,
* two reducers, one from downshift and an optional one from the user.
* Also calls the onChange handlers for state values that have changed.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useEnhancedReducer(reducer, initialState, props) {
const prevStateRef = (0,external_React_.useRef)();
const actionRef = (0,external_React_.useRef)();
const enhancedReducer = (0,external_React_.useCallback)((state, action) => {
actionRef.current = action;
state = getState(state, action.props);
const changes = reducer(state, action);
const newState = action.props.stateReducer(state, { ...action,
changes
});
return newState;
}, [reducer]);
const [state, dispatch] = (0,external_React_.useReducer)(enhancedReducer, initialState);
const propsRef = downshift_esm_useLatestRef(props);
const dispatchWithProps = (0,external_React_.useCallback)(action => dispatch({
props: propsRef.current,
...action
}), [propsRef]);
const action = actionRef.current;
(0,external_React_.useEffect)(() => {
if (action && prevStateRef.current && prevStateRef.current !== state) {
callOnChangeProps(action, getState(prevStateRef.current, action.props), state);
}
prevStateRef.current = state;
}, [state, props, action]);
return [state, dispatchWithProps];
}
/**
* Wraps the useEnhancedReducer and applies the controlled prop values before
* returning the new state.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useControlledReducer$1(reducer, initialState, props) {
const [state, dispatch] = useEnhancedReducer(reducer, initialState, props);
return [getState(state, props), dispatch];
}
const defaultProps$3 = {
itemToString,
stateReducer,
getA11ySelectionMessage,
scrollIntoView,
circularNavigation: false,
environment:
/* istanbul ignore next (ssr) */
typeof window === 'undefined' ? {} : window
};
function getDefaultValue$1(props, propKey, defaultStateValues) {
if (defaultStateValues === void 0) {
defaultStateValues = dropdownDefaultStateValues;
}
const defaultValue = props[`default${capitalizeString(propKey)}`];
if (defaultValue !== undefined) {
return defaultValue;
}
return defaultStateValues[propKey];
}
function getInitialValue$1(props, propKey, defaultStateValues) {
if (defaultStateValues === void 0) {
defaultStateValues = dropdownDefaultStateValues;
}
const value = props[propKey];
if (value !== undefined) {
return value;
}
const initialValue = props[`initial${capitalizeString(propKey)}`];
if (initialValue !== undefined) {
return initialValue;
}
return getDefaultValue$1(props, propKey, defaultStateValues);
}
function getInitialState$2(props) {
const selectedItem = getInitialValue$1(props, 'selectedItem');
const isOpen = getInitialValue$1(props, 'isOpen');
const highlightedIndex = getInitialValue$1(props, 'highlightedIndex');
const inputValue = getInitialValue$1(props, 'inputValue');
return {
highlightedIndex: highlightedIndex < 0 && selectedItem && isOpen ? props.items.indexOf(selectedItem) : highlightedIndex,
isOpen,
selectedItem,
inputValue
};
}
function getHighlightedIndexOnOpen(props, state, offset, getItemNodeFromIndex) {
const {
items,
initialHighlightedIndex,
defaultHighlightedIndex
} = props;
const {
selectedItem,
highlightedIndex
} = state;
if (items.length === 0) {
return -1;
} // initialHighlightedIndex will give value to highlightedIndex on initial state only.
if (initialHighlightedIndex !== undefined && highlightedIndex === initialHighlightedIndex) {
return initialHighlightedIndex;
}
if (defaultHighlightedIndex !== undefined) {
return defaultHighlightedIndex;
}
if (selectedItem) {
if (offset === 0) {
return items.indexOf(selectedItem);
}
return getNextWrappingIndex(offset, items.indexOf(selectedItem), items.length, getItemNodeFromIndex, false);
}
if (offset === 0) {
return -1;
}
return offset < 0 ? items.length - 1 : 0;
}
/**
* Reuse the movement tracking of mouse and touch events.
*
* @param {boolean} isOpen Whether the dropdown is open or not.
* @param {Array<Object>} downshiftElementRefs Downshift element refs to track movement (toggleButton, menu etc.)
* @param {Object} environment Environment where component/hook exists.
* @param {Function} handleBlur Handler on blur from mouse or touch.
* @returns {Object} Ref containing whether mouseDown or touchMove event is happening
*/
function useMouseAndTouchTracker(isOpen, downshiftElementRefs, environment, handleBlur) {
const mouseAndTouchTrackersRef = (0,external_React_.useRef)({
isMouseDown: false,
isTouchMove: false
});
(0,external_React_.useEffect)(() => {
// The same strategy for checking if a click occurred inside or outside downsift
// as in downshift.js.
const onMouseDown = () => {
mouseAndTouchTrackersRef.current.isMouseDown = true;
};
const onMouseUp = event => {
mouseAndTouchTrackersRef.current.isMouseDown = false;
if (isOpen && !targetWithinDownshift(event.target, downshiftElementRefs.map(ref => ref.current), environment)) {
handleBlur();
}
};
const onTouchStart = () => {
mouseAndTouchTrackersRef.current.isTouchMove = false;
};
const onTouchMove = () => {
mouseAndTouchTrackersRef.current.isTouchMove = true;
};
const onTouchEnd = event => {
if (isOpen && !mouseAndTouchTrackersRef.current.isTouchMove && !targetWithinDownshift(event.target, downshiftElementRefs.map(ref => ref.current), environment, false)) {
handleBlur();
}
};
environment.addEventListener('mousedown', onMouseDown);
environment.addEventListener('mouseup', onMouseUp);
environment.addEventListener('touchstart', onTouchStart);
environment.addEventListener('touchmove', onTouchMove);
environment.addEventListener('touchend', onTouchEnd);
return function cleanup() {
environment.removeEventListener('mousedown', onMouseDown);
environment.removeEventListener('mouseup', onMouseUp);
environment.removeEventListener('touchstart', onTouchStart);
environment.removeEventListener('touchmove', onTouchMove);
environment.removeEventListener('touchend', onTouchEnd);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, environment]);
return mouseAndTouchTrackersRef;
}
/* istanbul ignore next */
// eslint-disable-next-line import/no-mutable-exports
let useGetterPropsCalledChecker = () => downshift_esm_noop;
/**
* Custom hook that checks if getter props are called correctly.
*
* @param {...any} propKeys Getter prop names to be handled.
* @returns {Function} Setter function called inside getter props to set call information.
*/
/* istanbul ignore next */
if (false) {}
function useA11yMessageSetter(getA11yMessage, dependencyArray, _ref2) {
let {
isInitialMount,
highlightedIndex,
items,
environment,
...rest
} = _ref2;
// Sets a11y status message on changes in state.
(0,external_React_.useEffect)(() => {
if (isInitialMount || false) {
return;
}
updateA11yStatus(() => getA11yMessage({
highlightedIndex,
highlightedItem: items[highlightedIndex],
resultCount: items.length,
...rest
}), environment.document); // eslint-disable-next-line react-hooks/exhaustive-deps
}, dependencyArray);
}
function useScrollIntoView(_ref3) {
let {
highlightedIndex,
isOpen,
itemRefs,
getItemNodeFromIndex,
menuElement,
scrollIntoView: scrollIntoViewProp
} = _ref3;
// used not to scroll on highlight by mouse.
const shouldScrollRef = (0,external_React_.useRef)(true); // Scroll on highlighted item if change comes from keyboard.
downshift_esm_useIsomorphicLayoutEffect(() => {
if (highlightedIndex < 0 || !isOpen || !Object.keys(itemRefs.current).length) {
return;
}
if (shouldScrollRef.current === false) {
shouldScrollRef.current = true;
} else {
scrollIntoViewProp(getItemNodeFromIndex(highlightedIndex), menuElement);
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, [highlightedIndex]);
return shouldScrollRef;
} // eslint-disable-next-line import/no-mutable-exports
let useControlPropsValidator = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
/* eslint-disable complexity */
function downshiftCommonReducer(state, action, stateChangeTypes) {
const {
type,
props
} = action;
let changes;
switch (type) {
case stateChangeTypes.ItemMouseMove:
changes = {
highlightedIndex: action.disabled ? -1 : action.index
};
break;
case stateChangeTypes.MenuMouseLeave:
changes = {
highlightedIndex: -1
};
break;
case stateChangeTypes.ToggleButtonClick:
case stateChangeTypes.FunctionToggleMenu:
changes = {
isOpen: !state.isOpen,
highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0)
};
break;
case stateChangeTypes.FunctionOpenMenu:
changes = {
isOpen: true,
highlightedIndex: getHighlightedIndexOnOpen(props, state, 0)
};
break;
case stateChangeTypes.FunctionCloseMenu:
changes = {
isOpen: false
};
break;
case stateChangeTypes.FunctionSetHighlightedIndex:
changes = {
highlightedIndex: action.highlightedIndex
};
break;
case stateChangeTypes.FunctionSetInputValue:
changes = {
inputValue: action.inputValue
};
break;
case stateChangeTypes.FunctionReset:
changes = {
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
isOpen: getDefaultValue$1(props, 'isOpen'),
selectedItem: getDefaultValue$1(props, 'selectedItem'),
inputValue: getDefaultValue$1(props, 'inputValue')
};
break;
default:
throw new Error('Reducer called without proper action type.');
}
return { ...state,
...changes
};
}
/* eslint-enable complexity */
function getItemIndexByCharacterKey(_a) {
var keysSoFar = _a.keysSoFar, highlightedIndex = _a.highlightedIndex, items = _a.items, itemToString = _a.itemToString, getItemNodeFromIndex = _a.getItemNodeFromIndex;
var lowerCasedKeysSoFar = keysSoFar.toLowerCase();
for (var index = 0; index < items.length; index++) {
var offsetIndex = (index + highlightedIndex + 1) % items.length;
var item = items[offsetIndex];
if (item !== undefined &&
itemToString(item)
.toLowerCase()
.startsWith(lowerCasedKeysSoFar)) {
var element = getItemNodeFromIndex(offsetIndex);
if (!(element === null || element === void 0 ? void 0 : element.hasAttribute('disabled'))) {
return offsetIndex;
}
}
}
return highlightedIndex;
}
var propTypes$2 = {
items: (prop_types_default()).array.isRequired,
itemToString: (prop_types_default()).func,
getA11yStatusMessage: (prop_types_default()).func,
getA11ySelectionMessage: (prop_types_default()).func,
circularNavigation: (prop_types_default()).bool,
highlightedIndex: (prop_types_default()).number,
defaultHighlightedIndex: (prop_types_default()).number,
initialHighlightedIndex: (prop_types_default()).number,
isOpen: (prop_types_default()).bool,
defaultIsOpen: (prop_types_default()).bool,
initialIsOpen: (prop_types_default()).bool,
selectedItem: (prop_types_default()).any,
initialSelectedItem: (prop_types_default()).any,
defaultSelectedItem: (prop_types_default()).any,
id: (prop_types_default()).string,
labelId: (prop_types_default()).string,
menuId: (prop_types_default()).string,
getItemId: (prop_types_default()).func,
toggleButtonId: (prop_types_default()).string,
stateReducer: (prop_types_default()).func,
onSelectedItemChange: (prop_types_default()).func,
onHighlightedIndexChange: (prop_types_default()).func,
onStateChange: (prop_types_default()).func,
onIsOpenChange: (prop_types_default()).func,
environment: prop_types_default().shape({
addEventListener: (prop_types_default()).func,
removeEventListener: (prop_types_default()).func,
document: prop_types_default().shape({
getElementById: (prop_types_default()).func,
activeElement: (prop_types_default()).any,
body: (prop_types_default()).any
})
})
};
/**
* Default implementation for status message. Only added when menu is open.
* Will specift if there are results in the list, and if so, how many,
* and what keys are relevant.
*
* @param {Object} param the downshift state and other relevant properties
* @return {String} the a11y status message
*/
function getA11yStatusMessage(_a) {
var isOpen = _a.isOpen, resultCount = _a.resultCount, previousResultCount = _a.previousResultCount;
if (!isOpen) {
return '';
}
if (!resultCount) {
return 'No results are available.';
}
if (resultCount !== previousResultCount) {
return "".concat(resultCount, " result").concat(resultCount === 1 ? ' is' : 's are', " available, use up and down arrow keys to navigate. Press Enter or Space Bar keys to select.");
}
return '';
}
var defaultProps$2 = __assign(__assign({}, defaultProps$3), { getA11yStatusMessage: getA11yStatusMessage });
// eslint-disable-next-line import/no-mutable-exports
var validatePropTypes$2 = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
const MenuKeyDownArrowDown = false ? 0 : 0;
const MenuKeyDownArrowUp = false ? 0 : 1;
const MenuKeyDownEscape = false ? 0 : 2;
const MenuKeyDownHome = false ? 0 : 3;
const MenuKeyDownEnd = false ? 0 : 4;
const MenuKeyDownEnter = false ? 0 : 5;
const MenuKeyDownSpaceButton = false ? 0 : 6;
const MenuKeyDownCharacter = false ? 0 : 7;
const MenuBlur = false ? 0 : 8;
const MenuMouseLeave$1 = false ? 0 : 9;
const ItemMouseMove$1 = false ? 0 : 10;
const ItemClick$1 = false ? 0 : 11;
const ToggleButtonClick$1 = false ? 0 : 12;
const ToggleButtonKeyDownArrowDown = false ? 0 : 13;
const ToggleButtonKeyDownArrowUp = false ? 0 : 14;
const ToggleButtonKeyDownCharacter = false ? 0 : 15;
const FunctionToggleMenu$1 = false ? 0 : 16;
const FunctionOpenMenu$1 = false ? 0 : 17;
const FunctionCloseMenu$1 = false ? 0 : 18;
const FunctionSetHighlightedIndex$1 = false ? 0 : 19;
const FunctionSelectItem$1 = false ? 0 : 20;
const FunctionSetInputValue$1 = false ? 0 : 21;
const FunctionReset$2 = false ? 0 : 22;
var stateChangeTypes$2 = /*#__PURE__*/Object.freeze({
__proto__: null,
MenuKeyDownArrowDown: MenuKeyDownArrowDown,
MenuKeyDownArrowUp: MenuKeyDownArrowUp,
MenuKeyDownEscape: MenuKeyDownEscape,
MenuKeyDownHome: MenuKeyDownHome,
MenuKeyDownEnd: MenuKeyDownEnd,
MenuKeyDownEnter: MenuKeyDownEnter,
MenuKeyDownSpaceButton: MenuKeyDownSpaceButton,
MenuKeyDownCharacter: MenuKeyDownCharacter,
MenuBlur: MenuBlur,
MenuMouseLeave: MenuMouseLeave$1,
ItemMouseMove: ItemMouseMove$1,
ItemClick: ItemClick$1,
ToggleButtonClick: ToggleButtonClick$1,
ToggleButtonKeyDownArrowDown: ToggleButtonKeyDownArrowDown,
ToggleButtonKeyDownArrowUp: ToggleButtonKeyDownArrowUp,
ToggleButtonKeyDownCharacter: ToggleButtonKeyDownCharacter,
FunctionToggleMenu: FunctionToggleMenu$1,
FunctionOpenMenu: FunctionOpenMenu$1,
FunctionCloseMenu: FunctionCloseMenu$1,
FunctionSetHighlightedIndex: FunctionSetHighlightedIndex$1,
FunctionSelectItem: FunctionSelectItem$1,
FunctionSetInputValue: FunctionSetInputValue$1,
FunctionReset: FunctionReset$2
});
/* eslint-disable complexity */
function downshiftSelectReducer(state, action) {
const {
type,
props,
shiftKey
} = action;
let changes;
switch (type) {
case ItemClick$1:
changes = {
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
selectedItem: props.items[action.index]
};
break;
case ToggleButtonKeyDownCharacter:
{
const lowercasedKey = action.key;
const inputValue = `${state.inputValue}${lowercasedKey}`;
const itemIndex = getItemIndexByCharacterKey({
keysSoFar: inputValue,
highlightedIndex: state.selectedItem ? props.items.indexOf(state.selectedItem) : -1,
items: props.items,
itemToString: props.itemToString,
getItemNodeFromIndex: action.getItemNodeFromIndex
});
changes = {
inputValue,
...(itemIndex >= 0 && {
selectedItem: props.items[itemIndex]
})
};
}
break;
case ToggleButtonKeyDownArrowDown:
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, 1, action.getItemNodeFromIndex),
isOpen: true
};
break;
case ToggleButtonKeyDownArrowUp:
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, -1, action.getItemNodeFromIndex),
isOpen: true
};
break;
case MenuKeyDownEnter:
case MenuKeyDownSpaceButton:
changes = {
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
...(state.highlightedIndex >= 0 && {
selectedItem: props.items[state.highlightedIndex]
})
};
break;
case MenuKeyDownHome:
changes = {
highlightedIndex: getNextNonDisabledIndex(1, 0, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case MenuKeyDownEnd:
changes = {
highlightedIndex: getNextNonDisabledIndex(-1, props.items.length - 1, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case MenuKeyDownEscape:
changes = {
isOpen: false,
highlightedIndex: -1
};
break;
case MenuBlur:
changes = {
isOpen: false,
highlightedIndex: -1
};
break;
case MenuKeyDownCharacter:
{
const lowercasedKey = action.key;
const inputValue = `${state.inputValue}${lowercasedKey}`;
const highlightedIndex = getItemIndexByCharacterKey({
keysSoFar: inputValue,
highlightedIndex: state.highlightedIndex,
items: props.items,
itemToString: props.itemToString,
getItemNodeFromIndex: action.getItemNodeFromIndex
});
changes = {
inputValue,
...(highlightedIndex >= 0 && {
highlightedIndex
})
};
}
break;
case MenuKeyDownArrowDown:
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? 5 : 1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
break;
case MenuKeyDownArrowUp:
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? -5 : -1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
break;
case FunctionSelectItem$1:
changes = {
selectedItem: action.selectedItem
};
break;
default:
return downshiftCommonReducer(state, action, stateChangeTypes$2);
}
return { ...state,
...changes
};
}
/* eslint-enable complexity */
/* eslint-disable max-statements */
useSelect.stateChangeTypes = stateChangeTypes$2;
function useSelect(userProps) {
if (userProps === void 0) {
userProps = {};
}
validatePropTypes$2(userProps, useSelect); // Props defaults and destructuring.
const props = { ...defaultProps$2,
...userProps
};
const {
items,
scrollIntoView,
environment,
initialIsOpen,
defaultIsOpen,
itemToString,
getA11ySelectionMessage,
getA11yStatusMessage
} = props; // Initial state depending on controlled props.
const initialState = getInitialState$2(props);
const [state, dispatch] = useControlledReducer$1(downshiftSelectReducer, initialState, props);
const {
isOpen,
highlightedIndex,
selectedItem,
inputValue
} = state; // Element efs.
const toggleButtonRef = (0,external_React_.useRef)(null);
const menuRef = (0,external_React_.useRef)(null);
const itemRefs = (0,external_React_.useRef)({}); // used not to trigger menu blur action in some scenarios.
const shouldBlurRef = (0,external_React_.useRef)(true); // used to keep the inputValue clearTimeout object between renders.
const clearTimeoutRef = (0,external_React_.useRef)(null); // prevent id re-generation between renders.
const elementIds = useElementIds(props); // used to keep track of how many items we had on previous cycle.
const previousResultCountRef = (0,external_React_.useRef)();
const isInitialMountRef = (0,external_React_.useRef)(true); // utility callback to get item element.
const latest = downshift_esm_useLatestRef({
state,
props
}); // Some utils.
const getItemNodeFromIndex = (0,external_React_.useCallback)(index => itemRefs.current[elementIds.getItemId(index)], [elementIds]); // Effects.
// Sets a11y status message on changes in state.
useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Sets a11y status message on changes in selectedItem.
useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Scroll on highlighted item if change comes from keyboard.
const shouldScrollRef = useScrollIntoView({
menuElement: menuRef.current,
highlightedIndex,
isOpen,
itemRefs,
scrollIntoView,
getItemNodeFromIndex
}); // Sets cleanup for the keysSoFar callback, debounded after 500ms.
(0,external_React_.useEffect)(() => {
// init the clean function here as we need access to dispatch.
clearTimeoutRef.current = downshift_esm_debounce(outerDispatch => {
outerDispatch({
type: FunctionSetInputValue$1,
inputValue: ''
});
}, 500); // Cancel any pending debounced calls on mount
return () => {
clearTimeoutRef.current.cancel();
};
}, []); // Invokes the keysSoFar callback set up above.
(0,external_React_.useEffect)(() => {
if (!inputValue) {
return;
}
clearTimeoutRef.current(dispatch);
}, [dispatch, inputValue]);
useControlPropsValidator({
isInitialMount: isInitialMountRef.current,
props,
state
});
/* Controls the focus on the menu or the toggle button. */
(0,external_React_.useEffect)(() => {
// Don't focus menu on first render.
if (isInitialMountRef.current) {
// Unless it was initialised as open.
if ((initialIsOpen || defaultIsOpen || isOpen) && menuRef.current) {
menuRef.current.focus();
}
return;
} // Focus menu on open.
if (isOpen) {
// istanbul ignore else
if (menuRef.current) {
menuRef.current.focus();
}
return;
} // Focus toggleButton on close, but not if it was closed with (Shift+)Tab.
if (environment.document.activeElement === menuRef.current) {
// istanbul ignore else
if (toggleButtonRef.current) {
shouldBlurRef.current = false;
toggleButtonRef.current.focus();
}
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen]);
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
previousResultCountRef.current = items.length;
}); // Add mouse/touch events to document.
const mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [menuRef, toggleButtonRef], environment, () => {
dispatch({
type: MenuBlur
});
});
const setGetterPropCallInfo = useGetterPropsCalledChecker('getMenuProps', 'getToggleButtonProps'); // Make initial ref false.
(0,external_React_.useEffect)(() => {
isInitialMountRef.current = false;
}, []); // Reset itemRefs on close.
(0,external_React_.useEffect)(() => {
if (!isOpen) {
itemRefs.current = {};
}
}, [isOpen]); // Event handler functions.
const toggleButtonKeyDownHandlers = (0,external_React_.useMemo)(() => ({
ArrowDown(event) {
event.preventDefault();
dispatch({
type: ToggleButtonKeyDownArrowDown,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
},
ArrowUp(event) {
event.preventDefault();
dispatch({
type: ToggleButtonKeyDownArrowUp,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
}
}), [dispatch, getItemNodeFromIndex]);
const menuKeyDownHandlers = (0,external_React_.useMemo)(() => ({
ArrowDown(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownArrowDown,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
},
ArrowUp(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownArrowUp,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
},
Home(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownHome,
getItemNodeFromIndex
});
},
End(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownEnd,
getItemNodeFromIndex
});
},
Escape() {
dispatch({
type: MenuKeyDownEscape
});
},
Enter(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownEnter
});
},
' '(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownSpaceButton
});
}
}), [dispatch, getItemNodeFromIndex]); // Action functions.
const toggleMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionToggleMenu$1
});
}, [dispatch]);
const closeMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionCloseMenu$1
});
}, [dispatch]);
const openMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionOpenMenu$1
});
}, [dispatch]);
const setHighlightedIndex = (0,external_React_.useCallback)(newHighlightedIndex => {
dispatch({
type: FunctionSetHighlightedIndex$1,
highlightedIndex: newHighlightedIndex
});
}, [dispatch]);
const selectItem = (0,external_React_.useCallback)(newSelectedItem => {
dispatch({
type: FunctionSelectItem$1,
selectedItem: newSelectedItem
});
}, [dispatch]);
const reset = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionReset$2
});
}, [dispatch]);
const setInputValue = (0,external_React_.useCallback)(newInputValue => {
dispatch({
type: FunctionSetInputValue$1,
inputValue: newInputValue
});
}, [dispatch]); // Getter functions.
const getLabelProps = (0,external_React_.useCallback)(labelProps => ({
id: elementIds.labelId,
htmlFor: elementIds.toggleButtonId,
...labelProps
}), [elementIds]);
const getMenuProps = (0,external_React_.useCallback)(function (_temp, _temp2) {
let {
onMouseLeave,
refKey = 'ref',
onKeyDown,
onBlur,
ref,
...rest
} = _temp === void 0 ? {} : _temp;
let {
suppressRefError = false
} = _temp2 === void 0 ? {} : _temp2;
const latestState = latest.current.state;
const menuHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && menuKeyDownHandlers[key]) {
menuKeyDownHandlers[key](event);
} else if (isAcceptedCharacterKey(key)) {
dispatch({
type: MenuKeyDownCharacter,
key,
getItemNodeFromIndex
});
}
};
const menuHandleBlur = () => {
// if the blur was a result of selection, we don't trigger this action.
if (shouldBlurRef.current === false) {
shouldBlurRef.current = true;
return;
}
const shouldBlur = !mouseAndTouchTrackersRef.current.isMouseDown;
/* istanbul ignore else */
if (shouldBlur) {
dispatch({
type: MenuBlur
});
}
};
const menuHandleMouseLeave = () => {
dispatch({
type: MenuMouseLeave$1
});
};
setGetterPropCallInfo('getMenuProps', suppressRefError, refKey, menuRef);
return {
[refKey]: handleRefs(ref, menuNode => {
menuRef.current = menuNode;
}),
id: elementIds.menuId,
role: 'listbox',
'aria-labelledby': elementIds.labelId,
tabIndex: -1,
...(latestState.isOpen && latestState.highlightedIndex > -1 && {
'aria-activedescendant': elementIds.getItemId(latestState.highlightedIndex)
}),
onMouseLeave: callAllEventHandlers(onMouseLeave, menuHandleMouseLeave),
onKeyDown: callAllEventHandlers(onKeyDown, menuHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, menuHandleBlur),
...rest
};
}, [dispatch, latest, menuKeyDownHandlers, mouseAndTouchTrackersRef, setGetterPropCallInfo, elementIds, getItemNodeFromIndex]);
const getToggleButtonProps = (0,external_React_.useCallback)(function (_temp3, _temp4) {
let {
onClick,
onKeyDown,
refKey = 'ref',
ref,
...rest
} = _temp3 === void 0 ? {} : _temp3;
let {
suppressRefError = false
} = _temp4 === void 0 ? {} : _temp4;
const toggleButtonHandleClick = () => {
dispatch({
type: ToggleButtonClick$1
});
};
const toggleButtonHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && toggleButtonKeyDownHandlers[key]) {
toggleButtonKeyDownHandlers[key](event);
} else if (isAcceptedCharacterKey(key)) {
dispatch({
type: ToggleButtonKeyDownCharacter,
key,
getItemNodeFromIndex
});
}
};
const toggleProps = {
[refKey]: handleRefs(ref, toggleButtonNode => {
toggleButtonRef.current = toggleButtonNode;
}),
id: elementIds.toggleButtonId,
'aria-haspopup': 'listbox',
'aria-expanded': latest.current.state.isOpen,
'aria-labelledby': `${elementIds.labelId} ${elementIds.toggleButtonId}`,
...rest
};
if (!rest.disabled) {
toggleProps.onClick = callAllEventHandlers(onClick, toggleButtonHandleClick);
toggleProps.onKeyDown = callAllEventHandlers(onKeyDown, toggleButtonHandleKeyDown);
}
setGetterPropCallInfo('getToggleButtonProps', suppressRefError, refKey, toggleButtonRef);
return toggleProps;
}, [dispatch, latest, toggleButtonKeyDownHandlers, setGetterPropCallInfo, elementIds, getItemNodeFromIndex]);
const getItemProps = (0,external_React_.useCallback)(function (_temp5) {
let {
item,
index,
onMouseMove,
onClick,
refKey = 'ref',
ref,
disabled,
...rest
} = _temp5 === void 0 ? {} : _temp5;
const {
state: latestState,
props: latestProps
} = latest.current;
const itemHandleMouseMove = () => {
if (index === latestState.highlightedIndex) {
return;
}
shouldScrollRef.current = false;
dispatch({
type: ItemMouseMove$1,
index,
disabled
});
};
const itemHandleClick = () => {
dispatch({
type: ItemClick$1,
index
});
};
const itemIndex = getItemIndex(index, item, latestProps.items);
if (itemIndex < 0) {
throw new Error('Pass either item or item index in getItemProps!');
}
const itemProps = {
disabled,
role: 'option',
'aria-selected': `${itemIndex === latestState.highlightedIndex}`,
id: elementIds.getItemId(itemIndex),
[refKey]: handleRefs(ref, itemNode => {
if (itemNode) {
itemRefs.current[elementIds.getItemId(itemIndex)] = itemNode;
}
}),
...rest
};
if (!disabled) {
itemProps.onClick = callAllEventHandlers(onClick, itemHandleClick);
}
itemProps.onMouseMove = callAllEventHandlers(onMouseMove, itemHandleMouseMove);
return itemProps;
}, [dispatch, latest, shouldScrollRef, elementIds]);
return {
// prop getters.
getToggleButtonProps,
getLabelProps,
getMenuProps,
getItemProps,
// actions.
toggleMenu,
openMenu,
closeMenu,
setHighlightedIndex,
selectItem,
reset,
setInputValue,
// state.
highlightedIndex,
isOpen,
selectedItem,
inputValue
};
}
const InputKeyDownArrowDown = false ? 0 : 0;
const InputKeyDownArrowUp = false ? 0 : 1;
const InputKeyDownEscape = false ? 0 : 2;
const InputKeyDownHome = false ? 0 : 3;
const InputKeyDownEnd = false ? 0 : 4;
const InputKeyDownEnter = false ? 0 : 5;
const InputChange = false ? 0 : 6;
const InputBlur = false ? 0 : 7;
const MenuMouseLeave = false ? 0 : 8;
const ItemMouseMove = false ? 0 : 9;
const ItemClick = false ? 0 : 10;
const ToggleButtonClick = false ? 0 : 11;
const FunctionToggleMenu = false ? 0 : 12;
const FunctionOpenMenu = false ? 0 : 13;
const FunctionCloseMenu = false ? 0 : 14;
const FunctionSetHighlightedIndex = false ? 0 : 15;
const FunctionSelectItem = false ? 0 : 16;
const FunctionSetInputValue = false ? 0 : 17;
const FunctionReset$1 = false ? 0 : 18;
const ControlledPropUpdatedSelectedItem = false ? 0 : 19;
var stateChangeTypes$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
InputKeyDownArrowDown: InputKeyDownArrowDown,
InputKeyDownArrowUp: InputKeyDownArrowUp,
InputKeyDownEscape: InputKeyDownEscape,
InputKeyDownHome: InputKeyDownHome,
InputKeyDownEnd: InputKeyDownEnd,
InputKeyDownEnter: InputKeyDownEnter,
InputChange: InputChange,
InputBlur: InputBlur,
MenuMouseLeave: MenuMouseLeave,
ItemMouseMove: ItemMouseMove,
ItemClick: ItemClick,
ToggleButtonClick: ToggleButtonClick,
FunctionToggleMenu: FunctionToggleMenu,
FunctionOpenMenu: FunctionOpenMenu,
FunctionCloseMenu: FunctionCloseMenu,
FunctionSetHighlightedIndex: FunctionSetHighlightedIndex,
FunctionSelectItem: FunctionSelectItem,
FunctionSetInputValue: FunctionSetInputValue,
FunctionReset: FunctionReset$1,
ControlledPropUpdatedSelectedItem: ControlledPropUpdatedSelectedItem
});
function getInitialState$1(props) {
const initialState = getInitialState$2(props);
const {
selectedItem
} = initialState;
let {
inputValue
} = initialState;
if (inputValue === '' && selectedItem && props.defaultInputValue === undefined && props.initialInputValue === undefined && props.inputValue === undefined) {
inputValue = props.itemToString(selectedItem);
}
return { ...initialState,
inputValue
};
}
const propTypes$1 = {
items: (prop_types_default()).array.isRequired,
itemToString: (prop_types_default()).func,
getA11yStatusMessage: (prop_types_default()).func,
getA11ySelectionMessage: (prop_types_default()).func,
circularNavigation: (prop_types_default()).bool,
highlightedIndex: (prop_types_default()).number,
defaultHighlightedIndex: (prop_types_default()).number,
initialHighlightedIndex: (prop_types_default()).number,
isOpen: (prop_types_default()).bool,
defaultIsOpen: (prop_types_default()).bool,
initialIsOpen: (prop_types_default()).bool,
selectedItem: (prop_types_default()).any,
initialSelectedItem: (prop_types_default()).any,
defaultSelectedItem: (prop_types_default()).any,
inputValue: (prop_types_default()).string,
defaultInputValue: (prop_types_default()).string,
initialInputValue: (prop_types_default()).string,
id: (prop_types_default()).string,
labelId: (prop_types_default()).string,
menuId: (prop_types_default()).string,
getItemId: (prop_types_default()).func,
inputId: (prop_types_default()).string,
toggleButtonId: (prop_types_default()).string,
stateReducer: (prop_types_default()).func,
onSelectedItemChange: (prop_types_default()).func,
onHighlightedIndexChange: (prop_types_default()).func,
onStateChange: (prop_types_default()).func,
onIsOpenChange: (prop_types_default()).func,
onInputValueChange: (prop_types_default()).func,
environment: prop_types_default().shape({
addEventListener: (prop_types_default()).func,
removeEventListener: (prop_types_default()).func,
document: prop_types_default().shape({
getElementById: (prop_types_default()).func,
activeElement: (prop_types_default()).any,
body: (prop_types_default()).any
})
})
};
/**
* The useCombobox version of useControlledReducer, which also
* checks if the controlled prop selectedItem changed between
* renders. If so, it will also update inputValue with its
* string equivalent. It uses the common useEnhancedReducer to
* compute the rest of the state.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useControlledReducer(reducer, initialState, props) {
const previousSelectedItemRef = (0,external_React_.useRef)();
const [state, dispatch] = useEnhancedReducer(reducer, initialState, props); // ToDo: if needed, make same approach as selectedItemChanged from Downshift.
(0,external_React_.useEffect)(() => {
if (isControlledProp(props, 'selectedItem')) {
if (previousSelectedItemRef.current !== props.selectedItem) {
dispatch({
type: ControlledPropUpdatedSelectedItem,
inputValue: props.itemToString(props.selectedItem)
});
}
previousSelectedItemRef.current = state.selectedItem === previousSelectedItemRef.current ? props.selectedItem : state.selectedItem;
}
});
return [getState(state, props), dispatch];
} // eslint-disable-next-line import/no-mutable-exports
let validatePropTypes$1 = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
const defaultProps$1 = { ...defaultProps$3,
getA11yStatusMessage: getA11yStatusMessage$1,
circularNavigation: true
};
/* eslint-disable complexity */
function downshiftUseComboboxReducer(state, action) {
const {
type,
props,
shiftKey
} = action;
let changes;
switch (type) {
case ItemClick:
changes = {
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
selectedItem: props.items[action.index],
inputValue: props.itemToString(props.items[action.index])
};
break;
case InputKeyDownArrowDown:
if (state.isOpen) {
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? 5 : 1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
} else {
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, 1, action.getItemNodeFromIndex),
isOpen: props.items.length >= 0
};
}
break;
case InputKeyDownArrowUp:
if (state.isOpen) {
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? -5 : -1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
} else {
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, -1, action.getItemNodeFromIndex),
isOpen: props.items.length >= 0
};
}
break;
case InputKeyDownEnter:
changes = { ...(state.isOpen && state.highlightedIndex >= 0 && {
selectedItem: props.items[state.highlightedIndex],
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
inputValue: props.itemToString(props.items[state.highlightedIndex])
})
};
break;
case InputKeyDownEscape:
changes = {
isOpen: false,
highlightedIndex: -1,
...(!state.isOpen && {
selectedItem: null,
inputValue: ''
})
};
break;
case InputKeyDownHome:
changes = {
highlightedIndex: getNextNonDisabledIndex(1, 0, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case InputKeyDownEnd:
changes = {
highlightedIndex: getNextNonDisabledIndex(-1, props.items.length - 1, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case InputBlur:
changes = {
isOpen: false,
highlightedIndex: -1,
...(state.highlightedIndex >= 0 && action.selectItem && {
selectedItem: props.items[state.highlightedIndex],
inputValue: props.itemToString(props.items[state.highlightedIndex])
})
};
break;
case InputChange:
changes = {
isOpen: true,
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
inputValue: action.inputValue
};
break;
case FunctionSelectItem:
changes = {
selectedItem: action.selectedItem,
inputValue: props.itemToString(action.selectedItem)
};
break;
case ControlledPropUpdatedSelectedItem:
changes = {
inputValue: action.inputValue
};
break;
default:
return downshiftCommonReducer(state, action, stateChangeTypes$1);
}
return { ...state,
...changes
};
}
/* eslint-enable complexity */
/* eslint-disable max-statements */
useCombobox.stateChangeTypes = stateChangeTypes$1;
function useCombobox(userProps) {
if (userProps === void 0) {
userProps = {};
}
validatePropTypes$1(userProps, useCombobox); // Props defaults and destructuring.
const props = { ...defaultProps$1,
...userProps
};
const {
initialIsOpen,
defaultIsOpen,
items,
scrollIntoView,
environment,
getA11yStatusMessage,
getA11ySelectionMessage,
itemToString
} = props; // Initial state depending on controlled props.
const initialState = getInitialState$1(props);
const [state, dispatch] = useControlledReducer(downshiftUseComboboxReducer, initialState, props);
const {
isOpen,
highlightedIndex,
selectedItem,
inputValue
} = state; // Element refs.
const menuRef = (0,external_React_.useRef)(null);
const itemRefs = (0,external_React_.useRef)({});
const inputRef = (0,external_React_.useRef)(null);
const toggleButtonRef = (0,external_React_.useRef)(null);
const comboboxRef = (0,external_React_.useRef)(null);
const isInitialMountRef = (0,external_React_.useRef)(true); // prevent id re-generation between renders.
const elementIds = useElementIds(props); // used to keep track of how many items we had on previous cycle.
const previousResultCountRef = (0,external_React_.useRef)(); // utility callback to get item element.
const latest = downshift_esm_useLatestRef({
state,
props
});
const getItemNodeFromIndex = (0,external_React_.useCallback)(index => itemRefs.current[elementIds.getItemId(index)], [elementIds]); // Effects.
// Sets a11y status message on changes in state.
useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Sets a11y status message on changes in selectedItem.
useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Scroll on highlighted item if change comes from keyboard.
const shouldScrollRef = useScrollIntoView({
menuElement: menuRef.current,
highlightedIndex,
isOpen,
itemRefs,
scrollIntoView,
getItemNodeFromIndex
});
useControlPropsValidator({
isInitialMount: isInitialMountRef.current,
props,
state
}); // Focus the input on first render if required.
(0,external_React_.useEffect)(() => {
const focusOnOpen = initialIsOpen || defaultIsOpen || isOpen;
if (focusOnOpen && inputRef.current) {
inputRef.current.focus();
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
previousResultCountRef.current = items.length;
}); // Add mouse/touch events to document.
const mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [comboboxRef, menuRef, toggleButtonRef], environment, () => {
dispatch({
type: InputBlur,
selectItem: false
});
});
const setGetterPropCallInfo = useGetterPropsCalledChecker('getInputProps', 'getComboboxProps', 'getMenuProps'); // Make initial ref false.
(0,external_React_.useEffect)(() => {
isInitialMountRef.current = false;
}, []); // Reset itemRefs on close.
(0,external_React_.useEffect)(() => {
if (!isOpen) {
itemRefs.current = {};
}
}, [isOpen]);
/* Event handler functions */
const inputKeyDownHandlers = (0,external_React_.useMemo)(() => ({
ArrowDown(event) {
event.preventDefault();
dispatch({
type: InputKeyDownArrowDown,
shiftKey: event.shiftKey,
getItemNodeFromIndex
});
},
ArrowUp(event) {
event.preventDefault();
dispatch({
type: InputKeyDownArrowUp,
shiftKey: event.shiftKey,
getItemNodeFromIndex
});
},
Home(event) {
if (!latest.current.state.isOpen) {
return;
}
event.preventDefault();
dispatch({
type: InputKeyDownHome,
getItemNodeFromIndex
});
},
End(event) {
if (!latest.current.state.isOpen) {
return;
}
event.preventDefault();
dispatch({
type: InputKeyDownEnd,
getItemNodeFromIndex
});
},
Escape(event) {
const latestState = latest.current.state;
if (latestState.isOpen || latestState.inputValue || latestState.selectedItem || latestState.highlightedIndex > -1) {
event.preventDefault();
dispatch({
type: InputKeyDownEscape
});
}
},
Enter(event) {
const latestState = latest.current.state; // if closed or no highlighted index, do nothing.
if (!latestState.isOpen || latestState.highlightedIndex < 0 || event.which === 229 // if IME composing, wait for next Enter keydown event.
) {
return;
}
event.preventDefault();
dispatch({
type: InputKeyDownEnter,
getItemNodeFromIndex
});
}
}), [dispatch, latest, getItemNodeFromIndex]); // Getter props.
const getLabelProps = (0,external_React_.useCallback)(labelProps => ({
id: elementIds.labelId,
htmlFor: elementIds.inputId,
...labelProps
}), [elementIds]);
const getMenuProps = (0,external_React_.useCallback)(function (_temp, _temp2) {
let {
onMouseLeave,
refKey = 'ref',
ref,
...rest
} = _temp === void 0 ? {} : _temp;
let {
suppressRefError = false
} = _temp2 === void 0 ? {} : _temp2;
setGetterPropCallInfo('getMenuProps', suppressRefError, refKey, menuRef);
return {
[refKey]: handleRefs(ref, menuNode => {
menuRef.current = menuNode;
}),
id: elementIds.menuId,
role: 'listbox',
'aria-labelledby': elementIds.labelId,
onMouseLeave: callAllEventHandlers(onMouseLeave, () => {
dispatch({
type: MenuMouseLeave
});
}),
...rest
};
}, [dispatch, setGetterPropCallInfo, elementIds]);
const getItemProps = (0,external_React_.useCallback)(function (_temp3) {
let {
item,
index,
refKey = 'ref',
ref,
onMouseMove,
onMouseDown,
onClick,
onPress,
disabled,
...rest
} = _temp3 === void 0 ? {} : _temp3;
const {
props: latestProps,
state: latestState
} = latest.current;
const itemIndex = getItemIndex(index, item, latestProps.items);
if (itemIndex < 0) {
throw new Error('Pass either item or item index in getItemProps!');
}
const onSelectKey = 'onClick';
const customClickHandler = onClick;
const itemHandleMouseMove = () => {
if (index === latestState.highlightedIndex) {
return;
}
shouldScrollRef.current = false;
dispatch({
type: ItemMouseMove,
index,
disabled
});
};
const itemHandleClick = () => {
dispatch({
type: ItemClick,
index
});
};
const itemHandleMouseDown = e => e.preventDefault();
return {
[refKey]: handleRefs(ref, itemNode => {
if (itemNode) {
itemRefs.current[elementIds.getItemId(itemIndex)] = itemNode;
}
}),
disabled,
role: 'option',
'aria-selected': `${itemIndex === latestState.highlightedIndex}`,
id: elementIds.getItemId(itemIndex),
...(!disabled && {
[onSelectKey]: callAllEventHandlers(customClickHandler, itemHandleClick)
}),
onMouseMove: callAllEventHandlers(onMouseMove, itemHandleMouseMove),
onMouseDown: callAllEventHandlers(onMouseDown, itemHandleMouseDown),
...rest
};
}, [dispatch, latest, shouldScrollRef, elementIds]);
const getToggleButtonProps = (0,external_React_.useCallback)(function (_temp4) {
let {
onClick,
onPress,
refKey = 'ref',
ref,
...rest
} = _temp4 === void 0 ? {} : _temp4;
const toggleButtonHandleClick = () => {
dispatch({
type: ToggleButtonClick
});
if (!latest.current.state.isOpen && inputRef.current) {
inputRef.current.focus();
}
};
return {
[refKey]: handleRefs(ref, toggleButtonNode => {
toggleButtonRef.current = toggleButtonNode;
}),
id: elementIds.toggleButtonId,
tabIndex: -1,
...(!rest.disabled && { ...({
onClick: callAllEventHandlers(onClick, toggleButtonHandleClick)
})
}),
...rest
};
}, [dispatch, latest, elementIds]);
const getInputProps = (0,external_React_.useCallback)(function (_temp5, _temp6) {
let {
onKeyDown,
onChange,
onInput,
onBlur,
onChangeText,
refKey = 'ref',
ref,
...rest
} = _temp5 === void 0 ? {} : _temp5;
let {
suppressRefError = false
} = _temp6 === void 0 ? {} : _temp6;
setGetterPropCallInfo('getInputProps', suppressRefError, refKey, inputRef);
const latestState = latest.current.state;
const inputHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && inputKeyDownHandlers[key]) {
inputKeyDownHandlers[key](event);
}
};
const inputHandleChange = event => {
dispatch({
type: InputChange,
inputValue: event.target.value
});
};
const inputHandleBlur = () => {
/* istanbul ignore else */
if (latestState.isOpen && !mouseAndTouchTrackersRef.current.isMouseDown) {
dispatch({
type: InputBlur,
selectItem: true
});
}
};
/* istanbul ignore next (preact) */
const onChangeKey = 'onChange';
let eventHandlers = {};
if (!rest.disabled) {
eventHandlers = {
[onChangeKey]: callAllEventHandlers(onChange, onInput, inputHandleChange),
onKeyDown: callAllEventHandlers(onKeyDown, inputHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, inputHandleBlur)
};
}
return {
[refKey]: handleRefs(ref, inputNode => {
inputRef.current = inputNode;
}),
id: elementIds.inputId,
'aria-autocomplete': 'list',
'aria-controls': elementIds.menuId,
...(latestState.isOpen && latestState.highlightedIndex > -1 && {
'aria-activedescendant': elementIds.getItemId(latestState.highlightedIndex)
}),
'aria-labelledby': elementIds.labelId,
// https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
// revert back since autocomplete="nope" is ignored on latest Chrome and Opera
autoComplete: 'off',
value: latestState.inputValue,
...eventHandlers,
...rest
};
}, [dispatch, inputKeyDownHandlers, latest, mouseAndTouchTrackersRef, setGetterPropCallInfo, elementIds]);
const getComboboxProps = (0,external_React_.useCallback)(function (_temp7, _temp8) {
let {
refKey = 'ref',
ref,
...rest
} = _temp7 === void 0 ? {} : _temp7;
let {
suppressRefError = false
} = _temp8 === void 0 ? {} : _temp8;
setGetterPropCallInfo('getComboboxProps', suppressRefError, refKey, comboboxRef);
return {
[refKey]: handleRefs(ref, comboboxNode => {
comboboxRef.current = comboboxNode;
}),
role: 'combobox',
'aria-haspopup': 'listbox',
'aria-owns': elementIds.menuId,
'aria-expanded': latest.current.state.isOpen,
...rest
};
}, [latest, setGetterPropCallInfo, elementIds]); // returns
const toggleMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionToggleMenu
});
}, [dispatch]);
const closeMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionCloseMenu
});
}, [dispatch]);
const openMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionOpenMenu
});
}, [dispatch]);
const setHighlightedIndex = (0,external_React_.useCallback)(newHighlightedIndex => {
dispatch({
type: FunctionSetHighlightedIndex,
highlightedIndex: newHighlightedIndex
});
}, [dispatch]);
const selectItem = (0,external_React_.useCallback)(newSelectedItem => {
dispatch({
type: FunctionSelectItem,
selectedItem: newSelectedItem
});
}, [dispatch]);
const setInputValue = (0,external_React_.useCallback)(newInputValue => {
dispatch({
type: FunctionSetInputValue,
inputValue: newInputValue
});
}, [dispatch]);
const reset = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionReset$1
});
}, [dispatch]);
return {
// prop getters.
getItemProps,
getLabelProps,
getMenuProps,
getInputProps,
getComboboxProps,
getToggleButtonProps,
// actions.
toggleMenu,
openMenu,
closeMenu,
setHighlightedIndex,
setInputValue,
selectItem,
reset,
// state.
highlightedIndex,
isOpen,
selectedItem,
inputValue
};
}
const defaultStateValues = {
activeIndex: -1,
selectedItems: []
};
/**
* Returns the initial value for a state key in the following order:
* 1. controlled prop, 2. initial prop, 3. default prop, 4. default
* value from Downshift.
*
* @param {Object} props Props passed to the hook.
* @param {string} propKey Props key to generate the value for.
* @returns {any} The initial value for that prop.
*/
function getInitialValue(props, propKey) {
return getInitialValue$1(props, propKey, defaultStateValues);
}
/**
* Returns the default value for a state key in the following order:
* 1. controlled prop, 2. default prop, 3. default value from Downshift.
*
* @param {Object} props Props passed to the hook.
* @param {string} propKey Props key to generate the value for.
* @returns {any} The initial value for that prop.
*/
function getDefaultValue(props, propKey) {
return getDefaultValue$1(props, propKey, defaultStateValues);
}
/**
* Gets the initial state based on the provided props. It uses initial, default
* and controlled props related to state in order to compute the initial value.
*
* @param {Object} props Props passed to the hook.
* @returns {Object} The initial state.
*/
function getInitialState(props) {
const activeIndex = getInitialValue(props, 'activeIndex');
const selectedItems = getInitialValue(props, 'selectedItems');
return {
activeIndex,
selectedItems
};
}
/**
* Returns true if dropdown keydown operation is permitted. Should not be
* allowed on keydown with modifier keys (ctrl, alt, shift, meta), on
* input element with text content that is either highlighted or selection
* cursor is not at the starting position.
*
* @param {KeyboardEvent} event The event from keydown.
* @returns {boolean} Whether the operation is allowed.
*/
function isKeyDownOperationPermitted(event) {
if (event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) {
return false;
}
const element = event.target;
if (element instanceof HTMLInputElement && // if element is a text input
element.value !== '' && ( // and we have text in it
// and cursor is either not at the start or is currently highlighting text.
element.selectionStart !== 0 || element.selectionEnd !== 0)) {
return false;
}
return true;
}
/**
* Returns a message to be added to aria-live region when item is removed.
*
* @param {Object} selectionParameters Parameters required to build the message.
* @returns {string} The a11y message.
*/
function getA11yRemovalMessage(selectionParameters) {
const {
removedSelectedItem,
itemToString: itemToStringLocal
} = selectionParameters;
return `${itemToStringLocal(removedSelectedItem)} has been removed.`;
}
const propTypes = {
selectedItems: (prop_types_default()).array,
initialSelectedItems: (prop_types_default()).array,
defaultSelectedItems: (prop_types_default()).array,
itemToString: (prop_types_default()).func,
getA11yRemovalMessage: (prop_types_default()).func,
stateReducer: (prop_types_default()).func,
activeIndex: (prop_types_default()).number,
initialActiveIndex: (prop_types_default()).number,
defaultActiveIndex: (prop_types_default()).number,
onActiveIndexChange: (prop_types_default()).func,
onSelectedItemsChange: (prop_types_default()).func,
keyNavigationNext: (prop_types_default()).string,
keyNavigationPrevious: (prop_types_default()).string,
environment: prop_types_default().shape({
addEventListener: (prop_types_default()).func,
removeEventListener: (prop_types_default()).func,
document: prop_types_default().shape({
getElementById: (prop_types_default()).func,
activeElement: (prop_types_default()).any,
body: (prop_types_default()).any
})
})
};
const defaultProps = {
itemToString: defaultProps$3.itemToString,
stateReducer: defaultProps$3.stateReducer,
environment: defaultProps$3.environment,
getA11yRemovalMessage,
keyNavigationNext: 'ArrowRight',
keyNavigationPrevious: 'ArrowLeft'
}; // eslint-disable-next-line import/no-mutable-exports
let validatePropTypes = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
const SelectedItemClick = false ? 0 : 0;
const SelectedItemKeyDownDelete = false ? 0 : 1;
const SelectedItemKeyDownBackspace = false ? 0 : 2;
const SelectedItemKeyDownNavigationNext = false ? 0 : 3;
const SelectedItemKeyDownNavigationPrevious = false ? 0 : 4;
const DropdownKeyDownNavigationPrevious = false ? 0 : 5;
const DropdownKeyDownBackspace = false ? 0 : 6;
const DropdownClick = false ? 0 : 7;
const FunctionAddSelectedItem = false ? 0 : 8;
const FunctionRemoveSelectedItem = false ? 0 : 9;
const FunctionSetSelectedItems = false ? 0 : 10;
const FunctionSetActiveIndex = false ? 0 : 11;
const FunctionReset = false ? 0 : 12;
var stateChangeTypes = /*#__PURE__*/Object.freeze({
__proto__: null,
SelectedItemClick: SelectedItemClick,
SelectedItemKeyDownDelete: SelectedItemKeyDownDelete,
SelectedItemKeyDownBackspace: SelectedItemKeyDownBackspace,
SelectedItemKeyDownNavigationNext: SelectedItemKeyDownNavigationNext,
SelectedItemKeyDownNavigationPrevious: SelectedItemKeyDownNavigationPrevious,
DropdownKeyDownNavigationPrevious: DropdownKeyDownNavigationPrevious,
DropdownKeyDownBackspace: DropdownKeyDownBackspace,
DropdownClick: DropdownClick,
FunctionAddSelectedItem: FunctionAddSelectedItem,
FunctionRemoveSelectedItem: FunctionRemoveSelectedItem,
FunctionSetSelectedItems: FunctionSetSelectedItems,
FunctionSetActiveIndex: FunctionSetActiveIndex,
FunctionReset: FunctionReset
});
/* eslint-disable complexity */
function downshiftMultipleSelectionReducer(state, action) {
const {
type,
index,
props,
selectedItem
} = action;
const {
activeIndex,
selectedItems
} = state;
let changes;
switch (type) {
case SelectedItemClick:
changes = {
activeIndex: index
};
break;
case SelectedItemKeyDownNavigationPrevious:
changes = {
activeIndex: activeIndex - 1 < 0 ? 0 : activeIndex - 1
};
break;
case SelectedItemKeyDownNavigationNext:
changes = {
activeIndex: activeIndex + 1 >= selectedItems.length ? -1 : activeIndex + 1
};
break;
case SelectedItemKeyDownBackspace:
case SelectedItemKeyDownDelete:
{
let newActiveIndex = activeIndex;
if (selectedItems.length === 1) {
newActiveIndex = -1;
} else if (activeIndex === selectedItems.length - 1) {
newActiveIndex = selectedItems.length - 2;
}
changes = {
selectedItems: [...selectedItems.slice(0, activeIndex), ...selectedItems.slice(activeIndex + 1)],
...{
activeIndex: newActiveIndex
}
};
break;
}
case DropdownKeyDownNavigationPrevious:
changes = {
activeIndex: selectedItems.length - 1
};
break;
case DropdownKeyDownBackspace:
changes = {
selectedItems: selectedItems.slice(0, selectedItems.length - 1)
};
break;
case FunctionAddSelectedItem:
changes = {
selectedItems: [...selectedItems, selectedItem]
};
break;
case DropdownClick:
changes = {
activeIndex: -1
};
break;
case FunctionRemoveSelectedItem:
{
let newActiveIndex = activeIndex;
const selectedItemIndex = selectedItems.indexOf(selectedItem);
if (selectedItemIndex >= 0) {
if (selectedItems.length === 1) {
newActiveIndex = -1;
} else if (selectedItemIndex === selectedItems.length - 1) {
newActiveIndex = selectedItems.length - 2;
}
changes = {
selectedItems: [...selectedItems.slice(0, selectedItemIndex), ...selectedItems.slice(selectedItemIndex + 1)],
activeIndex: newActiveIndex
};
}
break;
}
case FunctionSetSelectedItems:
{
const {
selectedItems: newSelectedItems
} = action;
changes = {
selectedItems: newSelectedItems
};
break;
}
case FunctionSetActiveIndex:
{
const {
activeIndex: newActiveIndex
} = action;
changes = {
activeIndex: newActiveIndex
};
break;
}
case FunctionReset:
changes = {
activeIndex: getDefaultValue(props, 'activeIndex'),
selectedItems: getDefaultValue(props, 'selectedItems')
};
break;
default:
throw new Error('Reducer called without proper action type.');
}
return { ...state,
...changes
};
}
useMultipleSelection.stateChangeTypes = stateChangeTypes;
function useMultipleSelection(userProps) {
if (userProps === void 0) {
userProps = {};
}
validatePropTypes(userProps, useMultipleSelection); // Props defaults and destructuring.
const props = { ...defaultProps,
...userProps
};
const {
getA11yRemovalMessage,
itemToString,
environment,
keyNavigationNext,
keyNavigationPrevious
} = props; // Reducer init.
const [state, dispatch] = useControlledReducer$1(downshiftMultipleSelectionReducer, getInitialState(props), props);
const {
activeIndex,
selectedItems
} = state; // Refs.
const isInitialMountRef = (0,external_React_.useRef)(true);
const dropdownRef = (0,external_React_.useRef)(null);
const previousSelectedItemsRef = (0,external_React_.useRef)(selectedItems);
const selectedItemRefs = (0,external_React_.useRef)();
selectedItemRefs.current = [];
const latest = downshift_esm_useLatestRef({
state,
props
}); // Effects.
/* Sets a11y status message on changes in selectedItem. */
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
if (selectedItems.length < previousSelectedItemsRef.current.length) {
const removedSelectedItem = previousSelectedItemsRef.current.find(item => selectedItems.indexOf(item) < 0);
setStatus(getA11yRemovalMessage({
itemToString,
resultCount: selectedItems.length,
removedSelectedItem,
activeIndex,
activeSelectedItem: selectedItems[activeIndex]
}), environment.document);
}
previousSelectedItemsRef.current = selectedItems; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedItems.length]); // Sets focus on active item.
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
if (activeIndex === -1 && dropdownRef.current) {
dropdownRef.current.focus();
} else if (selectedItemRefs.current[activeIndex]) {
selectedItemRefs.current[activeIndex].focus();
}
}, [activeIndex]);
useControlPropsValidator({
isInitialMount: isInitialMountRef.current,
props,
state
});
const setGetterPropCallInfo = useGetterPropsCalledChecker('getDropdownProps'); // Make initial ref false.
(0,external_React_.useEffect)(() => {
isInitialMountRef.current = false;
}, []); // Event handler functions.
const selectedItemKeyDownHandlers = (0,external_React_.useMemo)(() => ({
[keyNavigationPrevious]() {
dispatch({
type: SelectedItemKeyDownNavigationPrevious
});
},
[keyNavigationNext]() {
dispatch({
type: SelectedItemKeyDownNavigationNext
});
},
Delete() {
dispatch({
type: SelectedItemKeyDownDelete
});
},
Backspace() {
dispatch({
type: SelectedItemKeyDownBackspace
});
}
}), [dispatch, keyNavigationNext, keyNavigationPrevious]);
const dropdownKeyDownHandlers = (0,external_React_.useMemo)(() => ({
[keyNavigationPrevious](event) {
if (isKeyDownOperationPermitted(event)) {
dispatch({
type: DropdownKeyDownNavigationPrevious
});
}
},
Backspace(event) {
if (isKeyDownOperationPermitted(event)) {
dispatch({
type: DropdownKeyDownBackspace
});
}
}
}), [dispatch, keyNavigationPrevious]); // Getter props.
const getSelectedItemProps = (0,external_React_.useCallback)(function (_temp) {
let {
refKey = 'ref',
ref,
onClick,
onKeyDown,
selectedItem,
index,
...rest
} = _temp === void 0 ? {} : _temp;
const {
state: latestState
} = latest.current;
const itemIndex = getItemIndex(index, selectedItem, latestState.selectedItems);
if (itemIndex < 0) {
throw new Error('Pass either selectedItem or index in getSelectedItemProps!');
}
const selectedItemHandleClick = () => {
dispatch({
type: SelectedItemClick,
index
});
};
const selectedItemHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && selectedItemKeyDownHandlers[key]) {
selectedItemKeyDownHandlers[key](event);
}
};
return {
[refKey]: handleRefs(ref, selectedItemNode => {
if (selectedItemNode) {
selectedItemRefs.current.push(selectedItemNode);
}
}),
tabIndex: index === latestState.activeIndex ? 0 : -1,
onClick: callAllEventHandlers(onClick, selectedItemHandleClick),
onKeyDown: callAllEventHandlers(onKeyDown, selectedItemHandleKeyDown),
...rest
};
}, [dispatch, latest, selectedItemKeyDownHandlers]);
const getDropdownProps = (0,external_React_.useCallback)(function (_temp2, _temp3) {
let {
refKey = 'ref',
ref,
onKeyDown,
onClick,
preventKeyAction = false,
...rest
} = _temp2 === void 0 ? {} : _temp2;
let {
suppressRefError = false
} = _temp3 === void 0 ? {} : _temp3;
setGetterPropCallInfo('getDropdownProps', suppressRefError, refKey, dropdownRef);
const dropdownHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && dropdownKeyDownHandlers[key]) {
dropdownKeyDownHandlers[key](event);
}
};
const dropdownHandleClick = () => {
dispatch({
type: DropdownClick
});
};
return {
[refKey]: handleRefs(ref, dropdownNode => {
if (dropdownNode) {
dropdownRef.current = dropdownNode;
}
}),
...(!preventKeyAction && {
onKeyDown: callAllEventHandlers(onKeyDown, dropdownHandleKeyDown),
onClick: callAllEventHandlers(onClick, dropdownHandleClick)
}),
...rest
};
}, [dispatch, dropdownKeyDownHandlers, setGetterPropCallInfo]); // returns
const addSelectedItem = (0,external_React_.useCallback)(selectedItem => {
dispatch({
type: FunctionAddSelectedItem,
selectedItem
});
}, [dispatch]);
const removeSelectedItem = (0,external_React_.useCallback)(selectedItem => {
dispatch({
type: FunctionRemoveSelectedItem,
selectedItem
});
}, [dispatch]);
const setSelectedItems = (0,external_React_.useCallback)(newSelectedItems => {
dispatch({
type: FunctionSetSelectedItems,
selectedItems: newSelectedItems
});
}, [dispatch]);
const setActiveIndex = (0,external_React_.useCallback)(newActiveIndex => {
dispatch({
type: FunctionSetActiveIndex,
activeIndex: newActiveIndex
});
}, [dispatch]);
const reset = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionReset
});
}, [dispatch]);
return {
getSelectedItemProps,
getDropdownProps,
addSelectedItem,
removeSelectedItem,
setSelectedItems,
setActiveIndex,
reset,
selectedItems,
activeIndex
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-select-control/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const backCompatMinWidth = props => !props.__nextUnconstrainedWidth ? /*#__PURE__*/emotion_react_browser_esm_css(Container, "{min-width:130px;}" + ( true ? "" : 0), true ? "" : 0) : '';
const InputBaseWithBackCompatMinWidth = /*#__PURE__*/createStyled(input_base, true ? {
target: "eswuck60"
} : 0)(backCompatMinWidth, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-select-control/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const custom_select_control_itemToString = item => item?.name; // This is needed so that in Windows, where
// the menu does not necessarily open on
// key up/down, you can still switch between
// options with the menu closed.
const custom_select_control_stateReducer = ({
selectedItem
}, {
type,
changes,
props: {
items
}
}) => {
switch (type) {
case useSelect.stateChangeTypes.ToggleButtonKeyDownArrowDown:
// If we already have a selected item, try to select the next one,
// without circular navigation. Otherwise, select the first item.
return {
selectedItem: items[selectedItem ? Math.min(items.indexOf(selectedItem) + 1, items.length - 1) : 0]
};
case useSelect.stateChangeTypes.ToggleButtonKeyDownArrowUp:
// If we already have a selected item, try to select the previous one,
// without circular navigation. Otherwise, select the last item.
return {
selectedItem: items[selectedItem ? Math.max(items.indexOf(selectedItem) - 1, 0) : items.length - 1]
};
default:
return changes;
}
};
function CustomSelectControl(props) {
const {
/** Start opting into the larger default height that will become the default size in a future version. */
__next36pxDefaultSize = false,
/** Start opting into the unconstrained width that will become the default in a future version. */
__nextUnconstrainedWidth = false,
className,
hideLabelFromVision,
label,
describedBy,
options: items,
onChange: onSelectedItemChange,
/** @type {import('../select-control/types').SelectControlProps.size} */
size = 'default',
value: _selectedItem,
onMouseOver,
onMouseOut,
onFocus,
onBlur,
__experimentalShowSelectedHint = false
} = props;
const {
getLabelProps,
getToggleButtonProps,
getMenuProps,
getItemProps,
isOpen,
highlightedIndex,
selectedItem
} = useSelect({
initialSelectedItem: items[0],
items,
itemToString: custom_select_control_itemToString,
onSelectedItemChange,
...(typeof _selectedItem !== 'undefined' && _selectedItem !== null ? {
selectedItem: _selectedItem
} : undefined),
stateReducer: custom_select_control_stateReducer
});
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
function handleOnFocus(e) {
setIsFocused(true);
onFocus?.(e);
}
function handleOnBlur(e) {
setIsFocused(false);
onBlur?.(e);
}
if (!__nextUnconstrainedWidth) {
external_wp_deprecated_default()('Constrained width styles for wp.components.CustomSelectControl', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextUnconstrainedWidth` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
function getDescribedBy() {
if (describedBy) {
return describedBy;
}
if (!selectedItem) {
return (0,external_wp_i18n_namespaceObject.__)('No selection');
} // translators: %s: The selected option.
return (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Currently selected: %s'), selectedItem.name);
}
const menuProps = getMenuProps({
className: 'components-custom-select-control__menu',
'aria-hidden': !isOpen
});
const onKeyDownHandler = (0,external_wp_element_namespaceObject.useCallback)(e => {
e.stopPropagation();
menuProps?.onKeyDown?.(e);
}, [menuProps]); // We need this here, because the null active descendant is not fully ARIA compliant.
if (menuProps['aria-activedescendant']?.startsWith('downshift-null')) {
delete menuProps['aria-activedescendant'];
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-custom-select-control', className)
}, hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label",
...getLabelProps()
}, label) :
/* eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for */
(0,external_wp_element_namespaceObject.createElement)(StyledLabel, { ...getLabelProps({
className: 'components-custom-select-control__label'
})
}, label), (0,external_wp_element_namespaceObject.createElement)(InputBaseWithBackCompatMinWidth, {
__next36pxDefaultSize: __next36pxDefaultSize,
__nextUnconstrainedWidth: __nextUnconstrainedWidth,
isFocused: isOpen || isFocused,
__unstableInputWidth: __nextUnconstrainedWidth ? undefined : 'auto',
labelPosition: __nextUnconstrainedWidth ? undefined : 'top',
size: size,
suffix: (0,external_wp_element_namespaceObject.createElement)(select_control_chevron_down, null)
}, (0,external_wp_element_namespaceObject.createElement)(Select, {
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
as: "button",
onFocus: handleOnFocus,
onBlur: handleOnBlur,
selectSize: size,
__next36pxDefaultSize: __next36pxDefaultSize,
...getToggleButtonProps({
// This is needed because some speech recognition software don't support `aria-labelledby`.
'aria-label': label,
'aria-labelledby': undefined,
className: 'components-custom-select-control__button',
describedBy: getDescribedBy()
})
}, custom_select_control_itemToString(selectedItem), __experimentalShowSelectedHint && selectedItem.__experimentalHint && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-custom-select-control__hint"
}, selectedItem.__experimentalHint))), (0,external_wp_element_namespaceObject.createElement)("ul", { ...menuProps,
onKeyDown: onKeyDownHandler
}, isOpen && items.map((item, index) => // eslint-disable-next-line react/jsx-key
(0,external_wp_element_namespaceObject.createElement)("li", { ...getItemProps({
item,
index,
key: item.key,
className: classnames_default()(item.className, 'components-custom-select-control__item', {
'is-highlighted': index === highlightedIndex,
'has-hint': !!item.__experimentalHint,
'is-next-36px-default-size': __next36pxDefaultSize
}),
style: item.style
})
}, item.name, item.__experimentalHint && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-custom-select-control__item-hint"
}, item.__experimentalHint), item === selectedItem && (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_check,
className: "components-custom-select-control__item-icon"
})))));
}
function StableCustomSelectControl(props) {
return (0,external_wp_element_namespaceObject.createElement)(CustomSelectControl, { ...props,
__experimentalShowSelectedHint: false
});
}
;// CONCATENATED MODULE: ./node_modules/use-lilius/build/index.es.js
function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
function requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
}
}
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @param {Date|Number} argument - the value to convert
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
*
* @example
* // Clone the date:
* const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* const result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
function toDate(argument) {
requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument); // Clone the date
if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new Date(argument.getTime());
} else if (typeof argument === 'number' || argStr === '[object Number]') {
return new Date(argument);
} else {
if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
// eslint-disable-next-line no-console
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); // eslint-disable-next-line no-console
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
/**
* @name addDays
* @category Day Helpers
* @summary Add the specified number of days to the given date.
*
* @description
* Add the specified number of days to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} - the new date with the days added
* @throws {TypeError} - 2 arguments required
*
* @example
* // Add 10 days to 1 September 2014:
* const result = addDays(new Date(2014, 8, 1), 10)
* //=> Thu Sep 11 2014 00:00:00
*/
function addDays(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var amount = toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 days, no-op to avoid changing times in the hour before end of DST
return date;
}
date.setDate(date.getDate() + amount);
return date;
}
/**
* @name addMonths
* @category Month Helpers
* @summary Add the specified number of months to the given date.
*
* @description
* Add the specified number of months to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 months to 1 September 2014:
* const result = addMonths(new Date(2014, 8, 1), 5)
* //=> Sun Feb 01 2015 00:00:00
*/
function addMonths(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var amount = toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 months, no-op to avoid changing times in the hour before end of DST
return date;
}
var dayOfMonth = date.getDate(); // The JS Date object supports date math by accepting out-of-bounds values for
// month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and
// new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we
// want except that dates will wrap around the end of a month, meaning that
// new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
// we'll default to the end of the desired month by adding 1 to the desired
// month and using a date of 0 to back up one day to the end of the desired
// month.
var endOfDesiredMonth = new Date(date.getTime());
endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
var daysInMonth = endOfDesiredMonth.getDate();
if (dayOfMonth >= daysInMonth) {
// If we're already at the end of the month, then this is the correct date
// and we're done.
return endOfDesiredMonth;
} else {
// Otherwise, we now know that setting the original day-of-month value won't
// cause an overflow, so set the desired day-of-month. Note that we can't
// just set the date of `endOfDesiredMonth` because that object may have had
// its time changed in the unusual case where where a DST transition was on
// the last day of the month and its local time was in the hour skipped or
// repeated next to a DST transition. So we use `date` instead which is
// guaranteed to still have the original time.
date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
return date;
}
}
var index_es_defaultOptions = {};
function getDefaultOptions() {
return index_es_defaultOptions;
}
/**
* @name startOfWeek
* @category Week Helpers
* @summary Return the start of a week for the given date.
*
* @description
* Return the start of a week for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date} the start of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The start of a week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Aug 31 2014 00:00:00
*
* @example
* // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions = getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setDate(date.getDate() - diff);
date.setHours(0, 0, 0, 0);
return date;
}
/**
* @name startOfDay
* @category Day Helpers
* @summary Return the start of a day for the given date.
*
* @description
* Return the start of a day for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a day
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a day for 2 September 2014 11:55:00:
* const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 00:00:00
*/
function startOfDay(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
date.setHours(0, 0, 0, 0);
return date;
}
/**
* @name addWeeks
* @category Week Helpers
* @summary Add the specified number of weeks to the given date.
*
* @description
* Add the specified number of week to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 4 weeks to 1 September 2014:
* const result = addWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Sep 29 2014 00:00:00
*/
function addWeeks(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
var days = amount * 7;
return addDays(dirtyDate, days);
}
/**
* @name addYears
* @category Year Helpers
* @summary Add the specified number of years to the given date.
*
* @description
* Add the specified number of years to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of years to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the years added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 years to 1 September 2014:
* const result = addYears(new Date(2014, 8, 1), 5)
* //=> Sun Sep 01 2019 00:00:00
*/
function addYears(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMonths(dirtyDate, amount * 12);
}
/**
* @name endOfMonth
* @category Month Helpers
* @summary Return the end of a month for the given date.
*
* @description
* Return the end of a month for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a month for 2 September 2014 11:55:00:
* const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 23:59:59.999
*/
function endOfMonth(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var month = date.getMonth();
date.setFullYear(date.getFullYear(), month + 1, 0);
date.setHours(23, 59, 59, 999);
return date;
}
/**
* @name eachDayOfInterval
* @category Interval Helpers
* @summary Return the array of dates within the specified time interval.
*
* @description
* Return the array of dates within the specified time interval.
*
* @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
* @param {Object} [options] - an object with options.
* @param {Number} [options.step=1] - the step to increment by. The value should be more than 1.
* @returns {Date[]} the array with starts of days from the day of the interval start to the day of the interval end
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.step` must be a number greater than 1
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // Each day between 6 October 2014 and 10 October 2014:
* const result = eachDayOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 9, 10)
* })
* //=> [
* // Mon Oct 06 2014 00:00:00,
* // Tue Oct 07 2014 00:00:00,
* // Wed Oct 08 2014 00:00:00,
* // Thu Oct 09 2014 00:00:00,
* // Fri Oct 10 2014 00:00:00
* // ]
*/
function eachDayOfInterval(dirtyInterval, options) {
var _options$step;
requiredArgs(1, arguments);
var interval = dirtyInterval || {};
var startDate = toDate(interval.start);
var endDate = toDate(interval.end);
var endTime = endDate.getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(startDate.getTime() <= endTime)) {
throw new RangeError('Invalid interval');
}
var dates = [];
var currentDate = startDate;
currentDate.setHours(0, 0, 0, 0);
var step = Number((_options$step = options === null || options === void 0 ? void 0 : options.step) !== null && _options$step !== void 0 ? _options$step : 1);
if (step < 1 || isNaN(step)) throw new RangeError('`options.step` must be a number greater than 1');
while (currentDate.getTime() <= endTime) {
dates.push(toDate(currentDate));
currentDate.setDate(currentDate.getDate() + step);
currentDate.setHours(0, 0, 0, 0);
}
return dates;
}
/**
* @name eachMonthOfInterval
* @category Interval Helpers
* @summary Return the array of months within the specified time interval.
*
* @description
* Return the array of months within the specified time interval.
*
* @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
* @returns {Date[]} the array with starts of months from the month of the interval start to the month of the interval end
* @throws {TypeError} 1 argument required
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // Each month between 6 February 2014 and 10 August 2014:
* const result = eachMonthOfInterval({
* start: new Date(2014, 1, 6),
* end: new Date(2014, 7, 10)
* })
* //=> [
* // Sat Feb 01 2014 00:00:00,
* // Sat Mar 01 2014 00:00:00,
* // Tue Apr 01 2014 00:00:00,
* // Thu May 01 2014 00:00:00,
* // Sun Jun 01 2014 00:00:00,
* // Tue Jul 01 2014 00:00:00,
* // Fri Aug 01 2014 00:00:00
* // ]
*/
function eachMonthOfInterval(dirtyInterval) {
requiredArgs(1, arguments);
var interval = dirtyInterval || {};
var startDate = toDate(interval.start);
var endDate = toDate(interval.end);
var endTime = endDate.getTime();
var dates = []; // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(startDate.getTime() <= endTime)) {
throw new RangeError('Invalid interval');
}
var currentDate = startDate;
currentDate.setHours(0, 0, 0, 0);
currentDate.setDate(1);
while (currentDate.getTime() <= endTime) {
dates.push(toDate(currentDate));
currentDate.setMonth(currentDate.getMonth() + 1);
}
return dates;
}
/**
* @name eachWeekOfInterval
* @category Interval Helpers
* @summary Return the array of weeks within the specified time interval.
*
* @description
* Return the array of weeks within the specified time interval.
*
* @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date[]} the array with starts of weeks from the week of the interval start to the week of the interval end
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be 0, 1, ..., 6
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // Each week within interval 6 October 2014 - 23 November 2014:
* const result = eachWeekOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 10, 23)
* })
* //=> [
* // Sun Oct 05 2014 00:00:00,
* // Sun Oct 12 2014 00:00:00,
* // Sun Oct 19 2014 00:00:00,
* // Sun Oct 26 2014 00:00:00,
* // Sun Nov 02 2014 00:00:00,
* // Sun Nov 09 2014 00:00:00,
* // Sun Nov 16 2014 00:00:00,
* // Sun Nov 23 2014 00:00:00
* // ]
*/
function eachWeekOfInterval(dirtyInterval, options) {
requiredArgs(1, arguments);
var interval = dirtyInterval || {};
var startDate = toDate(interval.start);
var endDate = toDate(interval.end);
var endTime = endDate.getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(startDate.getTime() <= endTime)) {
throw new RangeError('Invalid interval');
}
var startDateWeek = startOfWeek(startDate, options);
var endDateWeek = startOfWeek(endDate, options); // Some timezones switch DST at midnight, making start of day unreliable in these timezones, 3pm is a safe bet
startDateWeek.setHours(15);
endDateWeek.setHours(15);
endTime = endDateWeek.getTime();
var weeks = [];
var currentWeek = startDateWeek;
while (currentWeek.getTime() <= endTime) {
currentWeek.setHours(0);
weeks.push(toDate(currentWeek));
currentWeek = addWeeks(currentWeek, 1);
currentWeek.setHours(15);
}
return weeks;
}
/**
* @name startOfMonth
* @category Month Helpers
* @summary Return the start of a month for the given date.
*
* @description
* Return the start of a month for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a month for 2 September 2014 11:55:00:
* const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfMonth(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
date.setDate(1);
date.setHours(0, 0, 0, 0);
return date;
}
/**
* @name endOfWeek
* @category Week Helpers
* @summary Return the end of a week for the given date.
*
* @description
* Return the end of a week for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date} the end of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The end of a week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sat Sep 06 2014 23:59:59.999
*
* @example
* // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 23:59:59.999
*/
function endOfWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions = getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
date.setDate(date.getDate() + diff);
date.setHours(23, 59, 59, 999);
return date;
}
/**
* @name getDaysInMonth
* @category Month Helpers
* @summary Get the number of days in a month of the given date.
*
* @description
* Get the number of days in a month of the given date.
*
* @param {Date|Number} date - the given date
* @returns {Number} the number of days in a month
* @throws {TypeError} 1 argument required
*
* @example
* // How many days are in February 2000?
* const result = getDaysInMonth(new Date(2000, 1))
* //=> 29
*/
function getDaysInMonth(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var year = date.getFullYear();
var monthIndex = date.getMonth();
var lastDayOfMonth = new Date(0);
lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
lastDayOfMonth.setHours(0, 0, 0, 0);
return lastDayOfMonth.getDate();
}
/**
* @name isAfter
* @category Common Helpers
* @summary Is the first date after the second one?
*
* @description
* Is the first date after the second one?
*
* @param {Date|Number} date - the date that should be after the other one to return true
* @param {Date|Number} dateToCompare - the date to compare with
* @returns {Boolean} the first date is after the second date
* @throws {TypeError} 2 arguments required
*
* @example
* // Is 10 July 1989 after 11 February 1987?
* const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> true
*/
function isAfter(dirtyDate, dirtyDateToCompare) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var dateToCompare = toDate(dirtyDateToCompare);
return date.getTime() > dateToCompare.getTime();
}
/**
* @name isBefore
* @category Common Helpers
* @summary Is the first date before the second one?
*
* @description
* Is the first date before the second one?
*
* @param {Date|Number} date - the date that should be before the other one to return true
* @param {Date|Number} dateToCompare - the date to compare with
* @returns {Boolean} the first date is before the second date
* @throws {TypeError} 2 arguments required
*
* @example
* // Is 10 July 1989 before 11 February 1987?
* const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> false
*/
function isBefore(dirtyDate, dirtyDateToCompare) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var dateToCompare = toDate(dirtyDateToCompare);
return date.getTime() < dateToCompare.getTime();
}
/**
* @name isEqual
* @category Common Helpers
* @summary Are the given dates equal?
*
* @description
* Are the given dates equal?
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Boolean} the dates are equal
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?
* const result = isEqual(
* new Date(2014, 6, 2, 6, 30, 45, 0),
* new Date(2014, 6, 2, 6, 30, 45, 500)
* )
* //=> false
*/
function isEqual(dirtyLeftDate, dirtyRightDate) {
requiredArgs(2, arguments);
var dateLeft = toDate(dirtyLeftDate);
var dateRight = toDate(dirtyRightDate);
return dateLeft.getTime() === dateRight.getTime();
}
/**
* @name setMonth
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} month - the month of the new date
* @returns {Date} the new date with the month set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set February to 1 September 2014:
* const result = setMonth(new Date(2014, 8, 1), 1)
* //=> Sat Feb 01 2014 00:00:00
*/
function setMonth(dirtyDate, dirtyMonth) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var month = toInteger(dirtyMonth);
var year = date.getFullYear();
var day = date.getDate();
var dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setFullYear(year, month, 15);
dateWithDesiredMonth.setHours(0, 0, 0, 0);
var daysInMonth = getDaysInMonth(dateWithDesiredMonth); // Set the last day of the new month
// if the original date was the last day of the longer month
date.setMonth(month, Math.min(day, daysInMonth));
return date;
}
/**
* @name set
* @category Common Helpers
* @summary Set date values to a given date.
*
* @description
* Set date values to a given date.
*
* Sets time values to date from object `values`.
* A value is not set if it is undefined or null or doesn't exist in `values`.
*
* Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts
* to use native `Date#setX` methods. If you use this function, you may not want to include the
* other `setX` functions that date-fns provides if you are concerned about the bundle size.
*
* @param {Date|Number} date - the date to be changed
* @param {Object} values - an object with options
* @param {Number} [values.year] - the number of years to be set
* @param {Number} [values.month] - the number of months to be set
* @param {Number} [values.date] - the number of days to be set
* @param {Number} [values.hours] - the number of hours to be set
* @param {Number} [values.minutes] - the number of minutes to be set
* @param {Number} [values.seconds] - the number of seconds to be set
* @param {Number} [values.milliseconds] - the number of milliseconds to be set
* @returns {Date} the new date with options set
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `values` must be an object
*
* @example
* // Transform 1 September 2014 into 20 October 2015 in a single line:
* const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })
* //=> Tue Oct 20 2015 00:00:00
*
* @example
* // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:
* const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })
* //=> Mon Sep 01 2014 12:23:45
*/
function set(dirtyDate, values) {
requiredArgs(2, arguments);
if (typeof values !== 'object' || values === null) {
throw new RangeError('values parameter must be an object');
}
var date = toDate(dirtyDate); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(date.getTime())) {
return new Date(NaN);
}
if (values.year != null) {
date.setFullYear(values.year);
}
if (values.month != null) {
date = setMonth(date, values.month);
}
if (values.date != null) {
date.setDate(toInteger(values.date));
}
if (values.hours != null) {
date.setHours(toInteger(values.hours));
}
if (values.minutes != null) {
date.setMinutes(toInteger(values.minutes));
}
if (values.seconds != null) {
date.setSeconds(toInteger(values.seconds));
}
if (values.milliseconds != null) {
date.setMilliseconds(toInteger(values.milliseconds));
}
return date;
}
/**
* @name setYear
* @category Year Helpers
* @summary Set the year to the given date.
*
* @description
* Set the year to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} year - the year of the new date
* @returns {Date} the new date with the year set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set year 2013 to 1 September 2014:
* const result = setYear(new Date(2014, 8, 1), 2013)
* //=> Sun Sep 01 2013 00:00:00
*/
function setYear(dirtyDate, dirtyYear) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var year = toInteger(dirtyYear); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(date.getTime())) {
return new Date(NaN);
}
date.setFullYear(year);
return date;
}
/**
* @name startOfToday
* @category Day Helpers
* @summary Return the start of today.
* @pure false
*
* @description
* Return the start of today.
*
* > ⚠️ Please note that this function is not present in the FP submodule as
* > it uses `Date.now()` internally hence impure and can't be safely curried.
*
* @returns {Date} the start of today
*
* @example
* // If today is 6 October 2014:
* const result = startOfToday()
* //=> Mon Oct 6 2014 00:00:00
*/
function startOfToday() {
return startOfDay(Date.now());
}
/**
* @name subMonths
* @category Month Helpers
* @summary Subtract the specified number of months from the given date.
*
* @description
* Subtract the specified number of months from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 months from 1 February 2015:
* const result = subMonths(new Date(2015, 1, 1), 5)
* //=> Mon Sep 01 2014 00:00:00
*/
function subMonths(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMonths(dirtyDate, -amount);
}
/**
* @name subYears
* @category Year Helpers
* @summary Subtract the specified number of years from the given date.
*
* @description
* Subtract the specified number of years from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the years subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 years from 1 September 2014:
* const result = subYears(new Date(2014, 8, 1), 5)
* //=> Tue Sep 01 2009 00:00:00
*/
function subYears(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addYears(dirtyDate, -amount);
}
var Month;
(function (Month) {
Month[Month["JANUARY"] = 0] = "JANUARY";
Month[Month["FEBRUARY"] = 1] = "FEBRUARY";
Month[Month["MARCH"] = 2] = "MARCH";
Month[Month["APRIL"] = 3] = "APRIL";
Month[Month["MAY"] = 4] = "MAY";
Month[Month["JUNE"] = 5] = "JUNE";
Month[Month["JULY"] = 6] = "JULY";
Month[Month["AUGUST"] = 7] = "AUGUST";
Month[Month["SEPTEMBER"] = 8] = "SEPTEMBER";
Month[Month["OCTOBER"] = 9] = "OCTOBER";
Month[Month["NOVEMBER"] = 10] = "NOVEMBER";
Month[Month["DECEMBER"] = 11] = "DECEMBER";
})(Month || (Month = {}));
var Day;
(function (Day) {
Day[Day["SUNDAY"] = 0] = "SUNDAY";
Day[Day["MONDAY"] = 1] = "MONDAY";
Day[Day["TUESDAY"] = 2] = "TUESDAY";
Day[Day["WEDNESDAY"] = 3] = "WEDNESDAY";
Day[Day["THURSDAY"] = 4] = "THURSDAY";
Day[Day["FRIDAY"] = 5] = "FRIDAY";
Day[Day["SATURDAY"] = 6] = "SATURDAY";
})(Day || (Day = {}));
var inRange = function (date, min, max) {
return (isEqual(date, min) || isAfter(date, min)) && (isEqual(date, max) || isBefore(date, max));
};
var clearTime = function (date) { return set(date, { hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }); };
var useLilius = function (_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.weekStartsOn, weekStartsOn = _c === void 0 ? Day.SUNDAY : _c, _d = _b.viewing, initialViewing = _d === void 0 ? new Date() : _d, _e = _b.selected, initialSelected = _e === void 0 ? [] : _e, _f = _b.numberOfMonths, numberOfMonths = _f === void 0 ? 1 : _f;
var _g = (0,external_React_.useState)(initialViewing), viewing = _g[0], setViewing = _g[1];
var viewToday = (0,external_React_.useCallback)(function () { return setViewing(startOfToday()); }, [setViewing]);
var viewMonth = (0,external_React_.useCallback)(function (month) { return setViewing(function (v) { return setMonth(v, month); }); }, []);
var viewPreviousMonth = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return subMonths(v, 1); }); }, []);
var viewNextMonth = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return addMonths(v, 1); }); }, []);
var viewYear = (0,external_React_.useCallback)(function (year) { return setViewing(function (v) { return setYear(v, year); }); }, []);
var viewPreviousYear = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return subYears(v, 1); }); }, []);
var viewNextYear = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return addYears(v, 1); }); }, []);
var _h = (0,external_React_.useState)(initialSelected.map(clearTime)), selected = _h[0], setSelected = _h[1];
var clearSelected = function () { return setSelected([]); };
var isSelected = (0,external_React_.useCallback)(function (date) { return selected.findIndex(function (s) { return isEqual(s, date); }) > -1; }, [selected]);
var select = (0,external_React_.useCallback)(function (date, replaceExisting) {
if (replaceExisting) {
setSelected(Array.isArray(date) ? date : [date]);
}
else {
setSelected(function (selectedItems) { return selectedItems.concat(Array.isArray(date) ? date : [date]); });
}
}, []);
var deselect = (0,external_React_.useCallback)(function (date) {
return setSelected(function (selectedItems) {
return Array.isArray(date)
? selectedItems.filter(function (s) { return !date.map(function (d) { return d.getTime(); }).includes(s.getTime()); })
: selectedItems.filter(function (s) { return !isEqual(s, date); });
});
}, []);
var toggle = (0,external_React_.useCallback)(function (date, replaceExisting) { return (isSelected(date) ? deselect(date) : select(date, replaceExisting)); }, [deselect, isSelected, select]);
var selectRange = (0,external_React_.useCallback)(function (start, end, replaceExisting) {
if (replaceExisting) {
setSelected(eachDayOfInterval({ start: start, end: end }));
}
else {
setSelected(function (selectedItems) { return selectedItems.concat(eachDayOfInterval({ start: start, end: end })); });
}
}, []);
var deselectRange = (0,external_React_.useCallback)(function (start, end) {
setSelected(function (selectedItems) {
return selectedItems.filter(function (s) {
return !eachDayOfInterval({ start: start, end: end })
.map(function (d) { return d.getTime(); })
.includes(s.getTime());
});
});
}, []);
var calendar = (0,external_React_.useMemo)(function () {
return eachMonthOfInterval({
start: startOfMonth(viewing),
end: endOfMonth(addMonths(viewing, numberOfMonths - 1)),
}).map(function (month) {
return eachWeekOfInterval({
start: startOfMonth(month),
end: endOfMonth(month),
}, { weekStartsOn: weekStartsOn }).map(function (week) {
return eachDayOfInterval({
start: startOfWeek(week, { weekStartsOn: weekStartsOn }),
end: endOfWeek(week, { weekStartsOn: weekStartsOn }),
});
});
});
}, [viewing, weekStartsOn, numberOfMonths]);
return {
clearTime: clearTime,
inRange: inRange,
viewing: viewing,
setViewing: setViewing,
viewToday: viewToday,
viewMonth: viewMonth,
viewPreviousMonth: viewPreviousMonth,
viewNextMonth: viewNextMonth,
viewYear: viewYear,
viewPreviousYear: viewPreviousYear,
viewNextYear: viewNextYear,
selected: selected,
setSelected: setSelected,
clearSelected: clearSelected,
isSelected: isSelected,
select: select,
deselect: deselect,
toggle: toggle,
selectRange: selectRange,
deselectRange: deselectRange,
calendar: calendar,
};
};
;// CONCATENATED MODULE: ./node_modules/date-fns/node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/requiredArgs/index.js
function requiredArgs_requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/toDate/index.js
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @param {Date|Number} argument - the value to convert
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
*
* @example
* // Clone the date:
* const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* const result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
function toDate_toDate(argument) {
requiredArgs_requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument);
// Clone the date
if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new Date(argument.getTime());
} else if (typeof argument === 'number' || argStr === '[object Number]') {
return new Date(argument);
} else {
if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
// eslint-disable-next-line no-console
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
// eslint-disable-next-line no-console
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfDay/index.js
/**
* @name startOfDay
* @category Day Helpers
* @summary Return the start of a day for the given date.
*
* @description
* Return the start of a day for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a day
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a day for 2 September 2014 11:55:00:
* const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 00:00:00
*/
function startOfDay_startOfDay(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
date.setHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/toInteger/index.js
function toInteger_toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addMonths/index.js
/**
* @name addMonths
* @category Month Helpers
* @summary Add the specified number of months to the given date.
*
* @description
* Add the specified number of months to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 months to 1 September 2014:
* const result = addMonths(new Date(2014, 8, 1), 5)
* //=> Sun Feb 01 2015 00:00:00
*/
function addMonths_addMonths(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var amount = toInteger_toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 months, no-op to avoid changing times in the hour before end of DST
return date;
}
var dayOfMonth = date.getDate();
// The JS Date object supports date math by accepting out-of-bounds values for
// month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and
// new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we
// want except that dates will wrap around the end of a month, meaning that
// new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
// we'll default to the end of the desired month by adding 1 to the desired
// month and using a date of 0 to back up one day to the end of the desired
// month.
var endOfDesiredMonth = new Date(date.getTime());
endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
var daysInMonth = endOfDesiredMonth.getDate();
if (dayOfMonth >= daysInMonth) {
// If we're already at the end of the month, then this is the correct date
// and we're done.
return endOfDesiredMonth;
} else {
// Otherwise, we now know that setting the original day-of-month value won't
// cause an overflow, so set the desired day-of-month. Note that we can't
// just set the date of `endOfDesiredMonth` because that object may have had
// its time changed in the unusual case where where a DST transition was on
// the last day of the month and its local time was in the hour skipped or
// repeated next to a DST transition. So we use `date` instead which is
// guaranteed to still have the original time.
date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
return date;
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/subMonths/index.js
/**
* @name subMonths
* @category Month Helpers
* @summary Subtract the specified number of months from the given date.
*
* @description
* Subtract the specified number of months from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 months from 1 February 2015:
* const result = subMonths(new Date(2015, 1, 1), 5)
* //=> Mon Sep 01 2014 00:00:00
*/
function subMonths_subMonths(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var amount = toInteger_toInteger(dirtyAmount);
return addMonths_addMonths(dirtyDate, -amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isDate/index.js
/**
* @name isDate
* @category Common Helpers
* @summary Is the given value a date?
*
* @description
* Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
*
* @param {*} value - the value to check
* @returns {boolean} true if the given value is a date
* @throws {TypeError} 1 arguments required
*
* @example
* // For a valid date:
* const result = isDate(new Date())
* //=> true
*
* @example
* // For an invalid date:
* const result = isDate(new Date(NaN))
* //=> true
*
* @example
* // For some value:
* const result = isDate('2014-02-31')
* //=> false
*
* @example
* // For an object:
* const result = isDate({})
* //=> false
*/
function isDate(value) {
requiredArgs_requiredArgs(1, arguments);
return value instanceof Date || _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isValid/index.js
/**
* @name isValid
* @category Common Helpers
* @summary Is the given date valid?
*
* @description
* Returns false if argument is Invalid Date and true otherwise.
* Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* Invalid Date is a Date, whose time value is NaN.
*
* Time value of Date: http://es5.github.io/#x15.9.1.1
*
* @param {*} date - the date to check
* @returns {Boolean} the date is valid
* @throws {TypeError} 1 argument required
*
* @example
* // For the valid date:
* const result = isValid(new Date(2014, 1, 31))
* //=> true
*
* @example
* // For the value, convertable into a date:
* const result = isValid(1393804800000)
* //=> true
*
* @example
* // For the invalid date:
* const result = isValid(new Date(''))
* //=> false
*/
function isValid(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
return false;
}
var date = toDate_toDate(dirtyDate);
return !isNaN(Number(date));
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addMilliseconds/index.js
/**
* @name addMilliseconds
* @category Millisecond Helpers
* @summary Add the specified number of milliseconds to the given date.
*
* @description
* Add the specified number of milliseconds to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the milliseconds added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 750 milliseconds to 10 July 2014 12:45:30.000:
* const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:30.750
*/
function addMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var timestamp = toDate_toDate(dirtyDate).getTime();
var amount = toInteger_toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/subMilliseconds/index.js
/**
* @name subMilliseconds
* @category Millisecond Helpers
* @summary Subtract the specified number of milliseconds from the given date.
*
* @description
* Subtract the specified number of milliseconds from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the milliseconds subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
* const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:29.250
*/
function subMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var amount = toInteger_toInteger(dirtyAmount);
return addMilliseconds(dirtyDate, -amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js
var MILLISECONDS_IN_DAY = 86400000;
function getUTCDayOfYear(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var timestamp = date.getTime();
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
var startOfYearTimestamp = date.getTime();
var difference = timestamp - startOfYearTimestamp;
return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js
function startOfUTCISOWeek(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var weekStartsOn = 1;
var date = toDate_toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js
function getUTCISOWeekYear(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var year = date.getUTCFullYear();
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = new Date(0);
fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js
function startOfUTCISOWeekYear(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var year = getUTCISOWeekYear(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setUTCFullYear(year, 0, 4);
fourthOfJanuary.setUTCHours(0, 0, 0, 0);
var date = startOfUTCISOWeek(fourthOfJanuary);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js
var MILLISECONDS_IN_WEEK = 604800000;
function getUTCISOWeek(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
// Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/defaultOptions/index.js
var defaultOptions_defaultOptions = {};
function defaultOptions_getDefaultOptions() {
return defaultOptions_defaultOptions;
}
function setDefaultOptions(newOptions) {
defaultOptions_defaultOptions = newOptions;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js
function startOfUTCWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs_requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var weekStartsOn = toInteger_toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate_toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js
function getUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var year = date.getUTCFullYear();
var defaultOptions = defaultOptions_getDefaultOptions();
var firstWeekContainsDate = toInteger_toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
// Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var firstWeekOfNextYear = new Date(0);
firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
var firstWeekOfThisYear = new Date(0);
firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js
function startOfUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs_requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var firstWeekContainsDate = toInteger_toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
var year = getUTCWeekYear(dirtyDate, options);
var firstWeek = new Date(0);
firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeek.setUTCHours(0, 0, 0, 0);
var date = startOfUTCWeek(firstWeek, options);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCWeek/index.js
var getUTCWeek_MILLISECONDS_IN_WEEK = 604800000;
function getUTCWeek(dirtyDate, options) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
// Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / getUTCWeek_MILLISECONDS_IN_WEEK) + 1;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/addLeadingZeros/index.js
function addLeadingZeros(number, targetLength) {
var sign = number < 0 ? '-' : '';
var output = Math.abs(number).toString();
while (output.length < targetLength) {
output = '0' + output;
}
return sign + output;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/format/lightFormatters/index.js
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | |
* | d | Day of month | D | |
* | h | Hour [1-12] | H | Hour [0-23] |
* | m | Minute | M | Month |
* | s | Second | S | Fraction of second |
* | y | Year (abs) | Y | |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*/
var formatters = {
// Year
y: function y(date, token) {
// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
// | Year | y | yy | yyy | yyyy | yyyyy |
// |----------|-------|----|-------|-------|-------|
// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
var signedYear = date.getUTCFullYear();
// Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
},
// Month
M: function M(date, token) {
var month = date.getUTCMonth();
return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
},
// Day of the month
d: function d(date, token) {
return addLeadingZeros(date.getUTCDate(), token.length);
},
// AM or PM
a: function a(date, token) {
var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
return dayPeriodEnumValue.toUpperCase();
case 'aaa':
return dayPeriodEnumValue;
case 'aaaaa':
return dayPeriodEnumValue[0];
case 'aaaa':
default:
return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
}
},
// Hour [1-12]
h: function h(date, token) {
return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
},
// Hour [0-23]
H: function H(date, token) {
return addLeadingZeros(date.getUTCHours(), token.length);
},
// Minute
m: function m(date, token) {
return addLeadingZeros(date.getUTCMinutes(), token.length);
},
// Second
s: function s(date, token) {
return addLeadingZeros(date.getUTCSeconds(), token.length);
},
// Fraction of second
S: function S(date, token) {
var numberOfDigits = token.length;
var milliseconds = date.getUTCMilliseconds();
var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
return addLeadingZeros(fractionalSeconds, token.length);
}
};
/* harmony default export */ var lightFormatters = (formatters);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/format/formatters/index.js
var dayPeriodEnum = {
am: 'am',
pm: 'pm',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
};
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | Milliseconds in day |
* | b | AM, PM, noon, midnight | B | Flexible day period |
* | c | Stand-alone local day of week | C* | Localized hour w/ day period |
* | d | Day of month | D | Day of year |
* | e | Local day of week | E | Day of week |
* | f | | F* | Day of week in month |
* | g* | Modified Julian day | G | Era |
* | h | Hour [1-12] | H | Hour [0-23] |
* | i! | ISO day of week | I! | ISO week of year |
* | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
* | k | Hour [1-24] | K | Hour [0-11] |
* | l* | (deprecated) | L | Stand-alone month |
* | m | Minute | M | Month |
* | n | | N | |
* | o! | Ordinal number modifier | O | Timezone (GMT) |
* | p! | Long localized time | P! | Long localized date |
* | q | Stand-alone quarter | Q | Quarter |
* | r* | Related Gregorian year | R! | ISO week-numbering year |
* | s | Second | S | Fraction of second |
* | t! | Seconds timestamp | T! | Milliseconds timestamp |
* | u | Extended year | U* | Cyclic year |
* | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
* | w | Local week of year | W* | Week of month |
* | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
* | y | Year (abs) | Y | Local week-numbering year |
* | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*
* Letters marked by ! are non-standard, but implemented by date-fns:
* - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
* - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
* i.e. 7 for Sunday, 1 for Monday, etc.
* - `I` is ISO week of year, as opposed to `w` which is local week of year.
* - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
* `R` is supposed to be used in conjunction with `I` and `i`
* for universal ISO week-numbering date, whereas
* `Y` is supposed to be used in conjunction with `w` and `e`
* for week-numbering date specific to the locale.
* - `P` is long localized date format
* - `p` is long localized time format
*/
var formatters_formatters = {
// Era
G: function G(date, token, localize) {
var era = date.getUTCFullYear() > 0 ? 1 : 0;
switch (token) {
// AD, BC
case 'G':
case 'GG':
case 'GGG':
return localize.era(era, {
width: 'abbreviated'
});
// A, B
case 'GGGGG':
return localize.era(era, {
width: 'narrow'
});
// Anno Domini, Before Christ
case 'GGGG':
default:
return localize.era(era, {
width: 'wide'
});
}
},
// Year
y: function y(date, token, localize) {
// Ordinal number
if (token === 'yo') {
var signedYear = date.getUTCFullYear();
// Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize.ordinalNumber(year, {
unit: 'year'
});
}
return lightFormatters.y(date, token);
},
// Local week-numbering year
Y: function Y(date, token, localize, options) {
var signedWeekYear = getUTCWeekYear(date, options);
// Returns 1 for 1 BC (which is year 0 in JavaScript)
var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
// Two digit year
if (token === 'YY') {
var twoDigitYear = weekYear % 100;
return addLeadingZeros(twoDigitYear, 2);
}
// Ordinal number
if (token === 'Yo') {
return localize.ordinalNumber(weekYear, {
unit: 'year'
});
}
// Padding
return addLeadingZeros(weekYear, token.length);
},
// ISO week-numbering year
R: function R(date, token) {
var isoWeekYear = getUTCISOWeekYear(date);
// Padding
return addLeadingZeros(isoWeekYear, token.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function u(date, token) {
var year = date.getUTCFullYear();
return addLeadingZeros(year, token.length);
},
// Quarter
Q: function Q(date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'Q':
return String(quarter);
// 01, 02, 03, 04
case 'QQ':
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'Qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'QQQ':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'formatting'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'QQQQQ':
return localize.quarter(quarter, {
width: 'narrow',
context: 'formatting'
});
// 1st quarter, 2nd quarter, ...
case 'QQQQ':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone quarter
q: function q(date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'q':
return String(quarter);
// 01, 02, 03, 04
case 'qq':
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'qqq':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'standalone'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'qqqqq':
return localize.quarter(quarter, {
width: 'narrow',
context: 'standalone'
});
// 1st quarter, 2nd quarter, ...
case 'qqqq':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'standalone'
});
}
},
// Month
M: function M(date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
case 'M':
case 'MM':
return lightFormatters.M(date, token);
// 1st, 2nd, ..., 12th
case 'Mo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'MMM':
return localize.month(month, {
width: 'abbreviated',
context: 'formatting'
});
// J, F, ..., D
case 'MMMMM':
return localize.month(month, {
width: 'narrow',
context: 'formatting'
});
// January, February, ..., December
case 'MMMM':
default:
return localize.month(month, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone month
L: function L(date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
// 1, 2, ..., 12
case 'L':
return String(month + 1);
// 01, 02, ..., 12
case 'LL':
return addLeadingZeros(month + 1, 2);
// 1st, 2nd, ..., 12th
case 'Lo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'LLL':
return localize.month(month, {
width: 'abbreviated',
context: 'standalone'
});
// J, F, ..., D
case 'LLLLL':
return localize.month(month, {
width: 'narrow',
context: 'standalone'
});
// January, February, ..., December
case 'LLLL':
default:
return localize.month(month, {
width: 'wide',
context: 'standalone'
});
}
},
// Local week of year
w: function w(date, token, localize, options) {
var week = getUTCWeek(date, options);
if (token === 'wo') {
return localize.ordinalNumber(week, {
unit: 'week'
});
}
return addLeadingZeros(week, token.length);
},
// ISO week of year
I: function I(date, token, localize) {
var isoWeek = getUTCISOWeek(date);
if (token === 'Io') {
return localize.ordinalNumber(isoWeek, {
unit: 'week'
});
}
return addLeadingZeros(isoWeek, token.length);
},
// Day of the month
d: function d(date, token, localize) {
if (token === 'do') {
return localize.ordinalNumber(date.getUTCDate(), {
unit: 'date'
});
}
return lightFormatters.d(date, token);
},
// Day of year
D: function D(date, token, localize) {
var dayOfYear = getUTCDayOfYear(date);
if (token === 'Do') {
return localize.ordinalNumber(dayOfYear, {
unit: 'dayOfYear'
});
}
return addLeadingZeros(dayOfYear, token.length);
},
// Day of week
E: function E(date, token, localize) {
var dayOfWeek = date.getUTCDay();
switch (token) {
// Tue
case 'E':
case 'EE':
case 'EEE':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'EEEEE':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'EEEEEE':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'EEEE':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Local day of week
e: function e(date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (Nth day of week with current locale or weekStartsOn)
case 'e':
return String(localDayOfWeek);
// Padded numerical value
case 'ee':
return addLeadingZeros(localDayOfWeek, 2);
// 1st, 2nd, ..., 7th
case 'eo':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'eee':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'eeeee':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'eeeeee':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'eeee':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone local day of week
c: function c(date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (same as in `e`)
case 'c':
return String(localDayOfWeek);
// Padded numerical value
case 'cc':
return addLeadingZeros(localDayOfWeek, token.length);
// 1st, 2nd, ..., 7th
case 'co':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'ccc':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'standalone'
});
// T
case 'ccccc':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'standalone'
});
// Tu
case 'cccccc':
return localize.day(dayOfWeek, {
width: 'short',
context: 'standalone'
});
// Tuesday
case 'cccc':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'standalone'
});
}
},
// ISO day of week
i: function i(date, token, localize) {
var dayOfWeek = date.getUTCDay();
var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
// 2
case 'i':
return String(isoDayOfWeek);
// 02
case 'ii':
return addLeadingZeros(isoDayOfWeek, token.length);
// 2nd
case 'io':
return localize.ordinalNumber(isoDayOfWeek, {
unit: 'day'
});
// Tue
case 'iii':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'iiiii':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'iiiiii':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'iiii':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// AM or PM
a: function a(date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'aaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
}).toLowerCase();
case 'aaaaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'aaaa':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// AM, PM, midnight, noon
b: function b(date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
}
switch (token) {
case 'b':
case 'bb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'bbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
}).toLowerCase();
case 'bbbbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'bbbb':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function B(date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case 'B':
case 'BB':
case 'BBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'BBBBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'BBBB':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// Hour [1-12]
h: function h(date, token, localize) {
if (token === 'ho') {
var hours = date.getUTCHours() % 12;
if (hours === 0) hours = 12;
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return lightFormatters.h(date, token);
},
// Hour [0-23]
H: function H(date, token, localize) {
if (token === 'Ho') {
return localize.ordinalNumber(date.getUTCHours(), {
unit: 'hour'
});
}
return lightFormatters.H(date, token);
},
// Hour [0-11]
K: function K(date, token, localize) {
var hours = date.getUTCHours() % 12;
if (token === 'Ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return addLeadingZeros(hours, token.length);
},
// Hour [1-24]
k: function k(date, token, localize) {
var hours = date.getUTCHours();
if (hours === 0) hours = 24;
if (token === 'ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return addLeadingZeros(hours, token.length);
},
// Minute
m: function m(date, token, localize) {
if (token === 'mo') {
return localize.ordinalNumber(date.getUTCMinutes(), {
unit: 'minute'
});
}
return lightFormatters.m(date, token);
},
// Second
s: function s(date, token, localize) {
if (token === 'so') {
return localize.ordinalNumber(date.getUTCSeconds(), {
unit: 'second'
});
}
return lightFormatters.s(date, token);
},
// Fraction of second
S: function S(date, token) {
return lightFormatters.S(date, token);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function X(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
if (timezoneOffset === 0) {
return 'Z';
}
switch (token) {
// Hours and optional minutes
case 'X':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XX`
case 'XXXX':
case 'XX':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XXX`
case 'XXXXX':
case 'XXX': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function x(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Hours and optional minutes
case 'x':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xx`
case 'xxxx':
case 'xx':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xxx`
case 'xxxxx':
case 'xxx': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (GMT)
O: function O(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'O':
case 'OO':
case 'OOO':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'OOOO':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Timezone (specific non-location)
z: function z(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'z':
case 'zz':
case 'zzz':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'zzzz':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Seconds timestamp
t: function t(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = Math.floor(originalDate.getTime() / 1000);
return addLeadingZeros(timestamp, token.length);
},
// Milliseconds timestamp
T: function T(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = originalDate.getTime();
return addLeadingZeros(timestamp, token.length);
}
};
function formatTimezoneShort(offset, dirtyDelimiter) {
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = Math.floor(absOffset / 60);
var minutes = absOffset % 60;
if (minutes === 0) {
return sign + String(hours);
}
var delimiter = dirtyDelimiter || '';
return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
if (offset % 60 === 0) {
var sign = offset > 0 ? '-' : '+';
return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
var delimiter = dirtyDelimiter || '';
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
var minutes = addLeadingZeros(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
/* harmony default export */ var format_formatters = (formatters_formatters);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/format/longFormatters/index.js
var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'P':
return formatLong.date({
width: 'short'
});
case 'PP':
return formatLong.date({
width: 'medium'
});
case 'PPP':
return formatLong.date({
width: 'long'
});
case 'PPPP':
default:
return formatLong.date({
width: 'full'
});
}
};
var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'p':
return formatLong.time({
width: 'short'
});
case 'pp':
return formatLong.time({
width: 'medium'
});
case 'ppp':
return formatLong.time({
width: 'long'
});
case 'pppp':
default:
return formatLong.time({
width: 'full'
});
}
};
var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
var matchResult = pattern.match(/(P+)(p+)?/) || [];
var datePattern = matchResult[1];
var timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong);
}
var dateTimeFormat;
switch (datePattern) {
case 'P':
dateTimeFormat = formatLong.dateTime({
width: 'short'
});
break;
case 'PP':
dateTimeFormat = formatLong.dateTime({
width: 'medium'
});
break;
case 'PPP':
dateTimeFormat = formatLong.dateTime({
width: 'long'
});
break;
case 'PPPP':
default:
dateTimeFormat = formatLong.dateTime({
width: 'full'
});
break;
}
return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
};
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
/* harmony default export */ var format_longFormatters = (longFormatters);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
/**
* Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
* They usually appear for dates that denote time before the timezones were introduced
* (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
* and GMT+01:00:00 after that date)
*
* Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
* which would lead to incorrect calculations.
*
* This function returns the timezone offset in milliseconds that takes seconds in account.
*/
function getTimezoneOffsetInMilliseconds(date) {
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
utcDate.setUTCFullYear(date.getFullYear());
return date.getTime() - utcDate.getTime();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/protectedTokens/index.js
var protectedDayOfYearTokens = ['D', 'DD'];
var protectedWeekYearTokens = ['YY', 'YYYY'];
function isProtectedDayOfYearToken(token) {
return protectedDayOfYearTokens.indexOf(token) !== -1;
}
function isProtectedWeekYearToken(token) {
return protectedWeekYearTokens.indexOf(token) !== -1;
}
function throwProtectedError(token, format, input) {
if (token === 'YYYY') {
throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === 'YY') {
throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === 'D') {
throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === 'DD') {
throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js
var formatDistanceLocale = {
lessThanXSeconds: {
one: 'less than a second',
other: 'less than {{count}} seconds'
},
xSeconds: {
one: '1 second',
other: '{{count}} seconds'
},
halfAMinute: 'half a minute',
lessThanXMinutes: {
one: 'less than a minute',
other: 'less than {{count}} minutes'
},
xMinutes: {
one: '1 minute',
other: '{{count}} minutes'
},
aboutXHours: {
one: 'about 1 hour',
other: 'about {{count}} hours'
},
xHours: {
one: '1 hour',
other: '{{count}} hours'
},
xDays: {
one: '1 day',
other: '{{count}} days'
},
aboutXWeeks: {
one: 'about 1 week',
other: 'about {{count}} weeks'
},
xWeeks: {
one: '1 week',
other: '{{count}} weeks'
},
aboutXMonths: {
one: 'about 1 month',
other: 'about {{count}} months'
},
xMonths: {
one: '1 month',
other: '{{count}} months'
},
aboutXYears: {
one: 'about 1 year',
other: 'about {{count}} years'
},
xYears: {
one: '1 year',
other: '{{count}} years'
},
overXYears: {
one: 'over 1 year',
other: 'over {{count}} years'
},
almostXYears: {
one: 'almost 1 year',
other: 'almost {{count}} years'
}
};
var formatDistance = function formatDistance(token, count, options) {
var result;
var tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === 'string') {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace('{{count}}', count.toString());
}
if (options !== null && options !== void 0 && options.addSuffix) {
if (options.comparison && options.comparison > 0) {
return 'in ' + result;
} else {
return result + ' ago';
}
}
return result;
};
/* harmony default export */ var _lib_formatDistance = (formatDistance);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js
function buildFormatLongFn(args) {
return function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// TODO: Remove String()
var width = options.width ? String(options.width) : args.defaultWidth;
var format = args.formats[width] || args.formats[args.defaultWidth];
return format;
};
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js
var dateFormats = {
full: 'EEEE, MMMM do, y',
long: 'MMMM do, y',
medium: 'MMM d, y',
short: 'MM/dd/yyyy'
};
var timeFormats = {
full: 'h:mm:ss a zzzz',
long: 'h:mm:ss a z',
medium: 'h:mm:ss a',
short: 'h:mm a'
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: '{{date}}, {{time}}',
short: '{{date}}, {{time}}'
};
var formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: 'full'
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: 'full'
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: 'full'
})
};
/* harmony default export */ var _lib_formatLong = (formatLong);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: 'P'
};
var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
return formatRelativeLocale[token];
};
/* harmony default export */ var _lib_formatRelative = (formatRelative);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js
function buildLocalizeFn(args) {
return function (dirtyIndex, options) {
var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
var valuesArray;
if (context === 'formatting' && args.formattingValues) {
var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
var _defaultWidth = args.defaultWidth;
var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[_width] || args.values[_defaultWidth];
}
var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
// @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
return valuesArray[index];
};
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js
var eraValues = {
narrow: ['B', 'A'],
abbreviated: ['BC', 'AD'],
wide: ['Before Christ', 'Anno Domini']
};
var quarterValues = {
narrow: ['1', '2', '3', '4'],
abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
};
// Note: in English, the names of days of the week and months are capitalized.
// If you are making a new locale based on this one, check if the same is true for the language you're working on.
// Generally, formatted dates should look like they are in the middle of a sentence,
// e.g. in Spanish language the weekdays and months should be in the lowercase.
var monthValues = {
narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
};
var dayValues = {
narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
};
var dayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
}
};
var formattingDayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
}
};
var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
var number = Number(dirtyNumber);
// If ordinal numbers depend on context, for example,
// if they are different for different grammatical genders,
// use `options.unit`.
//
// `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
// 'day', 'hour', 'minute', 'second'.
var rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + 'st';
case 2:
return number + 'nd';
case 3:
return number + 'rd';
}
}
return number + 'th';
};
var localize = {
ordinalNumber: ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: 'wide'
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: 'wide',
argumentCallback: function argumentCallback(quarter) {
return quarter - 1;
}
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: 'wide'
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: 'wide'
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: 'wide',
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: 'wide'
})
};
/* harmony default export */ var _lib_localize = (localize);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js
function buildMatchFn(args) {
return function (string) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var width = options.width;
var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
var matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
return pattern.test(matchedString);
}) : findKey(parsePatterns, function (pattern) {
return pattern.test(matchedString);
});
var value;
value = args.valueCallback ? args.valueCallback(key) : key;
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value: value,
rest: rest
};
};
}
function findKey(object, predicate) {
for (var key in object) {
if (object.hasOwnProperty(key) && predicate(object[key])) {
return key;
}
}
return undefined;
}
function findIndex(array, predicate) {
for (var key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
return undefined;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js
function buildMatchPatternFn(args) {
return function (string) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var matchResult = string.match(args.matchPattern);
if (!matchResult) return null;
var matchedString = matchResult[0];
var parseResult = string.match(args.parsePattern);
if (!parseResult) return null;
var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value: value,
rest: rest
};
};
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/match/index.js
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match_match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: function valueCallback(value) {
return parseInt(value, 10);
}
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseEraPatterns,
defaultParseWidth: 'any'
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseQuarterPatterns,
defaultParseWidth: 'any',
valueCallback: function valueCallback(index) {
return index + 1;
}
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseMonthPatterns,
defaultParseWidth: 'any'
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseDayPatterns,
defaultParseWidth: 'any'
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: 'any',
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: 'any'
})
};
/* harmony default export */ var _lib_match = (match_match);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/index.js
/**
* @type {Locale}
* @category Locales
* @summary English locale (United States).
* @language English
* @iso-639-2 eng
* @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
* @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
*/
var locale = {
code: 'en-US',
formatDistance: _lib_formatDistance,
formatLong: _lib_formatLong,
formatRelative: _lib_formatRelative,
localize: _lib_localize,
match: _lib_match,
options: {
weekStartsOn: 0 /* Sunday */,
firstWeekContainsDate: 1
}
};
/* harmony default export */ var en_US = (locale);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/defaultLocale/index.js
/* harmony default export */ var defaultLocale = (en_US);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/format/index.js
// This RegExp consists of three parts separated by `|`:
// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
// (one of the certain letters followed by `o`)
// - (\w)\1* matches any sequences of the same letter
// - '' matches two quote characters in a row
// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
// except a single quote symbol, which ends the sequence.
// Two quote characters do not end the sequence.
// If there is no matching single quote
// then the sequence will continue until the end of the string.
// - . matches any single character unmatched by previous parts of the RegExps
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
// This RegExp catches symbols escaped by quotes, and also
// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
/**
* @name format
* @category Common Helpers
* @summary Format the date.
*
* @description
* Return the formatted date string in the given format. The result may vary by locale.
*
* > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
* > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
*
* The characters wrapped between two single quotes characters (') are escaped.
* Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
* (see the last example)
*
* Format of the string is based on Unicode Technical Standard #35:
* https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
* with a few additions (see note 7 below the table).
*
* Accepted patterns:
* | Unit | Pattern | Result examples | Notes |
* |---------------------------------|---------|-----------------------------------|-------|
* | Era | G..GGG | AD, BC | |
* | | GGGG | Anno Domini, Before Christ | 2 |
* | | GGGGG | A, B | |
* | Calendar year | y | 44, 1, 1900, 2017 | 5 |
* | | yo | 44th, 1st, 0th, 17th | 5,7 |
* | | yy | 44, 01, 00, 17 | 5 |
* | | yyy | 044, 001, 1900, 2017 | 5 |
* | | yyyy | 0044, 0001, 1900, 2017 | 5 |
* | | yyyyy | ... | 3,5 |
* | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
* | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
* | | YY | 44, 01, 00, 17 | 5,8 |
* | | YYY | 044, 001, 1900, 2017 | 5 |
* | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
* | | YYYYY | ... | 3,5 |
* | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
* | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
* | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
* | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
* | | RRRRR | ... | 3,5,7 |
* | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
* | | uu | -43, 01, 1900, 2017 | 5 |
* | | uuu | -043, 001, 1900, 2017 | 5 |
* | | uuuu | -0043, 0001, 1900, 2017 | 5 |
* | | uuuuu | ... | 3,5 |
* | Quarter (formatting) | Q | 1, 2, 3, 4 | |
* | | Qo | 1st, 2nd, 3rd, 4th | 7 |
* | | QQ | 01, 02, 03, 04 | |
* | | QQQ | Q1, Q2, Q3, Q4 | |
* | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
* | | QQQQQ | 1, 2, 3, 4 | 4 |
* | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
* | | qo | 1st, 2nd, 3rd, 4th | 7 |
* | | qq | 01, 02, 03, 04 | |
* | | qqq | Q1, Q2, Q3, Q4 | |
* | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
* | | qqqqq | 1, 2, 3, 4 | 4 |
* | Month (formatting) | M | 1, 2, ..., 12 | |
* | | Mo | 1st, 2nd, ..., 12th | 7 |
* | | MM | 01, 02, ..., 12 | |
* | | MMM | Jan, Feb, ..., Dec | |
* | | MMMM | January, February, ..., December | 2 |
* | | MMMMM | J, F, ..., D | |
* | Month (stand-alone) | L | 1, 2, ..., 12 | |
* | | Lo | 1st, 2nd, ..., 12th | 7 |
* | | LL | 01, 02, ..., 12 | |
* | | LLL | Jan, Feb, ..., Dec | |
* | | LLLL | January, February, ..., December | 2 |
* | | LLLLL | J, F, ..., D | |
* | Local week of year | w | 1, 2, ..., 53 | |
* | | wo | 1st, 2nd, ..., 53th | 7 |
* | | ww | 01, 02, ..., 53 | |
* | ISO week of year | I | 1, 2, ..., 53 | 7 |
* | | Io | 1st, 2nd, ..., 53th | 7 |
* | | II | 01, 02, ..., 53 | 7 |
* | Day of month | d | 1, 2, ..., 31 | |
* | | do | 1st, 2nd, ..., 31st | 7 |
* | | dd | 01, 02, ..., 31 | |
* | Day of year | D | 1, 2, ..., 365, 366 | 9 |
* | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
* | | DD | 01, 02, ..., 365, 366 | 9 |
* | | DDD | 001, 002, ..., 365, 366 | |
* | | DDDD | ... | 3 |
* | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
* | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
* | | EEEEE | M, T, W, T, F, S, S | |
* | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
* | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
* | | io | 1st, 2nd, ..., 7th | 7 |
* | | ii | 01, 02, ..., 07 | 7 |
* | | iii | Mon, Tue, Wed, ..., Sun | 7 |
* | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
* | | iiiii | M, T, W, T, F, S, S | 7 |
* | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
* | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
* | | eo | 2nd, 3rd, ..., 1st | 7 |
* | | ee | 02, 03, ..., 01 | |
* | | eee | Mon, Tue, Wed, ..., Sun | |
* | | eeee | Monday, Tuesday, ..., Sunday | 2 |
* | | eeeee | M, T, W, T, F, S, S | |
* | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
* | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
* | | co | 2nd, 3rd, ..., 1st | 7 |
* | | cc | 02, 03, ..., 01 | |
* | | ccc | Mon, Tue, Wed, ..., Sun | |
* | | cccc | Monday, Tuesday, ..., Sunday | 2 |
* | | ccccc | M, T, W, T, F, S, S | |
* | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
* | AM, PM | a..aa | AM, PM | |
* | | aaa | am, pm | |
* | | aaaa | a.m., p.m. | 2 |
* | | aaaaa | a, p | |
* | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
* | | bbb | am, pm, noon, midnight | |
* | | bbbb | a.m., p.m., noon, midnight | 2 |
* | | bbbbb | a, p, n, mi | |
* | Flexible day period | B..BBB | at night, in the morning, ... | |
* | | BBBB | at night, in the morning, ... | 2 |
* | | BBBBB | at night, in the morning, ... | |
* | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
* | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
* | | hh | 01, 02, ..., 11, 12 | |
* | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
* | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
* | | HH | 00, 01, 02, ..., 23 | |
* | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
* | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
* | | KK | 01, 02, ..., 11, 00 | |
* | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
* | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
* | | kk | 24, 01, 02, ..., 23 | |
* | Minute | m | 0, 1, ..., 59 | |
* | | mo | 0th, 1st, ..., 59th | 7 |
* | | mm | 00, 01, ..., 59 | |
* | Second | s | 0, 1, ..., 59 | |
* | | so | 0th, 1st, ..., 59th | 7 |
* | | ss | 00, 01, ..., 59 | |
* | Fraction of second | S | 0, 1, ..., 9 | |
* | | SS | 00, 01, ..., 99 | |
* | | SSS | 000, 001, ..., 999 | |
* | | SSSS | ... | 3 |
* | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
* | | XX | -0800, +0530, Z | |
* | | XXX | -08:00, +05:30, Z | |
* | | XXXX | -0800, +0530, Z, +123456 | 2 |
* | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
* | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
* | | xx | -0800, +0530, +0000 | |
* | | xxx | -08:00, +05:30, +00:00 | 2 |
* | | xxxx | -0800, +0530, +0000, +123456 | |
* | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
* | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
* | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
* | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
* | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
* | Seconds timestamp | t | 512969520 | 7 |
* | | tt | ... | 3,7 |
* | Milliseconds timestamp | T | 512969520900 | 7 |
* | | TT | ... | 3,7 |
* | Long localized date | P | 04/29/1453 | 7 |
* | | PP | Apr 29, 1453 | 7 |
* | | PPP | April 29th, 1453 | 7 |
* | | PPPP | Friday, April 29th, 1453 | 2,7 |
* | Long localized time | p | 12:00 AM | 7 |
* | | pp | 12:00:00 AM | 7 |
* | | ppp | 12:00:00 AM GMT+2 | 7 |
* | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
* | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
* | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
* | | PPPppp | April 29th, 1453 at ... | 7 |
* | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
* Notes:
* 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
* are the same as "stand-alone" units, but are different in some languages.
* "Formatting" units are declined according to the rules of the language
* in the context of a date. "Stand-alone" units are always nominative singular:
*
* `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
*
* `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
*
* 2. Any sequence of the identical letters is a pattern, unless it is escaped by
* the single quote characters (see below).
* If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
* the output will be the same as default pattern for this unit, usually
* the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
* are marked with "2" in the last column of the table.
*
* `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
*
* `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
*
* `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
*
* 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
* The output will be padded with zeros to match the length of the pattern.
*
* `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
*
* 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
* These tokens represent the shortest form of the quarter.
*
* 5. The main difference between `y` and `u` patterns are B.C. years:
*
* | Year | `y` | `u` |
* |------|-----|-----|
* | AC 1 | 1 | 1 |
* | BC 1 | 1 | 0 |
* | BC 2 | 2 | -1 |
*
* Also `yy` always returns the last two digits of a year,
* while `uu` pads single digit years to 2 characters and returns other years unchanged:
*
* | Year | `yy` | `uu` |
* |------|------|------|
* | 1 | 01 | 01 |
* | 14 | 14 | 14 |
* | 376 | 76 | 376 |
* | 1453 | 53 | 1453 |
*
* The same difference is true for local and ISO week-numbering years (`Y` and `R`),
* except local week-numbering years are dependent on `options.weekStartsOn`
* and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
* and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
*
* 6. Specific non-location timezones are currently unavailable in `date-fns`,
* so right now these tokens fall back to GMT timezones.
*
* 7. These patterns are not in the Unicode Technical Standard #35:
* - `i`: ISO day of week
* - `I`: ISO week of year
* - `R`: ISO week-numbering year
* - `t`: seconds timestamp
* - `T`: milliseconds timestamp
* - `o`: ordinal number modifier
* - `P`: long localized date
* - `p`: long localized time
*
* 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
* You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
*
* 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
* You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
*
* @param {Date|Number} date - the original date
* @param {String} format - the string of tokens
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
* @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
* see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
* see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @returns {String} the formatted date string
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `date` must not be Invalid Date
* @throws {RangeError} `options.locale` must contain `localize` property
* @throws {RangeError} `options.locale` must contain `formatLong` property
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
* @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} format string contains an unescaped latin alphabet character
*
* @example
* // Represent 11 February 2014 in middle-endian format:
* const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
* //=> '02/11/2014'
*
* @example
* // Represent 2 July 2014 in Esperanto:
* import { eoLocale } from 'date-fns/locale/eo'
* const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
* locale: eoLocale
* })
* //=> '2-a de julio 2014'
*
* @example
* // Escape string by single quote characters:
* const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
* //=> "3 o'clock"
*/
function format(dirtyDate, dirtyFormatStr, options) {
var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
requiredArgs_requiredArgs(2, arguments);
var formatStr = String(dirtyFormatStr);
var defaultOptions = defaultOptions_getDefaultOptions();
var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale;
var firstWeekContainsDate = toInteger_toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
// Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var weekStartsOn = toInteger_toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
if (!locale.localize) {
throw new RangeError('locale must contain localize property');
}
if (!locale.formatLong) {
throw new RangeError('locale must contain formatLong property');
}
var originalDate = toDate_toDate(dirtyDate);
if (!isValid(originalDate)) {
throw new RangeError('Invalid time value');
}
// Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
// See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
var utcDate = subMilliseconds(originalDate, timezoneOffset);
var formatterOptions = {
firstWeekContainsDate: firstWeekContainsDate,
weekStartsOn: weekStartsOn,
locale: locale,
_originalDate: originalDate
};
var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
var firstCharacter = substring[0];
if (firstCharacter === 'p' || firstCharacter === 'P') {
var longFormatter = format_longFormatters[firstCharacter];
return longFormatter(substring, locale.formatLong);
}
return substring;
}).join('').match(formattingTokensRegExp).map(function (substring) {
// Replace two single quote characters with one single quote character
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = format_formatters[firstCharacter];
if (formatter) {
if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
return formatter(utcDate, substring, locale.localize, formatterOptions);
}
if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
}
return substring;
}).join('');
return result;
}
function cleanEscapedString(input) {
var matched = input.match(escapedStringRegExp);
if (!matched) {
return input;
}
return matched[1].replace(doubleQuoteRegExp, "'");
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isSameMonth/index.js
/**
* @name isSameMonth
* @category Month Helpers
* @summary Are the given dates in the same month (and year)?
*
* @description
* Are the given dates in the same month (and year)?
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same month (and year)
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 September 2014 and 25 September 2014 in the same month?
* const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))
* //=> true
*
* @example
* // Are 2 September 2014 and 25 September 2015 in the same month?
* const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))
* //=> false
*/
function isSameMonth(dirtyDateLeft, dirtyDateRight) {
requiredArgs_requiredArgs(2, arguments);
var dateLeft = toDate_toDate(dirtyDateLeft);
var dateRight = toDate_toDate(dirtyDateRight);
return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isEqual/index.js
/**
* @name isEqual
* @category Common Helpers
* @summary Are the given dates equal?
*
* @description
* Are the given dates equal?
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Boolean} the dates are equal
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?
* const result = isEqual(
* new Date(2014, 6, 2, 6, 30, 45, 0),
* new Date(2014, 6, 2, 6, 30, 45, 500)
* )
* //=> false
*/
function isEqual_isEqual(dirtyLeftDate, dirtyRightDate) {
requiredArgs_requiredArgs(2, arguments);
var dateLeft = toDate_toDate(dirtyLeftDate);
var dateRight = toDate_toDate(dirtyRightDate);
return dateLeft.getTime() === dateRight.getTime();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isSameDay/index.js
/**
* @name isSameDay
* @category Day Helpers
* @summary Are the given dates in the same day (and year and month)?
*
* @description
* Are the given dates in the same day (and year and month)?
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same day (and year and month)
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?
* const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))
* //=> true
*
* @example
* // Are 4 September and 4 October in the same day?
* const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))
* //=> false
*
* @example
* // Are 4 September, 2014 and 4 September, 2015 in the same day?
* const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))
* //=> false
*/
function isSameDay(dirtyDateLeft, dirtyDateRight) {
requiredArgs_requiredArgs(2, arguments);
var dateLeftStartOfDay = startOfDay_startOfDay(dirtyDateLeft);
var dateRightStartOfDay = startOfDay_startOfDay(dirtyDateRight);
return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addDays/index.js
/**
* @name addDays
* @category Day Helpers
* @summary Add the specified number of days to the given date.
*
* @description
* Add the specified number of days to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} - the new date with the days added
* @throws {TypeError} - 2 arguments required
*
* @example
* // Add 10 days to 1 September 2014:
* const result = addDays(new Date(2014, 8, 1), 10)
* //=> Thu Sep 11 2014 00:00:00
*/
function addDays_addDays(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var amount = toInteger_toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 days, no-op to avoid changing times in the hour before end of DST
return date;
}
date.setDate(date.getDate() + amount);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addWeeks/index.js
/**
* @name addWeeks
* @category Week Helpers
* @summary Add the specified number of weeks to the given date.
*
* @description
* Add the specified number of week to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 4 weeks to 1 September 2014:
* const result = addWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Sep 29 2014 00:00:00
*/
function addWeeks_addWeeks(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var amount = toInteger_toInteger(dirtyAmount);
var days = amount * 7;
return addDays_addDays(dirtyDate, days);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/subWeeks/index.js
/**
* @name subWeeks
* @category Week Helpers
* @summary Subtract the specified number of weeks from the given date.
*
* @description
* Subtract the specified number of weeks from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 4 weeks from 1 September 2014:
* const result = subWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Aug 04 2014 00:00:00
*/
function subWeeks(dirtyDate, dirtyAmount) {
requiredArgs_requiredArgs(2, arguments);
var amount = toInteger_toInteger(dirtyAmount);
return addWeeks_addWeeks(dirtyDate, -amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfWeek/index.js
/**
* @name startOfWeek
* @category Week Helpers
* @summary Return the start of a week for the given date.
*
* @description
* Return the start of a week for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date} the start of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The start of a week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Aug 31 2014 00:00:00
*
* @example
* // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfWeek_startOfWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs_requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var weekStartsOn = toInteger_toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate_toDate(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setDate(date.getDate() - diff);
date.setHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/endOfWeek/index.js
/**
* @name endOfWeek
* @category Week Helpers
* @summary Return the end of a week for the given date.
*
* @description
* Return the end of a week for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date} the end of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The end of a week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sat Sep 06 2014 23:59:59.999
*
* @example
* // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 23:59:59.999
*/
function endOfWeek_endOfWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs_requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var weekStartsOn = toInteger_toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate_toDate(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
date.setDate(date.getDate() + diff);
date.setHours(23, 59, 59, 999);
return date;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-right.js
/**
* WordPress dependencies
*/
const arrowRight = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "m14.5 6.5-1 1 3.7 3.7H4v1.6h13.2l-3.7 3.7 1 1 5.6-5.5z"
}));
/* harmony default export */ var arrow_right = (arrowRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-left.js
/**
* WordPress dependencies
*/
const arrowLeft = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z"
}));
/* harmony default export */ var arrow_left = (arrowLeft);
;// CONCATENATED MODULE: external ["wp","date"]
var external_wp_date_namespaceObject = window["wp"]["date"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date/styles.js
function date_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const styles_Wrapper = createStyled("div", true ? {
target: "e105ri6r5"
} : 0)( true ? {
name: "1khn195",
styles: "box-sizing:border-box"
} : 0);
const Navigator = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "e105ri6r4"
} : 0)("margin-bottom:", space(4), ";" + ( true ? "" : 0));
const NavigatorHeading = /*#__PURE__*/createStyled(heading_component, true ? {
target: "e105ri6r3"
} : 0)("font-size:", config_values.fontSize, ";font-weight:", config_values.fontWeight, ";strong{font-weight:", config_values.fontWeightHeading, ";}" + ( true ? "" : 0));
const Calendar = createStyled("div", true ? {
target: "e105ri6r2"
} : 0)("column-gap:", space(2), ";display:grid;grid-template-columns:0.5fr repeat( 5, 1fr ) 0.5fr;justify-items:center;row-gap:", space(2), ";" + ( true ? "" : 0));
const DayOfWeek = createStyled("div", true ? {
target: "e105ri6r1"
} : 0)("color:", COLORS.gray[700], ";font-size:", config_values.fontSize, ";line-height:", config_values.fontLineHeightBase, ";&:nth-of-type( 1 ){justify-self:start;}&:nth-of-type( 7 ){justify-self:end;}" + ( true ? "" : 0));
const DayButton = /*#__PURE__*/createStyled(build_module_button, true ? {
shouldForwardProp: prop => !['column', 'isSelected', 'isToday', 'hasEvents'].includes(prop),
target: "e105ri6r0"
} : 0)("grid-column:", props => props.column, ";position:relative;justify-content:center;", props => props.column === 1 && `
justify-self: start;
`, " ", props => props.column === 7 && `
justify-self: end;
`, " ", props => props.disabled && `
pointer-events: none;
`, " &&&{border-radius:100%;height:", space(7), ";width:", space(7), ";", props => props.isSelected && `
background: ${COLORS.ui.theme};
color: ${COLORS.white};
`, " ", props => !props.isSelected && props.isToday && `
background: ${COLORS.gray[200]};
`, ";}", props => props.hasEvents && `
::before {
background: ${props.isSelected ? COLORS.white : COLORS.ui.theme};
border-radius: 2px;
bottom: 0;
content: " ";
height: 4px;
left: 50%;
margin-left: -2px;
position: absolute;
width: 4px;
}
`, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/utils.js
/**
* External dependencies
*/
/**
* Like date-fn's toDate, but tries to guess the format when a string is
* given.
*
* @param input Value to turn into a date.
*/
function inputToDate(input) {
if (typeof input === 'string') {
return new Date(input);
}
return toDate_toDate(input);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/constants.js
const TIMEZONELESS_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* DatePicker is a React component that renders a calendar for date selection.
*
* ```jsx
* import { DatePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDatePicker = () => {
* const [ date, setDate ] = useState( new Date() );
*
* return (
* <DatePicker
* currentDate={ date }
* onChange={ ( newDate ) => setDate( newDate ) }
* />
* );
* };
* ```
*/
function DatePicker({
currentDate,
onChange,
events = [],
isInvalidDate,
onMonthPreviewed,
startOfWeek: weekStartsOn = 0
}) {
const date = currentDate ? inputToDate(currentDate) : new Date();
const {
calendar,
viewing,
setSelected,
setViewing,
isSelected,
viewPreviousMonth,
viewNextMonth
} = useLilius({
selected: [startOfDay_startOfDay(date)],
viewing: startOfDay_startOfDay(date),
weekStartsOn
}); // Used to implement a roving tab index. Tracks the day that receives focus
// when the user tabs into the calendar.
const [focusable, setFocusable] = (0,external_wp_element_namespaceObject.useState)(startOfDay_startOfDay(date)); // Allows us to only programmatically focus() a day when focus was already
// within the calendar. This stops us stealing focus from e.g. a TimePicker
// input.
const [isFocusWithinCalendar, setIsFocusWithinCalendar] = (0,external_wp_element_namespaceObject.useState)(false); // Update internal state when currentDate prop changes.
const [prevCurrentDate, setPrevCurrentDate] = (0,external_wp_element_namespaceObject.useState)(currentDate);
if (currentDate !== prevCurrentDate) {
setPrevCurrentDate(currentDate);
setSelected([startOfDay_startOfDay(date)]);
setViewing(startOfDay_startOfDay(date));
setFocusable(startOfDay_startOfDay(date));
}
return (0,external_wp_element_namespaceObject.createElement)(styles_Wrapper, {
className: "components-datetime__date",
role: "application",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Calendar')
}, (0,external_wp_element_namespaceObject.createElement)(Navigator, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? arrow_right : arrow_left,
variant: "tertiary",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('View previous month'),
onClick: () => {
viewPreviousMonth();
setFocusable(subMonths_subMonths(focusable, 1));
onMonthPreviewed?.(format(subMonths_subMonths(viewing, 1), TIMEZONELESS_FORMAT));
}
}), (0,external_wp_element_namespaceObject.createElement)(NavigatorHeading, {
level: 3
}, (0,external_wp_element_namespaceObject.createElement)("strong", null, (0,external_wp_date_namespaceObject.dateI18n)('F', viewing, -viewing.getTimezoneOffset())), ' ', (0,external_wp_date_namespaceObject.dateI18n)('Y', viewing, -viewing.getTimezoneOffset())), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? arrow_left : arrow_right,
variant: "tertiary",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('View next month'),
onClick: () => {
viewNextMonth();
setFocusable(addMonths_addMonths(focusable, 1));
onMonthPreviewed?.(format(addMonths_addMonths(viewing, 1), TIMEZONELESS_FORMAT));
}
})), (0,external_wp_element_namespaceObject.createElement)(Calendar, {
onFocus: () => setIsFocusWithinCalendar(true),
onBlur: () => setIsFocusWithinCalendar(false)
}, calendar[0][0].map(day => (0,external_wp_element_namespaceObject.createElement)(DayOfWeek, {
key: day.toString()
}, (0,external_wp_date_namespaceObject.dateI18n)('D', day, -day.getTimezoneOffset()))), calendar[0].map(week => week.map((day, index) => {
if (!isSameMonth(day, viewing)) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(date_Day, {
key: day.toString(),
day: day,
column: index + 1,
isSelected: isSelected(day),
isFocusable: isEqual_isEqual(day, focusable),
isFocusAllowed: isFocusWithinCalendar,
isToday: isSameDay(day, new Date()),
isInvalid: isInvalidDate ? isInvalidDate(day) : false,
numEvents: events.filter(event => isSameDay(event.date, day)).length,
onClick: () => {
setSelected([day]);
setFocusable(day);
onChange?.(format( // Don't change the selected date's time fields.
new Date(day.getFullYear(), day.getMonth(), day.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()), TIMEZONELESS_FORMAT));
},
onKeyDown: event => {
let nextFocusable;
if (event.key === 'ArrowLeft') {
nextFocusable = addDays_addDays(day, (0,external_wp_i18n_namespaceObject.isRTL)() ? 1 : -1);
}
if (event.key === 'ArrowRight') {
nextFocusable = addDays_addDays(day, (0,external_wp_i18n_namespaceObject.isRTL)() ? -1 : 1);
}
if (event.key === 'ArrowUp') {
nextFocusable = subWeeks(day, 1);
}
if (event.key === 'ArrowDown') {
nextFocusable = addWeeks_addWeeks(day, 1);
}
if (event.key === 'PageUp') {
nextFocusable = subMonths_subMonths(day, 1);
}
if (event.key === 'PageDown') {
nextFocusable = addMonths_addMonths(day, 1);
}
if (event.key === 'Home') {
nextFocusable = startOfWeek_startOfWeek(day);
}
if (event.key === 'End') {
nextFocusable = startOfDay_startOfDay(endOfWeek_endOfWeek(day));
}
if (nextFocusable) {
event.preventDefault();
setFocusable(nextFocusable);
if (!isSameMonth(nextFocusable, viewing)) {
setViewing(nextFocusable);
onMonthPreviewed?.(format(nextFocusable, TIMEZONELESS_FORMAT));
}
}
}
});
}))));
}
function date_Day({
day,
column,
isSelected,
isFocusable,
isFocusAllowed,
isToday,
isInvalid,
numEvents,
onClick,
onKeyDown
}) {
const ref = (0,external_wp_element_namespaceObject.useRef)(); // Focus the day when it becomes focusable, e.g. because an arrow key is
// pressed. Only do this if focus is allowed - this stops us stealing focus
// from e.g. a TimePicker input.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (ref.current && isFocusable && isFocusAllowed) {
ref.current.focus();
} // isFocusAllowed is not a dep as there is no point calling focus() on
// an already focused element.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isFocusable]);
return (0,external_wp_element_namespaceObject.createElement)(DayButton, {
ref: ref,
className: "components-datetime__date__day" // Unused, for backwards compatibility.
,
disabled: isInvalid,
tabIndex: isFocusable ? 0 : -1,
"aria-label": getDayLabel(day, isSelected, numEvents),
column: column,
isSelected: isSelected,
isToday: isToday,
hasEvents: numEvents > 0,
onClick: onClick,
onKeyDown: onKeyDown
}, (0,external_wp_date_namespaceObject.dateI18n)('j', day, -day.getTimezoneOffset()));
}
function getDayLabel(date, isSelected, numEvents) {
const {
formats
} = (0,external_wp_date_namespaceObject.getSettings)();
const localizedDate = (0,external_wp_date_namespaceObject.dateI18n)(formats.date, date, -date.getTimezoneOffset());
if (isSelected && numEvents > 0) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: The calendar date. 2: Number of events on the calendar date.
(0,external_wp_i18n_namespaceObject._n)('%1$s. Selected. There is %2$d event', '%1$s. Selected. There are %2$d events', numEvents), localizedDate, numEvents);
} else if (isSelected) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The calendar date.
(0,external_wp_i18n_namespaceObject.__)('%1$s. Selected'), localizedDate);
} else if (numEvents > 0) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: The calendar date. 2: Number of events on the calendar date.
(0,external_wp_i18n_namespaceObject._n)('%1$s. There is %2$d event', '%1$s. There are %2$d events', numEvents), localizedDate, numEvents);
}
return localizedDate;
}
/* harmony default export */ var date = (DatePicker);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfMinute/index.js
/**
* @name startOfMinute
* @category Minute Helpers
* @summary Return the start of a minute for the given date.
*
* @description
* Return the start of a minute for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a minute
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a minute for 1 December 2014 22:15:45.400:
* const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:00
*/
function startOfMinute(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
date.setSeconds(0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/getDaysInMonth/index.js
/**
* @name getDaysInMonth
* @category Month Helpers
* @summary Get the number of days in a month of the given date.
*
* @description
* Get the number of days in a month of the given date.
*
* @param {Date|Number} date - the given date
* @returns {Number} the number of days in a month
* @throws {TypeError} 1 argument required
*
* @example
* // How many days are in February 2000?
* const result = getDaysInMonth(new Date(2000, 1))
* //=> 29
*/
function getDaysInMonth_getDaysInMonth(dirtyDate) {
requiredArgs_requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var year = date.getFullYear();
var monthIndex = date.getMonth();
var lastDayOfMonth = new Date(0);
lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
lastDayOfMonth.setHours(0, 0, 0, 0);
return lastDayOfMonth.getDate();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/setMonth/index.js
/**
* @name setMonth
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} month - the month of the new date
* @returns {Date} the new date with the month set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set February to 1 September 2014:
* const result = setMonth(new Date(2014, 8, 1), 1)
* //=> Sat Feb 01 2014 00:00:00
*/
function setMonth_setMonth(dirtyDate, dirtyMonth) {
requiredArgs_requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var month = toInteger_toInteger(dirtyMonth);
var year = date.getFullYear();
var day = date.getDate();
var dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setFullYear(year, month, 15);
dateWithDesiredMonth.setHours(0, 0, 0, 0);
var daysInMonth = getDaysInMonth_getDaysInMonth(dateWithDesiredMonth);
// Set the last day of the new month
// if the original date was the last day of the longer month
date.setMonth(month, Math.min(day, daysInMonth));
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/set/index.js
/**
* @name set
* @category Common Helpers
* @summary Set date values to a given date.
*
* @description
* Set date values to a given date.
*
* Sets time values to date from object `values`.
* A value is not set if it is undefined or null or doesn't exist in `values`.
*
* Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts
* to use native `Date#setX` methods. If you use this function, you may not want to include the
* other `setX` functions that date-fns provides if you are concerned about the bundle size.
*
* @param {Date|Number} date - the date to be changed
* @param {Object} values - an object with options
* @param {Number} [values.year] - the number of years to be set
* @param {Number} [values.month] - the number of months to be set
* @param {Number} [values.date] - the number of days to be set
* @param {Number} [values.hours] - the number of hours to be set
* @param {Number} [values.minutes] - the number of minutes to be set
* @param {Number} [values.seconds] - the number of seconds to be set
* @param {Number} [values.milliseconds] - the number of milliseconds to be set
* @returns {Date} the new date with options set
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `values` must be an object
*
* @example
* // Transform 1 September 2014 into 20 October 2015 in a single line:
* const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })
* //=> Tue Oct 20 2015 00:00:00
*
* @example
* // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:
* const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })
* //=> Mon Sep 01 2014 12:23:45
*/
function set_set(dirtyDate, values) {
requiredArgs_requiredArgs(2, arguments);
if (_typeof(values) !== 'object' || values === null) {
throw new RangeError('values parameter must be an object');
}
var date = toDate_toDate(dirtyDate);
// Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(date.getTime())) {
return new Date(NaN);
}
if (values.year != null) {
date.setFullYear(values.year);
}
if (values.month != null) {
date = setMonth_setMonth(date, values.month);
}
if (values.date != null) {
date.setDate(toInteger_toInteger(values.date));
}
if (values.hours != null) {
date.setHours(toInteger_toInteger(values.hours));
}
if (values.minutes != null) {
date.setMinutes(toInteger_toInteger(values.minutes));
}
if (values.seconds != null) {
date.setSeconds(toInteger_toInteger(values.seconds));
}
if (values.milliseconds != null) {
date.setMilliseconds(toInteger_toInteger(values.milliseconds));
}
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/setHours/index.js
/**
* @name setHours
* @category Hour Helpers
* @summary Set the hours to the given date.
*
* @description
* Set the hours to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} hours - the hours of the new date
* @returns {Date} the new date with the hours set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set 4 hours to 1 September 2014 11:30:00:
* const result = setHours(new Date(2014, 8, 1, 11, 30), 4)
* //=> Mon Sep 01 2014 04:30:00
*/
function setHours(dirtyDate, dirtyHours) {
requiredArgs_requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var hours = toInteger_toInteger(dirtyHours);
date.setHours(hours);
return date;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/time/styles.js
function time_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const time_styles_Wrapper = createStyled("div", true ? {
target: "evcr23110"
} : 0)("box-sizing:border-box;font-size:", config_values.fontSize, ";" + ( true ? "" : 0));
const Fieldset = createStyled("fieldset", true ? {
target: "evcr2319"
} : 0)("border:0;margin:0 0 ", space(2 * 2), " 0;padding:0;&:last-child{margin-bottom:0;}" + ( true ? "" : 0));
const TimeWrapper = createStyled("div", true ? {
target: "evcr2318"
} : 0)( true ? {
name: "pd0mhc",
styles: "direction:ltr;display:flex"
} : 0);
const baseInput = /*#__PURE__*/emotion_react_browser_esm_css("&&& ", Input, "{padding-left:", space(2), ";padding-right:", space(2), ";text-align:center;}" + ( true ? "" : 0), true ? "" : 0);
const HoursInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2317"
} : 0)(baseInput, " width:", space(9), ";&&& ", Input, "{padding-right:0;}&&& ", BackdropUI, "{border-right:0;border-top-right-radius:0;border-bottom-right-radius:0;}" + ( true ? "" : 0));
const TimeSeparator = createStyled("span", true ? {
target: "evcr2316"
} : 0)("border-top:", config_values.borderWidth, " solid ", COLORS.gray[700], ";border-bottom:", config_values.borderWidth, " solid ", COLORS.gray[700], ";line-height:calc(\n\t\t", config_values.controlHeight, " - ", config_values.borderWidth, " * 2\n\t);display:inline-block;" + ( true ? "" : 0));
const MinutesInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2315"
} : 0)(baseInput, " width:", space(9), ";&&& ", Input, "{padding-left:0;}&&& ", BackdropUI, "{border-left:0;border-top-left-radius:0;border-bottom-left-radius:0;}" + ( true ? "" : 0)); // Ideally we wouldn't need a wrapper, but can't otherwise target the
// <BaseControl> in <SelectControl>
const MonthSelectWrapper = createStyled("div", true ? {
target: "evcr2314"
} : 0)( true ? {
name: "1ff36h2",
styles: "flex-grow:1"
} : 0);
const MonthSelect = /*#__PURE__*/createStyled(select_control, true ? {
target: "evcr2313"
} : 0)("height:36px;", Select, "{line-height:30px;}" + ( true ? "" : 0));
const DayInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2312"
} : 0)(baseInput, " width:", space(9), ";" + ( true ? "" : 0));
const YearInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2311"
} : 0)(baseInput, " width:", space(14), ";" + ( true ? "" : 0));
const TimeZone = createStyled("div", true ? {
target: "evcr2310"
} : 0)( true ? {
name: "ebu3jh",
styles: "text-decoration:underline dotted"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/time/timezone.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Displays timezone information when user timezone is different from site
* timezone.
*/
const timezone_TimeZone = () => {
const {
timezone
} = (0,external_wp_date_namespaceObject.getSettings)(); // Convert timezone offset to hours.
const userTimezoneOffset = -1 * (new Date().getTimezoneOffset() / 60); // System timezone and user timezone match, nothing needed.
// Compare as numbers because it comes over as string.
if (Number(timezone.offset) === userTimezoneOffset) {
return null;
}
const offsetSymbol = Number(timezone.offset) >= 0 ? '+' : '';
const zoneAbbr = '' !== timezone.abbr && isNaN(Number(timezone.abbr)) ? timezone.abbr : `UTC${offsetSymbol}${timezone.offset}`;
const timezoneDetail = 'UTC' === timezone.string ? (0,external_wp_i18n_namespaceObject.__)('Coordinated Universal Time') : `(${zoneAbbr}) ${timezone.string.replace('_', ' ')}`;
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
position: "top center",
text: timezoneDetail
}, (0,external_wp_element_namespaceObject.createElement)(TimeZone, {
className: "components-datetime__timezone"
}, zoneAbbr));
};
/* harmony default export */ var timezone = (timezone_TimeZone);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/time/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function from12hTo24h(hours, isPm) {
return isPm ? (hours % 12 + 12) % 24 : hours % 12;
}
/**
* Creates an InputControl reducer used to pad an input so that it is always a
* given width. For example, the hours and minutes inputs are padded to 2 so
* that '4' appears as '04'.
*
* @param pad How many digits the value should be.
*/
function buildPadInputStateReducer(pad) {
return (state, action) => {
const nextState = { ...state
};
if (action.type === COMMIT || action.type === PRESS_UP || action.type === PRESS_DOWN) {
if (nextState.value !== undefined) {
nextState.value = nextState.value.toString().padStart(pad, '0');
}
}
return nextState;
};
}
/**
* TimePicker is a React component that renders a clock for time selection.
*
* ```jsx
* import { TimePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTimePicker = () => {
* const [ time, setTime ] = useState( new Date() );
*
* return (
* <TimePicker
* currentTime={ date }
* onChange={ ( newTime ) => setTime( newTime ) }
* is12Hour
* />
* );
* };
* ```
*/
function TimePicker({
is12Hour,
currentTime,
onChange
}) {
const [date, setDate] = (0,external_wp_element_namespaceObject.useState)(() => // Truncate the date at the minutes, see: #15495.
currentTime ? startOfMinute(inputToDate(currentTime)) : new Date()); // Reset the state when currentTime changed.
// TODO: useEffect() shouldn't be used like this, causes an unnecessary render
(0,external_wp_element_namespaceObject.useEffect)(() => {
setDate(currentTime ? startOfMinute(inputToDate(currentTime)) : new Date());
}, [currentTime]);
const {
day,
month,
year,
minutes,
hours,
am
} = (0,external_wp_element_namespaceObject.useMemo)(() => ({
day: format(date, 'dd'),
month: format(date, 'MM'),
year: format(date, 'yyyy'),
minutes: format(date, 'mm'),
hours: format(date, is12Hour ? 'hh' : 'HH'),
am: format(date, 'a')
}), [date, is12Hour]);
const buildNumberControlChangeCallback = method => {
const callback = (value, {
event
}) => {
if (!(event.target instanceof HTMLInputElement)) {
return;
}
if (!event.target.validity.valid) {
return;
} // We can safely assume value is a number if target is valid.
let numberValue = Number(value); // If the 12-hour format is being used and the 'PM' period is
// selected, then the incoming value (which ranges 1-12) should be
// increased by 12 to match the expected 24-hour format.
if (method === 'hours' && is12Hour) {
numberValue = from12hTo24h(numberValue, am === 'PM');
}
const newDate = set_set(date, {
[method]: numberValue
});
setDate(newDate);
onChange?.(format(newDate, TIMEZONELESS_FORMAT));
};
return callback;
};
function buildAmPmChangeCallback(value) {
return () => {
if (am === value) {
return;
}
const parsedHours = parseInt(hours, 10);
const newDate = setHours(date, from12hTo24h(parsedHours, value === 'PM'));
setDate(newDate);
onChange?.(format(newDate, TIMEZONELESS_FORMAT));
};
}
const dayField = (0,external_wp_element_namespaceObject.createElement)(DayInput, {
className: "components-datetime__time-field components-datetime__time-field-day" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Day'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: day,
step: 1,
min: 1,
max: 31,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('date')
});
const monthField = (0,external_wp_element_namespaceObject.createElement)(MonthSelectWrapper, null, (0,external_wp_element_namespaceObject.createElement)(MonthSelect, {
className: "components-datetime__time-field components-datetime__time-field-month" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Month'),
hideLabelFromVision: true,
__nextHasNoMarginBottom: true,
value: month,
options: [{
value: '01',
label: (0,external_wp_i18n_namespaceObject.__)('January')
}, {
value: '02',
label: (0,external_wp_i18n_namespaceObject.__)('February')
}, {
value: '03',
label: (0,external_wp_i18n_namespaceObject.__)('March')
}, {
value: '04',
label: (0,external_wp_i18n_namespaceObject.__)('April')
}, {
value: '05',
label: (0,external_wp_i18n_namespaceObject.__)('May')
}, {
value: '06',
label: (0,external_wp_i18n_namespaceObject.__)('June')
}, {
value: '07',
label: (0,external_wp_i18n_namespaceObject.__)('July')
}, {
value: '08',
label: (0,external_wp_i18n_namespaceObject.__)('August')
}, {
value: '09',
label: (0,external_wp_i18n_namespaceObject.__)('September')
}, {
value: '10',
label: (0,external_wp_i18n_namespaceObject.__)('October')
}, {
value: '11',
label: (0,external_wp_i18n_namespaceObject.__)('November')
}, {
value: '12',
label: (0,external_wp_i18n_namespaceObject.__)('December')
}],
onChange: value => {
const newDate = setMonth_setMonth(date, Number(value) - 1);
setDate(newDate);
onChange?.(format(newDate, TIMEZONELESS_FORMAT));
}
}));
return (0,external_wp_element_namespaceObject.createElement)(time_styles_Wrapper, {
className: "components-datetime__time" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(Fieldset, null, (0,external_wp_element_namespaceObject.createElement)(base_control.VisualLabel, {
as: "legend",
className: "components-datetime__time-legend" // Unused, for backwards compatibility.
}, (0,external_wp_i18n_namespaceObject.__)('Time')), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-datetime__time-wrapper" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(TimeWrapper, {
className: "components-datetime__time-field components-datetime__time-field-time" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(HoursInput, {
className: "components-datetime__time-field-hours-input" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Hours'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: hours,
step: 1,
min: is12Hour ? 1 : 0,
max: is12Hour ? 12 : 23,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('hours'),
__unstableStateReducer: buildPadInputStateReducer(2)
}), (0,external_wp_element_namespaceObject.createElement)(TimeSeparator, {
className: "components-datetime__time-separator" // Unused, for backwards compatibility.
,
"aria-hidden": "true"
}, ":"), (0,external_wp_element_namespaceObject.createElement)(MinutesInput, {
className: "components-datetime__time-field-minutes-input" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Minutes'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: minutes,
step: 1,
min: 0,
max: 59,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('minutes'),
__unstableStateReducer: buildPadInputStateReducer(2)
})), is12Hour && (0,external_wp_element_namespaceObject.createElement)(button_group, {
className: "components-datetime__time-field components-datetime__time-field-am-pm" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-datetime__time-am-button" // Unused, for backwards compatibility.
,
variant: am === 'AM' ? 'primary' : 'secondary',
onClick: buildAmPmChangeCallback('AM')
}, (0,external_wp_i18n_namespaceObject.__)('AM')), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-datetime__time-pm-button" // Unused, for backwards compatibility.
,
variant: am === 'PM' ? 'primary' : 'secondary',
onClick: buildAmPmChangeCallback('PM')
}, (0,external_wp_i18n_namespaceObject.__)('PM'))), (0,external_wp_element_namespaceObject.createElement)(spacer_component, null), (0,external_wp_element_namespaceObject.createElement)(timezone, null))), (0,external_wp_element_namespaceObject.createElement)(Fieldset, null, (0,external_wp_element_namespaceObject.createElement)(base_control.VisualLabel, {
as: "legend",
className: "components-datetime__time-legend" // Unused, for backwards compatibility.
}, (0,external_wp_i18n_namespaceObject.__)('Date')), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-datetime__time-wrapper" // Unused, for backwards compatibility.
}, is12Hour ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, monthField, dayField) : (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, dayField, monthField), (0,external_wp_element_namespaceObject.createElement)(YearInput, {
className: "components-datetime__time-field components-datetime__time-field-year" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Year'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: year,
step: 1,
min: 1,
max: 9999,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('year'),
__unstableStateReducer: buildPadInputStateReducer(4)
}))));
}
/* harmony default export */ var time = (TimePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date-time/styles.js
function date_time_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const date_time_styles_Wrapper = /*#__PURE__*/createStyled(v_stack_component, true ? {
target: "e1p5onf00"
} : 0)( true ? {
name: "1khn195",
styles: "box-sizing:border-box"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date-time/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const date_time_noop = () => {};
function UnforwardedDateTimePicker({
currentDate,
is12Hour,
isInvalidDate,
onMonthPreviewed = date_time_noop,
onChange,
events,
startOfWeek
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)(date_time_styles_Wrapper, {
ref: ref,
className: "components-datetime",
spacing: 4
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(time, {
currentTime: currentDate,
onChange: onChange,
is12Hour: is12Hour
}), (0,external_wp_element_namespaceObject.createElement)(date, {
currentDate: currentDate,
onChange: onChange,
isInvalidDate: isInvalidDate,
events: events,
onMonthPreviewed: onMonthPreviewed,
startOfWeek: startOfWeek
})));
}
/**
* DateTimePicker is a React component that renders a calendar and clock for
* date and time selection. The calendar and clock components can be accessed
* individually using the `DatePicker` and `TimePicker` components respectively.
*
* ```jsx
* import { DateTimePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDateTimePicker = () => {
* const [ date, setDate ] = useState( new Date() );
*
* return (
* <DateTimePicker
* currentDate={ date }
* onChange={ ( newDate ) => setDate( newDate ) }
* is12Hour
* />
* );
* };
* ```
*/
const DateTimePicker = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedDateTimePicker);
/* harmony default export */ var date_time = (DateTimePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/index.js
/**
* Internal dependencies
*/
/* harmony default export */ var build_module_date_time = (date_time);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dimension-control/sizes.js
/**
* Sizes
*
* defines the sizes used in dimension controls
* all hardcoded `size` values are based on the value of
* the Sass variable `$block-padding` from
* `packages/block-editor/src/components/dimension-control/sizes.js`.
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Finds the correct size object from the provided sizes
* table by size slug (eg: `medium`)
*
* @param sizes containing objects for each size definition.
* @param slug a string representation of the size (eg: `medium`).
*/
const findSizeBySlug = (sizes, slug) => sizes.find(size => slug === size.slug);
/* harmony default export */ var dimension_control_sizes = ([{
name: (0,external_wp_i18n_namespaceObject._x)('None', 'Size of a UI element'),
slug: 'none'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Small', 'Size of a UI element'),
slug: 'small'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Medium', 'Size of a UI element'),
slug: 'medium'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Large', 'Size of a UI element'),
slug: 'large'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Extra Large', 'Size of a UI element'),
slug: 'xlarge'
}]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dimension-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* `DimensionControl` is a component designed to provide a UI to control spacing and/or dimensions.
*
* This feature is still experimental. “Experimental” means this is an early implementation subject to drastic and breaking changes.
*
* ```jsx
* import { __experimentalDimensionControl as DimensionControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* export default function MyCustomDimensionControl() {
* const [ paddingSize, setPaddingSize ] = useState( '' );
*
* return (
* <DimensionControl
* label={ 'Padding' }
* icon={ 'desktop' }
* onChange={ ( value ) => setPaddingSize( value ) }
* value={ paddingSize }
* />
* );
* }
* ```
*/
function DimensionControl(props) {
const {
label,
value,
sizes = dimension_control_sizes,
icon,
onChange,
className = ''
} = props;
const onChangeSpacingSize = val => {
const theSize = findSizeBySlug(sizes, val);
if (!theSize || value === theSize.slug) {
onChange?.(undefined);
} else if (typeof onChange === 'function') {
onChange(theSize.slug);
}
};
const formatSizesAsOptions = theSizes => {
const options = theSizes.map(({
name,
slug
}) => ({
label: name,
value: slug
}));
return [{
label: (0,external_wp_i18n_namespaceObject.__)('Default'),
value: ''
}, ...options];
};
const selectLabel = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, icon && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}), label);
return (0,external_wp_element_namespaceObject.createElement)(select_control, {
className: classnames_default()(className, 'block-editor-dimension-control'),
label: selectLabel,
hideLabelFromVision: false,
value: value,
onChange: onChangeSpacingSize,
options: formatSizesAsOptions(sizes)
});
}
/* harmony default export */ var dimension_control = (DimensionControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/disabled/styles/disabled-styles.js
function disabled_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const disabled_styles_disabledStyles = true ? {
name: "u2jump",
styles: "position:relative;pointer-events:none;&::after{content:'';position:absolute;top:0;right:0;bottom:0;left:0;}*{pointer-events:none;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/disabled/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const Context = (0,external_wp_element_namespaceObject.createContext)(false);
const {
Consumer,
Provider: disabled_Provider
} = Context;
/**
* `Disabled` is a component which disables descendant tabbable elements and
* prevents pointer interaction.
*
* _Note: this component may not behave as expected in browsers that don't
* support the `inert` HTML attribute. We recommend adding the official WICG
* polyfill when using this component in your project._
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inert
*
* ```jsx
* import { Button, Disabled, TextControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDisabled = () => {
* const [ isDisabled, setIsDisabled ] = useState( true );
*
* let input = <TextControl label="Input" onChange={ () => {} } />;
* if ( isDisabled ) {
* input = <Disabled>{ input }</Disabled>;
* }
*
* const toggleDisabled = () => {
* setIsDisabled( ( state ) => ! state );
* };
*
* return (
* <div>
* { input }
* <Button variant="primary" onClick={ toggleDisabled }>
* Toggle Disabled
* </Button>
* </div>
* );
* };
* ```
*/
function Disabled({
className,
children,
isDisabled = true,
...props
}) {
const cx = useCx();
return (0,external_wp_element_namespaceObject.createElement)(disabled_Provider, {
value: isDisabled
}, (0,external_wp_element_namespaceObject.createElement)("div", {
// @ts-ignore Reason: inert is a recent HTML attribute
inert: isDisabled ? 'true' : undefined,
className: isDisabled ? cx(disabled_styles_disabledStyles, className, 'components-disabled') : undefined,
...props
}, children));
}
Disabled.Context = Context;
Disabled.Consumer = Consumer;
/* harmony default export */ var disabled = (Disabled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/draggable/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const dragImageClass = 'components-draggable__invisible-drag-image';
const cloneWrapperClass = 'components-draggable__clone';
const clonePadding = 0;
const bodyClass = 'is-dragging-components-draggable';
/**
* `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 dragComponentRef = (0,external_wp_element_namespaceObject.useRef)(null);
const cleanup = (0,external_wp_element_namespaceObject.useRef)(() => {});
/**
* Removes the element clone, resets cursor, and removes drag listener.
*
* @param event The non-custom DragEvent.
*/
function end(event) {
event.preventDefault();
cleanup.current();
if (onDragEnd) {
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;
event.dataTransfer.setData(transferDataType, JSON.stringify(transferData));
const cloneWrapper = ownerDocument.createElement('div'); // Reset position to 0,0. Natural stacking order will position this lower, even with a transform otherwise.
cloneWrapper.style.top = '0';
cloneWrapper.style.left = '0';
const dragImage = ownerDocument.createElement('div'); // Set a fake drag image to avoid browser defaults. Remove from DOM
// right after. event.dataTransfer.setDragImage is not supported yet in
// IE, we need to check for its existence first.
if ('function' === typeof event.dataTransfer.setDragImage) {
dragImage.classList.add(dragImageClass);
ownerDocument.body.appendChild(dragImage);
event.dataTransfer.setDragImage(dragImage, 0, 0);
}
cloneWrapper.classList.add(cloneWrapperClass);
if (cloneClassname) {
cloneWrapper.classList.add(cloneClassname);
}
let x = 0;
let y = 0; // If a dragComponent is defined, the following logic will clone the
// HTML node and inject it into the cloneWrapper.
if (dragComponentRef.current) {
// Position dragComponent at the same position as the cursor.
x = event.clientX;
y = event.clientY;
cloneWrapper.style.transform = `translate( ${x}px, ${y}px )`;
const clonedDragComponent = ownerDocument.createElement('div');
clonedDragComponent.innerHTML = dragComponentRef.current.innerHTML;
cloneWrapper.appendChild(clonedDragComponent); // Inject the cloneWrapper into the DOM.
ownerDocument.body.appendChild(cloneWrapper);
} else {
const element = ownerDocument.getElementById(elementId); // Prepare element clone and append to element wrapper.
const elementRect = element.getBoundingClientRect();
const elementWrapper = element.parentNode;
const elementTopOffset = elementRect.top;
const elementLeftOffset = elementRect.left;
cloneWrapper.style.width = `${elementRect.width + clonePadding * 2}px`;
const clone = element.cloneNode(true);
clone.id = `clone-${elementId}`; // Position clone right over the original element (20px padding).
x = elementLeftOffset - clonePadding;
y = elementTopOffset - clonePadding;
cloneWrapper.style.transform = `translate( ${x}px, ${y}px )`; // Hack: Remove iFrames as it's causing the embeds drag clone to freeze.
Array.from(clone.querySelectorAll('iframe')).forEach(child => child.parentNode?.removeChild(child));
cloneWrapper.appendChild(clone); // Inject the cloneWrapper into the DOM.
if (appendToOwnerDocument) {
ownerDocument.body.appendChild(cloneWrapper);
} else {
elementWrapper?.appendChild(cloneWrapper);
}
} // Mark the current cursor coordinates.
let cursorLeft = event.clientX;
let cursorTop = event.clientY;
function over(e) {
// Skip doing any work if mouse has not moved.
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;
if (onDragOver) {
onDragOver(e);
}
} // Aim for 60fps (16 ms per frame) for now. We can potentially use requestAnimationFrame (raf) instead,
// note that browsers may throttle raf below 60fps in certain conditions.
// @ts-ignore
const throttledDragOver = (0,external_wp_compose_namespaceObject.throttle)(over, 16);
ownerDocument.addEventListener('dragover', throttledDragOver); // Update cursor to 'grabbing', document wide.
ownerDocument.body.classList.add(bodyClass);
if (onDragStart) {
onDragStart(event);
}
cleanup.current = () => {
// Remove drag clone.
if (cloneWrapper && cloneWrapper.parentNode) {
cloneWrapper.parentNode.removeChild(cloneWrapper);
}
if (dragImage && dragImage.parentNode) {
dragImage.parentNode.removeChild(dragImage);
} // Reset cursor.
ownerDocument.body.classList.remove(bodyClass);
ownerDocument.removeEventListener('dragover', throttledDragOver);
};
}
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
cleanup.current();
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children({
onDraggableStart: start,
onDraggableEnd: end
}), dragComponent && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-draggable-drag-component-root",
style: {
display: 'none'
},
ref: dragComponentRef
}, dragComponent));
}
/* harmony default export */ var draggable = (Draggable);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/upload.js
/**
* WordPress dependencies
*/
const upload = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M18.5 15v3.5H13V6.7l4.5 4.1 1-1.1-6.2-5.8-5.8 5.8 1 1.1 4-4v11.7h-6V15H4v5h16v-5z"
}));
/* harmony default export */ var library_upload = (upload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/drop-zone/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* `DropZone` is a component creating a drop zone area taking the full size of its parent element. It supports dropping files, HTML content or any other HTML drop event.
*
* ```jsx
* import { DropZone } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDropZone = () => {
* const [ hasDropped, setHasDropped ] = useState( false );
*
* return (
* <div>
* { hasDropped ? 'Dropped!' : 'Drop something here' }
* <DropZone
* onFilesDrop={ () => setHasDropped( true ) }
* onHTMLDrop={ () => setHasDropped( true ) }
* onDrop={ () => setHasDropped( true ) }
* />
* </div>
* );
* }
* ```
*/
function DropZoneComponent({
className,
label,
onFilesDrop,
onHTMLDrop,
onDrop,
...restProps
}) {
const [isDraggingOverDocument, setIsDraggingOverDocument] = (0,external_wp_element_namespaceObject.useState)();
const [isDraggingOverElement, setIsDraggingOverElement] = (0,external_wp_element_namespaceObject.useState)();
const [type, setType] = (0,external_wp_element_namespaceObject.useState)();
const ref = (0,external_wp_compose_namespaceObject.__experimentalUseDropZone)({
onDrop(event) {
const files = event.dataTransfer ? (0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(event.dataTransfer) : [];
const html = event.dataTransfer?.getData('text/html');
/**
* From Windows Chrome 96, the `event.dataTransfer` returns both file object and HTML.
* The order of the checks is important to recognise the HTML drop.
*/
if (html && onHTMLDrop) {
onHTMLDrop(html);
} else if (files.length && onFilesDrop) {
onFilesDrop(files);
} else if (onDrop) {
onDrop(event);
}
},
onDragStart(event) {
setIsDraggingOverDocument(true);
let _type = 'default';
/**
* From Windows Chrome 96, the `event.dataTransfer` returns both file object and HTML.
* The order of the checks is important to recognise the HTML drop.
*/
if (event.dataTransfer?.types.includes('text/html')) {
_type = 'html';
} else if ( // Check for the types because sometimes the files themselves
// are only available on drop.
event.dataTransfer?.types.includes('Files') || (event.dataTransfer ? (0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(event.dataTransfer) : []).length > 0) {
_type = 'file';
}
setType(_type);
},
onDragEnd() {
setIsDraggingOverDocument(false);
setType(undefined);
},
onDragEnter() {
setIsDraggingOverElement(true);
},
onDragLeave() {
setIsDraggingOverElement(false);
}
});
const disableMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
let children;
const backdrop = {
hidden: {
opacity: 0
},
show: {
opacity: 1,
transition: {
type: 'tween',
duration: 0.2,
delay: 0,
delayChildren: 0.1
}
},
exit: {
opacity: 0,
transition: {
duration: 0.2,
delayChildren: 0
}
}
};
const foreground = {
hidden: {
opacity: 0,
scale: 0.9
},
show: {
opacity: 1,
scale: 1,
transition: {
duration: 0.1
}
},
exit: {
opacity: 0,
scale: 0.9
}
};
if (isDraggingOverElement) {
children = (0,external_wp_element_namespaceObject.createElement)(motion.div, {
variants: backdrop,
initial: disableMotion ? 'show' : 'hidden',
animate: "show",
exit: disableMotion ? 'show' : 'exit',
className: "components-drop-zone__content" // Without this, when this div is shown,
// Safari calls a onDropZoneLeave causing a loop because of this bug
// https://bugs.webkit.org/show_bug.cgi?id=66547
,
style: {
pointerEvents: 'none'
}
}, (0,external_wp_element_namespaceObject.createElement)(motion.div, {
variants: foreground
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_upload,
className: "components-drop-zone__content-icon"
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-drop-zone__content-text"
}, label ? label : (0,external_wp_i18n_namespaceObject.__)('Drop files to upload'))));
}
const classes = classnames_default()('components-drop-zone', className, {
'is-active': (isDraggingOverDocument || isDraggingOverElement) && (type === 'file' && onFilesDrop || type === 'html' && onHTMLDrop || type === 'default' && onDrop),
'is-dragging-over-document': isDraggingOverDocument,
'is-dragging-over-element': isDraggingOverElement,
[`is-dragging-${type}`]: !!type
});
return (0,external_wp_element_namespaceObject.createElement)("div", { ...restProps,
ref: ref,
className: classes
}, disableMotion ? children : (0,external_wp_element_namespaceObject.createElement)(AnimatePresence, null, children));
}
/* harmony default export */ var drop_zone = (DropZoneComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/drop-zone/provider.js
/**
* WordPress dependencies
*/
function DropZoneProvider({
children
}) {
external_wp_deprecated_default()('wp.components.DropZoneProvider', {
since: '5.8',
hint: 'wp.component.DropZone no longer needs a provider. wp.components.DropZoneProvider is safe to remove from your code.'
});
return children;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/swatch.js
/**
* WordPress dependencies
*/
const swatch = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M5 17.7c.4.5.8.9 1.2 1.2l1.1-1.4c-.4-.3-.7-.6-1-1L5 17.7zM5 6.3l1.4 1.1c.3-.4.6-.7 1-1L6.3 5c-.5.4-.9.8-1.3 1.3zm.1 7.8l-1.7.5c.2.6.4 1.1.7 1.6l1.5-.8c-.2-.4-.4-.8-.5-1.3zM4.8 12v-.7L3 11.1v1.8l1.7-.2c.1-.2.1-.5.1-.7zm3 7.9c.5.3 1.1.5 1.6.7l.5-1.7c-.5-.1-.9-.3-1.3-.5l-.8 1.5zM19 6.3c-.4-.5-.8-.9-1.2-1.2l-1.1 1.4c.4.3.7.6 1 1L19 6.3zm-.1 3.6l1.7-.5c-.2-.6-.4-1.1-.7-1.6l-1.5.8c.2.4.4.8.5 1.3zM5.6 8.6l-1.5-.8c-.3.5-.5 1-.7 1.6l1.7.5c.1-.5.3-.9.5-1.3zm2.2-4.5l.8 1.5c.4-.2.8-.4 1.3-.5l-.5-1.7c-.6.2-1.1.4-1.6.7zm8.8 13.5l1.1 1.4c.5-.4.9-.8 1.2-1.2l-1.4-1.1c-.2.3-.5.6-.9.9zm1.8-2.2l1.5.8c.3-.5.5-1.1.7-1.6l-1.7-.5c-.1.5-.3.9-.5 1.3zm2.6-4.3l-1.7.2v1.4l1.7.2V12v-.9zM11.1 3l.2 1.7h1.4l.2-1.7h-1.8zm3 2.1c.5.1.9.3 1.3.5l.8-1.5c-.5-.3-1.1-.5-1.6-.7l-.5 1.7zM12 19.2h-.7l-.2 1.8h1.8l-.2-1.7c-.2-.1-.5-.1-.7-.1zm2.1-.3l.5 1.7c.6-.2 1.1-.4 1.6-.7l-.8-1.5c-.4.2-.8.4-1.3.5z"
}));
/* harmony default export */ var library_swatch = (swatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
colord_k([names]);
/**
* Object representation for a color.
*
* @typedef {Object} RGBColor
* @property {number} r Red component of the color in the range [0,1].
* @property {number} g Green component of the color in the range [0,1].
* @property {number} b Blue component of the color in the range [0,1].
*/
/**
* Calculate the brightest and darkest values from a color palette.
*
* @param palette Color palette for the theme.
*
* @return Tuple of the darkest color and brightest color.
*/
function getDefaultColors(palette) {
// A default dark and light color are required.
if (!palette || palette.length < 2) return ['#000', '#fff'];
return palette.map(({
color
}) => ({
color,
brightness: colord_w(color).brightness()
})).reduce(([min, max], current) => {
return [current.brightness <= min.brightness ? current : min, current.brightness >= max.brightness ? current : max];
}, [{
brightness: 1,
color: ''
}, {
brightness: 0,
color: ''
}]).map(({
color
}) => color);
}
/**
* Generate a duotone gradient from a list of colors.
*
* @param colors CSS color strings.
* @param angle CSS gradient angle.
*
* @return CSS gradient string for the duotone swatch.
*/
function getGradientFromCSSColors(colors = [], angle = '90deg') {
const l = 100 / colors.length;
const stops = colors.map((c, i) => `${c} ${i * l}%, ${c} ${(i + 1) * l}%`).join(', ');
return `linear-gradient( ${angle}, ${stops} )`;
}
/**
* Convert a color array to an array of color stops.
*
* @param colors CSS colors array
*
* @return Color stop information.
*/
function getColorStopsFromColors(colors) {
return colors.map((color, i) => ({
position: i * 100 / (colors.length - 1),
color
}));
}
/**
* Convert a color stop array to an array colors.
*
* @param colorStops Color stop information.
*
* @return CSS colors array.
*/
function getColorsFromColorStops(colorStops = []) {
return colorStops.map(({
color
}) => color);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/duotone-swatch.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DuotoneSwatch({
values
}) {
return values ? (0,external_wp_element_namespaceObject.createElement)(color_indicator, {
colorValue: getGradientFromCSSColors(values, '135deg')
}) : (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_swatch
});
}
/* harmony default export */ var duotone_swatch = (DuotoneSwatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/color-list-picker/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ColorOption({
label,
value,
colors,
disableCustomColors,
enableAlpha,
onChange
}) {
const [isOpen, setIsOpen] = (0,external_wp_element_namespaceObject.useState)(false);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-color-list-picker__swatch-button",
onClick: () => setIsOpen(prev => !prev)
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
justify: "flex-start",
spacing: 2
}, value ? (0,external_wp_element_namespaceObject.createElement)(color_indicator, {
colorValue: value,
className: "components-color-list-picker__swatch-color"
}) : (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_swatch
}), (0,external_wp_element_namespaceObject.createElement)("span", null, label))), isOpen && (0,external_wp_element_namespaceObject.createElement)(color_palette, {
className: "components-color-list-picker__color-picker",
colors: colors,
value: value,
clearable: false,
onChange: onChange,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha
}));
}
function ColorListPicker({
colors,
labels,
value = [],
disableCustomColors,
enableAlpha,
onChange
}) {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-color-list-picker"
}, labels.map((label, index) => (0,external_wp_element_namespaceObject.createElement)(ColorOption, {
key: index,
label: label,
value: value[index],
colors: colors,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
onChange: newColor => {
const newColors = value.slice();
newColors[index] = newColor;
onChange(newColors);
}
})));
}
/* harmony default export */ var color_list_picker = (ColorListPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/custom-duotone-bar.js
/**
* Internal dependencies
*/
const PLACEHOLDER_VALUES = ['#333', '#CCC'];
function CustomDuotoneBar({
value,
onChange
}) {
const hasGradient = !!value;
const values = hasGradient ? value : PLACEHOLDER_VALUES;
const background = getGradientFromCSSColors(values);
const controlPoints = getColorStopsFromColors(values);
return (0,external_wp_element_namespaceObject.createElement)(CustomGradientBar, {
disableInserter: true,
background: background,
hasGradient: hasGradient,
value: controlPoints,
onChange: newColorStops => {
const newValue = getColorsFromColorStops(newColorStops);
onChange(newValue);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/duotone-picker.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* ```jsx
* import { DuotonePicker, DuotoneSwatch } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const DUOTONE_PALETTE = [
* { colors: [ '#8c00b7', '#fcff41' ], name: 'Purple and yellow', slug: 'purple-yellow' },
* { colors: [ '#000097', '#ff4747' ], name: 'Blue and red', slug: 'blue-red' },
* ];
*
* const COLOR_PALETTE = [
* { color: '#ff4747', name: 'Red', slug: 'red' },
* { color: '#fcff41', name: 'Yellow', slug: 'yellow' },
* { color: '#000097', name: 'Blue', slug: 'blue' },
* { color: '#8c00b7', name: 'Purple', slug: 'purple' },
* ];
*
* const Example = () => {
* const [ duotone, setDuotone ] = useState( [ '#000000', '#ffffff' ] );
* return (
* <>
* <DuotonePicker
* duotonePalette={ DUOTONE_PALETTE }
* colorPalette={ COLOR_PALETTE }
* value={ duotone }
* onChange={ setDuotone }
* />
* <DuotoneSwatch values={ duotone } />
* </>
* );
* };
* ```
*/
function DuotonePicker({
clearable = true,
unsetable = true,
colorPalette,
duotonePalette,
disableCustomColors,
disableCustomDuotone,
value,
onChange
}) {
const [defaultDark, defaultLight] = (0,external_wp_element_namespaceObject.useMemo)(() => getDefaultColors(colorPalette), [colorPalette]);
const isUnset = value === 'unset';
const unsetOption = (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.Option, {
key: "unset",
value: "unset",
isSelected: isUnset,
tooltipText: (0,external_wp_i18n_namespaceObject.__)('Unset'),
className: "components-duotone-picker__color-indicator",
onClick: () => {
onChange(isUnset ? undefined : 'unset');
}
});
const options = duotonePalette.map(({
colors,
slug,
name
}) => {
const style = {
background: getGradientFromCSSColors(colors, '135deg'),
color: 'transparent'
};
const tooltipText = name !== null && name !== void 0 ? name : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: duotone code e.g: "dark-grayscale" or "7f7f7f-ffffff".
(0,external_wp_i18n_namespaceObject.__)('Duotone code: %s'), slug);
const label = name ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the option e.g: "Dark grayscale".
(0,external_wp_i18n_namespaceObject.__)('Duotone: %s'), name) : tooltipText;
const isSelected = es6_default()(colors, value);
return (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.Option, {
key: slug,
value: colors,
isSelected: isSelected,
"aria-label": label,
tooltipText: tooltipText,
style: style,
onClick: () => {
onChange(isSelected ? undefined : colors);
}
});
});
return (0,external_wp_element_namespaceObject.createElement)(circular_option_picker, {
options: unsetable ? [unsetOption, ...options] : options,
actions: !!clearable && (0,external_wp_element_namespaceObject.createElement)(circular_option_picker.ButtonAction, {
onClick: () => onChange(undefined)
}, (0,external_wp_i18n_namespaceObject.__)('Clear'))
}, (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
paddingTop: 4
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3
}, !disableCustomColors && !disableCustomDuotone && (0,external_wp_element_namespaceObject.createElement)(CustomDuotoneBar, {
value: isUnset ? undefined : value,
onChange: onChange
}), !disableCustomDuotone && (0,external_wp_element_namespaceObject.createElement)(color_list_picker, {
labels: [(0,external_wp_i18n_namespaceObject.__)('Shadows'), (0,external_wp_i18n_namespaceObject.__)('Highlights')],
colors: colorPalette,
value: isUnset ? undefined : value,
disableCustomColors: disableCustomColors,
enableAlpha: true,
onChange: newColors => {
if (!newColors[0]) {
newColors[0] = defaultDark;
}
if (!newColors[1]) {
newColors[1] = defaultLight;
}
const newValue = newColors.length >= 2 ? newColors : undefined; // @ts-expect-error TODO: The color arrays for a DuotonePicker should be a tuple of two colors,
// but it's currently typed as a string[].
// See also https://github.com/WordPress/gutenberg/pull/49060#discussion_r1136951035
onChange(newValue);
}
}))));
}
/* harmony default export */ var duotone_picker = (DuotonePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
/**
* WordPress dependencies
*/
const external = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z"
}));
/* harmony default export */ var library_external = (external);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/external-link/styles/external-link-styles.js
function external_link_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const StyledIcon = /*#__PURE__*/createStyled(icons_build_module_icon, true ? {
target: "esh4a730"
} : 0)( true ? {
name: "rvs7bx",
styles: "width:1em;height:1em;margin:0;vertical-align:middle;fill:currentColor"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/external-link/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedExternalLink(props, ref) {
const {
href,
children,
className,
rel = '',
...additionalProps
} = props;
const optimizedRel = [...new Set([...rel.split(' '), 'external', 'noreferrer', 'noopener'].filter(Boolean))].join(' ');
const classes = classnames_default()('components-external-link', className);
/* Anchor links are perceived as external links.
This constant helps check for on page anchor links,
to prevent them from being opened in the editor. */
const isInternalAnchor = !!href?.startsWith('#');
const onClickHandler = event => {
if (isInternalAnchor) {
event.preventDefault();
}
if (props.onClick) {
props.onClick(event);
}
};
return (
/* eslint-disable react/jsx-no-target-blank */
(0,external_wp_element_namespaceObject.createElement)("a", { ...additionalProps,
className: classes,
href: href,
onClick: onClickHandler,
target: "_blank",
rel: optimizedRel,
ref: ref
}, children, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "span"
},
/* translators: accessibility text */
(0,external_wp_i18n_namespaceObject.__)('(opens in a new tab)')), (0,external_wp_element_namespaceObject.createElement)(StyledIcon, {
icon: library_external,
className: "components-external-link__icon"
}))
/* eslint-enable react/jsx-no-target-blank */
);
}
/**
* Link to an external resource.
*
* ```jsx
* import { ExternalLink } from '@wordpress/components';
*
* const MyExternalLink = () => (
* <ExternalLink href="https://wordpress.org">WordPress.org</ExternalLink>
* );
* ```
*/
const ExternalLink = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedExternalLink);
/* harmony default export */ var external_link = (ExternalLink);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/utils.js
const INITIAL_BOUNDS = {
width: 200,
height: 170
};
const VIDEO_EXTENSIONS = ['avi', 'mpg', 'mpeg', 'mov', 'mp4', 'm4v', 'ogg', 'ogv', 'webm', 'wmv'];
/**
* Gets the extension of a file name.
*
* @param filename The file name.
* @return The extension of the file name.
*/
function getExtension(filename = '') {
const parts = filename.split('.');
return parts[parts.length - 1];
}
/**
* Checks if a file is a video.
*
* @param filename The file name.
* @return Whether the file is a video.
*/
function isVideoType(filename = '') {
if (!filename) return false;
return filename.startsWith('data:video/') || VIDEO_EXTENSIONS.includes(getExtension(filename));
}
/**
* Transforms a fraction value to a percentage value.
*
* @param fraction The fraction value.
* @return A percentage value.
*/
function fractionToPercentage(fraction) {
return Math.round(fraction * 100);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/styles/focal-point-picker-style.js
function focal_point_picker_style_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const MediaWrapper = createStyled("div", true ? {
target: "eeew7dm8"
} : 0)( true ? {
name: "w0nf6b",
styles: "background-color:transparent;text-align:center;width:100%"
} : 0);
const MediaContainer = createStyled("div", true ? {
target: "eeew7dm7"
} : 0)( true ? {
name: "megach",
styles: "align-items:center;box-shadow:0 0 0 1px rgba( 0, 0, 0, 0.2 );cursor:pointer;display:inline-flex;justify-content:center;margin:auto;position:relative;height:100%;img,video{box-sizing:border-box;display:block;height:auto;margin:0;max-height:100%;max-width:100%;pointer-events:none;user-select:none;width:auto;}"
} : 0);
const MediaPlaceholder = createStyled("div", true ? {
target: "eeew7dm6"
} : 0)("background:", COLORS.gray[100], ";box-sizing:border-box;height:", INITIAL_BOUNDS.height, "px;max-width:280px;min-width:", INITIAL_BOUNDS.width, "px;width:100%;" + ( true ? "" : 0));
const StyledUnitControl = /*#__PURE__*/createStyled(unit_control, true ? {
target: "eeew7dm5"
} : 0)( true ? {
name: "1pzk433",
styles: "width:100px"
} : 0);
var focal_point_picker_style_ref2 = true ? {
name: "1mn7kwb",
styles: "padding-bottom:1em"
} : 0;
const focal_point_picker_style_deprecatedBottomMargin = ({
__nextHasNoMarginBottom
}) => {
return !__nextHasNoMarginBottom ? focal_point_picker_style_ref2 : undefined;
};
var focal_point_picker_style_ref = true ? {
name: "1mn7kwb",
styles: "padding-bottom:1em"
} : 0;
const extraHelpTextMargin = ({
hasHelpText = false
}) => {
return hasHelpText ? focal_point_picker_style_ref : undefined;
};
const ControlWrapper = /*#__PURE__*/createStyled(flex_component, true ? {
target: "eeew7dm4"
} : 0)("max-width:320px;padding-top:1em;", extraHelpTextMargin, " ", focal_point_picker_style_deprecatedBottomMargin, ";" + ( true ? "" : 0));
const GridView = createStyled("div", true ? {
target: "eeew7dm3"
} : 0)("left:50%;overflow:hidden;pointer-events:none;position:absolute;top:50%;transform:translate3d( -50%, -50%, 0 );transition:opacity 120ms linear;z-index:1;opacity:", ({
showOverlay
}) => showOverlay ? 1 : 0, ";" + ( true ? "" : 0));
const GridLine = createStyled("div", true ? {
target: "eeew7dm2"
} : 0)( true ? {
name: "1d42i6k",
styles: "background:white;box-shadow:0 0 2px rgba( 0, 0, 0, 0.6 );position:absolute;opacity:0.4;transform:translateZ( 0 )"
} : 0);
const GridLineX = /*#__PURE__*/createStyled(GridLine, true ? {
target: "eeew7dm1"
} : 0)( true ? {
name: "1qp910y",
styles: "height:1px;left:0;right:0"
} : 0);
const GridLineY = /*#__PURE__*/createStyled(GridLine, true ? {
target: "eeew7dm0"
} : 0)( true ? {
name: "1oz3zka",
styles: "width:1px;top:0;bottom:0"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/controls.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TEXTCONTROL_MIN = 0;
const TEXTCONTROL_MAX = 100;
const controls_noop = () => {};
function FocalPointPickerControls({
__nextHasNoMarginBottom,
hasHelpText,
onChange = controls_noop,
point = {
x: 0.5,
y: 0.5
}
}) {
const valueX = fractionToPercentage(point.x);
const valueY = fractionToPercentage(point.y);
const handleChange = (value, axis) => {
if (value === undefined) return;
const num = parseInt(value, 10);
if (!isNaN(num)) {
onChange({ ...point,
[axis]: num / 100
});
}
};
return (0,external_wp_element_namespaceObject.createElement)(ControlWrapper, {
className: "focal-point-picker__controls",
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
hasHelpText: hasHelpText
}, (0,external_wp_element_namespaceObject.createElement)(FocalPointUnitControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Left'),
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Focal point left position'),
value: [valueX, '%'].join(''),
onChange: next => handleChange(next, 'x'),
dragDirection: "e"
}), (0,external_wp_element_namespaceObject.createElement)(FocalPointUnitControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Top'),
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Focal point top position'),
value: [valueY, '%'].join(''),
onChange: next => handleChange(next, 'y'),
dragDirection: "s"
}));
}
function FocalPointUnitControl(props) {
return (0,external_wp_element_namespaceObject.createElement)(StyledUnitControl, {
className: "focal-point-picker__controls-position-unit-control",
labelPosition: "top",
max: TEXTCONTROL_MAX,
min: TEXTCONTROL_MIN,
units: [{
value: '%',
label: '%'
}],
...props
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/styles/focal-point-style.js
/**
* External dependencies
*/
const PointerCircle = createStyled("div", true ? {
target: "e19snlhg0"
} : 0)("background-color:transparent;cursor:grab;height:48px;margin:-24px 0 0 -24px;position:absolute;user-select:none;width:48px;will-change:transform;z-index:10000;background:rgba( 255, 255, 255, 0.6 );border-radius:50%;backdrop-filter:blur( 4px );box-shadow:rgb( 0 0 0 / 20% ) 0px 0px 10px;", ({
isDragging
}) => isDragging && 'cursor: grabbing;', ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/focal-point.js
/**
* Internal dependencies
*/
/**
* External dependencies
*/
function FocalPoint({
left = '50%',
top = '50%',
...props
}) {
const classes = classnames_default()('components-focal-point-picker__icon_container');
const style = {
left,
top
};
return (0,external_wp_element_namespaceObject.createElement)(PointerCircle, { ...props,
className: classes,
style: style
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/grid.js
/**
* Internal dependencies
*/
function FocalPointPickerGrid({
bounds,
...props
}) {
return (0,external_wp_element_namespaceObject.createElement)(GridView, { ...props,
className: "components-focal-point-picker__grid",
style: {
width: bounds.width,
height: bounds.height
}
}, (0,external_wp_element_namespaceObject.createElement)(GridLineX, {
style: {
top: '33%'
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineX, {
style: {
top: '66%'
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineY, {
style: {
left: '33%'
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineY, {
style: {
left: '66%'
}
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/media.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function media_Media({
alt,
autoPlay,
src,
onLoad,
mediaRef,
// Exposing muted prop for test rendering purposes
// https://github.com/testing-library/react-testing-library/issues/470
muted = true,
...props
}) {
if (!src) {
return (0,external_wp_element_namespaceObject.createElement)(MediaPlaceholder, {
className: "components-focal-point-picker__media components-focal-point-picker__media--placeholder",
ref: mediaRef,
...props
});
}
const isVideo = isVideoType(src);
return isVideo ? (0,external_wp_element_namespaceObject.createElement)("video", { ...props,
autoPlay: autoPlay,
className: "components-focal-point-picker__media components-focal-point-picker__media--video",
loop: true,
muted: muted,
onLoadedData: onLoad,
ref: mediaRef,
src: src
}) : (0,external_wp_element_namespaceObject.createElement)("img", { ...props,
alt: alt,
className: "components-focal-point-picker__media components-focal-point-picker__media--image",
onLoad: onLoad,
ref: mediaRef,
src: src
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
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.
*
* This component addresses a specific problem: with large background images it is common to see undesirable crops,
* especially when viewing on smaller viewports such as mobile phones. 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.
* This value can be easily converted into the CSS `background-position` attribute, and will ensure that the
* focal point is never cropped out, regardless of viewport.
*
* - Example focal point picker value: `{ x: 0.5, y: 0.1 }`
* - Corresponding CSS: `background-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.5,
* } );
*
* const url = '/path/to/image';
*
* // Example function to render the CSS styles based on Focal Point Picker value
* const style = {
* backgroundImage: `url(${ url })`,
* backgroundPosition: `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`,
* };
*
* return (
* <>
* <FocalPointPicker
* url={ url }
* value={ focalPoint }
* onDragStart={ setFocalPoint }
* onDrag={ setFocalPoint }
* onChange={ setFocalPoint }
* />
* <div style={ style } />
* </>
* );
* };
* ```
*/
function FocalPointPicker({
__nextHasNoMarginBottom,
autoPlay = true,
className,
help,
label,
onChange,
onDrag,
onDragEnd,
onDragStart,
resolvePoint,
url,
value: valueProp = {
x: 0.5,
y: 0.5
},
...restProps
}) {
const [point, setPoint] = (0,external_wp_element_namespaceObject.useState)(valueProp);
const [showGridOverlay, setShowGridOverlay] = (0,external_wp_element_namespaceObject.useState)(false);
const {
startDrag,
endDrag,
isDragging
} = (0,external_wp_compose_namespaceObject.__experimentalUseDragging)({
onDragStart: event => {
dragAreaRef.current?.focus();
const value = getValueWithinDragArea(event); // `value` can technically be undefined if getValueWithinDragArea() is
// called before dragAreaRef is set, but this shouldn't happen in reality.
if (!value) return;
onDragStart?.(value, event);
setPoint(value);
},
onDragMove: event => {
// Prevents text-selection when dragging.
event.preventDefault();
const value = getValueWithinDragArea(event);
if (!value) return;
onDrag?.(value, event);
setPoint(value);
},
onDragEnd: () => {
onDragEnd?.();
onChange?.(point);
}
}); // Uses the internal point while dragging or else the value from props.
const {
x,
y
} = isDragging ? point : valueProp;
const dragAreaRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [bounds, setBounds] = (0,external_wp_element_namespaceObject.useState)(INITIAL_BOUNDS);
const refUpdateBounds = (0,external_wp_element_namespaceObject.useRef)(() => {
if (!dragAreaRef.current) return;
const {
clientWidth: width,
clientHeight: height
} = dragAreaRef.current; // Falls back to initial bounds if the ref has no size. Since styles
// give the drag area dimensions even when the media has not loaded
// this should only happen in unit tests (jsdom).
setBounds(width > 0 && height > 0 ? {
width,
height
} : { ...INITIAL_BOUNDS
});
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
const updateBounds = refUpdateBounds.current;
if (!dragAreaRef.current) return;
const {
defaultView
} = dragAreaRef.current.ownerDocument;
defaultView?.addEventListener('resize', updateBounds);
return () => defaultView?.removeEventListener('resize', updateBounds);
}, []); // Updates the bounds to cover cases of unspecified media or load failures.
(0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => void refUpdateBounds.current(), []); // TODO: Consider refactoring getValueWithinDragArea() into a pure function.
// https://github.com/WordPress/gutenberg/pull/43872#discussion_r963455173
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; // Enables holding shift to jump values by 10%.
if (shiftKey) {
nextX = Math.round(nextX / 0.1) * 0.1;
nextY = Math.round(nextY / 0.1) * 0.1;
}
return getFinalValue({
x: nextX,
y: nextY
});
};
const getFinalValue = value => {
var _resolvePoint;
const resolvedValue = (_resolvePoint = resolvePoint?.(value)) !== null && _resolvePoint !== void 0 ? _resolvePoint : 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 * 1e2) / 1e2;
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 ? 0.1 : 0.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 * bounds.width,
top: y * bounds.height
};
const classes = classnames_default()('components-focal-point-picker-control', className);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(FocalPointPicker);
const id = `inspector-focal-point-picker-control-${instanceId}`;
use_update_effect(() => {
setShowGridOverlay(true);
const timeout = window.setTimeout(() => {
setShowGridOverlay(false);
}, GRID_OVERLAY_TIMEOUT);
return () => window.clearTimeout(timeout);
}, [x, y]);
return (0,external_wp_element_namespaceObject.createElement)(base_control, { ...restProps,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
id: id,
help: help,
className: classes
}, (0,external_wp_element_namespaceObject.createElement)(MediaWrapper, {
className: "components-focal-point-picker-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(MediaContainer, {
className: "components-focal-point-picker",
onKeyDown: arrowKeyStep,
onMouseDown: startDrag,
onBlur: () => {
if (isDragging) endDrag();
},
ref: dragAreaRef,
role: "button",
tabIndex: -1
}, (0,external_wp_element_namespaceObject.createElement)(FocalPointPickerGrid, {
bounds: bounds,
showOverlay: showGridOverlay
}), (0,external_wp_element_namespaceObject.createElement)(media_Media, {
alt: (0,external_wp_i18n_namespaceObject.__)('Media preview'),
autoPlay: autoPlay,
onLoad: refUpdateBounds.current,
src: url
}), (0,external_wp_element_namespaceObject.createElement)(FocalPoint, { ...focalPointPosition,
isDragging: isDragging
}))), (0,external_wp_element_namespaceObject.createElement)(FocalPointPickerControls, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
hasHelpText: !!help,
point: {
x,
y
},
onChange: value => {
onChange?.(getFinalValue(value));
}
}));
}
/* harmony default export */ var focal_point_picker = (FocalPointPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focusable-iframe/index.js
/**
* WordPress dependencies
*/
/**
* @param {Object} props
* @param {import('react').Ref<HTMLIFrameElement>} props.iframeRef
*/
function FocusableIframe({
iframeRef,
...props
}) {
const ref = (0,external_wp_compose_namespaceObject.useMergeRefs)([iframeRef, (0,external_wp_compose_namespaceObject.useFocusableIframe)()]);
external_wp_deprecated_default()('wp.components.FocusableIframe', {
since: '5.9',
alternative: 'wp.compose.useFocusableIframe'
}); // Disable reason: The rendered iframe is a pass-through component,
// assigning props inherited from the rendering parent. It's the
// responsibility of the parent to assign a title.
// eslint-disable-next-line jsx-a11y/iframe-has-title
return (0,external_wp_element_namespaceObject.createElement)("iframe", {
ref: ref,
...props
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/settings.js
/**
* WordPress dependencies
*/
const settings = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M14.5 13.8c-1.1 0-2.1.7-2.4 1.8H4V17h8.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20v-1.5h-3.1c-.3-1-1.3-1.7-2.4-1.7zM11.9 7c-.3-1-1.3-1.8-2.4-1.8S7.4 6 7.1 7H4v1.5h3.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20V7h-8.1z"
}));
/* harmony default export */ var library_settings = (settings);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Some themes use css vars for their font sizes, so until we
* have the way of calculating them don't display them.
*
* @param value The value that is checked.
* @return Whether the value is a simple css value.
*/
function isSimpleCssValue(value) {
const sizeRegex = /^[\d\.]+(px|em|rem|vw|vh|%)?$/i;
return sizeRegex.test(String(value));
}
/**
* If all of the given font sizes have the same unit (e.g. 'px'), return that
* unit. Otherwise return null.
*
* @param fontSizes List of font sizes.
* @return The common unit, or null.
*/
function getCommonSizeUnit(fontSizes) {
const [firstFontSize, ...otherFontSizes] = fontSizes;
if (!firstFontSize) {
return null;
}
const [, firstUnit] = parseQuantityAndUnitFromRawValue(firstFontSize.size);
const areAllSizesSameUnit = otherFontSizes.every(fontSize => {
const [, unit] = parseQuantityAndUnitFromRawValue(fontSize.size);
return unit === firstUnit;
});
return areAllSizesSameUnit ? firstUnit : null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/styles.js
function font_size_picker_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const styles_Container = createStyled("fieldset", true ? {
target: "e8tqeku5"
} : 0)( true ? {
name: "1t1ytme",
styles: "border:0;margin:0;padding:0"
} : 0);
const font_size_picker_styles_Header = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "e8tqeku4"
} : 0)("height:", space(4), ";" + ( true ? "" : 0));
const HeaderToggle = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "e8tqeku3"
} : 0)("margin-top:", space(-1), ";" + ( true ? "" : 0));
const HeaderLabel = /*#__PURE__*/createStyled(base_control.VisualLabel, true ? {
target: "e8tqeku2"
} : 0)("display:flex;gap:", space(1), ";justify-content:flex-start;margin-bottom:0;" + ( true ? "" : 0));
const HeaderHint = createStyled("span", true ? {
target: "e8tqeku1"
} : 0)("color:", COLORS.gray[700], ";" + ( true ? "" : 0));
const Controls = createStyled("div", true ? {
target: "e8tqeku0"
} : 0)(props => !props.__nextHasNoMarginBottom && `margin-bottom: ${space(6)};`, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/font-size-picker-select.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_OPTION = {
key: 'default',
name: (0,external_wp_i18n_namespaceObject.__)('Default'),
value: undefined
};
const CUSTOM_OPTION = {
key: 'custom',
name: (0,external_wp_i18n_namespaceObject.__)('Custom')
};
const FontSizePickerSelect = props => {
var _options$find;
const {
fontSizes,
value,
disableCustomFontSizes,
size,
onChange,
onSelectCustom
} = props;
const areAllSizesSameUnit = !!getCommonSizeUnit(fontSizes);
const options = [DEFAULT_OPTION, ...fontSizes.map(fontSize => {
let hint;
if (areAllSizesSameUnit) {
const [quantity] = parseQuantityAndUnitFromRawValue(fontSize.size);
if (quantity !== undefined) {
hint = String(quantity);
}
} else if (isSimpleCssValue(fontSize.size)) {
hint = String(fontSize.size);
}
return {
key: fontSize.slug,
name: fontSize.name || fontSize.slug,
value: fontSize.size,
__experimentalHint: hint
};
}), ...(disableCustomFontSizes ? [] : [CUSTOM_OPTION])];
const selectedOption = value ? (_options$find = options.find(option => option.value === value)) !== null && _options$find !== void 0 ? _options$find : CUSTOM_OPTION : DEFAULT_OPTION;
return (0,external_wp_element_namespaceObject.createElement)(CustomSelectControl, {
__nextUnconstrainedWidth: true,
className: "components-font-size-picker__select",
label: (0,external_wp_i18n_namespaceObject.__)('Font size'),
hideLabelFromVision: true,
describedBy: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Currently selected font size.
(0,external_wp_i18n_namespaceObject.__)('Currently selected font size: %s'), selectedOption.name),
options: options,
value: selectedOption,
__experimentalShowSelectedHint: true,
onChange: ({
selectedItem
}) => {
if (selectedItem === CUSTOM_OPTION) {
onSelectCustom();
} else {
onChange(selectedItem.value);
}
},
size: size
});
};
/* harmony default export */ var font_size_picker_select = (FontSizePickerSelect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/styles.js
function toggle_group_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ToggleGroupControl = ({
isBlock,
isDeselectable,
size
}) => /*#__PURE__*/emotion_react_browser_esm_css("background:", COLORS.ui.background, ";border:1px solid transparent;border-radius:", config_values.controlBorderRadius, ";display:inline-flex;min-width:0;padding:2px;position:relative;transition:transform ", config_values.transitionDurationFastest, " linear;", reduceMotion('transition'), " ", toggleGroupControlSize(size), " ", !isDeselectable && enclosingBorders(isBlock), ";" + ( true ? "" : 0), true ? "" : 0);
const enclosingBorders = isBlock => {
const enclosingBorder = /*#__PURE__*/emotion_react_browser_esm_css("border-color:", COLORS.ui.border, ";" + ( true ? "" : 0), true ? "" : 0);
return /*#__PURE__*/emotion_react_browser_esm_css(isBlock && enclosingBorder, " &:hover{border-color:", COLORS.ui.borderHover, ";}&:focus-within{border-color:", COLORS.ui.borderFocus, ";box-shadow:", config_values.controlBoxShadowFocus, ";z-index:1;outline:2px solid transparent;outline-offset:-2px;}" + ( true ? "" : 0), true ? "" : 0);
};
const toggleGroupControlSize = size => {
const heights = {
default: '36px',
'__unstable-large': '40px'
};
return /*#__PURE__*/emotion_react_browser_esm_css("min-height:", heights[size], ";" + ( true ? "" : 0), true ? "" : 0);
};
const toggle_group_control_styles_block = true ? {
name: "7whenc",
styles: "display:flex;width:100%"
} : 0;
const BackdropView = createStyled("div", true ? {
target: "eakva831"
} : 0)("background:", COLORS.gray[900], ";border-radius:", config_values.controlBorderRadius, ";left:0;position:absolute;top:2px;bottom:2px;transition:transform ", config_values.transitionDurationFast, " ease;", reduceMotion('transition'), " z-index:1;outline:2px solid transparent;outline-offset:-3px;" + ( true ? "" : 0));
const VisualLabelWrapper = createStyled("div", true ? {
target: "eakva830"
} : 0)( true ? {
name: "zjik7",
styles: "display:flex"
} : 0);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Radio/RadioState.js
function useRadioState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
initialValue = _useSealedState.state,
_useSealedState$loop = _useSealedState.loop,
loop = _useSealedState$loop === void 0 ? true : _useSealedState$loop,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["state", "loop"]);
var _React$useState = (0,external_React_.useState)(initialValue),
state = _React$useState[0],
setState = _React$useState[1];
var composite = useCompositeState(_objectSpread2(_objectSpread2({}, sealed), {}, {
loop: loop
}));
return _objectSpread2(_objectSpread2({}, composite), {}, {
state: state,
setState: setState
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-d251e56b.js
// Automatically generated
var RADIO_STATE_KEYS = ["baseId", "unstable_idCountRef", "unstable_virtual", "rtl", "orientation", "items", "groups", "currentId", "loop", "wrap", "shift", "unstable_moves", "unstable_hasActiveWidget", "unstable_includesBaseElement", "state", "setBaseId", "registerItem", "unregisterItem", "registerGroup", "unregisterGroup", "move", "next", "previous", "up", "down", "first", "last", "sort", "unstable_setVirtual", "setRTL", "setOrientation", "setCurrentId", "setLoop", "setWrap", "setShift", "reset", "unstable_setIncludesBaseElement", "unstable_setHasActiveWidget", "setState"];
var RADIO_KEYS = [].concat(RADIO_STATE_KEYS, ["value", "checked", "unstable_checkOnFocus"]);
var RADIO_GROUP_KEYS = RADIO_STATE_KEYS;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Radio/RadioGroup.js
var useRadioGroup = createHook({
name: "RadioGroup",
compose: useComposite,
keys: RADIO_GROUP_KEYS,
useProps: function useProps(_, htmlProps) {
return _objectSpread2({
role: "radiogroup"
}, htmlProps);
}
});
var RadioGroup = createComponent({
as: "div",
useHook: useRadioGroup,
useCreateElement: function useCreateElement$1(type, props, children) {
false ? 0 : void 0;
return useCreateElement(type, props, children);
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/toggle-group-control-backdrop.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToggleGroupControlBackdrop({
containerRef,
containerWidth,
isAdaptiveWidth,
state
}) {
const [left, setLeft] = (0,external_wp_element_namespaceObject.useState)(0);
const [width, setWidth] = (0,external_wp_element_namespaceObject.useState)(0);
const [canAnimate, setCanAnimate] = (0,external_wp_element_namespaceObject.useState)(false);
const [renderBackdrop, setRenderBackdrop] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const containerNode = containerRef?.current;
if (!containerNode) return;
/**
* Workaround for Reakit
*/
const targetNode = containerNode.querySelector(`[data-value="${state}"]`);
setRenderBackdrop(!!targetNode);
if (!targetNode) {
return;
}
const computeDimensions = () => {
const {
width: offsetWidth,
x
} = targetNode.getBoundingClientRect();
const {
x: parentX
} = containerNode.getBoundingClientRect();
const borderWidth = 1;
const offsetLeft = x - parentX - borderWidth;
setLeft(offsetLeft);
setWidth(offsetWidth);
}; // Fix to make the component appear as expected inside popovers.
// If the targetNode width is 0 it means the element was not yet rendered we should allow
// some time for the render to happen.
// requestAnimationFrame instead of setTimeout with a small time does not seems to work.
const dimensionsRequestId = window.setTimeout(computeDimensions, 100);
let animationRequestId;
if (!canAnimate) {
animationRequestId = window.requestAnimationFrame(() => {
setCanAnimate(true);
});
}
return () => {
window.clearTimeout(dimensionsRequestId);
window.cancelAnimationFrame(animationRequestId);
};
}, [canAnimate, containerRef, containerWidth, state, isAdaptiveWidth]);
if (!renderBackdrop) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(BackdropView, {
role: "presentation",
style: {
transform: `translateX(${left}px)`,
transition: canAnimate ? undefined : 'none',
width
}
});
}
/* harmony default export */ var toggle_group_control_backdrop = ((0,external_wp_element_namespaceObject.memo)(ToggleGroupControlBackdrop));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ToggleGroupControlContext = (0,external_wp_element_namespaceObject.createContext)({});
const useToggleGroupControlContext = () => (0,external_wp_element_namespaceObject.useContext)(ToggleGroupControlContext);
/* harmony default export */ var toggle_group_control_context = (ToggleGroupControlContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/as-radio-group.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlAsRadioGroup({
children,
isAdaptiveWidth,
label,
onChange,
size,
value,
...otherProps
}, forwardedRef) {
const containerRef = (0,external_wp_element_namespaceObject.useRef)();
const [resizeListener, sizes] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const baseId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlAsRadioGroup, 'toggle-group-control-as-radio-group').toString();
const radio = useRadioState({
baseId,
state: value
});
const previousValue = (0,external_wp_compose_namespaceObject.usePrevious)(value); // Propagate radio.state change.
use_update_effect(() => {
// Avoid calling onChange if radio state changed
// from incoming value.
if (previousValue !== radio.state) {
onChange(radio.state);
}
}, [radio.state]); // Sync incoming value with radio.state.
use_update_effect(() => {
if (value !== radio.state) {
radio.setState(value);
}
}, [value]);
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_context.Provider, {
value: { ...radio,
isBlock: !isAdaptiveWidth,
size
}
}, (0,external_wp_element_namespaceObject.createElement)(RadioGroup, { ...radio,
"aria-label": label,
as: component,
...otherProps,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([containerRef, forwardedRef])
}, resizeListener, (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_backdrop, {
state: radio.state,
containerRef: containerRef,
containerWidth: sizes.width,
isAdaptiveWidth: isAdaptiveWidth
}), children));
}
const ToggleGroupControlAsRadioGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlAsRadioGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/as-button-group.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlAsButtonGroup({
children,
isAdaptiveWidth,
label,
onChange,
size,
value,
...otherProps
}, forwardedRef) {
const containerRef = (0,external_wp_element_namespaceObject.useRef)();
const [resizeListener, sizes] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const baseId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlAsButtonGroup, 'toggle-group-control-as-button-group').toString();
const [selectedValue, setSelectedValue] = (0,external_wp_element_namespaceObject.useState)(value);
const groupContext = {
baseId,
state: selectedValue,
setState: setSelectedValue
};
const previousValue = (0,external_wp_compose_namespaceObject.usePrevious)(value); // Propagate groupContext.state change.
use_update_effect(() => {
// Avoid calling onChange if groupContext state changed
// from incoming value.
if (previousValue !== groupContext.state) {
onChange(groupContext.state);
}
}, [groupContext.state]); // Sync incoming value with groupContext.state.
use_update_effect(() => {
if (value !== groupContext.state) {
groupContext.setState(value);
}
}, [value]);
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_context.Provider, {
value: { ...groupContext,
isBlock: !isAdaptiveWidth,
isDeselectable: true,
size
}
}, (0,external_wp_element_namespaceObject.createElement)(component, {
"aria-label": label,
...otherProps,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([containerRef, forwardedRef]),
role: "group"
}, resizeListener, (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_backdrop, {
state: groupContext.state,
containerRef: containerRef,
containerWidth: sizes.width,
isAdaptiveWidth: isAdaptiveWidth
}), children));
}
const ToggleGroupControlAsButtonGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlAsButtonGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const component_noop = () => {};
function UnconnectedToggleGroupControl(props, forwardedRef) {
const {
__nextHasNoMarginBottom = false,
className,
isAdaptiveWidth = false,
isBlock = false,
isDeselectable = false,
label,
hideLabelFromVision = false,
help,
onChange = component_noop,
size = 'default',
value,
children,
...otherProps
} = useContextSystem(props, 'ToggleGroupControl');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(ToggleGroupControl({
isBlock,
isDeselectable,
size
}), isBlock && toggle_group_control_styles_block, className), [className, cx, isBlock, isDeselectable, size]);
const MainControl = isDeselectable ? ToggleGroupControlAsButtonGroup : ToggleGroupControlAsRadioGroup;
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
help: help,
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, !hideLabelFromVision && (0,external_wp_element_namespaceObject.createElement)(VisualLabelWrapper, null, (0,external_wp_element_namespaceObject.createElement)(base_control.VisualLabel, null, label)), (0,external_wp_element_namespaceObject.createElement)(MainControl, { ...otherProps,
children: children,
className: classes,
isAdaptiveWidth: isAdaptiveWidth,
label: label,
onChange: onChange,
ref: forwardedRef,
size: size,
value: value
}));
}
/**
* `ToggleGroupControl` is a form component that lets users choose options
* represented in horizontal segments. To render options for this control use
* `ToggleGroupControlOption` component.
*
* This component is intended for selecting a single persistent value from a set of options,
* similar to a how a radio button group would work. If you simply want a toggle to switch between views,
* use a `TabPanel` instead.
*
* Only use this control when you know for sure the labels of items inside won't
* wrap. For items with longer labels, you can consider a `SelectControl` or a
* `CustomSelectControl` component instead.
*
* ```jsx
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOption as ToggleGroupControlOption,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ToggleGroupControl label="my label" value="vertical" isBlock>
* <ToggleGroupControlOption value="horizontal" label="Horizontal" />
* <ToggleGroupControlOption value="vertical" label="Vertical" />
* </ToggleGroupControl>
* );
* }
* ```
*/
const component_ToggleGroupControl = contextConnect(UnconnectedToggleGroupControl, 'ToggleGroupControl');
/* harmony default export */ var toggle_group_control_component = (component_ToggleGroupControl);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Radio/Radio.js
function getChecked(options) {
if (typeof options.checked !== "undefined") {
return options.checked;
}
return typeof options.value !== "undefined" && options.state === options.value;
}
function useInitialChecked(options) {
var _React$useState = (0,external_React_.useState)(function () {
return getChecked(options);
}),
initialChecked = _React$useState[0];
var _React$useState2 = (0,external_React_.useState)(options.currentId),
initialCurrentId = _React$useState2[0];
var id = options.id,
setCurrentId = options.setCurrentId;
(0,external_React_.useEffect)(function () {
if (initialChecked && id && initialCurrentId !== id) {
setCurrentId === null || setCurrentId === void 0 ? void 0 : setCurrentId(id);
}
}, [initialChecked, id, setCurrentId, initialCurrentId]);
}
function fireChange(element, onChange) {
var event = createEvent(element, "change");
Object.defineProperties(event, {
type: {
value: "change"
},
target: {
value: element
},
currentTarget: {
value: element
}
});
onChange === null || onChange === void 0 ? void 0 : onChange(event);
}
var useRadio = createHook({
name: "Radio",
compose: useCompositeItem,
keys: RADIO_KEYS,
useOptions: function useOptions(_ref, _ref2) {
var _options$value;
var value = _ref2.value,
checked = _ref2.checked;
var _ref$unstable_clickOn = _ref.unstable_clickOnEnter,
unstable_clickOnEnter = _ref$unstable_clickOn === void 0 ? false : _ref$unstable_clickOn,
_ref$unstable_checkOn = _ref.unstable_checkOnFocus,
unstable_checkOnFocus = _ref$unstable_checkOn === void 0 ? true : _ref$unstable_checkOn,
options = _objectWithoutPropertiesLoose(_ref, ["unstable_clickOnEnter", "unstable_checkOnFocus"]);
return _objectSpread2(_objectSpread2({
checked: checked,
unstable_clickOnEnter: unstable_clickOnEnter,
unstable_checkOnFocus: unstable_checkOnFocus
}, options), {}, {
value: (_options$value = options.value) != null ? _options$value : value
});
},
useProps: function useProps(options, _ref3) {
var htmlRef = _ref3.ref,
htmlOnChange = _ref3.onChange,
htmlOnClick = _ref3.onClick,
htmlProps = _objectWithoutPropertiesLoose(_ref3, ["ref", "onChange", "onClick"]);
var ref = (0,external_React_.useRef)(null);
var _React$useState3 = (0,external_React_.useState)(true),
isNativeRadio = _React$useState3[0],
setIsNativeRadio = _React$useState3[1];
var checked = getChecked(options);
var isCurrentItemRef = useLiveRef(options.currentId === options.id);
var onChangeRef = useLiveRef(htmlOnChange);
var onClickRef = useLiveRef(htmlOnClick);
useInitialChecked(options);
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (!element) {
false ? 0 : void 0;
return;
}
if (element.tagName !== "INPUT" || element.type !== "radio") {
setIsNativeRadio(false);
}
}, []);
var onChange = (0,external_React_.useCallback)(function (event) {
var _onChangeRef$current, _options$setState;
(_onChangeRef$current = onChangeRef.current) === null || _onChangeRef$current === void 0 ? void 0 : _onChangeRef$current.call(onChangeRef, event);
if (event.defaultPrevented) return;
if (options.disabled) return;
(_options$setState = options.setState) === null || _options$setState === void 0 ? void 0 : _options$setState.call(options, options.value);
}, [options.disabled, options.setState, options.value]);
var onClick = (0,external_React_.useCallback)(function (event) {
var _onClickRef$current;
(_onClickRef$current = onClickRef.current) === null || _onClickRef$current === void 0 ? void 0 : _onClickRef$current.call(onClickRef, event);
if (event.defaultPrevented) return;
if (isNativeRadio) return;
fireChange(event.currentTarget, onChange);
}, [onChange, isNativeRadio]);
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (!element) return;
if (options.unstable_moves && isCurrentItemRef.current && options.unstable_checkOnFocus) {
fireChange(element, onChange);
}
}, [options.unstable_moves, options.unstable_checkOnFocus, onChange]);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
role: !isNativeRadio ? "radio" : undefined,
type: isNativeRadio ? "radio" : undefined,
value: isNativeRadio ? options.value : undefined,
name: isNativeRadio ? options.baseId : undefined,
"aria-checked": checked,
checked: checked,
onChange: onChange,
onClick: onClick
}, htmlProps);
}
});
var Radio = createComponent({
as: "input",
memo: true,
useHook: useRadio
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-base/styles.js
function toggle_group_control_option_base_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const LabelView = createStyled("div", true ? {
target: "et6ln9s1"
} : 0)( true ? {
name: "sln1fl",
styles: "display:inline-flex;max-width:100%;min-width:0;position:relative"
} : 0);
const labelBlock = true ? {
name: "82a6rk",
styles: "flex:1"
} : 0;
const buttonView = ({
isDeselectable,
isIcon,
isPressed,
size
}) => /*#__PURE__*/emotion_react_browser_esm_css("align-items:center;appearance:none;background:transparent;border:none;border-radius:", config_values.controlBorderRadius, ";color:", COLORS.gray[700], ";fill:currentColor;cursor:pointer;display:flex;font-family:inherit;height:100%;justify-content:center;line-height:100%;outline:none;padding:0 12px;position:relative;text-align:center;transition:background ", config_values.transitionDurationFast, " linear,color ", config_values.transitionDurationFast, " linear,font-weight 60ms linear;", reduceMotion('transition'), " user-select:none;width:100%;z-index:2;&::-moz-focus-inner{border:0;}&:active{background:", config_values.toggleGroupControlBackgroundColor, ";}", isDeselectable && deselectable, " ", isIcon && isIconStyles({
size
}), " ", isPressed && pressed, ";" + ( true ? "" : 0), true ? "" : 0);
const pressed = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.white, ";&:active{background:transparent;}" + ( true ? "" : 0), true ? "" : 0);
const deselectable = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";&:focus{box-shadow:inset 0 0 0 1px ", COLORS.white, ",0 0 0 ", config_values.borderWidthFocus, " ", COLORS.ui.theme, ";outline:2px solid transparent;}" + ( true ? "" : 0), true ? "" : 0);
const ButtonContentView = createStyled("div", true ? {
target: "et6ln9s0"
} : 0)("display:flex;font-size:", config_values.fontSize, ";line-height:1;" + ( true ? "" : 0));
const isIconStyles = ({
size = 'default'
}) => {
const iconButtonSizes = {
default: '30px',
'__unstable-large': '34px'
};
return /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";width:", iconButtonSizes[size], ";padding-left:0;padding-right:0;" + ( true ? "" : 0), true ? "" : 0);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-base/component.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
ButtonContentView: component_ButtonContentView,
LabelView: component_LabelView
} = toggle_group_control_option_base_styles_namespaceObject;
const WithToolTip = ({
showTooltip,
text,
children
}) => {
if (showTooltip && text) {
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: text,
position: "top center"
}, children);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children);
};
function ToggleGroupControlOptionBase(props, forwardedRef) {
const toggleGroupControlContext = useToggleGroupControlContext();
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlOptionBase, toggleGroupControlContext.baseId || 'toggle-group-control-option-base');
const buttonProps = useContextSystem({ ...props,
id
}, 'ToggleGroupControlOptionBase');
const {
isBlock = false,
isDeselectable = false,
size = 'default',
...otherContextProps
/* context props for Ariakit Radio */
} = toggleGroupControlContext;
const {
className,
isIcon = false,
value,
children,
showTooltip = false,
...otherButtonProps
} = buttonProps;
const isPressed = otherContextProps.state === value;
const cx = useCx();
const labelViewClasses = cx(isBlock && labelBlock);
const classes = cx(buttonView({
isDeselectable,
isIcon,
isPressed,
size
}), className);
const buttonOnClick = () => {
if (isDeselectable && isPressed) {
otherContextProps.setState(undefined);
} else {
otherContextProps.setState(value);
}
};
const commonProps = { ...otherButtonProps,
className: classes,
'data-value': value,
ref: forwardedRef
};
return (0,external_wp_element_namespaceObject.createElement)(component_LabelView, {
className: labelViewClasses
}, (0,external_wp_element_namespaceObject.createElement)(WithToolTip, {
showTooltip: showTooltip,
text: otherButtonProps['aria-label']
}, isDeselectable ? (0,external_wp_element_namespaceObject.createElement)("button", { ...commonProps,
"aria-pressed": isPressed,
type: "button",
onClick: buttonOnClick
}, (0,external_wp_element_namespaceObject.createElement)(component_ButtonContentView, null, children)) : (0,external_wp_element_namespaceObject.createElement)(Radio, { ...commonProps,
...otherContextProps
/* these are only for Ariakit Radio */
,
as: "button",
value: value
}, (0,external_wp_element_namespaceObject.createElement)(component_ButtonContentView, null, children))));
}
/**
* `ToggleGroupControlOptionBase` is a form component and is meant to be used as an internal,
* generic component for any children of `ToggleGroupControl`.
*
* @example
* ```jsx
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOptionBase as ToggleGroupControlOptionBase,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ToggleGroupControl label="my label" value="vertical" isBlock>
* <ToggleGroupControlOption value="horizontal" label="Horizontal" />
* <ToggleGroupControlOption value="vertical" label="Vertical" />
* </ToggleGroupControl>
* );
* }
* ```
*/
const ConnectedToggleGroupControlOptionBase = contextConnect(ToggleGroupControlOptionBase, 'ToggleGroupControlOptionBase');
/* harmony default export */ var toggle_group_control_option_base_component = (ConnectedToggleGroupControlOptionBase);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlOption(props, ref) {
const {
label,
...restProps
} = props;
const optionLabel = restProps['aria-label'] || label;
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_option_base_component, { ...restProps,
"aria-label": optionLabel,
ref: ref
}, label);
}
/**
* `ToggleGroupControlOption` is a form component and is meant to be used as a
* child of `ToggleGroupControl`.
*
* ```jsx
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOption as ToggleGroupControlOption,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ToggleGroupControl label="my label" value="vertical" isBlock>
* <ToggleGroupControlOption value="horizontal" label="Horizontal" />
* <ToggleGroupControlOption value="vertical" label="Vertical" />
* </ToggleGroupControl>
* );
* }
* ```
*/
const ToggleGroupControlOption = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlOption);
/* harmony default export */ var toggle_group_control_option_component = (ToggleGroupControlOption);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/constants.js
/**
* WordPress dependencies
*/
/**
* List of T-shirt abbreviations.
*
* When there are 5 font sizes or fewer, we assume that the font sizes are
* ordered by size and show T-shirt labels.
*/
const T_SHIRT_ABBREVIATIONS = [
/* translators: S stands for 'small' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('S'),
/* translators: M stands for 'medium' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('M'),
/* translators: L stands for 'large' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('L'),
/* translators: XL stands for 'extra large' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('XL'),
/* translators: XXL stands for 'extra extra large' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('XXL')];
/**
* List of T-shirt names.
*
* When there are 5 font sizes or fewer, we assume that the font sizes are
* ordered by size and show T-shirt labels.
*/
const T_SHIRT_NAMES = [(0,external_wp_i18n_namespaceObject.__)('Small'), (0,external_wp_i18n_namespaceObject.__)('Medium'), (0,external_wp_i18n_namespaceObject.__)('Large'), (0,external_wp_i18n_namespaceObject.__)('Extra Large'), (0,external_wp_i18n_namespaceObject.__)('Extra Extra Large')];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/font-size-picker-toggle-group.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const FontSizePickerToggleGroup = props => {
const {
fontSizes,
value,
__nextHasNoMarginBottom,
size,
onChange
} = props;
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_component, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: (0,external_wp_i18n_namespaceObject.__)('Font size'),
hideLabelFromVision: true,
value: value,
onChange: onChange,
isBlock: true,
size: size
}, fontSizes.map((fontSize, index) => (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_option_component, {
key: fontSize.slug,
value: fontSize.size,
label: T_SHIRT_ABBREVIATIONS[index],
"aria-label": fontSize.name || T_SHIRT_NAMES[index],
showTooltip: true
})));
};
/* harmony default export */ var font_size_picker_toggle_group = (FontSizePickerToggleGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const UnforwardedFontSizePicker = (props, ref) => {
const {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMarginBottom = false,
fallbackFontSize,
fontSizes = [],
disableCustomFontSizes = false,
onChange,
size = 'default',
units: unitsProp,
value,
withSlider = false,
withReset = true
} = props;
if (!__nextHasNoMarginBottom) {
external_wp_deprecated_default()('Bottom margin styles for wp.components.FontSizePicker', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version.'
});
}
const units = useCustomUnits({
availableUnits: unitsProp || ['px', 'em', 'rem']
});
const shouldUseSelectControl = fontSizes.length > 5;
const selectedFontSize = fontSizes.find(fontSize => fontSize.size === value);
const isCustomValue = !!value && !selectedFontSize;
const [showCustomValueControl, setShowCustomValueControl] = (0,external_wp_element_namespaceObject.useState)(!disableCustomFontSizes && isCustomValue);
const headerHint = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (showCustomValueControl) {
return (0,external_wp_i18n_namespaceObject.__)('Custom');
}
if (!shouldUseSelectControl) {
if (selectedFontSize) {
return selectedFontSize.name || T_SHIRT_NAMES[fontSizes.indexOf(selectedFontSize)];
}
return '';
}
const commonUnit = getCommonSizeUnit(fontSizes);
if (commonUnit) {
return `(${commonUnit})`;
}
return '';
}, [showCustomValueControl, shouldUseSelectControl, selectedFontSize, fontSizes]);
if (fontSizes.length === 0 && disableCustomFontSizes) {
return null;
} // If neither the value or first font size is a string, then FontSizePicker
// operates in a legacy "unitless" mode where UnitControl can only be used
// to select px values and onChange() is always called with number values.
const hasUnits = typeof value === 'string' || typeof fontSizes[0]?.size === 'string';
const [valueQuantity, valueUnit] = parseQuantityAndUnitFromRawValue(value, units);
const isValueUnitRelative = !!valueUnit && ['em', 'rem'].includes(valueUnit);
return (0,external_wp_element_namespaceObject.createElement)(styles_Container, {
ref: ref,
className: "components-font-size-picker"
}, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Font size')), (0,external_wp_element_namespaceObject.createElement)(spacer_component, null, (0,external_wp_element_namespaceObject.createElement)(font_size_picker_styles_Header, {
className: "components-font-size-picker__header"
}, (0,external_wp_element_namespaceObject.createElement)(HeaderLabel, {
"aria-label": `${(0,external_wp_i18n_namespaceObject.__)('Size')} ${headerHint || ''}`
}, (0,external_wp_i18n_namespaceObject.__)('Size'), headerHint && (0,external_wp_element_namespaceObject.createElement)(HeaderHint, {
className: "components-font-size-picker__header__hint"
}, headerHint)), !disableCustomFontSizes && (0,external_wp_element_namespaceObject.createElement)(HeaderToggle, {
label: showCustomValueControl ? (0,external_wp_i18n_namespaceObject.__)('Use size preset') : (0,external_wp_i18n_namespaceObject.__)('Set custom size'),
icon: library_settings,
onClick: () => {
setShowCustomValueControl(!showCustomValueControl);
},
isPressed: showCustomValueControl,
isSmall: true
}))), (0,external_wp_element_namespaceObject.createElement)(Controls, {
className: "components-font-size-picker__controls",
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, !!fontSizes.length && shouldUseSelectControl && !showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(font_size_picker_select, {
fontSizes: fontSizes,
value: value,
disableCustomFontSizes: disableCustomFontSizes,
size: size,
onChange: newValue => {
if (newValue === undefined) {
onChange?.(undefined);
} else {
onChange?.(hasUnits ? newValue : Number(newValue), fontSizes.find(fontSize => fontSize.size === newValue));
}
},
onSelectCustom: () => setShowCustomValueControl(true)
}), !shouldUseSelectControl && !showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(font_size_picker_toggle_group, {
fontSizes: fontSizes,
value: value,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
size: size,
onChange: newValue => {
if (newValue === undefined) {
onChange?.(undefined);
} else {
onChange?.(hasUnits ? newValue : Number(newValue), fontSizes.find(fontSize => fontSize.size === newValue));
}
}
}), !disableCustomFontSizes && showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(flex_component, {
className: "components-font-size-picker__custom-size-control"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(unit_control, {
label: (0,external_wp_i18n_namespaceObject.__)('Custom'),
labelPosition: "top",
hideLabelFromVision: true,
value: value,
onChange: newValue => {
if (newValue === undefined) {
onChange?.(undefined);
} else {
onChange?.(hasUnits ? newValue : parseInt(newValue, 10));
}
},
size: size,
units: hasUnits ? units : [],
min: 0
})), withSlider && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginX: 2,
marginBottom: 0
}, (0,external_wp_element_namespaceObject.createElement)(range_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: "components-font-size-picker__custom-input",
label: (0,external_wp_i18n_namespaceObject.__)('Custom Size'),
hideLabelFromVision: true,
value: valueQuantity,
initialPosition: fallbackFontSize,
withInputField: false,
onChange: newValue => {
if (newValue === undefined) {
onChange?.(undefined);
} else if (hasUnits) {
onChange?.(newValue + (valueUnit !== null && valueUnit !== void 0 ? valueUnit : 'px'));
} else {
onChange?.(newValue);
}
},
min: 0,
max: isValueUnitRelative ? 10 : 100,
step: isValueUnitRelative ? 0.1 : 1
}))), withReset && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(Button, {
disabled: value === undefined,
onClick: () => {
onChange?.(undefined);
},
variant: "secondary",
__next40pxDefaultSize: true,
size: size !== '__unstable-large' ? 'small' : 'default'
}, (0,external_wp_i18n_namespaceObject.__)('Reset'))))));
};
const FontSizePicker = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedFontSizePicker);
/* harmony default export */ var font_size_picker = (FontSizePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-file-upload/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* FormFileUpload is a component that allows users to select files from their local device.
*
* ```jsx
* import { FormFileUpload } from '@wordpress/components';
*
* const MyFormFileUpload = () => (
* <FormFileUpload
* accept="image/*"
* onChange={ ( event ) => console.log( event.currentTarget.files ) }
* >
* Upload
* </FormFileUpload>
* );
* ```
*/
function FormFileUpload({
accept,
children,
multiple = false,
onChange,
onClick,
render,
...props
}) {
const ref = (0,external_wp_element_namespaceObject.useRef)(null);
const openFileDialog = () => {
ref.current?.click();
};
const ui = render ? render({
openFileDialog
}) : (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: openFileDialog,
...props
}, children);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-form-file-upload"
}, ui, (0,external_wp_element_namespaceObject.createElement)("input", {
type: "file",
ref: ref,
multiple: multiple,
style: {
display: 'none'
},
accept: accept,
onChange: onChange,
onClick: onClick,
"data-testid": "form-file-upload-input"
}));
}
/* harmony default export */ var form_file_upload = (FormFileUpload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-toggle/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const form_toggle_noop = () => {};
/**
* FormToggle switches a single setting on or off.
*
* ```jsx
* import { FormToggle } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyFormToggle = () => {
* const [ isChecked, setChecked ] = useState( true );
*
* return (
* <FormToggle
* checked={ isChecked }
* onChange={ () => setChecked( ( state ) => ! state ) }
* />
* );
* };
* ```
*/
function FormToggle(props) {
const {
className,
checked,
id,
disabled,
onChange = form_toggle_noop,
...additionalProps
} = props;
const wrapperClasses = classnames_default()('components-form-toggle', className, {
'is-checked': checked,
'is-disabled': disabled
});
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: wrapperClasses
}, (0,external_wp_element_namespaceObject.createElement)("input", {
className: "components-form-toggle__input",
id: id,
type: "checkbox",
checked: checked,
onChange: onChange,
disabled: disabled,
...additionalProps
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-form-toggle__track"
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-form-toggle__thumb"
}));
}
/* harmony default export */ var form_toggle = (FormToggle);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/token.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const token_noop = () => {};
function Token({
value,
status,
title,
displayTransform,
isBorderless = false,
disabled = false,
onClickRemove = token_noop,
onMouseEnter,
onMouseLeave,
messages,
termPosition,
termsCount
}) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Token);
const tokenClasses = classnames_default()('components-form-token-field__token', {
'is-error': 'error' === status,
'is-success': 'success' === status,
'is-validating': 'validating' === status,
'is-borderless': isBorderless,
'is-disabled': disabled
});
const onClick = () => onClickRemove({
value
});
const transformedValue = displayTransform(value);
const termPositionAndCount = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: term name, 2: term position in a set of terms, 3: total term set count. */
(0,external_wp_i18n_namespaceObject.__)('%1$s (%2$s of %3$s)'), transformedValue, termPosition, termsCount);
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: tokenClasses,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
title: title
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-form-token-field__token-text",
id: `components-form-token-field__token-text-${instanceId}`
}, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "span"
}, termPositionAndCount), (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-hidden": "true"
}, transformedValue)), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-form-token-field__remove-token",
icon: close_small,
onClick: !disabled ? onClick : undefined,
label: messages.remove,
"aria-describedby": `components-form-token-field__token-text-${instanceId}`
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const deprecatedPaddings = ({
__next40pxDefaultSize,
hasTokens
}) => !__next40pxDefaultSize && /*#__PURE__*/emotion_react_browser_esm_css("padding-top:", space(hasTokens ? 1 : 0.5), ";padding-bottom:", space(hasTokens ? 1 : 0.5), ";" + ( true ? "" : 0), true ? "" : 0);
const TokensAndInputWrapperFlex = /*#__PURE__*/createStyled(flex_component, true ? {
target: "ehq8nmi0"
} : 0)("padding:7px;", deprecatedPaddings, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const form_token_field_identity = value => value;
/**
* A `FormTokenField` is a field similar to the tags and categories fields in the interim editor chrome,
* or the "to" field in Mail on OS X. Tokens can be entered by typing them or selecting them from a list of suggested tokens.
*
* Up to one hundred suggestions that match what the user has typed so far will be shown from which the user can pick from (auto-complete).
* Tokens are separated by the "," character. Suggestions can be selected with the up or down arrows and added with the tab or enter key.
*
* The `value` property is handled in a manner similar to controlled form components.
* See [Forms](http://facebook.github.io/react/docs/forms.html) in the React Documentation for more information.
*/
function FormTokenField(props) {
const {
autoCapitalize,
autoComplete,
maxLength,
placeholder,
label = (0,external_wp_i18n_namespaceObject.__)('Add item'),
className,
suggestions = [],
maxSuggestions = 100,
value = [],
displayTransform = form_token_field_identity,
saveTransform = token => token.trim(),
onChange = () => {},
onInputChange = () => {},
onFocus = undefined,
isBorderless = false,
disabled = false,
tokenizeOnSpace = false,
messages = {
added: (0,external_wp_i18n_namespaceObject.__)('Item added.'),
removed: (0,external_wp_i18n_namespaceObject.__)('Item removed.'),
remove: (0,external_wp_i18n_namespaceObject.__)('Remove item'),
__experimentalInvalid: (0,external_wp_i18n_namespaceObject.__)('Invalid item')
},
__experimentalRenderItem,
__experimentalExpandOnFocus = false,
__experimentalValidateInput = () => true,
__experimentalShowHowTo = true,
__next40pxDefaultSize = false,
__experimentalAutoSelectFirstMatch = false,
__nextHasNoMarginBottom = false
} = useDeprecated36pxDefaultSizeProp(props, 'wp.components.FormTokenField');
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(FormTokenField); // We reset to these initial values again in the onBlur
const [incompleteTokenValue, setIncompleteTokenValue] = (0,external_wp_element_namespaceObject.useState)('');
const [inputOffsetFromEnd, setInputOffsetFromEnd] = (0,external_wp_element_namespaceObject.useState)(0);
const [isActive, setIsActive] = (0,external_wp_element_namespaceObject.useState)(false);
const [isExpanded, setIsExpanded] = (0,external_wp_element_namespaceObject.useState)(false);
const [selectedSuggestionIndex, setSelectedSuggestionIndex] = (0,external_wp_element_namespaceObject.useState)(-1);
const [selectedSuggestionScroll, setSelectedSuggestionScroll] = (0,external_wp_element_namespaceObject.useState)(false);
const prevSuggestions = (0,external_wp_compose_namespaceObject.usePrevious)(suggestions);
const prevValue = (0,external_wp_compose_namespaceObject.usePrevious)(value);
const input = (0,external_wp_element_namespaceObject.useRef)(null);
const tokensAndInput = (0,external_wp_element_namespaceObject.useRef)(null);
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Make sure to focus the input when the isActive state is true.
if (isActive && !hasFocus()) {
focus();
}
}, [isActive]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const suggestionsDidUpdate = !external_wp_isShallowEqual_default()(suggestions, prevSuggestions || []);
if (suggestionsDidUpdate || value !== prevValue) {
updateSuggestions(suggestionsDidUpdate);
} // TODO: updateSuggestions() should first be refactored so its actual deps are clearer.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [suggestions, prevSuggestions, value, prevValue]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
updateSuggestions(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [incompleteTokenValue]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
updateSuggestions(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [__experimentalAutoSelectFirstMatch]);
if (disabled && isActive) {
setIsActive(false);
setIncompleteTokenValue('');
}
function focus() {
input.current?.focus();
}
function hasFocus() {
return input.current === input.current?.ownerDocument.activeElement;
}
function onFocusHandler(event) {
// If focus is on the input or on the container, set the isActive state to true.
if (hasFocus() || event.target === tokensAndInput.current) {
setIsActive(true);
setIsExpanded(__experimentalExpandOnFocus || isExpanded);
} else {
/*
* Otherwise, focus is on one of the token "remove" buttons and we
* set the isActive state to false to prevent the input to be
* re-focused, see componentDidUpdate().
*/
setIsActive(false);
}
if ('function' === typeof onFocus) {
onFocus(event);
}
}
function onBlur() {
if (inputHasValidValue() && __experimentalValidateInput(incompleteTokenValue)) {
setIsActive(false);
} else {
// Reset to initial state
setIncompleteTokenValue('');
setInputOffsetFromEnd(0);
setIsActive(false);
setIsExpanded(false);
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
}
}
function onKeyDown(event) {
let preventDefault = false;
if (event.defaultPrevented || // Ignore keydowns from IMEs
event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
switch (event.key) {
case 'Backspace':
preventDefault = handleDeleteKey(deleteTokenBeforeInput);
break;
case 'Enter':
preventDefault = addCurrentToken();
break;
case 'ArrowLeft':
preventDefault = handleLeftArrowKey();
break;
case 'ArrowUp':
preventDefault = handleUpArrowKey();
break;
case 'ArrowRight':
preventDefault = handleRightArrowKey();
break;
case 'ArrowDown':
preventDefault = handleDownArrowKey();
break;
case 'Delete':
preventDefault = handleDeleteKey(deleteTokenAfterInput);
break;
case 'Space':
if (tokenizeOnSpace) {
preventDefault = addCurrentToken();
}
break;
case 'Escape':
preventDefault = handleEscapeKey(event);
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
}
function onKeyPress(event) {
let preventDefault = false;
switch (event.key) {
case ',':
preventDefault = handleCommaKey();
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
}
function onContainerTouched(event) {
// Prevent clicking/touching the tokensAndInput container from blurring
// the input and adding the current token.
if (event.target === tokensAndInput.current && isActive) {
event.preventDefault();
}
}
function onTokenClickRemove(event) {
deleteToken(event.value);
focus();
}
function onSuggestionHovered(suggestion) {
const index = getMatchingSuggestions().indexOf(suggestion);
if (index >= 0) {
setSelectedSuggestionIndex(index);
setSelectedSuggestionScroll(false);
}
}
function onSuggestionSelected(suggestion) {
addNewToken(suggestion);
}
function onInputChangeHandler(event) {
const text = event.value;
const separator = tokenizeOnSpace ? /[ ,\t]+/ : /[,\t]+/;
const items = text.split(separator);
const tokenValue = items[items.length - 1] || '';
if (items.length > 1) {
addNewTokens(items.slice(0, -1));
}
setIncompleteTokenValue(tokenValue);
onInputChange(tokenValue);
}
function handleDeleteKey(_deleteToken) {
let preventDefault = false;
if (hasFocus() && isInputEmpty()) {
_deleteToken();
preventDefault = true;
}
return preventDefault;
}
function handleLeftArrowKey() {
let preventDefault = false;
if (isInputEmpty()) {
moveInputBeforePreviousToken();
preventDefault = true;
}
return preventDefault;
}
function handleRightArrowKey() {
let preventDefault = false;
if (isInputEmpty()) {
moveInputAfterNextToken();
preventDefault = true;
}
return preventDefault;
}
function handleUpArrowKey() {
setSelectedSuggestionIndex(index => {
return (index === 0 ? getMatchingSuggestions(incompleteTokenValue, suggestions, value, maxSuggestions, saveTransform).length : index) - 1;
});
setSelectedSuggestionScroll(true);
return true; // PreventDefault.
}
function handleDownArrowKey() {
setSelectedSuggestionIndex(index => {
return (index + 1) % getMatchingSuggestions(incompleteTokenValue, suggestions, value, maxSuggestions, saveTransform).length;
});
setSelectedSuggestionScroll(true);
return true; // PreventDefault.
}
function handleEscapeKey(event) {
if (event.target instanceof HTMLInputElement) {
setIncompleteTokenValue(event.target.value);
setIsExpanded(false);
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
}
return true; // PreventDefault.
}
function handleCommaKey() {
if (inputHasValidValue()) {
addNewToken(incompleteTokenValue);
}
return true; // PreventDefault.
}
function moveInputToIndex(index) {
setInputOffsetFromEnd(value.length - Math.max(index, -1) - 1);
}
function moveInputBeforePreviousToken() {
setInputOffsetFromEnd(prevInputOffsetFromEnd => {
return Math.min(prevInputOffsetFromEnd + 1, value.length);
});
}
function moveInputAfterNextToken() {
setInputOffsetFromEnd(prevInputOffsetFromEnd => {
return Math.max(prevInputOffsetFromEnd - 1, 0);
});
}
function deleteTokenBeforeInput() {
const index = getIndexOfInput() - 1;
if (index > -1) {
deleteToken(value[index]);
}
}
function deleteTokenAfterInput() {
const index = getIndexOfInput();
if (index < value.length) {
deleteToken(value[index]); // Update input offset since it's the offset from the last token.
moveInputToIndex(index);
}
}
function addCurrentToken() {
let preventDefault = false;
const selectedSuggestion = getSelectedSuggestion();
if (selectedSuggestion) {
addNewToken(selectedSuggestion);
preventDefault = true;
} else if (inputHasValidValue()) {
addNewToken(incompleteTokenValue);
preventDefault = true;
}
return preventDefault;
}
function addNewTokens(tokens) {
const tokensToAdd = [...new Set(tokens.map(saveTransform).filter(Boolean).filter(token => !valueContainsToken(token)))];
if (tokensToAdd.length > 0) {
const newValue = [...value];
newValue.splice(getIndexOfInput(), 0, ...tokensToAdd);
onChange(newValue);
}
}
function addNewToken(token) {
if (!__experimentalValidateInput(token)) {
(0,external_wp_a11y_namespaceObject.speak)(messages.__experimentalInvalid, 'assertive');
return;
}
addNewTokens([token]);
(0,external_wp_a11y_namespaceObject.speak)(messages.added, 'assertive');
setIncompleteTokenValue('');
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
setIsExpanded(!__experimentalExpandOnFocus);
if (isActive) {
focus();
}
}
function deleteToken(token) {
const newTokens = value.filter(item => {
return getTokenValue(item) !== getTokenValue(token);
});
onChange(newTokens);
(0,external_wp_a11y_namespaceObject.speak)(messages.removed, 'assertive');
}
function getTokenValue(token) {
if ('object' === typeof token) {
return token.value;
}
return token;
}
function getMatchingSuggestions(searchValue = incompleteTokenValue, _suggestions = suggestions, _value = value, _maxSuggestions = maxSuggestions, _saveTransform = saveTransform) {
let match = _saveTransform(searchValue);
const startsWithMatch = [];
const containsMatch = [];
const normalizedValue = _value.map(item => {
if (typeof item === 'string') {
return item;
}
return item.value;
});
if (match.length === 0) {
_suggestions = _suggestions.filter(suggestion => !normalizedValue.includes(suggestion));
} else {
match = match.toLocaleLowerCase();
_suggestions.forEach(suggestion => {
const index = suggestion.toLocaleLowerCase().indexOf(match);
if (normalizedValue.indexOf(suggestion) === -1) {
if (index === 0) {
startsWithMatch.push(suggestion);
} else if (index > 0) {
containsMatch.push(suggestion);
}
}
});
_suggestions = startsWithMatch.concat(containsMatch);
}
return _suggestions.slice(0, _maxSuggestions);
}
function getSelectedSuggestion() {
if (selectedSuggestionIndex !== -1) {
return getMatchingSuggestions()[selectedSuggestionIndex];
}
return undefined;
}
function valueContainsToken(token) {
return value.some(item => {
return getTokenValue(token) === getTokenValue(item);
});
}
function getIndexOfInput() {
return value.length - inputOffsetFromEnd;
}
function isInputEmpty() {
return incompleteTokenValue.length === 0;
}
function inputHasValidValue() {
return saveTransform(incompleteTokenValue).length > 0;
}
function updateSuggestions(resetSelectedSuggestion = true) {
const inputHasMinimumChars = incompleteTokenValue.trim().length > 1;
const matchingSuggestions = getMatchingSuggestions(incompleteTokenValue);
const hasMatchingSuggestions = matchingSuggestions.length > 0;
const shouldExpandIfFocuses = hasFocus() && __experimentalExpandOnFocus;
setIsExpanded(shouldExpandIfFocuses || inputHasMinimumChars && hasMatchingSuggestions);
if (resetSelectedSuggestion) {
if (__experimentalAutoSelectFirstMatch && inputHasMinimumChars && hasMatchingSuggestions) {
setSelectedSuggestionIndex(0);
setSelectedSuggestionScroll(true);
} else {
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
}
}
if (inputHasMinimumChars) {
const message = hasMatchingSuggestions ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', matchingSuggestions.length), matchingSuggestions.length) : (0,external_wp_i18n_namespaceObject.__)('No results.');
debouncedSpeak(message, 'assertive');
}
}
function renderTokensAndInput() {
const components = value.map(renderToken);
components.splice(getIndexOfInput(), 0, renderInput());
return components;
}
function renderToken(token, index, tokens) {
const _value = getTokenValue(token);
const status = typeof token !== 'string' ? token.status : undefined;
const termPosition = index + 1;
const termsCount = tokens.length;
return (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
key: 'token-' + _value
}, (0,external_wp_element_namespaceObject.createElement)(Token, {
value: _value,
status: status,
title: typeof token !== 'string' ? token.title : undefined,
displayTransform: displayTransform,
onClickRemove: onTokenClickRemove,
isBorderless: typeof token !== 'string' && token.isBorderless || isBorderless,
onMouseEnter: typeof token !== 'string' ? token.onMouseEnter : undefined,
onMouseLeave: typeof token !== 'string' ? token.onMouseLeave : undefined,
disabled: 'error' !== status && disabled,
messages: messages,
termsCount: termsCount,
termPosition: termPosition
}));
}
function renderInput() {
const inputProps = {
instanceId,
autoCapitalize,
autoComplete,
placeholder: value.length === 0 ? placeholder : '',
key: 'input',
disabled,
value: incompleteTokenValue,
onBlur,
isExpanded,
selectedSuggestionIndex
};
return (0,external_wp_element_namespaceObject.createElement)(token_input, { ...inputProps,
onChange: !(maxLength && value.length >= maxLength) ? onInputChangeHandler : undefined,
ref: input
});
}
const classes = classnames_default()(className, 'components-form-token-field__input-container', {
'is-active': isActive,
'is-disabled': disabled
});
let tokenFieldProps = {
className: 'components-form-token-field',
tabIndex: -1
};
const matchingSuggestions = getMatchingSuggestions();
if (!disabled) {
tokenFieldProps = Object.assign({}, tokenFieldProps, {
onKeyDown,
onKeyPress,
onFocus: onFocusHandler
});
} // Disable reason: There is no appropriate role which describes the
// input container intended accessible usability.
// TODO: Refactor click detection to use blur to stop propagation.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)("div", { ...tokenFieldProps
}, (0,external_wp_element_namespaceObject.createElement)(StyledLabel, {
htmlFor: `components-form-token-input-${instanceId}`,
className: "components-form-token-field__label"
}, label), (0,external_wp_element_namespaceObject.createElement)("div", {
ref: tokensAndInput,
className: classes,
tabIndex: -1,
onMouseDown: onContainerTouched,
onTouchStart: onContainerTouched
}, (0,external_wp_element_namespaceObject.createElement)(TokensAndInputWrapperFlex, {
justify: "flex-start",
align: "center",
gap: 1,
wrap: true,
__next40pxDefaultSize: __next40pxDefaultSize,
hasTokens: !!value.length
}, renderTokensAndInput()), isExpanded && (0,external_wp_element_namespaceObject.createElement)(suggestions_list, {
instanceId: instanceId,
match: saveTransform(incompleteTokenValue),
displayTransform: displayTransform,
suggestions: matchingSuggestions,
selectedIndex: selectedSuggestionIndex,
scrollIntoView: selectedSuggestionScroll,
onHover: onSuggestionHovered,
onSelect: onSuggestionSelected,
__experimentalRenderItem: __experimentalRenderItem
})), !__nextHasNoMarginBottom && (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: 2
}), __experimentalShowHowTo && (0,external_wp_element_namespaceObject.createElement)(StyledHelp, {
id: `components-form-token-suggestions-howto-${instanceId}`,
className: "components-form-token-field__help",
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, tokenizeOnSpace ? (0,external_wp_i18n_namespaceObject.__)('Separate with commas, spaces, or the Enter key.') : (0,external_wp_i18n_namespaceObject.__)('Separate with commas or the Enter key.')));
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
/* harmony default export */ var form_token_field = (FormTokenField);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/icons.js
/**
* WordPress dependencies
*/
const PageControlIcon = () => (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
width: "8",
height: "8",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Circle, {
cx: "4",
cy: "4",
r: "4"
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/page-control.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PageControl({
currentPage,
numberOfPages,
setCurrentPage
}) {
return (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "components-guide__page-control",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Guide controls')
}, Array.from({
length: numberOfPages
}).map((_, page) => (0,external_wp_element_namespaceObject.createElement)("li", {
key: page // Set aria-current="step" on the active page, see https://www.w3.org/TR/wai-aria-1.1/#aria-current
,
"aria-current": page === currentPage ? 'step' : undefined
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: page,
icon: (0,external_wp_element_namespaceObject.createElement)(PageControlIcon, null),
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: current page number 2: total number of pages */
(0,external_wp_i18n_namespaceObject.__)('Page %1$d of %2$d'), page + 1, numberOfPages),
onClick: () => setCurrentPage(page)
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* `Guide` is a React component that renders a _user guide_ in a modal. The guide consists of several pages which the user can step through one by one. The guide is finished when the modal is closed or when the user clicks _Finish_ on the last page of the guide.
*
* ```jsx
* function MyTutorial() {
* const [ isOpen, setIsOpen ] = useState( true );
*
* if ( ! isOpen ) {
* return null;
* }
*
* return (
* <Guide
* onFinish={ () => setIsOpen( false ) }
* pages={ [
* {
* content: <p>Welcome to the ACME Store!</p>,
* },
* {
* image: <img src="https://acmestore.com/add-to-cart.png" />,
* content: (
* <p>
* Click <i>Add to Cart</i> to buy a product.
* </p>
* ),
* },
* ] }
* />
* );
* }
* ```
*/
function Guide({
children,
className,
contentLabel,
finishButtonText = (0,external_wp_i18n_namespaceObject.__)('Finish'),
onFinish,
pages = []
}) {
const ref = (0,external_wp_element_namespaceObject.useRef)(null);
const [currentPage, setCurrentPage] = (0,external_wp_element_namespaceObject.useState)(0);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Place focus at the top of the guide on mount and when the page changes.
const frame = ref.current?.querySelector('.components-guide');
if (frame instanceof HTMLElement) {
frame.focus();
}
}, [currentPage]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (external_wp_element_namespaceObject.Children.count(children)) {
external_wp_deprecated_default()('Passing children to <Guide>', {
since: '5.5',
alternative: 'the `pages` prop'
});
}
}, [children]);
if (external_wp_element_namespaceObject.Children.count(children)) {
var _Children$map;
pages = (_Children$map = external_wp_element_namespaceObject.Children.map(children, child => ({
content: child
}))) !== null && _Children$map !== void 0 ? _Children$map : [];
}
const canGoBack = currentPage > 0;
const canGoForward = currentPage < pages.length - 1;
const goBack = () => {
if (canGoBack) {
setCurrentPage(currentPage - 1);
}
};
const goForward = () => {
if (canGoForward) {
setCurrentPage(currentPage + 1);
}
};
if (pages.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(modal, {
className: classnames_default()('components-guide', className),
contentLabel: contentLabel,
isDismissible: pages.length > 1,
onRequestClose: onFinish,
onKeyDown: event => {
if (event.code === 'ArrowLeft') {
goBack(); // Do not scroll the modal's contents.
event.preventDefault();
} else if (event.code === 'ArrowRight') {
goForward(); // Do not scroll the modal's contents.
event.preventDefault();
}
},
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-guide__container"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-guide__page"
}, pages[currentPage].image, pages.length > 1 && (0,external_wp_element_namespaceObject.createElement)(PageControl, {
currentPage: currentPage,
numberOfPages: pages.length,
setCurrentPage: setCurrentPage
}), pages[currentPage].content), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-guide__footer"
}, canGoBack && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-guide__back-button",
variant: "tertiary",
onClick: goBack
}, (0,external_wp_i18n_namespaceObject.__)('Previous')), canGoForward && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-guide__forward-button",
variant: "primary",
onClick: goForward
}, (0,external_wp_i18n_namespaceObject.__)('Next')), !canGoForward && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-guide__finish-button",
variant: "primary",
onClick: onFinish
}, finishButtonText))));
}
/* harmony default export */ var guide = (Guide);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/page.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function GuidePage(props) {
(0,external_wp_element_namespaceObject.useEffect)(() => {
external_wp_deprecated_default()('<GuidePage>', {
since: '5.5',
alternative: 'the `pages` prop in <Guide>'
});
}, []);
return (0,external_wp_element_namespaceObject.createElement)("div", { ...props
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button/deprecated.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedIconButton({
label,
labelPosition,
size,
tooltip,
...props
}, ref) {
external_wp_deprecated_default()('wp.components.IconButton', {
since: '5.4',
alternative: 'wp.components.Button',
version: '6.2'
});
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, { ...props,
ref: ref,
tooltipPosition: labelPosition,
iconSize: size,
showTooltip: tooltip !== undefined ? !!tooltip : undefined,
label: tooltip || label
});
}
/* harmony default export */ var deprecated = ((0,external_wp_element_namespaceObject.forwardRef)(UnforwardedIconButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function hook_useItem(props) {
const {
as: asProp,
className,
onClick,
role = 'listitem',
size: sizeProp,
...otherProps
} = useContextSystem(props, 'Item');
const {
spacedAround,
size: contextSize
} = useItemGroupContext();
const size = sizeProp || contextSize;
const as = asProp || (typeof onClick !== 'undefined' ? 'button' : 'div');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(as === 'button' && unstyledButton, itemSizes[size] || itemSizes.medium, item, spacedAround && styles_spacedAround, className), [as, className, cx, size, spacedAround]);
const wrapperClassName = cx(itemWrapper);
return {
as,
className: classes,
onClick,
wrapperClassName,
role,
...otherProps
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedItem(props, forwardedRef) {
const {
role,
wrapperClassName,
...otherProps
} = hook_useItem(props);
return (0,external_wp_element_namespaceObject.createElement)("div", {
role: role,
className: wrapperClassName
}, (0,external_wp_element_namespaceObject.createElement)(component, { ...otherProps,
ref: forwardedRef
}));
}
/**
* `Item` is used in combination with `ItemGroup` to display a list of items
* grouped and styled together.
*
* @example
* ```jsx
* import {
* __experimentalItemGroup as ItemGroup,
* __experimentalItem as Item,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ItemGroup>
* <Item>Code</Item>
* <Item>is</Item>
* <Item>Poetry</Item>
* </ItemGroup>
* );
* }
* ```
*/
const component_Item = contextConnect(UnconnectedItem, 'Item');
/* harmony default export */ var item_component = (component_Item);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-prefix-wrapper.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedInputControlPrefixWrapper(props, forwardedRef) {
const derivedProps = useContextSystem(props, 'InputControlPrefixWrapper');
return (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: 0,
...derivedProps,
ref: forwardedRef
});
}
/**
* A convenience wrapper for the `prefix` when you want to apply
* standard padding in accordance with the size variant.
*
* ```jsx
* import {
* __experimentalInputControl as InputControl,
* __experimentalInputControlPrefixWrapper as InputControlPrefixWrapper,
* } from '@wordpress/components';
*
* <InputControl
* prefix={<InputControlPrefixWrapper>@</InputControlPrefixWrapper>}
* />
* ```
*/
const InputControlPrefixWrapper = contextConnect(UnconnectedInputControlPrefixWrapper, 'InputControlPrefixWrapper');
/* harmony default export */ var input_prefix_wrapper = (InputControlPrefixWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/keyboard-shortcuts/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function KeyboardShortcut({
target,
callback,
shortcut,
bindGlobal,
eventName
}) {
(0,external_wp_compose_namespaceObject.useKeyboardShortcut)(shortcut, callback, {
bindGlobal,
target,
eventName
});
return null;
}
/**
* `KeyboardShortcuts` is a component which handles keyboard sequences during the lifetime of the rendering element.
*
* When passed children, it will capture key events which occur on or within the children. If no children are passed, events are captured on the document.
*
* It uses the [Mousetrap](https://craig.is/killing/mice) library to implement keyboard sequence bindings.
*
* ```jsx
* import { KeyboardShortcuts } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyKeyboardShortcuts = () => {
* const [ isAllSelected, setIsAllSelected ] = useState( false );
* const selectAll = () => {
* setIsAllSelected( true );
* };
*
* return (
* <div>
* <KeyboardShortcuts
* shortcuts={ {
* 'mod+a': selectAll,
* } }
* />
* [cmd/ctrl + A] Combination pressed? { isAllSelected ? 'Yes' : 'No' }
* </div>
* );
* };
* ```
*/
function KeyboardShortcuts({
children,
shortcuts,
bindGlobal,
eventName
}) {
const target = (0,external_wp_element_namespaceObject.useRef)(null);
const element = Object.entries(shortcuts !== null && shortcuts !== void 0 ? shortcuts : {}).map(([shortcut, callback]) => (0,external_wp_element_namespaceObject.createElement)(KeyboardShortcut, {
key: shortcut,
shortcut: shortcut,
callback: callback,
bindGlobal: bindGlobal,
eventName: eventName,
target: target
})); // Render as non-visual if there are no children pressed. Keyboard
// events will be bound to the document instead.
if (!external_wp_element_namespaceObject.Children.count(children)) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, element);
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: target
}, element, children);
}
/* harmony default export */ var keyboard_shortcuts = (KeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/menu-group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* `MenuGroup` wraps a series of related `MenuItem` components into a common
* section.
*
* ```jsx
* import { MenuGroup, MenuItem } from '@wordpress/components';
*
* const MyMenuGroup = () => (
* <MenuGroup label="Settings">
* <MenuItem>Setting 1</MenuItem>
* <MenuItem>Setting 2</MenuItem>
* </MenuGroup>
* );
* ```
*/
function MenuGroup(props) {
const {
children,
className = '',
label,
hideSeparator
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(MenuGroup);
if (!external_wp_element_namespaceObject.Children.count(children)) {
return null;
}
const labelId = `components-menu-group-label-${instanceId}`;
const classNames = classnames_default()(className, 'components-menu-group', {
'has-hidden-separator': hideSeparator
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classNames
}, label && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-menu-group__label",
id: labelId,
"aria-hidden": "true"
}, label), (0,external_wp_element_namespaceObject.createElement)("div", {
role: "group",
"aria-labelledby": label ? labelId : undefined
}, children));
}
/* harmony default export */ var menu_group = (MenuGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/menu-item/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MenuItem(props, ref) {
let {
children,
info,
className,
icon,
iconPosition = 'right',
shortcut,
isSelected,
role = 'menuitem',
suffix,
...buttonProps
} = props;
className = classnames_default()('components-menu-item__button', className);
if (info) {
children = (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__info-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__item"
}, children), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__info"
}, info));
}
if (icon && typeof icon !== 'string') {
icon = (0,external_wp_element_namespaceObject.cloneElement)(icon, {
className: classnames_default()('components-menu-items__item-icon', {
'has-icon-right': iconPosition === 'right'
})
});
}
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
ref: ref // Make sure aria-checked matches spec https://www.w3.org/TR/wai-aria-1.1/#aria-checked
,
"aria-checked": role === 'menuitemcheckbox' || role === 'menuitemradio' ? isSelected : undefined,
role: role,
icon: iconPosition === 'left' ? icon : undefined,
className: className,
...buttonProps
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__item"
}, children), !suffix && (0,external_wp_element_namespaceObject.createElement)(build_module_shortcut, {
className: "components-menu-item__shortcut",
shortcut: shortcut
}), !suffix && icon && iconPosition === 'right' && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}), suffix);
}
/* harmony default export */ var menu_item = ((0,external_wp_element_namespaceObject.forwardRef)(MenuItem));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/menu-items-choice/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const menu_items_choice_noop = () => {};
/**
* `MenuItemsChoice` functions similarly to a set of `MenuItem`s, but allows the user to select one option from a set of multiple choices.
*
*
* ```jsx
* import { MenuGroup, MenuItemsChoice } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyMenuItemsChoice = () => {
* const [ mode, setMode ] = useState( 'visual' );
* const choices = [
* {
* value: 'visual',
* label: 'Visual editor',
* },
* {
* value: 'text',
* label: 'Code editor',
* },
* ];
*
* return (
* <MenuGroup label="Editor">
* <MenuItemsChoice
* choices={ choices }
* value={ mode }
* onSelect={ ( newMode ) => setMode( newMode ) }
* />
* </MenuGroup>
* );
* };
* ```
*/
function MenuItemsChoice({
choices = [],
onHover = menu_items_choice_noop,
onSelect,
value
}) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, choices.map(item => {
const isSelected = value === item.value;
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: item.value,
role: "menuitemradio",
icon: isSelected && library_check,
info: item.info,
isSelected: isSelected,
shortcut: item.shortcut,
className: "components-menu-items-choice",
onClick: () => {
if (!isSelected) {
onSelect(item.value);
}
},
onMouseEnter: () => onHover(item.value),
onMouseLeave: () => onHover(null),
"aria-label": item['aria-label']
}, item.label);
}));
}
/* harmony default export */ var menu_items_choice = (MenuItemsChoice);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigable-container/tabbable.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedTabbableContainer({
eventToOffset,
...props
}, ref) {
const innerEventToOffset = evt => {
const {
code,
shiftKey
} = evt;
if ('Tab' === code) {
return shiftKey ? -1 : 1;
} // Allow custom handling of keys besides Tab.
//
// By default, TabbableContainer will move focus forward on Tab and
// backward on Shift+Tab. The handler below will be used for all other
// events. The semantics for `eventToOffset`'s return
// values are the following:
//
// - +1: move focus forward
// - -1: move focus backward
// - 0: don't move focus, but acknowledge event and thus stop it
// - undefined: do nothing, let the event propagate.
if (eventToOffset) {
return eventToOffset(evt);
}
return undefined;
};
return (0,external_wp_element_namespaceObject.createElement)(container, {
ref: ref,
stopNavigationEvents: true,
onlyBrowserTabstops: true,
eventToOffset: innerEventToOffset,
...props
});
}
/**
* A container for tabbable elements.
*
* ```jsx
* import {
* TabbableContainer,
* Button,
* } from '@wordpress/components';
*
* function onNavigate( index, target ) {
* console.log( `Navigates to ${ index }`, target );
* }
*
* const MyTabbableContainer = () => (
* <div>
* <span>Tabbable Container:</span>
* <TabbableContainer onNavigate={ onNavigate }>
* <Button variant="secondary" tabIndex="0">
* Section 1
* </Button>
* <Button variant="secondary" tabIndex="0">
* Section 2
* </Button>
* <Button variant="secondary" tabIndex="0">
* Section 3
* </Button>
* <Button variant="secondary" tabIndex="0">
* Section 4
* </Button>
* </TabbableContainer>
* </div>
* );
* ```
*/
const TabbableContainer = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTabbableContainer);
/* harmony default export */ var tabbable = (TabbableContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/constants.js
const ROOT_MENU = 'root';
const SEARCH_FOCUS_DELAY = 100;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const context_noop = () => {};
const defaultIsEmpty = () => false;
const defaultGetter = () => undefined;
const NavigationContext = (0,external_wp_element_namespaceObject.createContext)({
activeItem: undefined,
activeMenu: ROOT_MENU,
setActiveMenu: context_noop,
navigationTree: {
items: {},
getItem: defaultGetter,
addItem: context_noop,
removeItem: context_noop,
menus: {},
getMenu: defaultGetter,
addMenu: context_noop,
removeMenu: context_noop,
childMenu: {},
traverseMenu: context_noop,
isMenuEmpty: defaultIsEmpty
}
});
const useNavigationContext = () => (0,external_wp_element_namespaceObject.useContext)(NavigationContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/search.js
/**
* WordPress dependencies
*/
const search = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M13 5c-3.3 0-6 2.7-6 6 0 1.4.5 2.7 1.3 3.7l-3.8 3.8 1.1 1.1 3.8-3.8c1 .8 2.3 1.3 3.7 1.3 3.3 0 6-2.7 6-6S16.3 5 13 5zm0 10.5c-2.5 0-4.5-2-4.5-4.5s2-4.5 4.5-4.5 4.5 2 4.5 4.5-2 4.5-4.5 4.5z"
}));
/* harmony default export */ var library_search = (search);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/search-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedSearchControl({
__nextHasNoMarginBottom,
className,
onChange,
onKeyDown,
value,
label,
placeholder = (0,external_wp_i18n_namespaceObject.__)('Search'),
hideLabelFromVision = true,
help,
onClose,
...restProps
}, forwardedRef) {
const searchRef = (0,external_wp_element_namespaceObject.useRef)();
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(SearchControl);
const id = `components-search-control-${instanceId}`;
const renderRightButton = () => {
if (onClose) {
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Close search'),
onClick: onClose
});
}
if (!!value) {
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Reset search'),
onClick: () => {
onChange('');
searchRef.current?.focus();
}
});
}
return (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_search
});
};
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
id: id,
hideLabelFromVision: hideLabelFromVision,
help: help,
className: classnames_default()(className, 'components-search-control')
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-search-control__input-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("input", { ...restProps,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([searchRef, forwardedRef]),
className: "components-search-control__input",
id: id,
type: "search",
placeholder: placeholder,
onChange: event => onChange(event.target.value),
onKeyDown: onKeyDown,
autoComplete: "off",
value: value || ''
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-search-control__icon"
}, renderRightButton())));
}
/**
* SearchControl components let users display a search control.
*
* ```jsx
* import { SearchControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* function MySearchControl( { className, setState } ) {
* const [ searchInput, setSearchInput ] = useState( '' );
*
* return (
* <SearchControl
* value={ searchInput }
* onChange={ setSearchInput }
* />
* );
* }
* ```
*/
const SearchControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSearchControl);
/* harmony default export */ var search_control = (SearchControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/styles/navigation-styles.js
function navigation_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const NavigationUI = createStyled("div", true ? {
target: "eeiismy11"
} : 0)("width:100%;box-sizing:border-box;padding:0 ", space(4), ";overflow:hidden;" + ( true ? "" : 0));
const MenuUI = createStyled("div", true ? {
target: "eeiismy10"
} : 0)("margin-top:", space(6), ";margin-bottom:", space(6), ";display:flex;flex-direction:column;ul{padding:0;margin:0;list-style:none;}.components-navigation__back-button{margin-bottom:", space(6), ";}.components-navigation__group+.components-navigation__group{margin-top:", space(6), ";}" + ( true ? "" : 0));
const MenuBackButtonUI = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "eeiismy9"
} : 0)( true ? {
name: "26l0q2",
styles: "&.is-tertiary{color:inherit;opacity:0.7;&:hover:not( :disabled ){opacity:1;box-shadow:none;color:inherit;}&:active:not( :disabled ){background:transparent;opacity:1;color:inherit;}}"
} : 0);
const MenuTitleUI = createStyled("div", true ? {
target: "eeiismy8"
} : 0)( true ? {
name: "1aubja5",
styles: "overflow:hidden;width:100%"
} : 0);
const MenuTitleActionsUI = createStyled("span", true ? {
target: "eeiismy7"
} : 0)("height:", space(6), ";.components-button.is-small{color:inherit;opacity:0.7;margin-right:", space(1), ";padding:0;&:active:not( :disabled ){background:none;opacity:1;color:inherit;}&:hover:not( :disabled ){box-shadow:none;opacity:1;color:inherit;}}" + ( true ? "" : 0));
const MenuTitleSearchUI = /*#__PURE__*/createStyled(search_control, true ? {
target: "eeiismy6"
} : 0)( true ? {
name: "za3n3e",
styles: "input[type='search'].components-search-control__input{margin:0;background:#303030;color:#fff;&:focus{background:#434343;color:#fff;}&::placeholder{color:rgba( 255, 255, 255, 0.6 );}}svg{fill:white;}.components-button.has-icon{padding:0;min-width:auto;}"
} : 0);
const GroupTitleUI = /*#__PURE__*/createStyled(heading_component, true ? {
target: "eeiismy5"
} : 0)("min-height:", space(12), ";align-items:center;color:inherit;display:flex;justify-content:space-between;margin-bottom:", space(2), ";padding:", () => (0,external_wp_i18n_namespaceObject.isRTL)() ? `${space(1)} ${space(4)} ${space(1)} ${space(2)}` : `${space(1)} ${space(2)} ${space(1)} ${space(4)}`, ";" + ( true ? "" : 0));
const ItemBaseUI = createStyled("li", true ? {
target: "eeiismy4"
} : 0)("border-radius:2px;color:inherit;margin-bottom:0;>button,>a.components-button,>a{width:100%;color:inherit;opacity:0.7;padding:", space(2), " ", space(4), ";", rtl({
textAlign: 'left'
}, {
textAlign: 'right'
}), " &:hover,&:focus:not( [aria-disabled='true'] ):active,&:active:not( [aria-disabled='true'] ):active{color:inherit;opacity:1;}}&.is-active{background-color:", COLORS.ui.theme, ";color:", COLORS.white, ";>button,>a{color:", COLORS.white, ";opacity:1;}}>svg path{color:", COLORS.gray[600], ";}" + ( true ? "" : 0));
const ItemUI = createStyled("div", true ? {
target: "eeiismy3"
} : 0)("display:flex;align-items:center;height:auto;min-height:40px;margin:0;padding:", space(1.5), " ", space(4), ";font-weight:400;line-height:20px;width:100%;color:inherit;opacity:0.7;" + ( true ? "" : 0));
const ItemIconUI = createStyled("span", true ? {
target: "eeiismy2"
} : 0)("display:flex;margin-right:", space(2), ";" + ( true ? "" : 0));
const ItemBadgeUI = createStyled("span", true ? {
target: "eeiismy1"
} : 0)("margin-left:", () => (0,external_wp_i18n_namespaceObject.isRTL)() ? '0' : space(2), ";margin-right:", () => (0,external_wp_i18n_namespaceObject.isRTL)() ? space(2) : '0', ";display:inline-flex;padding:", space(1), " ", space(3), ";border-radius:2px;animation:fade-in 250ms ease-out;@keyframes fade-in{from{opacity:0;}to{opacity:1;}}", reduceMotion('animation'), ";" + ( true ? "" : 0));
const ItemTitleUI = /*#__PURE__*/createStyled(text_component, true ? {
target: "eeiismy0"
} : 0)(() => (0,external_wp_i18n_namespaceObject.isRTL)() ? 'margin-left: auto;' : 'margin-right: auto;', " font-size:14px;line-height:20px;color:inherit;" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/use-navigation-tree-nodes.js
/**
* WordPress dependencies
*/
function useNavigationTreeNodes() {
const [nodes, setNodes] = (0,external_wp_element_namespaceObject.useState)({});
const getNode = key => nodes[key];
const addNode = (key, value) => {
const {
children,
...newNode
} = value;
return setNodes(original => ({ ...original,
[key]: newNode
}));
};
const removeNode = key => {
return setNodes(original => {
const {
[key]: removedNode,
...remainingNodes
} = original;
return remainingNodes;
});
};
return {
nodes,
getNode,
addNode,
removeNode
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/use-create-navigation-tree.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useCreateNavigationTree = () => {
const {
nodes: items,
getNode: getItem,
addNode: addItem,
removeNode: removeItem
} = useNavigationTreeNodes();
const {
nodes: menus,
getNode: getMenu,
addNode: addMenu,
removeNode: removeMenu
} = useNavigationTreeNodes();
/**
* Stores direct nested menus of menus
* This makes it easy to traverse menu tree
*
* Key is the menu prop of the menu
* Value is an array of menu keys
*/
const [childMenu, setChildMenu] = (0,external_wp_element_namespaceObject.useState)({});
const getChildMenu = menu => childMenu[menu] || [];
const traverseMenu = (startMenu, callback) => {
const visited = [];
let queue = [startMenu];
let current;
while (queue.length > 0) {
// Type cast to string is safe because of the `length > 0` check above.
current = getMenu(queue.shift());
if (!current || visited.includes(current.menu)) {
continue;
}
visited.push(current.menu);
queue = [...queue, ...getChildMenu(current.menu)];
if (callback(current) === false) {
break;
}
}
};
const isMenuEmpty = menuToCheck => {
let isEmpty = true;
traverseMenu(menuToCheck, current => {
if (!current.isEmpty) {
isEmpty = false;
return false;
}
return undefined;
});
return isEmpty;
};
return {
items,
getItem,
addItem,
removeItem,
menus,
getMenu,
addMenu: (key, value) => {
setChildMenu(state => {
const newState = { ...state
};
if (!value.parentMenu) {
return newState;
}
if (!newState[value.parentMenu]) {
newState[value.parentMenu] = [];
}
newState[value.parentMenu].push(key);
return newState;
});
addMenu(key, value);
},
removeMenu,
childMenu,
traverseMenu,
isMenuEmpty
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const navigation_noop = () => {};
/**
* Render a navigation list with optional groupings and hierarchy.
*
* @example
* ```jsx
* import {
* __experimentalNavigation as Navigation,
* __experimentalNavigationGroup as NavigationGroup,
* __experimentalNavigationItem as NavigationItem,
* __experimentalNavigationMenu as NavigationMenu,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <Navigation>
* <NavigationMenu title="Home">
* <NavigationGroup title="Group 1">
* <NavigationItem item="item-1" title="Item 1" />
* <NavigationItem item="item-2" title="Item 2" />
* </NavigationGroup>
* <NavigationGroup title="Group 2">
* <NavigationItem
* item="item-3"
* navigateToMenu="category"
* title="Category"
* />
* </NavigationGroup>
* </NavigationMenu>
*
* <NavigationMenu
* backButtonLabel="Home"
* menu="category"
* parentMenu="root"
* title="Category"
* >
* <NavigationItem badge="1" item="child-1" title="Child 1" />
* <NavigationItem item="child-2" title="Child 2" />
* </NavigationMenu>
* </Navigation>
* );
* ```
*/
function Navigation({
activeItem,
activeMenu = ROOT_MENU,
children,
className,
onActivateMenu = navigation_noop
}) {
const [menu, setMenu] = (0,external_wp_element_namespaceObject.useState)(activeMenu);
const [slideOrigin, setSlideOrigin] = (0,external_wp_element_namespaceObject.useState)();
const navigationTree = useCreateNavigationTree();
const defaultSlideOrigin = (0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left';
const setActiveMenu = (menuId, slideInOrigin = defaultSlideOrigin) => {
if (!navigationTree.getMenu(menuId)) {
return;
}
setSlideOrigin(slideInOrigin);
setMenu(menuId);
onActivateMenu(menuId);
}; // Used to prevent the sliding animation on mount
const isMounted = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isMounted.current) {
isMounted.current = true;
}
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (activeMenu !== menu) {
setActiveMenu(activeMenu);
} // Ignore exhaustive-deps here, as it would require either a larger refactor or some questionable workarounds.
// See https://github.com/WordPress/gutenberg/pull/41612 for context.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeMenu]);
const context = {
activeItem,
activeMenu: menu,
setActiveMenu,
navigationTree
};
const classes = classnames_default()('components-navigation', className);
const animateClassName = getAnimateClassName({
type: 'slide-in',
origin: slideOrigin
});
return (0,external_wp_element_namespaceObject.createElement)(NavigationUI, {
className: classes
}, (0,external_wp_element_namespaceObject.createElement)("div", {
key: menu,
className: animateClassName ? classnames_default()({
[animateClassName]: isMounted.current && slideOrigin
}) : undefined
}, (0,external_wp_element_namespaceObject.createElement)(NavigationContext.Provider, {
value: context
}, children)));
}
/* harmony default export */ var navigation = (Navigation);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-right.js
/**
* WordPress dependencies
*/
const chevronRight = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z"
}));
/* harmony default export */ var chevron_right = (chevronRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-left.js
/**
* WordPress dependencies
*/
const chevronLeft = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z"
}));
/* harmony default export */ var chevron_left = (chevronLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/back-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedNavigationBackButton({
backButtonLabel,
className,
href,
onClick,
parentMenu
}, ref) {
const {
setActiveMenu,
navigationTree
} = useNavigationContext();
const classes = classnames_default()('components-navigation__back-button', className);
const parentMenuTitle = parentMenu !== undefined ? navigationTree.getMenu(parentMenu)?.title : undefined;
const handleOnClick = event => {
if (typeof onClick === 'function') {
onClick(event);
}
const animationDirection = (0,external_wp_i18n_namespaceObject.isRTL)() ? 'left' : 'right';
if (parentMenu && !event.defaultPrevented) {
setActiveMenu(parentMenu, animationDirection);
}
};
const icon = (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_right : chevron_left;
return (0,external_wp_element_namespaceObject.createElement)(MenuBackButtonUI, {
className: classes,
href: href,
variant: "tertiary",
ref: ref,
onClick: handleOnClick
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: icon
}), backButtonLabel || parentMenuTitle || (0,external_wp_i18n_namespaceObject.__)('Back'));
}
const NavigationBackButton = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedNavigationBackButton);
/* harmony default export */ var back_button = (NavigationBackButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/group/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const NavigationGroupContext = (0,external_wp_element_namespaceObject.createContext)({
group: undefined
});
const useNavigationGroupContext = () => (0,external_wp_element_namespaceObject.useContext)(NavigationGroupContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
let uniqueId = 0;
function NavigationGroup({
children,
className,
title
}) {
const [groupId] = (0,external_wp_element_namespaceObject.useState)(`group-${++uniqueId}`);
const {
navigationTree: {
items
}
} = useNavigationContext();
const context = {
group: groupId
}; // Keep the children rendered to make sure invisible items are included in the navigation tree.
if (!Object.values(items).some(item => item.group === groupId && item._isVisible)) {
return (0,external_wp_element_namespaceObject.createElement)(NavigationGroupContext.Provider, {
value: context
}, children);
}
const groupTitleId = `components-navigation__group-title-${groupId}`;
const classes = classnames_default()('components-navigation__group', className);
return (0,external_wp_element_namespaceObject.createElement)(NavigationGroupContext.Provider, {
value: context
}, (0,external_wp_element_namespaceObject.createElement)("li", {
className: classes
}, title && (0,external_wp_element_namespaceObject.createElement)(GroupTitleUI, {
className: "components-navigation__group-title",
id: groupTitleId,
level: 3
}, title), (0,external_wp_element_namespaceObject.createElement)("ul", {
"aria-labelledby": groupTitleId,
role: "group"
}, children)));
}
/* harmony default export */ var group = (NavigationGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/base-content.js
/**
* Internal dependencies
*/
function NavigationItemBaseContent(props) {
const {
badge,
title
} = props;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, title && (0,external_wp_element_namespaceObject.createElement)(ItemTitleUI, {
className: "components-navigation__item-title",
as: "span"
}, title), badge && (0,external_wp_element_namespaceObject.createElement)(ItemBadgeUI, {
className: "components-navigation__item-badge"
}, badge));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const NavigationMenuContext = (0,external_wp_element_namespaceObject.createContext)({
menu: undefined,
search: ''
});
const useNavigationMenuContext = () => (0,external_wp_element_namespaceObject.useContext)(NavigationMenuContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/utils.js
/**
* External dependencies
*/
// @see packages/block-editor/src/components/inserter/search-items.js
const normalizeInput = input => remove_accents_default()(input).replace(/^\//, '').toLowerCase();
const normalizedSearch = (title, search) => -1 !== normalizeInput(title).indexOf(normalizeInput(search));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/use-navigation-tree-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useNavigationTreeItem = (itemId, props) => {
const {
activeMenu,
navigationTree: {
addItem,
removeItem
}
} = useNavigationContext();
const {
group
} = useNavigationGroupContext();
const {
menu,
search
} = useNavigationMenuContext();
(0,external_wp_element_namespaceObject.useEffect)(() => {
const isMenuActive = activeMenu === menu;
const isItemVisible = !search || props.title !== undefined && normalizedSearch(props.title, search);
addItem(itemId, { ...props,
group,
menu,
_isVisible: isMenuActive && isItemVisible
});
return () => {
removeItem(itemId);
}; // Ignore exhaustive-deps rule for now. See https://github.com/WordPress/gutenberg/pull/41639
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeMenu, search]);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/base.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
let base_uniqueId = 0;
function NavigationItemBase(props) {
// Also avoid to pass the `title` and `href` props to the ItemBaseUI styled component.
const {
children,
className,
title,
href,
...restProps
} = props;
const [itemId] = (0,external_wp_element_namespaceObject.useState)(`item-${++base_uniqueId}`);
useNavigationTreeItem(itemId, props);
const {
navigationTree
} = useNavigationContext();
if (!navigationTree.getItem(itemId)?._isVisible) {
return null;
}
const classes = classnames_default()('components-navigation__item', className);
return (0,external_wp_element_namespaceObject.createElement)(ItemBaseUI, {
className: classes,
...restProps
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const item_noop = () => {};
function NavigationItem(props) {
const {
badge,
children,
className,
href,
item,
navigateToMenu,
onClick = item_noop,
title,
icon,
hideIfTargetMenuEmpty,
isText,
...restProps
} = props;
const {
activeItem,
setActiveMenu,
navigationTree: {
isMenuEmpty
}
} = useNavigationContext(); // If hideIfTargetMenuEmpty prop is true
// And the menu we are supposed to navigate to
// Is marked as empty, then we skip rendering the item.
if (hideIfTargetMenuEmpty && navigateToMenu && isMenuEmpty(navigateToMenu)) {
return null;
}
const isActive = item && activeItem === item;
const classes = classnames_default()(className, {
'is-active': isActive
});
const onItemClick = event => {
if (navigateToMenu) {
setActiveMenu(navigateToMenu);
}
onClick(event);
};
const navigationIcon = (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left : chevron_right;
const baseProps = children ? props : { ...props,
onClick: undefined
};
const itemProps = isText ? restProps : {
as: build_module_button,
href,
onClick: onItemClick,
'aria-current': isActive ? 'page' : undefined,
...restProps
};
return (0,external_wp_element_namespaceObject.createElement)(NavigationItemBase, { ...baseProps,
className: classes
}, children || (0,external_wp_element_namespaceObject.createElement)(ItemUI, { ...itemProps
}, icon && (0,external_wp_element_namespaceObject.createElement)(ItemIconUI, null, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: icon
})), (0,external_wp_element_namespaceObject.createElement)(NavigationItemBaseContent, {
title: title,
badge: badge
}), navigateToMenu && (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: navigationIcon
})));
}
/* harmony default export */ var navigation_item = (NavigationItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/use-navigation-tree-menu.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useNavigationTreeMenu = props => {
const {
navigationTree: {
addMenu,
removeMenu
}
} = useNavigationContext();
const key = props.menu || ROOT_MENU;
(0,external_wp_element_namespaceObject.useEffect)(() => {
addMenu(key, { ...props,
menu: key
});
return () => {
removeMenu(key);
}; // Ignore exhaustive-deps rule for now. See https://github.com/WordPress/gutenberg/pull/44090
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-spoken-messages/index.js
/**
* WordPress dependencies
*/
/** @typedef {import('@wordpress/element').WPComponent} WPComponent */
/**
* A Higher Order Component used to be provide speak and debounced speak
* functions.
*
* @see https://developer.wordpress.org/block-editor/packages/packages-a11y/#speak
*
* @param {WPComponent} Component The component to be wrapped.
*
* @return {WPComponent} The wrapped component.
*/
/* harmony default export */ var with_spoken_messages = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(Component => props => (0,external_wp_element_namespaceObject.createElement)(Component, { ...props,
speak: external_wp_a11y_namespaceObject.speak,
debouncedSpeak: (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500)
}), 'withSpokenMessages'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/menu-title-search.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MenuTitleSearch({
debouncedSpeak,
onCloseSearch,
onSearch,
search,
title
}) {
const {
navigationTree: {
items
}
} = useNavigationContext();
const {
menu
} = useNavigationMenuContext();
const inputRef = (0,external_wp_element_namespaceObject.useRef)(null); // Wait for the slide-in animation to complete before autofocusing the input.
// This prevents scrolling to the input during the animation.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const delayedFocus = setTimeout(() => {
inputRef.current?.focus();
}, SEARCH_FOCUS_DELAY);
return () => {
clearTimeout(delayedFocus);
};
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!search) {
return;
}
const count = Object.values(items).filter(item => item._isVisible).length;
const resultsFoundMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found.', '%d results found.', count), count);
debouncedSpeak(resultsFoundMessage); // Ignore exhaustive-deps rule for now. See https://github.com/WordPress/gutenberg/pull/44090
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, search]);
const onClose = () => {
onSearch?.('');
onCloseSearch();
};
const onKeyDown = event => {
if (event.code === 'Escape' && !event.defaultPrevented) {
event.preventDefault();
onClose();
}
};
const inputId = `components-navigation__menu-title-search-${menu}`;
const placeholder = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: placeholder for menu search box. %s: menu title */
(0,external_wp_i18n_namespaceObject.__)('Search %s'), title?.toLowerCase()).trim();
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-navigation__menu-title-search"
}, (0,external_wp_element_namespaceObject.createElement)(MenuTitleSearchUI, {
autoComplete: "off",
className: "components-navigation__menu-search-input",
id: inputId,
onChange: value => onSearch?.(value),
onKeyDown: onKeyDown,
placeholder: placeholder,
onClose: onClose,
ref: inputRef,
type: "search",
value: search
}));
}
/* harmony default export */ var menu_title_search = (with_spoken_messages(MenuTitleSearch));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/menu-title.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationMenuTitle({
hasSearch,
onSearch,
search,
title,
titleAction
}) {
const [isSearching, setIsSearching] = (0,external_wp_element_namespaceObject.useState)(false);
const {
menu
} = useNavigationMenuContext();
const searchButtonRef = (0,external_wp_element_namespaceObject.useRef)(null);
if (!title) {
return null;
}
const onCloseSearch = () => {
setIsSearching(false); // Wait for the slide-in animation to complete before focusing the search button.
// eslint-disable-next-line @wordpress/react-no-unsafe-timeout
setTimeout(() => {
searchButtonRef.current?.focus();
}, SEARCH_FOCUS_DELAY);
};
const menuTitleId = `components-navigation__menu-title-${menu}`;
/* translators: search button label for menu search box. %s: menu title */
const searchButtonLabel = (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Search in %s'), title);
return (0,external_wp_element_namespaceObject.createElement)(MenuTitleUI, {
className: "components-navigation__menu-title"
}, !isSearching && (0,external_wp_element_namespaceObject.createElement)(GroupTitleUI, {
as: "h2",
className: "components-navigation__menu-title-heading",
level: 3
}, (0,external_wp_element_namespaceObject.createElement)("span", {
id: menuTitleId
}, title), (hasSearch || titleAction) && (0,external_wp_element_namespaceObject.createElement)(MenuTitleActionsUI, null, titleAction, hasSearch && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isSmall: true,
variant: "tertiary",
label: searchButtonLabel,
onClick: () => setIsSearching(true),
ref: searchButtonRef
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_search
})))), isSearching && (0,external_wp_element_namespaceObject.createElement)("div", {
className: getAnimateClassName({
type: 'slide-in',
origin: 'left'
})
}, (0,external_wp_element_namespaceObject.createElement)(menu_title_search, {
onCloseSearch: onCloseSearch,
onSearch: onSearch,
search: search,
title: title
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/search-no-results-found.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationSearchNoResultsFound({
search
}) {
const {
navigationTree: {
items
}
} = useNavigationContext();
const resultsCount = Object.values(items).filter(item => item._isVisible).length;
if (!search || !!resultsCount) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(ItemBaseUI, null, (0,external_wp_element_namespaceObject.createElement)(ItemUI, null, (0,external_wp_i18n_namespaceObject.__)('No results found.'), " "));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationMenu(props) {
const {
backButtonLabel,
children,
className,
hasSearch,
menu = ROOT_MENU,
onBackButtonClick,
onSearch: setControlledSearch,
parentMenu,
search: controlledSearch,
isSearchDebouncing,
title,
titleAction
} = props;
const [uncontrolledSearch, setUncontrolledSearch] = (0,external_wp_element_namespaceObject.useState)('');
useNavigationTreeMenu(props);
const {
activeMenu
} = useNavigationContext();
const context = {
menu,
search: uncontrolledSearch
}; // Keep the children rendered to make sure invisible items are included in the navigation tree.
if (activeMenu !== menu) {
return (0,external_wp_element_namespaceObject.createElement)(NavigationMenuContext.Provider, {
value: context
}, children);
}
const isControlledSearch = !!setControlledSearch;
const search = isControlledSearch ? controlledSearch : uncontrolledSearch;
const onSearch = isControlledSearch ? setControlledSearch : setUncontrolledSearch;
const menuTitleId = `components-navigation__menu-title-${menu}`;
const classes = classnames_default()('components-navigation__menu', className);
return (0,external_wp_element_namespaceObject.createElement)(NavigationMenuContext.Provider, {
value: context
}, (0,external_wp_element_namespaceObject.createElement)(MenuUI, {
className: classes
}, (parentMenu || onBackButtonClick) && (0,external_wp_element_namespaceObject.createElement)(back_button, {
backButtonLabel: backButtonLabel,
parentMenu: parentMenu,
onClick: onBackButtonClick
}), title && (0,external_wp_element_namespaceObject.createElement)(NavigationMenuTitle, {
hasSearch: hasSearch,
onSearch: onSearch,
search: search,
title: title,
titleAction: titleAction
}), (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, null, (0,external_wp_element_namespaceObject.createElement)("ul", {
"aria-labelledby": menuTitleId
}, children, search && !isSearchDebouncing && (0,external_wp_element_namespaceObject.createElement)(NavigationSearchNoResultsFound, {
search: search
})))));
}
/* harmony default export */ var navigation_menu = (NavigationMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const initialContextValue = {
location: {},
goTo: () => {},
goBack: () => {},
goToParent: () => {},
addScreen: () => {},
removeScreen: () => {},
params: {}
};
const NavigatorContext = (0,external_wp_element_namespaceObject.createContext)(initialContextValue);
;// CONCATENATED MODULE: ./node_modules/path-to-regexp/dist.es2015/index.js
/**
* Tokenize input string.
*/
function lexer(str) {
var tokens = [];
var i = 0;
while (i < str.length) {
var char = str[i];
if (char === "*" || char === "+" || char === "?") {
tokens.push({ type: "MODIFIER", index: i, value: str[i++] });
continue;
}
if (char === "\\") {
tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
continue;
}
if (char === "{") {
tokens.push({ type: "OPEN", index: i, value: str[i++] });
continue;
}
if (char === "}") {
tokens.push({ type: "CLOSE", index: i, value: str[i++] });
continue;
}
if (char === ":") {
var name = "";
var j = i + 1;
while (j < str.length) {
var code = str.charCodeAt(j);
if (
// `0-9`
(code >= 48 && code <= 57) ||
// `A-Z`
(code >= 65 && code <= 90) ||
// `a-z`
(code >= 97 && code <= 122) ||
// `_`
code === 95) {
name += str[j++];
continue;
}
break;
}
if (!name)
throw new TypeError("Missing parameter name at ".concat(i));
tokens.push({ type: "NAME", index: i, value: name });
i = j;
continue;
}
if (char === "(") {
var count = 1;
var pattern = "";
var j = i + 1;
if (str[j] === "?") {
throw new TypeError("Pattern cannot start with \"?\" at ".concat(j));
}
while (j < str.length) {
if (str[j] === "\\") {
pattern += str[j++] + str[j++];
continue;
}
if (str[j] === ")") {
count--;
if (count === 0) {
j++;
break;
}
}
else if (str[j] === "(") {
count++;
if (str[j + 1] !== "?") {
throw new TypeError("Capturing groups are not allowed at ".concat(j));
}
}
pattern += str[j++];
}
if (count)
throw new TypeError("Unbalanced pattern at ".concat(i));
if (!pattern)
throw new TypeError("Missing pattern at ".concat(i));
tokens.push({ type: "PATTERN", index: i, value: pattern });
i = j;
continue;
}
tokens.push({ type: "CHAR", index: i, value: str[i++] });
}
tokens.push({ type: "END", index: i, value: "" });
return tokens;
}
/**
* Parse a string for the raw tokens.
*/
function dist_es2015_parse(str, options) {
if (options === void 0) { options = {}; }
var tokens = lexer(str);
var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a;
var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
var result = [];
var key = 0;
var i = 0;
var path = "";
var tryConsume = function (type) {
if (i < tokens.length && tokens[i].type === type)
return tokens[i++].value;
};
var mustConsume = function (type) {
var value = tryConsume(type);
if (value !== undefined)
return value;
var _a = tokens[i], nextType = _a.type, index = _a.index;
throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
};
var consumeText = function () {
var result = "";
var value;
while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) {
result += value;
}
return result;
};
while (i < tokens.length) {
var char = tryConsume("CHAR");
var name = tryConsume("NAME");
var pattern = tryConsume("PATTERN");
if (name || pattern) {
var prefix = char || "";
if (prefixes.indexOf(prefix) === -1) {
path += prefix;
prefix = "";
}
if (path) {
result.push(path);
path = "";
}
result.push({
name: name || key++,
prefix: prefix,
suffix: "",
pattern: pattern || defaultPattern,
modifier: tryConsume("MODIFIER") || "",
});
continue;
}
var value = char || tryConsume("ESCAPED_CHAR");
if (value) {
path += value;
continue;
}
if (path) {
result.push(path);
path = "";
}
var open = tryConsume("OPEN");
if (open) {
var prefix = consumeText();
var name_1 = tryConsume("NAME") || "";
var pattern_1 = tryConsume("PATTERN") || "";
var suffix = consumeText();
mustConsume("CLOSE");
result.push({
name: name_1 || (pattern_1 ? key++ : ""),
pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
prefix: prefix,
suffix: suffix,
modifier: tryConsume("MODIFIER") || "",
});
continue;
}
mustConsume("END");
}
return result;
}
/**
* Compile a string to a template function for the path.
*/
function dist_es2015_compile(str, options) {
return tokensToFunction(dist_es2015_parse(str, options), options);
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens, options) {
if (options === void 0) { options = {}; }
var reFlags = flags(options);
var _a = options.encode, encode = _a === void 0 ? function (x) { return x; } : _a, _b = options.validate, validate = _b === void 0 ? true : _b;
// Compile all the tokens into regexps.
var matches = tokens.map(function (token) {
if (typeof token === "object") {
return new RegExp("^(?:".concat(token.pattern, ")$"), reFlags);
}
});
return function (data) {
var path = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === "string") {
path += token;
continue;
}
var value = data ? data[token.name] : undefined;
var optional = token.modifier === "?" || token.modifier === "*";
var repeat = token.modifier === "*" || token.modifier === "+";
if (Array.isArray(value)) {
if (!repeat) {
throw new TypeError("Expected \"".concat(token.name, "\" to not repeat, but got an array"));
}
if (value.length === 0) {
if (optional)
continue;
throw new TypeError("Expected \"".concat(token.name, "\" to not be empty"));
}
for (var j = 0; j < value.length; j++) {
var segment = encode(value[j], token);
if (validate && !matches[i].test(segment)) {
throw new TypeError("Expected all \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
}
path += token.prefix + segment + token.suffix;
}
continue;
}
if (typeof value === "string" || typeof value === "number") {
var segment = encode(String(value), token);
if (validate && !matches[i].test(segment)) {
throw new TypeError("Expected \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
}
path += token.prefix + segment + token.suffix;
continue;
}
if (optional)
continue;
var typeOfMessage = repeat ? "an array" : "a string";
throw new TypeError("Expected \"".concat(token.name, "\" to be ").concat(typeOfMessage));
}
return path;
};
}
/**
* Create path match function from `path-to-regexp` spec.
*/
function dist_es2015_match(str, options) {
var keys = [];
var re = pathToRegexp(str, keys, options);
return regexpToFunction(re, keys, options);
}
/**
* Create a path match function from `path-to-regexp` output.
*/
function regexpToFunction(re, keys, options) {
if (options === void 0) { options = {}; }
var _a = options.decode, decode = _a === void 0 ? function (x) { return x; } : _a;
return function (pathname) {
var m = re.exec(pathname);
if (!m)
return false;
var path = m[0], index = m.index;
var params = Object.create(null);
var _loop_1 = function (i) {
if (m[i] === undefined)
return "continue";
var key = keys[i - 1];
if (key.modifier === "*" || key.modifier === "+") {
params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) {
return decode(value, key);
});
}
else {
params[key.name] = decode(m[i], key);
}
};
for (var i = 1; i < m.length; i++) {
_loop_1(i);
}
return { path: path, index: index, params: params };
};
}
/**
* Escape a regular expression string.
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
}
/**
* Get the flags for a regexp from the options.
*/
function flags(options) {
return options && options.sensitive ? "" : "i";
}
/**
* Pull out keys from a regexp.
*/
function regexpToRegexp(path, keys) {
if (!keys)
return path;
var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
var index = 0;
var execResult = groupsRegex.exec(path.source);
while (execResult) {
keys.push({
// Use parenthesized substring match if available, index otherwise
name: execResult[1] || index++,
prefix: "",
suffix: "",
modifier: "",
pattern: "",
});
execResult = groupsRegex.exec(path.source);
}
return path;
}
/**
* Transform an array into a regexp.
*/
function arrayToRegexp(paths, keys, options) {
var parts = paths.map(function (path) { return pathToRegexp(path, keys, options).source; });
return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options));
}
/**
* Create a path regexp from string input.
*/
function stringToRegexp(path, keys, options) {
return tokensToRegexp(dist_es2015_parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*/
function tokensToRegexp(tokens, keys, options) {
if (options === void 0) { options = {}; }
var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function (x) { return x; } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
var delimiterRe = "[".concat(escapeString(delimiter), "]");
var route = start ? "^" : "";
// Iterate over the tokens and create our regexp string.
for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
var token = tokens_1[_i];
if (typeof token === "string") {
route += escapeString(encode(token));
}
else {
var prefix = escapeString(encode(token.prefix));
var suffix = escapeString(encode(token.suffix));
if (token.pattern) {
if (keys)
keys.push(token);
if (prefix || suffix) {
if (token.modifier === "+" || token.modifier === "*") {
var mod = token.modifier === "*" ? "?" : "";
route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod);
}
else {
route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier);
}
}
else {
if (token.modifier === "+" || token.modifier === "*") {
route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")");
}
else {
route += "(".concat(token.pattern, ")").concat(token.modifier);
}
}
}
else {
route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier);
}
}
}
if (end) {
if (!strict)
route += "".concat(delimiterRe, "?");
route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")");
}
else {
var endToken = tokens[tokens.length - 1];
var isEndDelimited = typeof endToken === "string"
? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1
: endToken === undefined;
if (!strict) {
route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?");
}
if (!isEndDelimited) {
route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")");
}
}
return new RegExp(route, flags(options));
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*/
function pathToRegexp(path, keys, options) {
if (path instanceof RegExp)
return regexpToRegexp(path, keys);
if (Array.isArray(path))
return arrayToRegexp(path, keys, options);
return stringToRegexp(path, keys, options);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/utils/router.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function matchPath(path, pattern) {
const matchingFunction = dist_es2015_match(pattern, {
decode: decodeURIComponent
});
return matchingFunction(path);
}
function patternMatch(path, screens) {
for (const screen of screens) {
const matched = matchPath(path, screen.path);
if (matched) {
return {
params: matched.params,
id: screen.id
};
}
}
return undefined;
}
function findParent(path, screens) {
if (!path.startsWith('/')) {
return undefined;
}
const pathParts = path.split('/');
let parentPath;
while (pathParts.length > 1 && parentPath === undefined) {
pathParts.pop();
const potentialParentPath = pathParts.join('/') === '' ? '/' : pathParts.join('/');
if (screens.find(screen => {
return matchPath(potentialParentPath, screen.path) !== false;
})) {
parentPath = potentialParentPath;
}
}
return parentPath;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-provider/component.js
function component_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const MAX_HISTORY_LENGTH = 50;
function screensReducer(state = [], action) {
switch (action.type) {
case 'add':
return [...state, action.screen];
case 'remove':
return state.filter(s => s.id !== action.screen.id);
}
return state;
}
var component_ref = true ? {
name: "15bx5k",
styles: "overflow-x:hidden"
} : 0;
function UnconnectedNavigatorProvider(props, forwardedRef) {
const {
initialPath,
children,
className,
...otherProps
} = useContextSystem(props, 'NavigatorProvider');
const [locationHistory, setLocationHistory] = (0,external_wp_element_namespaceObject.useState)([{
path: initialPath
}]);
const currentLocationHistory = (0,external_wp_element_namespaceObject.useRef)([]);
const [screens, dispatch] = (0,external_wp_element_namespaceObject.useReducer)(screensReducer, []);
const currentScreens = (0,external_wp_element_namespaceObject.useRef)([]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
currentScreens.current = screens;
}, [screens]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
currentLocationHistory.current = locationHistory;
}, [locationHistory]);
const currentMatch = (0,external_wp_element_namespaceObject.useRef)();
const matchedPath = (0,external_wp_element_namespaceObject.useMemo)(() => {
let currentPath;
if (locationHistory.length === 0 || (currentPath = locationHistory[locationHistory.length - 1].path) === undefined) {
currentMatch.current = undefined;
return undefined;
}
const resolvePath = path => {
const newMatch = patternMatch(path, screens); // If the new match is the same as the current match,
// return the previous one for performance reasons.
if (currentMatch.current && newMatch && external_wp_isShallowEqual_default()(newMatch.params, currentMatch.current.params) && newMatch.id === currentMatch.current.id) {
return currentMatch.current;
}
return newMatch;
};
const newMatch = resolvePath(currentPath);
currentMatch.current = newMatch;
return newMatch;
}, [screens, locationHistory]);
const addScreen = (0,external_wp_element_namespaceObject.useCallback)(screen => dispatch({
type: 'add',
screen
}), []);
const removeScreen = (0,external_wp_element_namespaceObject.useCallback)(screen => dispatch({
type: 'remove',
screen
}), []);
const goBack = (0,external_wp_element_namespaceObject.useCallback)(() => {
setLocationHistory(prevLocationHistory => {
if (prevLocationHistory.length <= 1) {
return prevLocationHistory;
}
return [...prevLocationHistory.slice(0, -2), { ...prevLocationHistory[prevLocationHistory.length - 2],
isBack: true,
hasRestoredFocus: false
}];
});
}, []);
const goTo = (0,external_wp_element_namespaceObject.useCallback)((path, options = {}) => {
const {
focusTargetSelector,
isBack = false,
skipFocus = false,
replace = false,
...restOptions
} = options;
const isNavigatingToPreviousPath = isBack && currentLocationHistory.current.length > 1 && currentLocationHistory.current[currentLocationHistory.current.length - 2].path === path;
if (isNavigatingToPreviousPath) {
goBack();
return;
}
setLocationHistory(prevLocationHistory => {
const newLocation = { ...restOptions,
path,
isBack,
hasRestoredFocus: false,
skipFocus
};
if (prevLocationHistory.length === 0) {
return replace ? [] : [newLocation];
}
const newLocationHistory = prevLocationHistory.slice(prevLocationHistory.length > MAX_HISTORY_LENGTH - 1 ? 1 : 0, -1);
if (!replace) {
newLocationHistory.push( // Assign `focusTargetSelector` to the previous location in history
// (the one we just navigated from).
{ ...prevLocationHistory[prevLocationHistory.length - 1],
focusTargetSelector
});
}
newLocationHistory.push(newLocation);
return newLocationHistory;
});
}, [goBack]);
const goToParent = (0,external_wp_element_namespaceObject.useCallback)((options = {}) => {
const currentPath = currentLocationHistory.current[currentLocationHistory.current.length - 1].path;
if (currentPath === undefined) {
return;
}
const parentPath = findParent(currentPath, currentScreens.current);
if (parentPath === undefined) {
return;
}
goTo(parentPath, { ...options,
isBack: true
});
}, [goTo]);
const navigatorContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
location: { ...locationHistory[locationHistory.length - 1],
isInitial: locationHistory.length === 1
},
params: matchedPath ? matchedPath.params : {},
match: matchedPath ? matchedPath.id : undefined,
goTo,
goBack,
goToParent,
addScreen,
removeScreen
}), [locationHistory, matchedPath, goTo, goBack, goToParent, addScreen, removeScreen]);
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)( // Prevents horizontal overflow while animating screen transitions.
() => cx(component_ref, className), [className, cx]);
return (0,external_wp_element_namespaceObject.createElement)(component, {
ref: forwardedRef,
className: classes,
...otherProps
}, (0,external_wp_element_namespaceObject.createElement)(NavigatorContext.Provider, {
value: navigatorContextValue
}, children));
}
/**
* The `NavigatorProvider` component allows rendering nested views/panels/menus
* (via the `NavigatorScreen` component and navigate between these different
* view (via the `NavigatorButton` and `NavigatorBackButton` components or the
* `useNavigator` hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorProvider = contextConnect(UnconnectedNavigatorProvider, 'NavigatorProvider');
/* harmony default export */ var navigator_provider_component = (NavigatorProvider);
;// CONCATENATED MODULE: external ["wp","escapeHtml"]
var external_wp_escapeHtml_namespaceObject = window["wp"]["escapeHtml"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-screen/component.js
function navigator_screen_component_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const animationEnterDelay = 0;
const animationEnterDuration = 0.14;
const animationExitDuration = 0.14;
const animationExitDelay = 0; // Props specific to `framer-motion` can't be currently passed to `NavigatorScreen`,
// as some of them would overlap with HTML props (e.g. `onAnimationStart`, ...)
var navigator_screen_component_ref = true ? {
name: "14x3t6z",
styles: "overflow-x:auto;max-height:100%"
} : 0;
function UnconnectedNavigatorScreen(props, forwardedRef) {
const screenId = (0,external_wp_element_namespaceObject.useId)();
const {
children,
className,
path,
...otherProps
} = useContextSystem(props, 'NavigatorScreen');
const prefersReducedMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
const {
location,
match,
addScreen,
removeScreen
} = (0,external_wp_element_namespaceObject.useContext)(NavigatorContext);
const isMatch = match === screenId;
const wrapperRef = (0,external_wp_element_namespaceObject.useRef)(null);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const screen = {
id: screenId,
path: (0,external_wp_escapeHtml_namespaceObject.escapeAttribute)(path)
};
addScreen(screen);
return () => removeScreen(screen);
}, [screenId, path, addScreen, removeScreen]);
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(navigator_screen_component_ref, className), [className, cx]);
const locationRef = (0,external_wp_element_namespaceObject.useRef)(location);
(0,external_wp_element_namespaceObject.useEffect)(() => {
locationRef.current = location;
}, [location]); // Focus restoration
const isInitialLocation = location.isInitial && !location.isBack;
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Only attempt to restore focus:
// - if the current location is not the initial one (to avoid moving focus on page load)
// - when the screen becomes visible
// - if the wrapper ref has been assigned
// - if focus hasn't already been restored for the current location
// - if the `skipFocus` option is not set to `true`. This is useful when we trigger the navigation outside of NavigatorScreen.
if (isInitialLocation || !isMatch || !wrapperRef.current || locationRef.current.hasRestoredFocus || location.skipFocus) {
return;
}
const activeElement = wrapperRef.current.ownerDocument.activeElement; // If an element is already focused within the wrapper do not focus the
// element. This prevents inputs or buttons from losing focus unnecessarily.
if (wrapperRef.current.contains(activeElement)) {
return;
}
let elementToFocus = null; // When navigating back, if a selector is provided, use it to look for the
// target element (assumed to be a node inside the current NavigatorScreen)
if (location.isBack && location?.focusTargetSelector) {
elementToFocus = wrapperRef.current.querySelector(location.focusTargetSelector);
} // If the previous query didn't run or find any element to focus, fallback
// to the first tabbable element in the screen (or the screen itself).
if (!elementToFocus) {
const firstTabbable = external_wp_dom_namespaceObject.focus.tabbable.find(wrapperRef.current)[0];
elementToFocus = firstTabbable !== null && firstTabbable !== void 0 ? firstTabbable : wrapperRef.current;
}
locationRef.current.hasRestoredFocus = true;
elementToFocus.focus();
}, [isInitialLocation, isMatch, location.isBack, location.focusTargetSelector, location.skipFocus]);
const mergedWrapperRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([forwardedRef, wrapperRef]);
if (!isMatch) {
return null;
}
if (prefersReducedMotion) {
return (0,external_wp_element_namespaceObject.createElement)(component, {
ref: mergedWrapperRef,
className: classes,
...otherProps
}, children);
}
const animate = {
opacity: 1,
transition: {
delay: animationEnterDelay,
duration: animationEnterDuration,
ease: 'easeInOut'
},
x: 0
}; // Disable the initial animation if the screen is the very first screen to be
// rendered within the current `NavigatorProvider`.
const initial = location.isInitial && !location.isBack ? false : {
opacity: 0,
x: (0,external_wp_i18n_namespaceObject.isRTL)() && location.isBack || !(0,external_wp_i18n_namespaceObject.isRTL)() && !location.isBack ? 50 : -50
};
const exit = {
delay: animationExitDelay,
opacity: 0,
x: !(0,external_wp_i18n_namespaceObject.isRTL)() && location.isBack || (0,external_wp_i18n_namespaceObject.isRTL)() && !location.isBack ? 50 : -50,
transition: {
duration: animationExitDuration,
ease: 'easeInOut'
}
};
const animatedProps = {
animate,
exit,
initial
};
return (0,external_wp_element_namespaceObject.createElement)(motion.div, {
ref: mergedWrapperRef,
className: classes,
...otherProps,
...animatedProps
}, children);
}
/**
* The `NavigatorScreen` component represents a single view/screen/panel and
* should be used in combination with the `NavigatorProvider`, the
* `NavigatorButton` and the `NavigatorBackButton` components (or the `useNavigator`
* hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorScreen = contextConnect(UnconnectedNavigatorScreen, 'NavigatorScreen');
/* harmony default export */ var navigator_screen_component = (NavigatorScreen);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/use-navigator.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Retrieves a `navigator` instance.
*/
function useNavigator() {
const {
location,
params,
goTo,
goBack,
goToParent
} = (0,external_wp_element_namespaceObject.useContext)(NavigatorContext);
return {
location,
goTo,
goBack,
goToParent,
params
};
}
/* harmony default export */ var use_navigator = (useNavigator);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-button/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const cssSelectorForAttribute = (attrName, attrValue) => `[${attrName}="${attrValue}"]`;
function useNavigatorButton(props) {
const {
path,
onClick,
as = build_module_button,
attributeName = 'id',
...otherProps
} = useContextSystem(props, 'NavigatorButton');
const escapedPath = (0,external_wp_escapeHtml_namespaceObject.escapeAttribute)(path);
const {
goTo
} = use_navigator();
const handleClick = (0,external_wp_element_namespaceObject.useCallback)(e => {
e.preventDefault();
goTo(escapedPath, {
focusTargetSelector: cssSelectorForAttribute(attributeName, escapedPath)
});
onClick?.(e);
}, [goTo, onClick, attributeName, escapedPath]);
return {
as,
onClick: handleClick,
...otherProps,
[attributeName]: escapedPath
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-button/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedNavigatorButton(props, forwardedRef) {
const navigatorButtonProps = useNavigatorButton(props);
return (0,external_wp_element_namespaceObject.createElement)(component, {
ref: forwardedRef,
...navigatorButtonProps
});
}
/**
* The `NavigatorButton` component can be used to navigate to a screen and should
* be used in combination with the `NavigatorProvider`, the `NavigatorScreen`
* and the `NavigatorBackButton` components (or the `useNavigator` hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorButton = contextConnect(UnconnectedNavigatorButton, 'NavigatorButton');
/* harmony default export */ var navigator_button_component = (NavigatorButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-back-button/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useNavigatorBackButton(props) {
const {
onClick,
as = build_module_button,
goToParent: goToParentProp = false,
...otherProps
} = useContextSystem(props, 'NavigatorBackButton');
const {
goBack,
goToParent
} = use_navigator();
const handleClick = (0,external_wp_element_namespaceObject.useCallback)(e => {
e.preventDefault();
if (goToParentProp) {
goToParent();
} else {
goBack();
}
onClick?.(e);
}, [goToParentProp, goToParent, goBack, onClick]);
return {
as,
onClick: handleClick,
...otherProps
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-back-button/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedNavigatorBackButton(props, forwardedRef) {
const navigatorBackButtonProps = useNavigatorBackButton(props);
return (0,external_wp_element_namespaceObject.createElement)(component, {
ref: forwardedRef,
...navigatorBackButtonProps
});
}
/**
* The `NavigatorBackButton` component can be used to navigate to a screen and
* should be used in combination with the `NavigatorProvider`, the
* `NavigatorScreen` and the `NavigatorButton` components (or the `useNavigator`
* hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorBackButton = contextConnect(UnconnectedNavigatorBackButton, 'NavigatorBackButton');
/* harmony default export */ var navigator_back_button_component = (NavigatorBackButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-to-parent-button/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedNavigatorToParentButton(props, forwardedRef) {
const navigatorToParentButtonProps = useNavigatorBackButton({ ...props,
goToParent: true
});
return (0,external_wp_element_namespaceObject.createElement)(component, {
ref: forwardedRef,
...navigatorToParentButtonProps
});
}
/*
* The `NavigatorToParentButton` component can be used to navigate to a screen and
* should be used in combination with the `NavigatorProvider`, the
* `NavigatorScreen` and the `NavigatorButton` components (or the `useNavigator`
* hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorToParentButton as NavigatorToParentButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorToParentButton>
* Go to parent
* </NavigatorToParentButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorToParentButton = contextConnect(UnconnectedNavigatorToParentButton, 'NavigatorToParentButton');
/* harmony default export */ var navigator_to_parent_button_component = (NavigatorToParentButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/notice/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const notice_noop = () => {};
/**
* Custom hook which announces the message with the given politeness, if a
* valid message is provided.
*/
function useSpokenMessage(message, politeness) {
const spokenMessage = typeof message === 'string' ? message : (0,external_wp_element_namespaceObject.renderToString)(message);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (spokenMessage) {
(0,external_wp_a11y_namespaceObject.speak)(spokenMessage, politeness);
}
}, [spokenMessage, politeness]);
}
function getDefaultPoliteness(status) {
switch (status) {
case 'success':
case 'warning':
case 'info':
return 'polite';
case 'error':
default:
return 'assertive';
}
}
/**
* `Notice` is a component used to communicate feedback to the user.
*
*```jsx
* import { Notice } from `@wordpress/components`;
*
* const MyNotice = () => (
* <Notice status="error">An unknown error occurred.</Notice>
* );
* ```
*/
function Notice({
className,
status = 'info',
children,
spokenMessage = children,
onRemove = notice_noop,
isDismissible = true,
actions = [],
politeness = getDefaultPoliteness(status),
__unstableHTML,
// onDismiss is a callback executed when the notice is dismissed.
// It is distinct from onRemove, which _looks_ like a callback but is
// actually the function to call to remove the notice from the UI.
onDismiss = notice_noop
}) {
useSpokenMessage(spokenMessage, politeness);
const classes = classnames_default()(className, 'components-notice', 'is-' + status, {
'is-dismissible': isDismissible
});
if (__unstableHTML && typeof children === 'string') {
children = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, children);
}
const onDismissNotice = event => {
event?.preventDefault?.();
onDismiss();
onRemove();
};
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-notice__content"
}, children, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-notice__actions"
}, actions.map(({
className: buttonCustomClasses,
label,
isPrimary,
variant,
noDefaultClasses = false,
onClick,
url
}, index) => {
let computedVariant = variant;
if (variant !== 'primary' && !noDefaultClasses) {
computedVariant = !url ? 'secondary' : 'link';
}
if (typeof computedVariant === 'undefined' && isPrimary) {
computedVariant = 'primary';
}
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: index,
href: url,
variant: computedVariant,
onClick: url ? undefined : onClick,
className: classnames_default()('components-notice__action', buttonCustomClasses)
}, label);
}))), isDismissible && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-notice__dismiss",
icon: library_close,
label: (0,external_wp_i18n_namespaceObject.__)('Dismiss this notice'),
onClick: onDismissNotice,
showTooltip: false
}));
}
/* harmony default export */ var build_module_notice = (Notice);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/notice/list.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const list_noop = () => {};
/**
* `NoticeList` is a component used to render a collection of notices.
*
*```jsx
* import { Notice, NoticeList } from `@wordpress/components`;
*
* const MyNoticeList = () => {
* const [ notices, setNotices ] = useState( [
* {
* id: 'second-notice',
* content: 'second notice content',
* },
* {
* id: 'fist-notice',
* content: 'first notice content',
* },
* ] );
*
* const removeNotice = ( id ) => {
* setNotices( notices.filter( ( notice ) => notice.id !== id ) );
* };
*
* return <NoticeList notices={ notices } onRemove={ removeNotice } />;
*};
*```
*/
function NoticeList({
notices,
onRemove = list_noop,
className,
children
}) {
const removeNotice = id => () => onRemove(id);
className = classnames_default()('components-notice-list', className);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, children, [...notices].reverse().map(notice => {
const {
content,
...restNotice
} = notice;
return (0,external_wp_element_namespaceObject.createElement)(build_module_notice, { ...restNotice,
key: notice.id,
onRemove: removeNotice(notice.id)
}, notice.content);
}));
}
/* harmony default export */ var list = (NoticeList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/header.js
/**
* Internal dependencies
*/
/**
* `PanelHeader` renders the header for the `Panel`.
* This is used by the `Panel` component under the hood,
* so it does not typically need to be used.
*/
function PanelHeader({
label,
children
}) {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-panel__header"
}, label && (0,external_wp_element_namespaceObject.createElement)("h2", null, label), children);
}
/* harmony default export */ var panel_header = (PanelHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedPanel({
header,
className,
children
}, ref) {
const classNames = classnames_default()(className, 'components-panel');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classNames,
ref: ref
}, header && (0,external_wp_element_namespaceObject.createElement)(panel_header, {
label: header
}), children);
}
/**
* `Panel` expands and collapses multiple sections of content.
*
* ```jsx
* import { Panel, PanelBody, PanelRow } from '@wordpress/components';
* import { more } from '@wordpress/icons';
*
* const MyPanel = () => (
* <Panel header="My Panel">
* <PanelBody title="My Block Settings" icon={ more } initialOpen={ true }>
* <PanelRow>My Panel Inputs and Labels</PanelRow>
* </PanelBody>
* </Panel>
* );
* ```
*/
const Panel = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedPanel);
/* harmony default export */ var panel = (Panel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-up.js
/**
* WordPress dependencies
*/
const chevronUp = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"
}));
/* harmony default export */ var chevron_up = (chevronUp);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/body.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const body_noop = () => {};
function UnforwardedPanelBody(props, ref) {
const {
buttonProps = {},
children,
className,
icon,
initialOpen,
onToggle = body_noop,
opened,
title,
scrollAfterOpen = true
} = props;
const [isOpened, setIsOpened] = use_controlled_state(opened, {
initial: initialOpen === undefined ? true : initialOpen,
fallback: false
});
const nodeRef = (0,external_wp_element_namespaceObject.useRef)(null); // Defaults to 'smooth' scrolling
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
const scrollBehavior = (0,external_wp_compose_namespaceObject.useReducedMotion)() ? 'auto' : 'smooth';
const handleOnToggle = event => {
event.preventDefault();
const next = !isOpened;
setIsOpened(next);
onToggle(next);
}; // Ref is used so that the effect does not re-run upon scrollAfterOpen changing value.
const scrollAfterOpenRef = (0,external_wp_element_namespaceObject.useRef)();
scrollAfterOpenRef.current = scrollAfterOpen; // Runs after initial render.
use_update_effect(() => {
if (isOpened && scrollAfterOpenRef.current && nodeRef.current?.scrollIntoView) {
/*
* Scrolls the content into view when visible.
* This improves the UX when there are multiple stacking <PanelBody />
* components in a scrollable container.
*/
nodeRef.current.scrollIntoView({
inline: 'nearest',
block: 'nearest',
behavior: scrollBehavior
});
}
}, [isOpened, scrollBehavior]);
const classes = classnames_default()('components-panel__body', className, {
'is-opened': isOpened
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([nodeRef, ref])
}, (0,external_wp_element_namespaceObject.createElement)(PanelBodyTitle, {
icon: icon,
isOpened: Boolean(isOpened),
onClick: handleOnToggle,
title: title,
...buttonProps
}), typeof children === 'function' ? children({
opened: Boolean(isOpened)
}) : isOpened && children);
}
const PanelBodyTitle = (0,external_wp_element_namespaceObject.forwardRef)(({
isOpened,
icon,
title,
...props
}, ref) => {
if (!title) return null;
return (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "components-panel__body-title"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-panel__body-toggle",
"aria-expanded": isOpened,
ref: ref,
...props
}, (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-hidden": "true"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
className: "components-panel__arrow",
icon: isOpened ? chevron_up : chevron_down
})), title, icon && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon,
className: "components-panel__icon",
size: 20
})));
});
const PanelBody = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedPanelBody);
/* harmony default export */ var body = (PanelBody);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/row.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function UnforwardedPanelRow({
className,
children
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-panel__row', className),
ref: ref
}, children);
}
/**
* `PanelRow` is a generic container for rows within a `PanelBody`.
* It is a flex container with a top margin for spacing.
*/
const PanelRow = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedPanelRow);
/* harmony default export */ var row = (PanelRow);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/placeholder/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PlaceholderIllustration = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
className: "components-placeholder__illustration",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 60 60",
preserveAspectRatio: "none"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
vectorEffect: "non-scaling-stroke",
d: "M60 60 0 0"
}));
/**
* Renders a placeholder. Normally used by blocks to render their empty state.
*
* ```jsx
* import { Placeholder } from '@wordpress/components';
* import { more } from '@wordpress/icons';
*
* const MyPlaceholder = () => <Placeholder icon={ more } label="Placeholder" />;
* ```
*/
function Placeholder(props) {
const {
icon,
children,
label,
instructions,
className,
notices,
preview,
isColumnLayout,
withIllustration,
...additionalProps
} = props;
const [resizeListener, {
width
}] = (0,external_wp_compose_namespaceObject.useResizeObserver)(); // Since `useResizeObserver` will report a width of `null` until after the
// first render, avoid applying any modifier classes until width is known.
let modifierClassNames;
if (typeof width === 'number') {
modifierClassNames = {
'is-large': width >= 480,
'is-medium': width >= 160 && width < 480,
'is-small': width < 160
};
}
const classes = classnames_default()('components-placeholder', className, modifierClassNames, withIllustration ? 'has-illustration' : null);
const fieldsetClasses = classnames_default()('components-placeholder__fieldset', {
'is-column-layout': isColumnLayout
});
return (0,external_wp_element_namespaceObject.createElement)("div", { ...additionalProps,
className: classes
}, withIllustration ? PlaceholderIllustration : null, resizeListener, notices, preview && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-placeholder__preview"
}, preview), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-placeholder__label"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}), label), (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: fieldsetClasses
}, !!instructions && (0,external_wp_element_namespaceObject.createElement)("legend", {
className: "components-placeholder__instructions"
}, instructions), children));
}
/* harmony default export */ var placeholder = (Placeholder);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/terms.js
/**
* Internal dependencies
*/
const ensureParentsAreDefined = terms => {
return terms.every(term => term.parent !== null);
};
/**
* Returns terms in a tree form.
*
* @param flatTerms Array of terms in flat format.
*
* @return Terms in tree format.
*/
function buildTermsTree(flatTerms) {
const flatTermsWithParentAndChildren = flatTerms.map(term => ({
children: [],
parent: null,
...term,
id: String(term.id)
})); // We use a custom type guard here to ensure that the parent property is
// defined on all terms. The type of the `parent` property is `number | null`
// and we need to ensure that it is `number`. This is because we use the
// `parent` property as a key in the `termsByParent` object.
if (!ensureParentsAreDefined(flatTermsWithParentAndChildren)) {
return flatTermsWithParentAndChildren;
}
const termsByParent = flatTermsWithParentAndChildren.reduce((acc, term) => {
const {
parent
} = term;
if (!acc[parent]) {
acc[parent] = [];
}
acc[parent].push(term);
return acc;
}, {});
const fillWithChildren = terms => {
return terms.map(term => {
const children = termsByParent[term.id];
return { ...term,
children: children && children.length ? fillWithChildren(children) : []
};
});
};
return fillWithChildren(termsByParent['0'] || []);
}
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-select/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getSelectOptions(tree, level = 0) {
return tree.flatMap(treeNode => [{
value: treeNode.id,
label: '\u00A0'.repeat(level * 3) + (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(treeNode.name)
}, ...getSelectOptions(treeNode.children || [], level + 1)]);
}
/**
* TreeSelect component is used to generate select input fields.
*
* @example
* ```jsx
* import { TreeSelect } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTreeSelect = () => {
* const [ page, setPage ] = useState( 'p21' );
*
* return (
* <TreeSelect
* label="Parent page"
* noOptionLabel="No parent page"
* onChange={ ( newPage ) => setPage( newPage ) }
* selectedId={ page }
* tree={ [
* {
* name: 'Page 1',
* id: 'p1',
* children: [
* { name: 'Descend 1 of page 1', id: 'p11' },
* { name: 'Descend 2 of page 1', id: 'p12' },
* ],
* },
* {
* name: 'Page 2',
* id: 'p2',
* children: [
* {
* name: 'Descend 1 of page 2',
* id: 'p21',
* children: [
* {
* name: 'Descend 1 of Descend 1 of page 2',
* id: 'p211',
* },
* ],
* },
* ],
* },
* ] }
* />
* );
* }
* ```
*/
function TreeSelect({
label,
noOptionLabel,
onChange,
selectedId,
tree = [],
...props
}) {
const options = (0,external_wp_element_namespaceObject.useMemo)(() => {
return [noOptionLabel && {
value: '',
label: noOptionLabel
}, ...getSelectOptions(tree)].filter(option => !!option);
}, [noOptionLabel, tree]);
return (0,external_wp_element_namespaceObject.createElement)(SelectControl, {
label,
options,
onChange,
value: selectedId,
...props
});
}
/* harmony default export */ var tree_select = (TreeSelect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/author-select.js
/**
* Internal dependencies
*/
function AuthorSelect({
label,
noOptionLabel,
authorList,
selectedAuthorId,
onChange: onChangeProp
}) {
if (!authorList) return null;
const termsTree = buildTermsTree(authorList);
return (0,external_wp_element_namespaceObject.createElement)(tree_select, {
label,
noOptionLabel,
onChange: onChangeProp,
tree: termsTree,
selectedId: selectedAuthorId !== undefined ? String(selectedAuthorId) : undefined,
__nextHasNoMarginBottom: true
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/category-select.js
/**
* Internal dependencies
*/
/**
* WordPress dependencies
*/
function CategorySelect({
label,
noOptionLabel,
categoriesList,
selectedCategoryId,
onChange: onChangeProp,
...props
}) {
const termsTree = (0,external_wp_element_namespaceObject.useMemo)(() => {
return buildTermsTree(categoriesList);
}, [categoriesList]);
return (0,external_wp_element_namespaceObject.createElement)(tree_select, {
label,
noOptionLabel,
onChange: onChangeProp,
tree: termsTree,
selectedId: selectedCategoryId !== undefined ? String(selectedCategoryId) : undefined,
...props,
__nextHasNoMarginBottom: true
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_MIN_ITEMS = 1;
const DEFAULT_MAX_ITEMS = 100;
const MAX_CATEGORIES_SUGGESTIONS = 20;
function isSingleCategorySelection(props) {
return 'categoriesList' in props;
}
function isMultipleCategorySelection(props) {
return 'categorySuggestions' in props;
}
/**
* Controls to query for posts.
*
* ```jsx
* const MyQueryControls = () => (
* <QueryControls
* { ...{ maxItems, minItems, numberOfItems, order, orderBy } }
* onOrderByChange={ ( newOrderBy ) => {
* updateQuery( { orderBy: newOrderBy } )
* }
* onOrderChange={ ( newOrder ) => {
* updateQuery( { order: newOrder } )
* }
* categoriesList={ categories }
* selectedCategoryId={ category }
* onCategoryChange={ ( newCategory ) => {
* updateQuery( { category: newCategory } )
* }
* onNumberOfItemsChange={ ( newNumberOfItems ) => {
* updateQuery( { numberOfItems: newNumberOfItems } )
* } }
* />
* );
* ```
*/
function QueryControls({
authorList,
selectedAuthorId,
numberOfItems,
order,
orderBy,
maxItems = DEFAULT_MAX_ITEMS,
minItems = DEFAULT_MIN_ITEMS,
onAuthorChange,
onNumberOfItemsChange,
onOrderChange,
onOrderByChange,
// Props for single OR multiple category selection are not destructured here,
// but instead are destructured inline where necessary.
...props
}) {
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: "4",
className: "components-query-controls"
}, [onOrderChange && onOrderByChange && (0,external_wp_element_namespaceObject.createElement)(select_control, {
__nextHasNoMarginBottom: true,
key: "query-controls-order-select",
label: (0,external_wp_i18n_namespaceObject.__)('Order by'),
value: `${orderBy}/${order}`,
options: [{
label: (0,external_wp_i18n_namespaceObject.__)('Newest to oldest'),
value: 'date/desc'
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Oldest to newest'),
value: 'date/asc'
}, {
/* translators: label for ordering posts by title in ascending order */
label: (0,external_wp_i18n_namespaceObject.__)('A → Z'),
value: 'title/asc'
}, {
/* translators: label for ordering posts by title in descending order */
label: (0,external_wp_i18n_namespaceObject.__)('Z → A'),
value: 'title/desc'
}],
onChange: value => {
if (typeof value !== 'string') {
return;
}
const [newOrderBy, newOrder] = value.split('/');
if (newOrder !== order) {
onOrderChange(newOrder);
}
if (newOrderBy !== orderBy) {
onOrderByChange(newOrderBy);
}
}
}), isSingleCategorySelection(props) && props.categoriesList && props.onCategoryChange && (0,external_wp_element_namespaceObject.createElement)(CategorySelect, {
key: "query-controls-category-select",
categoriesList: props.categoriesList,
label: (0,external_wp_i18n_namespaceObject.__)('Category'),
noOptionLabel: (0,external_wp_i18n_namespaceObject.__)('All'),
selectedCategoryId: props.selectedCategoryId,
onChange: props.onCategoryChange
}), isMultipleCategorySelection(props) && props.categorySuggestions && props.onCategoryChange && (0,external_wp_element_namespaceObject.createElement)(form_token_field, {
__nextHasNoMarginBottom: true,
key: "query-controls-categories-select",
label: (0,external_wp_i18n_namespaceObject.__)('Categories'),
value: props.selectedCategories && props.selectedCategories.map(item => ({
id: item.id,
// Keeping the fallback to `item.value` for legacy reasons,
// even if items of `selectedCategories` should not have a
// `value` property.
// @ts-expect-error
value: item.name || item.value
})),
suggestions: Object.keys(props.categorySuggestions),
onChange: props.onCategoryChange,
maxSuggestions: MAX_CATEGORIES_SUGGESTIONS
}), onAuthorChange && (0,external_wp_element_namespaceObject.createElement)(AuthorSelect, {
key: "query-controls-author-select",
authorList: authorList,
label: (0,external_wp_i18n_namespaceObject.__)('Author'),
noOptionLabel: (0,external_wp_i18n_namespaceObject.__)('All'),
selectedAuthorId: selectedAuthorId,
onChange: onAuthorChange
}), onNumberOfItemsChange && (0,external_wp_element_namespaceObject.createElement)(range_control, {
__nextHasNoMarginBottom: true,
key: "query-controls-range-control",
label: (0,external_wp_i18n_namespaceObject.__)('Number of items'),
value: numberOfItems,
onChange: onNumberOfItemsChange,
min: minItems,
max: maxItems,
required: true
})]);
}
/* harmony default export */ var query_controls = (QueryControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-group/radio-context/index.js
/**
* WordPress dependencies
*/
const RadioContext = (0,external_wp_element_namespaceObject.createContext)({
state: null,
setState: () => {}
});
/* harmony default export */ var radio_context = (RadioContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-group/radio/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function radio_Radio({
children,
value,
...props
}, ref) {
const radioContext = (0,external_wp_element_namespaceObject.useContext)(radio_context);
const checked = radioContext.state === value;
return (0,external_wp_element_namespaceObject.createElement)(Radio, {
ref: ref,
as: build_module_button,
variant: checked ? 'primary' : 'secondary',
value: value,
...radioContext,
...props
}, children || value);
}
/**
* @deprecated Use `RadioControl` or `ToggleGroupControl` instead.
*/
/* harmony default export */ var radio_group_radio = ((0,external_wp_element_namespaceObject.forwardRef)(radio_Radio));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-group/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function radio_group_RadioGroup({
label,
checked,
defaultChecked,
disabled,
onChange,
...props
}, ref) {
const radioState = useRadioState({
state: defaultChecked,
baseId: props.id
});
const radioContext = { ...radioState,
disabled,
// Controlled or uncontrolled.
state: checked !== null && checked !== void 0 ? checked : radioState.state,
setState: onChange !== null && onChange !== void 0 ? onChange : radioState.setState
};
return (0,external_wp_element_namespaceObject.createElement)(radio_context.Provider, {
value: radioContext
}, (0,external_wp_element_namespaceObject.createElement)(RadioGroup, {
ref: ref,
as: button_group,
"aria-label": label,
...radioState,
...props
}));
}
/**
* @deprecated Use `RadioControl` or `ToggleGroupControl` instead.
*/
/* harmony default export */ var radio_group = ((0,external_wp_element_namespaceObject.forwardRef)(radio_group_RadioGroup));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Render a user interface to select the user type using radio inputs.
*
* ```jsx
* import { RadioControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyRadioControl = () => {
* const [ option, setOption ] = useState( 'a' );
*
* return (
* <RadioControl
* label="User type"
* help="The type of the current user"
* selected={ option }
* options={ [
* { label: 'Author', value: 'a' },
* { label: 'Editor', value: 'e' },
* ] }
* onChange={ ( value ) => setOption( value ) }
* />
* );
* };
* ```
*/
function RadioControl(props) {
const {
label,
className,
selected,
help,
onChange,
hideLabelFromVision,
options = [],
...additionalProps
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(RadioControl);
const id = `inspector-radio-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.value);
if (!options?.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: true,
label: label,
id: id,
hideLabelFromVision: hideLabelFromVision,
help: help,
className: classnames_default()(className, 'components-radio-control')
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 1
}, options.map((option, index) => (0,external_wp_element_namespaceObject.createElement)("div", {
key: `${id}-${index}`,
className: "components-radio-control__option"
}, (0,external_wp_element_namespaceObject.createElement)("input", {
id: `${id}-${index}`,
className: "components-radio-control__input",
type: "radio",
name: id,
value: option.value,
onChange: onChangeValue,
checked: option.value === selected,
"aria-describedby": !!help ? `${id}__help` : undefined,
...additionalProps
}), (0,external_wp_element_namespaceObject.createElement)("label", {
htmlFor: `${id}-${index}`
}, option.label)))));
}
/* harmony default export */ var radio_control = (RadioControl);
;// CONCATENATED MODULE: ./node_modules/re-resizable/lib/resizer.js
var resizer_extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var resizer_assign = (undefined && undefined.__assign) || function () {
resizer_assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return resizer_assign.apply(this, arguments);
};
var rowSizeBase = {
width: '100%',
height: '10px',
top: '0px',
left: '0px',
cursor: 'row-resize',
};
var colSizeBase = {
width: '10px',
height: '100%',
top: '0px',
left: '0px',
cursor: 'col-resize',
};
var edgeBase = {
width: '20px',
height: '20px',
position: 'absolute',
};
var resizer_styles = {
top: resizer_assign(resizer_assign({}, rowSizeBase), { top: '-5px' }),
right: resizer_assign(resizer_assign({}, colSizeBase), { left: undefined, right: '-5px' }),
bottom: resizer_assign(resizer_assign({}, rowSizeBase), { top: undefined, bottom: '-5px' }),
left: resizer_assign(resizer_assign({}, colSizeBase), { left: '-5px' }),
topRight: resizer_assign(resizer_assign({}, edgeBase), { right: '-10px', top: '-10px', cursor: 'ne-resize' }),
bottomRight: resizer_assign(resizer_assign({}, edgeBase), { right: '-10px', bottom: '-10px', cursor: 'se-resize' }),
bottomLeft: resizer_assign(resizer_assign({}, edgeBase), { left: '-10px', bottom: '-10px', cursor: 'sw-resize' }),
topLeft: resizer_assign(resizer_assign({}, edgeBase), { left: '-10px', top: '-10px', cursor: 'nw-resize' }),
};
var Resizer = /** @class */ (function (_super) {
resizer_extends(Resizer, _super);
function Resizer() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.onMouseDown = function (e) {
_this.props.onResizeStart(e, _this.props.direction);
};
_this.onTouchStart = function (e) {
_this.props.onResizeStart(e, _this.props.direction);
};
return _this;
}
Resizer.prototype.render = function () {
return (external_React_.createElement("div", { className: this.props.className || '', style: resizer_assign(resizer_assign({ position: 'absolute', userSelect: 'none' }, resizer_styles[this.props.direction]), (this.props.replaceStyles || {})), onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart }, this.props.children));
};
return Resizer;
}(external_React_.PureComponent));
;// CONCATENATED MODULE: ./node_modules/re-resizable/lib/index.js
var lib_extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var lib_assign = (undefined && undefined.__assign) || function () {
lib_assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return lib_assign.apply(this, arguments);
};
var DEFAULT_SIZE = {
width: 'auto',
height: 'auto',
};
var lib_clamp = function (n, min, max) { return Math.max(Math.min(n, max), min); };
var snap = function (n, size) { return Math.round(n / size) * size; };
var hasDirection = function (dir, target) {
return new RegExp(dir, 'i').test(target);
};
// INFO: In case of window is a Proxy and does not porxy Events correctly, use isTouchEvent & isMouseEvent to distinguish event type instead of `instanceof`.
var isTouchEvent = function (event) {
return Boolean(event.touches && event.touches.length);
};
var isMouseEvent = function (event) {
return Boolean((event.clientX || event.clientX === 0) &&
(event.clientY || event.clientY === 0));
};
var findClosestSnap = function (n, snapArray, snapGap) {
if (snapGap === void 0) { snapGap = 0; }
var closestGapIndex = snapArray.reduce(function (prev, curr, index) { return (Math.abs(curr - n) < Math.abs(snapArray[prev] - n) ? index : prev); }, 0);
var gap = Math.abs(snapArray[closestGapIndex] - n);
return snapGap === 0 || gap < snapGap ? snapArray[closestGapIndex] : n;
};
var getStringSize = function (n) {
n = n.toString();
if (n === 'auto') {
return n;
}
if (n.endsWith('px')) {
return n;
}
if (n.endsWith('%')) {
return n;
}
if (n.endsWith('vh')) {
return n;
}
if (n.endsWith('vw')) {
return n;
}
if (n.endsWith('vmax')) {
return n;
}
if (n.endsWith('vmin')) {
return n;
}
return n + "px";
};
var getPixelSize = function (size, parentSize, innerWidth, innerHeight) {
if (size && typeof size === 'string') {
if (size.endsWith('px')) {
return Number(size.replace('px', ''));
}
if (size.endsWith('%')) {
var ratio = Number(size.replace('%', '')) / 100;
return parentSize * ratio;
}
if (size.endsWith('vw')) {
var ratio = Number(size.replace('vw', '')) / 100;
return innerWidth * ratio;
}
if (size.endsWith('vh')) {
var ratio = Number(size.replace('vh', '')) / 100;
return innerHeight * ratio;
}
}
return size;
};
var calculateNewMax = function (parentSize, innerWidth, innerHeight, maxWidth, maxHeight, minWidth, minHeight) {
maxWidth = getPixelSize(maxWidth, parentSize.width, innerWidth, innerHeight);
maxHeight = getPixelSize(maxHeight, parentSize.height, innerWidth, innerHeight);
minWidth = getPixelSize(minWidth, parentSize.width, innerWidth, innerHeight);
minHeight = getPixelSize(minHeight, parentSize.height, innerWidth, innerHeight);
return {
maxWidth: typeof maxWidth === 'undefined' ? undefined : Number(maxWidth),
maxHeight: typeof maxHeight === 'undefined' ? undefined : Number(maxHeight),
minWidth: typeof minWidth === 'undefined' ? undefined : Number(minWidth),
minHeight: typeof minHeight === 'undefined' ? undefined : Number(minHeight),
};
};
var definedProps = [
'as',
'style',
'className',
'grid',
'snap',
'bounds',
'boundsByDirection',
'size',
'defaultSize',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'lockAspectRatio',
'lockAspectRatioExtraWidth',
'lockAspectRatioExtraHeight',
'enable',
'handleStyles',
'handleClasses',
'handleWrapperStyle',
'handleWrapperClass',
'children',
'onResizeStart',
'onResize',
'onResizeStop',
'handleComponent',
'scale',
'resizeRatio',
'snapGap',
];
// HACK: This class is used to calculate % size.
var baseClassName = '__resizable_base__';
var Resizable = /** @class */ (function (_super) {
lib_extends(Resizable, _super);
function Resizable(props) {
var _this = _super.call(this, props) || this;
_this.ratio = 1;
_this.resizable = null;
// For parent boundary
_this.parentLeft = 0;
_this.parentTop = 0;
// For boundary
_this.resizableLeft = 0;
_this.resizableRight = 0;
_this.resizableTop = 0;
_this.resizableBottom = 0;
// For target boundary
_this.targetLeft = 0;
_this.targetTop = 0;
_this.appendBase = function () {
if (!_this.resizable || !_this.window) {
return null;
}
var parent = _this.parentNode;
if (!parent) {
return null;
}
var element = _this.window.document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
element.style.position = 'absolute';
element.style.transform = 'scale(0, 0)';
element.style.left = '0';
element.style.flex = '0 0 100%';
if (element.classList) {
element.classList.add(baseClassName);
}
else {
element.className += baseClassName;
}
parent.appendChild(element);
return element;
};
_this.removeBase = function (base) {
var parent = _this.parentNode;
if (!parent) {
return;
}
parent.removeChild(base);
};
_this.ref = function (c) {
if (c) {
_this.resizable = c;
}
};
_this.state = {
isResizing: false,
width: typeof (_this.propsSize && _this.propsSize.width) === 'undefined'
? 'auto'
: _this.propsSize && _this.propsSize.width,
height: typeof (_this.propsSize && _this.propsSize.height) === 'undefined'
? 'auto'
: _this.propsSize && _this.propsSize.height,
direction: 'right',
original: {
x: 0,
y: 0,
width: 0,
height: 0,
},
backgroundStyle: {
height: '100%',
width: '100%',
backgroundColor: 'rgba(0,0,0,0)',
cursor: 'auto',
opacity: 0,
position: 'fixed',
zIndex: 9999,
top: '0',
left: '0',
bottom: '0',
right: '0',
},
flexBasis: undefined,
};
_this.onResizeStart = _this.onResizeStart.bind(_this);
_this.onMouseMove = _this.onMouseMove.bind(_this);
_this.onMouseUp = _this.onMouseUp.bind(_this);
return _this;
}
Object.defineProperty(Resizable.prototype, "parentNode", {
get: function () {
if (!this.resizable) {
return null;
}
return this.resizable.parentNode;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "window", {
get: function () {
if (!this.resizable) {
return null;
}
if (!this.resizable.ownerDocument) {
return null;
}
return this.resizable.ownerDocument.defaultView;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "propsSize", {
get: function () {
return this.props.size || this.props.defaultSize || DEFAULT_SIZE;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "size", {
get: function () {
var width = 0;
var height = 0;
if (this.resizable && this.window) {
var orgWidth = this.resizable.offsetWidth;
var orgHeight = this.resizable.offsetHeight;
// HACK: Set position `relative` to get parent size.
// This is because when re-resizable set `absolute`, I can not get base width correctly.
var orgPosition = this.resizable.style.position;
if (orgPosition !== 'relative') {
this.resizable.style.position = 'relative';
}
// INFO: Use original width or height if set auto.
width = this.resizable.style.width !== 'auto' ? this.resizable.offsetWidth : orgWidth;
height = this.resizable.style.height !== 'auto' ? this.resizable.offsetHeight : orgHeight;
// Restore original position
this.resizable.style.position = orgPosition;
}
return { width: width, height: height };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "sizeStyle", {
get: function () {
var _this = this;
var size = this.props.size;
var getSize = function (key) {
if (typeof _this.state[key] === 'undefined' || _this.state[key] === 'auto') {
return 'auto';
}
if (_this.propsSize && _this.propsSize[key] && _this.propsSize[key].toString().endsWith('%')) {
if (_this.state[key].toString().endsWith('%')) {
return _this.state[key].toString();
}
var parentSize = _this.getParentSize();
var value = Number(_this.state[key].toString().replace('px', ''));
var percent = (value / parentSize[key]) * 100;
return percent + "%";
}
return getStringSize(_this.state[key]);
};
var width = size && typeof size.width !== 'undefined' && !this.state.isResizing
? getStringSize(size.width)
: getSize('width');
var height = size && typeof size.height !== 'undefined' && !this.state.isResizing
? getStringSize(size.height)
: getSize('height');
return { width: width, height: height };
},
enumerable: false,
configurable: true
});
Resizable.prototype.getParentSize = function () {
if (!this.parentNode) {
if (!this.window) {
return { width: 0, height: 0 };
}
return { width: this.window.innerWidth, height: this.window.innerHeight };
}
var base = this.appendBase();
if (!base) {
return { width: 0, height: 0 };
}
// INFO: To calculate parent width with flex layout
var wrapChanged = false;
var wrap = this.parentNode.style.flexWrap;
if (wrap !== 'wrap') {
wrapChanged = true;
this.parentNode.style.flexWrap = 'wrap';
// HACK: Use relative to get parent padding size
}
base.style.position = 'relative';
base.style.minWidth = '100%';
base.style.minHeight = '100%';
var size = {
width: base.offsetWidth,
height: base.offsetHeight,
};
if (wrapChanged) {
this.parentNode.style.flexWrap = wrap;
}
this.removeBase(base);
return size;
};
Resizable.prototype.bindEvents = function () {
if (this.window) {
this.window.addEventListener('mouseup', this.onMouseUp);
this.window.addEventListener('mousemove', this.onMouseMove);
this.window.addEventListener('mouseleave', this.onMouseUp);
this.window.addEventListener('touchmove', this.onMouseMove, {
capture: true,
passive: false,
});
this.window.addEventListener('touchend', this.onMouseUp);
}
};
Resizable.prototype.unbindEvents = function () {
if (this.window) {
this.window.removeEventListener('mouseup', this.onMouseUp);
this.window.removeEventListener('mousemove', this.onMouseMove);
this.window.removeEventListener('mouseleave', this.onMouseUp);
this.window.removeEventListener('touchmove', this.onMouseMove, true);
this.window.removeEventListener('touchend', this.onMouseUp);
}
};
Resizable.prototype.componentDidMount = function () {
if (!this.resizable || !this.window) {
return;
}
var computedStyle = this.window.getComputedStyle(this.resizable);
this.setState({
width: this.state.width || this.size.width,
height: this.state.height || this.size.height,
flexBasis: computedStyle.flexBasis !== 'auto' ? computedStyle.flexBasis : undefined,
});
};
Resizable.prototype.componentWillUnmount = function () {
if (this.window) {
this.unbindEvents();
}
};
Resizable.prototype.createSizeForCssProperty = function (newSize, kind) {
var propsSize = this.propsSize && this.propsSize[kind];
return this.state[kind] === 'auto' &&
this.state.original[kind] === newSize &&
(typeof propsSize === 'undefined' || propsSize === 'auto')
? 'auto'
: newSize;
};
Resizable.prototype.calculateNewMaxFromBoundary = function (maxWidth, maxHeight) {
var boundsByDirection = this.props.boundsByDirection;
var direction = this.state.direction;
var widthByDirection = boundsByDirection && hasDirection('left', direction);
var heightByDirection = boundsByDirection && hasDirection('top', direction);
var boundWidth;
var boundHeight;
if (this.props.bounds === 'parent') {
var parent_1 = this.parentNode;
if (parent_1) {
boundWidth = widthByDirection
? this.resizableRight - this.parentLeft
: parent_1.offsetWidth + (this.parentLeft - this.resizableLeft);
boundHeight = heightByDirection
? this.resizableBottom - this.parentTop
: parent_1.offsetHeight + (this.parentTop - this.resizableTop);
}
}
else if (this.props.bounds === 'window') {
if (this.window) {
boundWidth = widthByDirection ? this.resizableRight : this.window.innerWidth - this.resizableLeft;
boundHeight = heightByDirection ? this.resizableBottom : this.window.innerHeight - this.resizableTop;
}
}
else if (this.props.bounds) {
boundWidth = widthByDirection
? this.resizableRight - this.targetLeft
: this.props.bounds.offsetWidth + (this.targetLeft - this.resizableLeft);
boundHeight = heightByDirection
? this.resizableBottom - this.targetTop
: this.props.bounds.offsetHeight + (this.targetTop - this.resizableTop);
}
if (boundWidth && Number.isFinite(boundWidth)) {
maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;
}
if (boundHeight && Number.isFinite(boundHeight)) {
maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;
}
return { maxWidth: maxWidth, maxHeight: maxHeight };
};
Resizable.prototype.calculateNewSizeFromDirection = function (clientX, clientY) {
var scale = this.props.scale || 1;
var resizeRatio = this.props.resizeRatio || 1;
var _a = this.state, direction = _a.direction, original = _a.original;
var _b = this.props, lockAspectRatio = _b.lockAspectRatio, lockAspectRatioExtraHeight = _b.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _b.lockAspectRatioExtraWidth;
var newWidth = original.width;
var newHeight = original.height;
var extraHeight = lockAspectRatioExtraHeight || 0;
var extraWidth = lockAspectRatioExtraWidth || 0;
if (hasDirection('right', direction)) {
newWidth = original.width + ((clientX - original.x) * resizeRatio) / scale;
if (lockAspectRatio) {
newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;
}
}
if (hasDirection('left', direction)) {
newWidth = original.width - ((clientX - original.x) * resizeRatio) / scale;
if (lockAspectRatio) {
newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;
}
}
if (hasDirection('bottom', direction)) {
newHeight = original.height + ((clientY - original.y) * resizeRatio) / scale;
if (lockAspectRatio) {
newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;
}
}
if (hasDirection('top', direction)) {
newHeight = original.height - ((clientY - original.y) * resizeRatio) / scale;
if (lockAspectRatio) {
newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;
}
}
return { newWidth: newWidth, newHeight: newHeight };
};
Resizable.prototype.calculateNewSizeFromAspectRatio = function (newWidth, newHeight, max, min) {
var _a = this.props, lockAspectRatio = _a.lockAspectRatio, lockAspectRatioExtraHeight = _a.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _a.lockAspectRatioExtraWidth;
var computedMinWidth = typeof min.width === 'undefined' ? 10 : min.width;
var computedMaxWidth = typeof max.width === 'undefined' || max.width < 0 ? newWidth : max.width;
var computedMinHeight = typeof min.height === 'undefined' ? 10 : min.height;
var computedMaxHeight = typeof max.height === 'undefined' || max.height < 0 ? newHeight : max.height;
var extraHeight = lockAspectRatioExtraHeight || 0;
var extraWidth = lockAspectRatioExtraWidth || 0;
if (lockAspectRatio) {
var extraMinWidth = (computedMinHeight - extraHeight) * this.ratio + extraWidth;
var extraMaxWidth = (computedMaxHeight - extraHeight) * this.ratio + extraWidth;
var extraMinHeight = (computedMinWidth - extraWidth) / this.ratio + extraHeight;
var extraMaxHeight = (computedMaxWidth - extraWidth) / this.ratio + extraHeight;
var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth);
var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth);
var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight);
var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight);
newWidth = lib_clamp(newWidth, lockedMinWidth, lockedMaxWidth);
newHeight = lib_clamp(newHeight, lockedMinHeight, lockedMaxHeight);
}
else {
newWidth = lib_clamp(newWidth, computedMinWidth, computedMaxWidth);
newHeight = lib_clamp(newHeight, computedMinHeight, computedMaxHeight);
}
return { newWidth: newWidth, newHeight: newHeight };
};
Resizable.prototype.setBoundingClientRect = function () {
// For parent boundary
if (this.props.bounds === 'parent') {
var parent_2 = this.parentNode;
if (parent_2) {
var parentRect = parent_2.getBoundingClientRect();
this.parentLeft = parentRect.left;
this.parentTop = parentRect.top;
}
}
// For target(html element) boundary
if (this.props.bounds && typeof this.props.bounds !== 'string') {
var targetRect = this.props.bounds.getBoundingClientRect();
this.targetLeft = targetRect.left;
this.targetTop = targetRect.top;
}
// For boundary
if (this.resizable) {
var _a = this.resizable.getBoundingClientRect(), left = _a.left, top_1 = _a.top, right = _a.right, bottom = _a.bottom;
this.resizableLeft = left;
this.resizableRight = right;
this.resizableTop = top_1;
this.resizableBottom = bottom;
}
};
Resizable.prototype.onResizeStart = function (event, direction) {
if (!this.resizable || !this.window) {
return;
}
var clientX = 0;
var clientY = 0;
if (event.nativeEvent && isMouseEvent(event.nativeEvent)) {
clientX = event.nativeEvent.clientX;
clientY = event.nativeEvent.clientY;
}
else if (event.nativeEvent && isTouchEvent(event.nativeEvent)) {
clientX = event.nativeEvent.touches[0].clientX;
clientY = event.nativeEvent.touches[0].clientY;
}
if (this.props.onResizeStart) {
if (this.resizable) {
var startResize = this.props.onResizeStart(event, direction, this.resizable);
if (startResize === false) {
return;
}
}
}
// Fix #168
if (this.props.size) {
if (typeof this.props.size.height !== 'undefined' && this.props.size.height !== this.state.height) {
this.setState({ height: this.props.size.height });
}
if (typeof this.props.size.width !== 'undefined' && this.props.size.width !== this.state.width) {
this.setState({ width: this.props.size.width });
}
}
// For lockAspectRatio case
this.ratio =
typeof this.props.lockAspectRatio === 'number' ? this.props.lockAspectRatio : this.size.width / this.size.height;
var flexBasis;
var computedStyle = this.window.getComputedStyle(this.resizable);
if (computedStyle.flexBasis !== 'auto') {
var parent_3 = this.parentNode;
if (parent_3) {
var dir = this.window.getComputedStyle(parent_3).flexDirection;
this.flexDir = dir.startsWith('row') ? 'row' : 'column';
flexBasis = computedStyle.flexBasis;
}
}
// For boundary
this.setBoundingClientRect();
this.bindEvents();
var state = {
original: {
x: clientX,
y: clientY,
width: this.size.width,
height: this.size.height,
},
isResizing: true,
backgroundStyle: lib_assign(lib_assign({}, this.state.backgroundStyle), { cursor: this.window.getComputedStyle(event.target).cursor || 'auto' }),
direction: direction,
flexBasis: flexBasis,
};
this.setState(state);
};
Resizable.prototype.onMouseMove = function (event) {
var _this = this;
if (!this.state.isResizing || !this.resizable || !this.window) {
return;
}
if (this.window.TouchEvent && isTouchEvent(event)) {
try {
event.preventDefault();
event.stopPropagation();
}
catch (e) {
// Ignore on fail
}
}
var _a = this.props, maxWidth = _a.maxWidth, maxHeight = _a.maxHeight, minWidth = _a.minWidth, minHeight = _a.minHeight;
var clientX = isTouchEvent(event) ? event.touches[0].clientX : event.clientX;
var clientY = isTouchEvent(event) ? event.touches[0].clientY : event.clientY;
var _b = this.state, direction = _b.direction, original = _b.original, width = _b.width, height = _b.height;
var parentSize = this.getParentSize();
var max = calculateNewMax(parentSize, this.window.innerWidth, this.window.innerHeight, maxWidth, maxHeight, minWidth, minHeight);
maxWidth = max.maxWidth;
maxHeight = max.maxHeight;
minWidth = max.minWidth;
minHeight = max.minHeight;
// Calculate new size
var _c = this.calculateNewSizeFromDirection(clientX, clientY), newHeight = _c.newHeight, newWidth = _c.newWidth;
// Calculate max size from boundary settings
var boundaryMax = this.calculateNewMaxFromBoundary(maxWidth, maxHeight);
if (this.props.snap && this.props.snap.x) {
newWidth = findClosestSnap(newWidth, this.props.snap.x, this.props.snapGap);
}
if (this.props.snap && this.props.snap.y) {
newHeight = findClosestSnap(newHeight, this.props.snap.y, this.props.snapGap);
}
// Calculate new size from aspect ratio
var newSize = this.calculateNewSizeFromAspectRatio(newWidth, newHeight, { width: boundaryMax.maxWidth, height: boundaryMax.maxHeight }, { width: minWidth, height: minHeight });
newWidth = newSize.newWidth;
newHeight = newSize.newHeight;
if (this.props.grid) {
var newGridWidth = snap(newWidth, this.props.grid[0]);
var newGridHeight = snap(newHeight, this.props.grid[1]);
var gap = this.props.snapGap || 0;
newWidth = gap === 0 || Math.abs(newGridWidth - newWidth) <= gap ? newGridWidth : newWidth;
newHeight = gap === 0 || Math.abs(newGridHeight - newHeight) <= gap ? newGridHeight : newHeight;
}
var delta = {
width: newWidth - original.width,
height: newHeight - original.height,
};
if (width && typeof width === 'string') {
if (width.endsWith('%')) {
var percent = (newWidth / parentSize.width) * 100;
newWidth = percent + "%";
}
else if (width.endsWith('vw')) {
var vw = (newWidth / this.window.innerWidth) * 100;
newWidth = vw + "vw";
}
else if (width.endsWith('vh')) {
var vh = (newWidth / this.window.innerHeight) * 100;
newWidth = vh + "vh";
}
}
if (height && typeof height === 'string') {
if (height.endsWith('%')) {
var percent = (newHeight / parentSize.height) * 100;
newHeight = percent + "%";
}
else if (height.endsWith('vw')) {
var vw = (newHeight / this.window.innerWidth) * 100;
newHeight = vw + "vw";
}
else if (height.endsWith('vh')) {
var vh = (newHeight / this.window.innerHeight) * 100;
newHeight = vh + "vh";
}
}
var newState = {
width: this.createSizeForCssProperty(newWidth, 'width'),
height: this.createSizeForCssProperty(newHeight, 'height'),
};
if (this.flexDir === 'row') {
newState.flexBasis = newState.width;
}
else if (this.flexDir === 'column') {
newState.flexBasis = newState.height;
}
// For v18, update state sync
(0,external_ReactDOM_namespaceObject.flushSync)(function () {
_this.setState(newState);
});
if (this.props.onResize) {
this.props.onResize(event, direction, this.resizable, delta);
}
};
Resizable.prototype.onMouseUp = function (event) {
var _a = this.state, isResizing = _a.isResizing, direction = _a.direction, original = _a.original;
if (!isResizing || !this.resizable) {
return;
}
var delta = {
width: this.size.width - original.width,
height: this.size.height - original.height,
};
if (this.props.onResizeStop) {
this.props.onResizeStop(event, direction, this.resizable, delta);
}
if (this.props.size) {
this.setState(this.props.size);
}
this.unbindEvents();
this.setState({
isResizing: false,
backgroundStyle: lib_assign(lib_assign({}, this.state.backgroundStyle), { cursor: 'auto' }),
});
};
Resizable.prototype.updateSize = function (size) {
this.setState({ width: size.width, height: size.height });
};
Resizable.prototype.renderResizer = function () {
var _this = this;
var _a = this.props, enable = _a.enable, handleStyles = _a.handleStyles, handleClasses = _a.handleClasses, handleWrapperStyle = _a.handleWrapperStyle, handleWrapperClass = _a.handleWrapperClass, handleComponent = _a.handleComponent;
if (!enable) {
return null;
}
var resizers = Object.keys(enable).map(function (dir) {
if (enable[dir] !== false) {
return (external_React_.createElement(Resizer, { key: dir, direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir] }, handleComponent && handleComponent[dir] ? handleComponent[dir] : null));
}
return null;
});
// #93 Wrap the resize box in span (will not break 100% width/height)
return (external_React_.createElement("div", { className: handleWrapperClass, style: handleWrapperStyle }, resizers));
};
Resizable.prototype.render = function () {
var _this = this;
var extendsProps = Object.keys(this.props).reduce(function (acc, key) {
if (definedProps.indexOf(key) !== -1) {
return acc;
}
acc[key] = _this.props[key];
return acc;
}, {});
var style = lib_assign(lib_assign(lib_assign({ position: 'relative', userSelect: this.state.isResizing ? 'none' : 'auto' }, this.props.style), this.sizeStyle), { maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, minWidth: this.props.minWidth, minHeight: this.props.minHeight, boxSizing: 'border-box', flexShrink: 0 });
if (this.state.flexBasis) {
style.flexBasis = this.state.flexBasis;
}
var Wrapper = this.props.as || 'div';
return (external_React_.createElement(Wrapper, lib_assign({ ref: this.ref, style: style, className: this.props.className }, extendsProps),
this.state.isResizing && external_React_.createElement("div", { style: this.state.backgroundStyle }),
this.props.children,
this.renderResizer()));
};
Resizable.defaultProps = {
as: 'div',
onResizeStart: function () { },
onResize: function () { },
onResizeStop: function () { },
enable: {
top: true,
right: true,
bottom: true,
left: true,
topRight: true,
bottomRight: true,
bottomLeft: true,
topLeft: true,
},
style: {},
grid: [1, 1],
lockAspectRatio: false,
lockAspectRatioExtraWidth: 0,
lockAspectRatioExtraHeight: 0,
scale: 1,
resizeRatio: 1,
snapGap: 0,
};
return Resizable;
}(external_React_.PureComponent));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/utils.js
/**
* WordPress dependencies
*/
const utils_noop = () => {};
const POSITIONS = {
bottom: 'bottom',
corner: 'corner'
};
/**
* Custom hook that manages resize listener events. It also provides a label
* based on current resize width x height values.
*
* @param props
* @param props.axis Only shows the label corresponding to the axis.
* @param props.fadeTimeout Duration (ms) before deactivating the resize label.
* @param props.onResize Callback when a resize occurs. Provides { width, height } callback.
* @param props.position Adjusts label value.
* @param props.showPx Whether to add `PX` to the label.
*
* @return Properties for hook.
*/
function useResizeLabel({
axis,
fadeTimeout = 180,
onResize = utils_noop,
position = POSITIONS.bottom,
showPx = false
}) {
/*
* The width/height values derive from this special useResizeObserver hook.
* This custom hook uses the ResizeObserver API to listen for resize events.
*/
const [resizeListener, sizes] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
/*
* Indicates if the x/y axis is preferred.
* If set, we will avoid resetting the moveX and moveY values.
* This will allow for the preferred axis values to persist in the label.
*/
const isAxisControlled = !!axis;
/*
* The moveX and moveY values are used to track whether the label should
* display width, height, or width x height.
*/
const [moveX, setMoveX] = (0,external_wp_element_namespaceObject.useState)(false);
const [moveY, setMoveY] = (0,external_wp_element_namespaceObject.useState)(false);
/*
* Cached dimension values to check for width/height updates from the
* sizes property from useResizeAware()
*/
const {
width,
height
} = sizes;
const heightRef = (0,external_wp_element_namespaceObject.useRef)(height);
const widthRef = (0,external_wp_element_namespaceObject.useRef)(width);
/*
* This timeout is used with setMoveX and setMoveY to determine of
* both width and height values have changed at (roughly) the same time.
*/
const moveTimeoutRef = (0,external_wp_element_namespaceObject.useRef)();
const debounceUnsetMoveXY = (0,external_wp_element_namespaceObject.useCallback)(() => {
const unsetMoveXY = () => {
/*
* If axis is controlled, we will avoid resetting the moveX and moveY values.
* This will allow for the preferred axis values to persist in the label.
*/
if (isAxisControlled) return;
setMoveX(false);
setMoveY(false);
};
if (moveTimeoutRef.current) {
window.clearTimeout(moveTimeoutRef.current);
}
moveTimeoutRef.current = window.setTimeout(unsetMoveXY, fadeTimeout);
}, [fadeTimeout, isAxisControlled]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
/*
* On the initial render of useResizeAware, the height and width values are
* null. They are calculated then set using via an internal useEffect hook.
*/
const isRendered = width !== null || height !== null;
if (!isRendered) return;
const didWidthChange = width !== widthRef.current;
const didHeightChange = height !== heightRef.current;
if (!didWidthChange && !didHeightChange) return;
/*
* After the initial render, the useResizeAware will set the first
* width and height values. We'll sync those values with our
* width and height refs. However, we shouldn't render our Tooltip
* label on this first cycle.
*/
if (width && !widthRef.current && height && !heightRef.current) {
widthRef.current = width;
heightRef.current = height;
return;
}
/*
* After the first cycle, we can track width and height changes.
*/
if (didWidthChange) {
setMoveX(true);
widthRef.current = width;
}
if (didHeightChange) {
setMoveY(true);
heightRef.current = height;
}
onResize({
width,
height
});
debounceUnsetMoveXY();
}, [width, height, onResize, debounceUnsetMoveXY]);
const label = getSizeLabel({
axis,
height,
moveX,
moveY,
position,
showPx,
width
});
return {
label,
resizeListener
};
}
/**
* Gets the resize label based on width and height values (as well as recent changes).
*
* @param props
* @param props.axis Only shows the label corresponding to the axis.
* @param props.height Height value.
* @param props.moveX Recent width (x axis) changes.
* @param props.moveY Recent width (y axis) changes.
* @param props.position Adjusts label value.
* @param props.showPx Whether to add `PX` to the label.
* @param props.width Width value.
*
* @return The rendered label.
*/
function getSizeLabel({
axis,
height,
moveX = false,
moveY = false,
position = POSITIONS.bottom,
showPx = false,
width
}) {
if (!moveX && !moveY) return undefined;
/*
* Corner position...
* We want the label to appear like width x height.
*/
if (position === POSITIONS.corner) {
return `${width} x ${height}`;
}
/*
* Other POSITIONS...
* The label will combine both width x height values if both
* values have recently been changed.
*
* Otherwise, only width or height will be displayed.
* The `PX` unit will be added, if specified by the `showPx` prop.
*/
const labelUnit = showPx ? ' px' : '';
if (axis) {
if (axis === 'x' && moveX) {
return `${width}${labelUnit}`;
}
if (axis === 'y' && moveY) {
return `${height}${labelUnit}`;
}
}
if (moveX && moveY) {
return `${width} x ${height}`;
}
if (moveX) {
return `${width}${labelUnit}`;
}
if (moveY) {
return `${height}${labelUnit}`;
}
return undefined;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/styles/resize-tooltip.styles.js
function resize_tooltip_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const resize_tooltip_styles_Root = createStyled("div", true ? {
target: "e1wq7y4k3"
} : 0)( true ? {
name: "1cd7zoc",
styles: "bottom:0;box-sizing:border-box;left:0;pointer-events:none;position:absolute;right:0;top:0"
} : 0);
const TooltipWrapper = createStyled("div", true ? {
target: "e1wq7y4k2"
} : 0)( true ? {
name: "ajymcs",
styles: "align-items:center;box-sizing:border-box;display:inline-flex;justify-content:center;opacity:0;pointer-events:none;transition:opacity 120ms linear"
} : 0);
const resize_tooltip_styles_Tooltip = createStyled("div", true ? {
target: "e1wq7y4k1"
} : 0)("background:", COLORS.gray[900], ";border-radius:2px;box-sizing:border-box;font-family:", font('default.fontFamily'), ";font-size:12px;color:", COLORS.ui.textDark, ";padding:4px 8px;position:relative;" + ( true ? "" : 0)); // TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const LabelText = /*#__PURE__*/createStyled(text_component, true ? {
target: "e1wq7y4k0"
} : 0)("&&&{color:", COLORS.ui.textDark, ";display:block;font-size:13px;line-height:1.4;white-space:nowrap;}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/label.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const CORNER_OFFSET = 4;
const CURSOR_OFFSET_TOP = CORNER_OFFSET * 2.5;
function resize_tooltip_label_Label({
label,
position = POSITIONS.corner,
zIndex = 1000,
...props
}, ref) {
const showLabel = !!label;
const isBottom = position === POSITIONS.bottom;
const isCorner = position === POSITIONS.corner;
if (!showLabel) return null;
let style = {
opacity: showLabel ? 1 : undefined,
zIndex
};
let labelStyle = {};
if (isBottom) {
style = { ...style,
position: 'absolute',
bottom: CURSOR_OFFSET_TOP * -1,
left: '50%',
transform: 'translate(-50%, 0)'
};
labelStyle = {
transform: `translate(0, 100%)`
};
}
if (isCorner) {
style = { ...style,
position: 'absolute',
top: CORNER_OFFSET,
right: (0,external_wp_i18n_namespaceObject.isRTL)() ? undefined : CORNER_OFFSET,
left: (0,external_wp_i18n_namespaceObject.isRTL)() ? CORNER_OFFSET : undefined
};
}
return (0,external_wp_element_namespaceObject.createElement)(TooltipWrapper, {
"aria-hidden": "true",
className: "components-resizable-tooltip__tooltip-wrapper",
ref: ref,
style: style,
...props
}, (0,external_wp_element_namespaceObject.createElement)(resize_tooltip_styles_Tooltip, {
className: "components-resizable-tooltip__tooltip",
style: labelStyle
}, (0,external_wp_element_namespaceObject.createElement)(LabelText, {
as: "span"
}, label)));
}
const label_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(resize_tooltip_label_Label);
/* harmony default export */ var resize_tooltip_label = (label_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const resize_tooltip_noop = () => {};
function ResizeTooltip({
axis,
className,
fadeTimeout = 180,
isVisible = true,
labelRef,
onResize = resize_tooltip_noop,
position = POSITIONS.bottom,
showPx = true,
zIndex = 1000,
...props
}, ref) {
const {
label,
resizeListener
} = useResizeLabel({
axis,
fadeTimeout,
onResize,
showPx,
position
});
if (!isVisible) return null;
const classes = classnames_default()('components-resize-tooltip', className);
return (0,external_wp_element_namespaceObject.createElement)(resize_tooltip_styles_Root, {
"aria-hidden": "true",
className: classes,
ref: ref,
...props
}, resizeListener, (0,external_wp_element_namespaceObject.createElement)(resize_tooltip_label, {
"aria-hidden": props['aria-hidden'],
label: label,
position: position,
ref: labelRef,
zIndex: zIndex
}));
}
const resize_tooltip_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(ResizeTooltip);
/* harmony default export */ var resize_tooltip = (resize_tooltip_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/index.js
/**
* WordPress dependencies
*/
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const HANDLE_CLASS_NAME = 'components-resizable-box__handle';
const SIDE_HANDLE_CLASS_NAME = 'components-resizable-box__side-handle';
const CORNER_HANDLE_CLASS_NAME = 'components-resizable-box__corner-handle';
const HANDLE_CLASSES = {
top: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-top'),
right: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-right'),
bottom: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-bottom'),
left: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-left'),
topLeft: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-top', 'components-resizable-box__handle-left'),
topRight: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-top', 'components-resizable-box__handle-right'),
bottomRight: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-bottom', 'components-resizable-box__handle-right'),
bottomLeft: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-bottom', 'components-resizable-box__handle-left')
}; // Removes the inline styles in the drag handles.
const HANDLE_STYLES_OVERRIDES = {
width: undefined,
height: undefined,
top: undefined,
right: undefined,
bottom: undefined,
left: undefined
};
const HANDLE_STYLES = {
top: HANDLE_STYLES_OVERRIDES,
right: HANDLE_STYLES_OVERRIDES,
bottom: HANDLE_STYLES_OVERRIDES,
left: HANDLE_STYLES_OVERRIDES,
topLeft: HANDLE_STYLES_OVERRIDES,
topRight: HANDLE_STYLES_OVERRIDES,
bottomRight: HANDLE_STYLES_OVERRIDES,
bottomLeft: HANDLE_STYLES_OVERRIDES
};
function UnforwardedResizableBox({
className,
children,
showHandle = true,
__experimentalShowTooltip: showTooltip = false,
__experimentalTooltipProps: tooltipProps = {},
...props
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)(Resizable, {
className: classnames_default()('components-resizable-box__container', showHandle && 'has-show-handle', className),
handleClasses: HANDLE_CLASSES,
handleStyles: HANDLE_STYLES,
ref: ref,
...props
}, children, showTooltip && (0,external_wp_element_namespaceObject.createElement)(resize_tooltip, { ...tooltipProps
}));
}
const ResizableBox = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedResizableBox);
/* harmony default export */ var resizable_box = (ResizableBox);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/responsive-wrapper/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A wrapper component that maintains its aspect ratio when resized.
*
* ```jsx
* import { ResponsiveWrapper } from '@wordpress/components';
*
* const MyResponsiveWrapper = () => (
* <ResponsiveWrapper naturalWidth={ 2000 } naturalHeight={ 680 }>
* <img
* src="https://s.w.org/style/images/about/WordPress-logotype-standard.png"
* alt="WordPress"
* />
* </ResponsiveWrapper>
* );
* ```
*/
function ResponsiveWrapper({
naturalWidth,
naturalHeight,
children,
isInline = false
}) {
if (external_wp_element_namespaceObject.Children.count(children) !== 1) {
return null;
}
const TagName = isInline ? 'span' : 'div';
let aspectRatio;
if (naturalWidth && naturalHeight) {
aspectRatio = `${naturalWidth} / ${naturalHeight}`;
}
return (0,external_wp_element_namespaceObject.createElement)(TagName, {
className: "components-responsive-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.cloneElement)(children, {
className: classnames_default()('components-responsive-wrapper__content', children.props.className),
style: { ...children.props.style,
aspectRatio
}
})));
}
/* harmony default export */ var responsive_wrapper = (ResponsiveWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/sandbox/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const observeAndResizeJS = function () {
const {
MutationObserver
} = window;
if (!MutationObserver || !document.body || !window.parent) {
return;
}
function sendResize() {
const clientBoundingRect = document.body.getBoundingClientRect();
window.parent.postMessage({
action: 'resize',
width: clientBoundingRect.width,
height: clientBoundingRect.height
}, '*');
}
const observer = new MutationObserver(sendResize);
observer.observe(document.body, {
attributes: true,
attributeOldValue: false,
characterData: true,
characterDataOldValue: false,
childList: true,
subtree: true
});
window.addEventListener('load', sendResize, true); // Hack: Remove viewport unit styles, as these are relative
// the iframe root and interfere with our mechanism for
// determining the unconstrained page bounds.
function removeViewportStyles(ruleOrNode) {
if (ruleOrNode.style) {
['width', 'height', 'minHeight', 'maxHeight'].forEach(function (style) {
if (/^\\d+(vmin|vmax|vh|vw)$/.test(ruleOrNode.style[style])) {
ruleOrNode.style[style] = '';
}
});
}
}
Array.prototype.forEach.call(document.querySelectorAll('[style]'), removeViewportStyles);
Array.prototype.forEach.call(document.styleSheets, function (stylesheet) {
Array.prototype.forEach.call(stylesheet.cssRules || stylesheet.rules, removeViewportStyles);
});
document.body.style.position = 'absolute';
document.body.style.width = '100%';
document.body.setAttribute('data-resizable-iframe-connected', '');
sendResize(); // Resize events can change the width of elements with 100% width, but we don't
// get an DOM mutations for that, so do the resize when the window is resized, too.
window.addEventListener('resize', sendResize, true);
}; // TODO: These styles shouldn't be coupled with WordPress.
const style = `
body {
margin: 0;
}
html,
body,
body > div {
width: 100%;
}
html.wp-has-aspect-ratio,
body.wp-has-aspect-ratio,
body.wp-has-aspect-ratio > div,
body.wp-has-aspect-ratio > div iframe {
width: 100%;
height: 100%;
overflow: hidden; /* If it has an aspect ratio, it shouldn't scroll. */
}
body > div > * {
margin-top: 0 !important; /* Has to have !important to override inline styles. */
margin-bottom: 0 !important;
}
`;
/**
* This component provides an isolated environment for arbitrary HTML via iframes.
*
* ```jsx
* import { SandBox } from '@wordpress/components';
*
* const MySandBox = () => (
* <SandBox html="<p>Content</p>" title="SandBox" type="embed" />
* );
* ```
*/
function SandBox({
html = '',
title = '',
type,
styles = [],
scripts = [],
onFocus
}) {
const ref = (0,external_wp_element_namespaceObject.useRef)();
const [width, setWidth] = (0,external_wp_element_namespaceObject.useState)(0);
const [height, setHeight] = (0,external_wp_element_namespaceObject.useState)(0);
function isFrameAccessible() {
try {
return !!ref.current?.contentDocument?.body;
} catch (e) {
return false;
}
}
function trySandBox(forceRerender = false) {
if (!isFrameAccessible()) {
return;
}
const {
contentDocument,
ownerDocument
} = ref.current;
if (!forceRerender && null !== contentDocument?.body.getAttribute('data-resizable-iframe-connected')) {
return;
} // Put the html snippet into a html document, and then write it to the iframe's document
// we can use this in the future to inject custom styles or scripts.
// Scripts go into the body rather than the head, to support embedded content such as Instagram
// that expect the scripts to be part of the body.
const htmlDoc = (0,external_wp_element_namespaceObject.createElement)("html", {
lang: ownerDocument.documentElement.lang,
className: type
}, (0,external_wp_element_namespaceObject.createElement)("head", null, (0,external_wp_element_namespaceObject.createElement)("title", null, title), (0,external_wp_element_namespaceObject.createElement)("style", {
dangerouslySetInnerHTML: {
__html: style
}
}), styles.map((rules, i) => (0,external_wp_element_namespaceObject.createElement)("style", {
key: i,
dangerouslySetInnerHTML: {
__html: rules
}
}))), (0,external_wp_element_namespaceObject.createElement)("body", {
"data-resizable-iframe-connected": "data-resizable-iframe-connected",
className: type
}, (0,external_wp_element_namespaceObject.createElement)("div", {
dangerouslySetInnerHTML: {
__html: html
}
}), (0,external_wp_element_namespaceObject.createElement)("script", {
type: "text/javascript",
dangerouslySetInnerHTML: {
__html: `(${observeAndResizeJS.toString()})();`
}
}), scripts.map(src => (0,external_wp_element_namespaceObject.createElement)("script", {
key: src,
src: src
})))); // Writing the document like this makes it act in the same way as if it was
// loaded over the network, so DOM creation and mutation, script execution, etc.
// all work as expected.
contentDocument.open();
contentDocument.write('<!DOCTYPE html>' + (0,external_wp_element_namespaceObject.renderToString)(htmlDoc));
contentDocument.close();
}
(0,external_wp_element_namespaceObject.useEffect)(() => {
trySandBox();
function tryNoForceSandBox() {
trySandBox(false);
}
function checkMessageForResize(event) {
const iframe = ref.current; // Verify that the mounted element is the source of the message.
if (!iframe || iframe.contentWindow !== event.source) {
return;
} // Attempt to parse the message data as JSON if passed as string.
let data = event.data || {};
if ('string' === typeof data) {
try {
data = JSON.parse(data);
} catch (e) {}
} // Update the state only if the message is formatted as we expect,
// i.e. as an object with a 'resize' action.
if ('resize' !== data.action) {
return;
}
setWidth(data.width);
setHeight(data.height);
}
const iframe = ref.current;
const defaultView = iframe?.ownerDocument?.defaultView; // This used to be registered using <iframe onLoad={} />, but it made the iframe blank
// after reordering the containing block. See these two issues for more details:
// https://github.com/WordPress/gutenberg/issues/6146
// https://github.com/facebook/react/issues/18752
iframe?.addEventListener('load', tryNoForceSandBox, false);
defaultView?.addEventListener('message', checkMessageForResize);
return () => {
iframe?.removeEventListener('load', tryNoForceSandBox, false);
defaultView?.addEventListener('message', checkMessageForResize);
}; // Ignore reason: passing `exhaustive-deps` will likely involve a more detailed refactor.
// See https://github.com/WordPress/gutenberg/pull/44378
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
trySandBox(); // Ignore reason: passing `exhaustive-deps` will likely involve a more detailed refactor.
// See https://github.com/WordPress/gutenberg/pull/44378
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [title, styles, scripts]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
trySandBox(true); // Ignore reason: passing `exhaustive-deps` will likely involve a more detailed refactor.
// See https://github.com/WordPress/gutenberg/pull/44378
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [html, type]);
return (0,external_wp_element_namespaceObject.createElement)("iframe", {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, (0,external_wp_compose_namespaceObject.useFocusableIframe)()]),
title: title,
className: "components-sandbox",
sandbox: "allow-scripts allow-same-origin allow-presentation",
onFocus: onFocus,
width: Math.ceil(width),
height: Math.ceil(height)
});
}
/* harmony default export */ var sandbox = (SandBox);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/snackbar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const NOTICE_TIMEOUT = 10000;
/**
* Custom hook which announces the message with the given politeness, if a
* valid message is provided.
*
* @param message Message to announce.
* @param politeness Politeness to announce.
*/
function snackbar_useSpokenMessage(message, politeness) {
const spokenMessage = typeof message === 'string' ? message : (0,external_wp_element_namespaceObject.renderToString)(message);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (spokenMessage) {
(0,external_wp_a11y_namespaceObject.speak)(spokenMessage, politeness);
}
}, [spokenMessage, politeness]);
}
function UnforwardedSnackbar({
className,
children,
spokenMessage = children,
politeness = 'polite',
actions = [],
onRemove,
icon = null,
explicitDismiss = false,
// onDismiss is a callback executed when the snackbar is dismissed.
// It is distinct from onRemove, which _looks_ like a callback but is
// actually the function to call to remove the snackbar from the UI.
onDismiss,
listRef
}, ref) {
function dismissMe(event) {
if (event && event.preventDefault) {
event.preventDefault();
} // Prevent focus loss by moving it to the list element.
listRef?.current?.focus();
onDismiss?.();
onRemove?.();
}
function onActionClick(event, onClick) {
event.stopPropagation();
onRemove?.();
if (onClick) {
onClick(event);
}
}
snackbar_useSpokenMessage(spokenMessage, politeness); // Only set up the timeout dismiss if we're not explicitly dismissing.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const timeoutHandle = setTimeout(() => {
if (!explicitDismiss) {
onDismiss?.();
onRemove?.();
}
}, NOTICE_TIMEOUT);
return () => clearTimeout(timeoutHandle);
}, [onDismiss, onRemove, explicitDismiss]);
const classes = classnames_default()(className, 'components-snackbar', {
'components-snackbar-explicit-dismiss': !!explicitDismiss
});
if (actions && actions.length > 1) {
// We need to inform developers that snackbar only accepts 1 action.
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0; // return first element only while keeping it inside an array
actions = [actions[0]];
}
const snackbarContentClassnames = classnames_default()('components-snackbar__content', {
'components-snackbar__content-with-icon': !!icon
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
className: classes,
onClick: !explicitDismiss ? dismissMe : undefined,
tabIndex: 0,
role: !explicitDismiss ? 'button' : '',
onKeyPress: !explicitDismiss ? dismissMe : undefined,
"aria-label": !explicitDismiss ? (0,external_wp_i18n_namespaceObject.__)('Dismiss this notice') : ''
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: snackbarContentClassnames
}, icon && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-snackbar__icon"
}, icon), children, actions.map(({
label,
onClick,
url
}, index) => {
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: index,
href: url,
variant: "tertiary",
onClick: event => onActionClick(event, onClick),
className: "components-snackbar__action"
}, label);
}), explicitDismiss && (0,external_wp_element_namespaceObject.createElement)("span", {
role: "button",
"aria-label": "Dismiss this notice",
tabIndex: 0,
className: "components-snackbar__dismiss-button",
onClick: dismissMe,
onKeyPress: dismissMe
}, "\u2715")));
}
/**
* A Snackbar displays a succinct message that is cleared out after a small delay.
*
* It can also offer the user options, like viewing a published post.
* But these options should also be available elsewhere in the UI.
*
* ```jsx
* const MySnackbarNotice = () => (
* <Snackbar>Post published successfully.</Snackbar>
* );
* ```
*/
const Snackbar = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSnackbar);
/* harmony default export */ var snackbar = (Snackbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/snackbar/list.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SNACKBAR_VARIANTS = {
init: {
height: 0,
opacity: 0
},
open: {
height: 'auto',
opacity: 1,
transition: {
height: {
stiffness: 1000,
velocity: -100
}
}
},
exit: {
opacity: 0,
transition: {
duration: 0.5
}
}
};
/**
* Renders a list of notices.
*
* ```jsx
* const MySnackbarListNotice = () => (
* <SnackbarList
* notices={ notices }
* onRemove={ removeNotice }
* />
* );
* ```
*/
function SnackbarList({
notices,
className,
children,
onRemove
}) {
const listRef = (0,external_wp_element_namespaceObject.useRef)(null);
const isReducedMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
className = classnames_default()('components-snackbar-list', className);
const removeNotice = notice => () => onRemove?.(notice.id);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className,
tabIndex: -1,
ref: listRef
}, children, (0,external_wp_element_namespaceObject.createElement)(AnimatePresence, null, notices.map(notice => {
const {
content,
...restNotice
} = notice;
return (0,external_wp_element_namespaceObject.createElement)(motion.div, {
layout: !isReducedMotion // See https://www.framer.com/docs/animation/#layout-animations
,
initial: 'init',
animate: 'open',
exit: 'exit',
key: notice.id,
variants: isReducedMotion ? undefined : SNACKBAR_VARIANTS
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-snackbar-list__notice-container"
}, (0,external_wp_element_namespaceObject.createElement)(snackbar, { ...restNotice,
onRemove: removeNotice(notice),
listRef: listRef
}, notice.content)));
})));
}
/* harmony default export */ var snackbar_list = (SnackbarList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spinner/styles.js
function spinner_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const spinAnimation = emotion_react_browser_esm_keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
const StyledSpinner = createStyled("svg", true ? {
target: "ea4tfvq2"
} : 0)("width:", config_values.spinnerSize, "px;height:", config_values.spinnerSize, "px;display:inline-block;margin:5px 11px 0;position:relative;color:", COLORS.ui.theme, ";overflow:visible;opacity:1;background-color:transparent;" + ( true ? "" : 0));
const commonPathProps = true ? {
name: "9s4963",
styles: "fill:transparent;stroke-width:1.5px"
} : 0;
const SpinnerTrack = createStyled("circle", true ? {
target: "ea4tfvq1"
} : 0)(commonPathProps, ";stroke:", COLORS.gray[300], ";" + ( true ? "" : 0));
const SpinnerIndicator = createStyled("path", true ? {
target: "ea4tfvq0"
} : 0)(commonPathProps, ";stroke:currentColor;stroke-linecap:round;transform-origin:50% 50%;animation:1.4s linear infinite both ", spinAnimation, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spinner/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* WordPress dependencies
*/
function UnforwardedSpinner({
className,
...props
}, forwardedRef) {
return (0,external_wp_element_namespaceObject.createElement)(StyledSpinner, {
className: classnames_default()('components-spinner', className),
viewBox: "0 0 100 100",
width: "16",
height: "16",
xmlns: "http://www.w3.org/2000/svg",
role: "presentation",
focusable: "false",
...props,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(SpinnerTrack, {
cx: "50",
cy: "50",
r: "50",
vectorEffect: "non-scaling-stroke"
}), (0,external_wp_element_namespaceObject.createElement)(SpinnerIndicator, {
d: "m 50 0 a 50 50 0 0 1 50 50",
vectorEffect: "non-scaling-stroke"
}));
}
/**
* `Spinner` is a component used to notify users that their action is being processed.
*
* @example
* ```js
* import { Spinner } from '@wordpress/components';
*
* function Example() {
* return <Spinner />;
* }
* ```
*/
const Spinner = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSpinner);
/* harmony default export */ var spinner = (Spinner);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/surface/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedSurface(props, forwardedRef) {
const surfaceProps = useSurface(props);
return (0,external_wp_element_namespaceObject.createElement)(component, { ...surfaceProps,
ref: forwardedRef
});
}
/**
* `Surface` is a core component that renders a primary background color.
*
* In the example below, notice how the `Surface` renders in white (or dark gray if in dark mode).
*
* ```jsx
* import {
* __experimentalSurface as Surface,
* __experimentalText as Text,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <Surface>
* <Text>Code is Poetry</Text>
* </Surface>
* );
* }
* ```
*/
const component_Surface = contextConnect(UnconnectedSurface, 'Surface');
/* harmony default export */ var surface_component = (component_Surface);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tab-panel/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TabButton = ({
tabId,
children,
selected,
...rest
}) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
role: "tab",
tabIndex: selected ? undefined : -1,
"aria-selected": selected,
id: tabId,
__experimentalIsFocusable: true,
...rest
}, children);
/**
* TabPanel is an ARIA-compliant tabpanel.
*
* TabPanels organize content across different screens, data sets, and interactions.
* It has two sections: a list of tabs, and the view to show when tabs are chosen.
*
* ```jsx
* import { TabPanel } from '@wordpress/components';
*
* const onSelect = ( tabName ) => {
* console.log( 'Selecting tab', tabName );
* };
*
* const MyTabPanel = () => (
* <TabPanel
* className="my-tab-panel"
* activeClass="active-tab"
* onSelect={ onSelect }
* tabs={ [
* {
* name: 'tab1',
* title: 'Tab 1',
* className: 'tab-one',
* },
* {
* name: 'tab2',
* title: 'Tab 2',
* className: 'tab-two',
* },
* ] }
* >
* { ( tab ) => <p>{ tab.title }</p> }
* </TabPanel>
* );
* ```
*/
const UnforwardedTabPanel = ({
className,
children,
tabs,
selectOnMove = true,
initialTabName,
orientation = 'horizontal',
activeClass = 'is-active',
onSelect
}, ref) => {
var _selectedTab$name;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(TabPanel, 'tab-panel');
const [selected, setSelected] = (0,external_wp_element_namespaceObject.useState)();
const handleTabSelection = (0,external_wp_element_namespaceObject.useCallback)(tabKey => {
setSelected(tabKey);
onSelect?.(tabKey);
}, [onSelect]); // Simulate a click on the newly focused tab, which causes the component
// to show the `tab-panel` associated with the clicked tab.
const activateTabAutomatically = (_childIndex, child) => {
child.click();
};
const selectedTab = tabs.find(({
name
}) => name === selected);
const selectedId = `${instanceId}-${(_selectedTab$name = selectedTab?.name) !== null && _selectedTab$name !== void 0 ? _selectedTab$name : 'none'}`; // Handle selecting the initial tab.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
// If there's a selected tab, don't override it.
if (selectedTab) {
return;
}
const initialTab = tabs.find(tab => tab.name === initialTabName); // Wait for the denoted initial tab to be declared before making a
// selection. This ensures that if a tab is declared lazily it can
// still receive initial selection.
if (initialTabName && !initialTab) {
return;
}
if (initialTab && !initialTab.disabled) {
// Select the initial tab if it's not disabled.
handleTabSelection(initialTab.name);
} else {
// Fallback to the first enabled tab when the initial is disabled.
const firstEnabledTab = tabs.find(tab => !tab.disabled);
if (firstEnabledTab) handleTabSelection(firstEnabledTab.name);
}
}, [tabs, selectedTab, initialTabName, handleTabSelection]); // Handle the currently selected tab becoming disabled.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// This effect only runs when the selected tab is defined and becomes disabled.
if (!selectedTab?.disabled) {
return;
}
const firstEnabledTab = tabs.find(tab => !tab.disabled); // If the currently selected tab becomes disabled, select the first enabled tab.
// (if there is one).
if (firstEnabledTab) {
handleTabSelection(firstEnabledTab.name);
}
}, [tabs, selectedTab?.disabled, handleTabSelection]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className,
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, {
role: "tablist",
orientation: orientation,
onNavigate: selectOnMove ? activateTabAutomatically : undefined,
className: "components-tab-panel__tabs"
}, tabs.map(tab => (0,external_wp_element_namespaceObject.createElement)(TabButton, {
className: classnames_default()('components-tab-panel__tabs-item', tab.className, {
[activeClass]: tab.name === selected
}),
tabId: `${instanceId}-${tab.name}`,
"aria-controls": `${instanceId}-${tab.name}-view`,
selected: tab.name === selected,
key: tab.name,
onClick: () => handleTabSelection(tab.name),
disabled: tab.disabled,
label: tab.icon && tab.title,
icon: tab.icon,
showTooltip: !!tab.icon
}, !tab.icon && tab.title))), selectedTab && (0,external_wp_element_namespaceObject.createElement)("div", {
key: selectedId,
"aria-labelledby": selectedId,
role: "tabpanel",
id: `${selectedId}-view`,
className: "components-tab-panel__tab-content"
}, children(selectedTab)));
};
const TabPanel = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTabPanel);
/* harmony default export */ var tab_panel = (TabPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedTextControl(props, ref) {
const {
__nextHasNoMarginBottom,
label,
hideLabelFromVision,
value,
help,
className,
onChange,
type = 'text',
...additionalProps
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(TextControl);
const id = `inspector-text-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.value);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
hideLabelFromVision: hideLabelFromVision,
id: id,
help: help,
className: className
}, (0,external_wp_element_namespaceObject.createElement)("input", {
className: "components-text-control__input",
type: type,
id: id,
value: value,
onChange: onChangeValue,
"aria-describedby": !!help ? id + '__help' : undefined,
ref: ref,
...additionalProps
}));
}
/**
* TextControl components let users enter and edit text.
*
* ```jsx
* import { TextControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTextControl = () => {
* const [ className, setClassName ] = useState( '' );
*
* return (
* <TextControl
* label="Additional CSS Class"
* value={ className }
* onChange={ ( value ) => setClassName( value ) }
* />
* );
* };
* ```
*/
const TextControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTextControl);
/* harmony default export */ var text_control = (TextControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/input/base.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const inputStyleNeutral = /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:0 0 0 transparent;transition:box-shadow 0.1s linear;border-radius:", config_values.radiusBlockUi, ";border:", config_values.borderWidth, " solid ", COLORS.ui.border, ";" + ( true ? "" : 0), true ? "" : 0);
const inputStyleFocus = /*#__PURE__*/emotion_react_browser_esm_css("border-color:", COLORS.ui.theme, ";box-shadow:0 0 0 calc( ", config_values.borderWidthFocus, " - ", config_values.borderWidth, " ) ", COLORS.ui.theme, ";outline:2px solid transparent;" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/breakpoint-values.js
/* harmony default export */ var breakpoint_values = ({
huge: '1440px',
wide: '1280px',
'x-large': '1080px',
large: '960px',
// admin sidebar auto folds
medium: '782px',
// Adminbar goes big.
small: '600px',
mobile: '480px',
'zoomed-in': '280px'
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/breakpoint.js
/**
* Internal dependencies
*/
/**
* @param {keyof breakpoints} point
* @return {string} Media query declaration.
*/
const breakpoint = point => `@media (min-width: ${breakpoint_values[point]})`;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/input/input-control.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const inputControl = /*#__PURE__*/emotion_react_browser_esm_css("display:block;font-family:", font('default.fontFamily'), ";padding:6px 8px;", inputStyleNeutral, ";font-size:", font('mobileTextMinFontSize'), ";line-height:normal;", breakpoint('small'), "{font-size:", font('default.fontSize'), ";line-height:normal;}&:focus{", inputStyleFocus, ";}&::-webkit-input-placeholder{color:", COLORS.ui.darkGrayPlaceholder, ";}&::-moz-placeholder{opacity:1;color:", COLORS.ui.darkGrayPlaceholder, ";}&:-ms-input-placeholder{color:", COLORS.ui.darkGrayPlaceholder, ";}.is-dark-theme &{&::-webkit-input-placeholder{color:", COLORS.ui.lightGrayPlaceholder, ";}&::-moz-placeholder{opacity:1;color:", COLORS.ui.lightGrayPlaceholder, ";}&:-ms-input-placeholder{color:", COLORS.ui.lightGrayPlaceholder, ";}}" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/textarea-control/styles/textarea-control-styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const StyledTextarea = createStyled("textarea", true ? {
target: "e1w5nnrk0"
} : 0)("width:100%;", inputControl, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/textarea-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* TextareaControls are TextControls that allow for multiple lines of text, and
* wrap overflow text onto a new line. They are a fixed height and scroll
* vertically when the cursor reaches the bottom of the field.
*
* ```jsx
* import { TextareaControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTextareaControl = () => {
* const [ text, setText ] = useState( '' );
*
* return (
* <TextareaControl
* label="Text"
* help="Enter some text"
* value={ text }
* onChange={ ( value ) => setText( value ) }
* />
* );
* };
* ```
*/
function TextareaControl(props) {
const {
__nextHasNoMarginBottom,
label,
hideLabelFromVision,
value,
help,
onChange,
rows = 4,
className,
...additionalProps
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(TextareaControl);
const id = `inspector-textarea-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.value);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
hideLabelFromVision: hideLabelFromVision,
id: id,
help: help,
className: className
}, (0,external_wp_element_namespaceObject.createElement)(StyledTextarea, {
className: "components-textarea-control__input",
id: id,
rows: rows,
onChange: onChangeValue,
"aria-describedby": !!help ? id + '__help' : undefined,
value: value,
...additionalProps
}));
}
/* harmony default export */ var textarea_control = (TextareaControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text-highlight/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Highlights occurrences of a given string within another string of text. Wraps
* each match with a `<mark>` tag which provides browser default styling.
*
* ```jsx
* import { TextHighlight } from '@wordpress/components';
*
* const MyTextHighlight = () => (
* <TextHighlight
* text="Why do we like Gutenberg? Because Gutenberg is the best!"
* highlight="Gutenberg"
* />
* );
* ```
*/
const TextHighlight = props => {
const {
text = '',
highlight = ''
} = props;
const trimmedHighlightText = highlight.trim();
if (!trimmedHighlightText) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, text);
}
const regex = new RegExp(`(${escapeRegExp(trimmedHighlightText)})`, 'gi');
return (0,external_wp_element_namespaceObject.createInterpolateElement)(text.replace(regex, '<mark>$&</mark>'), {
mark: (0,external_wp_element_namespaceObject.createElement)("mark", null)
});
};
/* harmony default export */ var text_highlight = (TextHighlight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/tip.js
/**
* WordPress dependencies
*/
const tip = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M12 15.8c-3.7 0-6.8-3-6.8-6.8s3-6.8 6.8-6.8c3.7 0 6.8 3 6.8 6.8s-3.1 6.8-6.8 6.8zm0-12C9.1 3.8 6.8 6.1 6.8 9s2.4 5.2 5.2 5.2c2.9 0 5.2-2.4 5.2-5.2S14.9 3.8 12 3.8zM8 17.5h8V19H8zM10 20.5h4V22h-4z"
}));
/* harmony default export */ var library_tip = (tip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tip/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Tip(props) {
const {
children
} = props;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-tip"
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_tip
}), (0,external_wp_element_namespaceObject.createElement)("p", null, children));
}
/* harmony default export */ var build_module_tip = (Tip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* ToggleControl is used to generate a toggle user interface.
*
* ```jsx
* import { ToggleControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyToggleControl = () => {
* const [ value, setValue ] = useState( false );
*
* return (
* <ToggleControl
* label="Fixed Background"
* checked={ value }
* onChange={ () => setValue( ( state ) => ! state ) }
* />
* );
* };
* ```
*/
function ToggleControl({
__nextHasNoMarginBottom,
label,
checked,
help,
className,
onChange,
disabled
}) {
function onChangeToggle(event) {
onChange(event.target.checked);
}
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleControl);
const id = `inspector-toggle-control-${instanceId}`;
const cx = useCx();
const classes = cx('components-toggle-control', className, !__nextHasNoMarginBottom && /*#__PURE__*/emotion_react_browser_esm_css({
marginBottom: space(3)
}, true ? "" : 0, true ? "" : 0));
let describedBy, helpLabel;
if (help) {
if (typeof help === 'function') {
// `help` as a function works only for controlled components where
// `checked` is passed down from parent component. Uncontrolled
// component can show only a static help label.
if (checked !== undefined) {
helpLabel = help(checked);
}
} else {
helpLabel = help;
}
if (helpLabel) {
describedBy = id + '__help';
}
}
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
id: id,
help: helpLabel,
className: classes,
__nextHasNoMarginBottom: true
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
justify: "flex-start",
spacing: 3
}, (0,external_wp_element_namespaceObject.createElement)(form_toggle, {
id: id,
checked: checked,
onChange: onChangeToggle,
"aria-describedby": describedBy,
disabled: disabled
}), (0,external_wp_element_namespaceObject.createElement)(flex_block_component, {
as: "label",
htmlFor: id,
className: "components-toggle-control__label"
}, label)));
}
/* harmony default export */ var toggle_control = (ToggleControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-icon/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlOptionIcon(props, ref) {
const {
icon,
label,
...restProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_option_base_component, { ...restProps,
isIcon: true,
"aria-label": label,
showTooltip: true,
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}));
}
/**
* `ToggleGroupControlOptionIcon` is a form component which is meant to be used as a
* child of `ToggleGroupControl` and displays an icon.
*
* ```jsx
*
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOptionIcon as ToggleGroupControlOptionIcon,
* from '@wordpress/components';
* import { formatLowercase, formatUppercase } from '@wordpress/icons';
*
* function Example() {
* return (
* <ToggleGroupControl>
* <ToggleGroupControlOptionIcon
* value="uppercase"
* label="Uppercase"
* icon={ formatUppercase }
* />
* <ToggleGroupControlOptionIcon
* value="lowercase"
* label="Lowercase"
* icon={ formatLowercase }
* />
* </ToggleGroupControl>
* );
* }
* ```
*/
const ToggleGroupControlOptionIcon = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlOptionIcon);
/* harmony default export */ var toggle_group_control_option_icon_component = (ToggleGroupControlOptionIcon);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/BMLNRUFQ.js
// src/focusable/focusable-context.ts
var FocusableContext = (0,external_React_.createContext)(true);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/PNRLI7OV.js
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var PNRLI7OV_spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var PNRLI7OV_spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/PNRLI7OV.js
var PNRLI7OV_defProp = Object.defineProperty;
var PNRLI7OV_defProps = Object.defineProperties;
var PNRLI7OV_getOwnPropDescs = Object.getOwnPropertyDescriptors;
var PNRLI7OV_getOwnPropSymbols = Object.getOwnPropertySymbols;
var PNRLI7OV_hasOwnProp = Object.prototype.hasOwnProperty;
var PNRLI7OV_propIsEnum = Object.prototype.propertyIsEnumerable;
var PNRLI7OV_defNormalProp = (obj, key, value) => key in obj ? PNRLI7OV_defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var _chunks_PNRLI7OV_spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (PNRLI7OV_hasOwnProp.call(b, prop))
PNRLI7OV_defNormalProp(a, prop, b[prop]);
if (PNRLI7OV_getOwnPropSymbols)
for (var prop of PNRLI7OV_getOwnPropSymbols(b)) {
if (PNRLI7OV_propIsEnum.call(b, prop))
PNRLI7OV_defNormalProp(a, prop, b[prop]);
}
return a;
};
var _chunks_PNRLI7OV_spreadProps = (a, b) => PNRLI7OV_defProps(a, PNRLI7OV_getOwnPropDescs(b));
var PNRLI7OV_objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (PNRLI7OV_hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && PNRLI7OV_getOwnPropSymbols)
for (var prop of PNRLI7OV_getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && PNRLI7OV_propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/WVTCK5PV.js
// src/utils/misc.ts
function WVTCK5PV_noop(..._) {
}
function WVTCK5PV_shallowEqual(a, b) {
if (a === b)
return true;
if (!a)
return false;
if (!b)
return false;
if (typeof a !== "object")
return false;
if (typeof b !== "object")
return false;
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
const { length } = aKeys;
if (bKeys.length !== length)
return false;
for (const key of aKeys) {
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
function WVTCK5PV_applyState(argument, currentValue) {
if (WVTCK5PV_isUpdater(argument)) {
const value = isLazyValue(currentValue) ? currentValue() : currentValue;
return argument(value);
}
return argument;
}
function WVTCK5PV_isUpdater(argument) {
return typeof argument === "function";
}
function isLazyValue(value) {
return typeof value === "function";
}
function WVTCK5PV_isObject(arg) {
return typeof arg === "object" && arg != null;
}
function isEmpty(arg) {
if (Array.isArray(arg))
return !arg.length;
if (WVTCK5PV_isObject(arg))
return !Object.keys(arg).length;
if (arg == null)
return true;
if (arg === "")
return true;
return false;
}
function isInteger(arg) {
if (typeof arg === "number") {
return Math.floor(arg) === arg;
}
return String(Math.floor(Number(arg))) === arg;
}
function WVTCK5PV_hasOwnProperty(object, prop) {
return Object.prototype.hasOwnProperty.call(object, prop);
}
function WVTCK5PV_chain(...fns) {
return (...args) => {
for (const fn of fns) {
if (typeof fn === "function") {
fn(...args);
}
}
};
}
function cx(...args) {
return args.filter(Boolean).join(" ") || void 0;
}
function normalizeString(str) {
return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
function omit(object, keys) {
const result = _chunks_PNRLI7OV_spreadValues({}, object);
for (const key of keys) {
if (WVTCK5PV_hasOwnProperty(result, key)) {
delete result[key];
}
}
return result;
}
function pick(object, paths) {
const result = {};
for (const key of paths) {
if (WVTCK5PV_hasOwnProperty(object, key)) {
result[key] = object[key];
}
}
return result;
}
function WVTCK5PV_identity(value) {
return value;
}
function beforePaint(cb = WVTCK5PV_noop) {
const raf = requestAnimationFrame(cb);
return () => cancelAnimationFrame(raf);
}
function afterPaint(cb = WVTCK5PV_noop) {
let raf = requestAnimationFrame(() => {
raf = requestAnimationFrame(cb);
});
return () => cancelAnimationFrame(raf);
}
function WVTCK5PV_invariant(condition, message) {
if (condition)
return;
if (typeof message !== "string")
throw new Error("Invariant failed");
throw new Error(message);
}
function getKeys(obj) {
return Object.keys(obj);
}
function isFalsyBooleanCallback(booleanOrCallback, ...args) {
const result = typeof booleanOrCallback === "function" ? booleanOrCallback(...args) : booleanOrCallback;
if (result == null)
return false;
return !result;
}
function defaultValue(...values) {
for (const value of values) {
if (value !== void 0)
return value;
}
return void 0;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/CP3U4HPL.js
// src/utils/misc.ts
function CP3U4HPL_setRef(ref, value) {
if (typeof ref === "function") {
ref(value);
} else if (ref) {
ref.current = value;
}
}
function isValidElementWithRef(element) {
if (!element)
return false;
if (!(0,external_React_.isValidElement)(element))
return false;
if (!("ref" in element))
return false;
return true;
}
function getRefProperty(element) {
if (!isValidElementWithRef(element))
return null;
return element.ref;
}
function CP3U4HPL_mergeProps(base, overrides) {
const props = PNRLI7OV_spreadValues({}, base);
for (const key in overrides) {
if (!WVTCK5PV_hasOwnProperty(overrides, key))
continue;
if (key === "className") {
const prop = "className";
props[prop] = base[prop] ? `${base[prop]} ${overrides[prop]}` : overrides[prop];
continue;
}
if (key === "style") {
const prop = "style";
props[prop] = base[prop] ? PNRLI7OV_spreadValues(PNRLI7OV_spreadValues({}, base[prop]), overrides[prop]) : overrides[prop];
continue;
}
const overrideValue = overrides[key];
if (typeof overrideValue === "function" && key.startsWith("on")) {
const baseValue = base[key];
if (typeof baseValue === "function") {
props[key] = (...args) => {
overrideValue(...args);
baseValue(...args);
};
continue;
}
}
props[key] = overrideValue;
}
return props;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/O35LWD4W.js
// src/utils/dom.ts
var O35LWD4W_canUseDOM = O35LWD4W_checkIsBrowser();
function O35LWD4W_checkIsBrowser() {
var _a;
return typeof window !== "undefined" && !!((_a = window.document) == null ? void 0 : _a.createElement);
}
function O35LWD4W_getDocument(node) {
return node ? node.ownerDocument || node : document;
}
function O35LWD4W_getWindow(node) {
return O35LWD4W_getDocument(node).defaultView || window;
}
function O35LWD4W_getActiveElement(node, activeDescendant = false) {
const { activeElement } = O35LWD4W_getDocument(node);
if (!(activeElement == null ? void 0 : activeElement.nodeName)) {
return null;
}
if (O35LWD4W_isFrame(activeElement) && activeElement.contentDocument) {
return O35LWD4W_getActiveElement(
activeElement.contentDocument.body,
activeDescendant
);
}
if (activeDescendant) {
const id = activeElement.getAttribute("aria-activedescendant");
if (id) {
const element = O35LWD4W_getDocument(activeElement).getElementById(id);
if (element) {
return element;
}
}
}
return activeElement;
}
function O35LWD4W_contains(parent, child) {
return parent === child || parent.contains(child);
}
function O35LWD4W_isFrame(element) {
return element.tagName === "IFRAME";
}
function O35LWD4W_isButton(element) {
const tagName = element.tagName.toLowerCase();
if (tagName === "button")
return true;
if (tagName === "input" && element.type) {
return O35LWD4W_buttonInputTypes.indexOf(element.type) !== -1;
}
return false;
}
var O35LWD4W_buttonInputTypes = [
"button",
"color",
"file",
"image",
"reset",
"submit"
];
function O35LWD4W_matches(element, selectors) {
if ("matches" in element) {
return element.matches(selectors);
}
if ("msMatchesSelector" in element) {
return element.msMatchesSelector(selectors);
}
return element.webkitMatchesSelector(selectors);
}
function O35LWD4W_isVisible(element) {
const htmlElement = element;
return htmlElement.offsetWidth > 0 || htmlElement.offsetHeight > 0 || element.getClientRects().length > 0;
}
function O35LWD4W_closest(element, selectors) {
if ("closest" in element)
return element.closest(selectors);
do {
if (O35LWD4W_matches(element, selectors))
return element;
element = element.parentElement || element.parentNode;
} while (element !== null && element.nodeType === 1);
return null;
}
function O35LWD4W_isTextField(element) {
try {
const isTextInput = element instanceof HTMLInputElement && element.selectionStart !== null;
const isTextArea = element.tagName === "TEXTAREA";
return isTextInput || isTextArea || false;
} catch (error) {
return false;
}
}
function getPopupRole(element, fallback) {
const allowedPopupRoles = ["dialog", "menu", "listbox", "tree", "grid"];
const role = element == null ? void 0 : element.getAttribute("role");
if (role && allowedPopupRoles.indexOf(role) !== -1) {
return role;
}
return fallback;
}
function getPopupItemRole(element, fallback) {
var _a;
const itemRoleByPopupRole = {
menu: "menuitem",
listbox: "option",
tree: "treeitem",
grid: "gridcell"
};
const popupRole = getPopupRole(element);
if (!popupRole)
return fallback;
const key = popupRole;
return (_a = itemRoleByPopupRole[key]) != null ? _a : fallback;
}
function getTextboxSelection(element) {
let start = 0;
let end = 0;
if (O35LWD4W_isTextField(element)) {
start = element.selectionStart || 0;
end = element.selectionEnd || 0;
} else if (element.isContentEditable) {
const selection = O35LWD4W_getDocument(element).getSelection();
if ((selection == null ? void 0 : selection.rangeCount) && selection.anchorNode && O35LWD4W_contains(element, selection.anchorNode) && selection.focusNode && O35LWD4W_contains(element, selection.focusNode)) {
const range = selection.getRangeAt(0);
const nextRange = range.cloneRange();
nextRange.selectNodeContents(element);
nextRange.setEnd(range.startContainer, range.startOffset);
start = nextRange.toString().length;
nextRange.setEnd(range.endContainer, range.endOffset);
end = nextRange.toString().length;
}
}
return { start, end };
}
function scrollIntoViewIfNeeded(element, arg) {
if (isPartiallyHidden(element) && "scrollIntoView" in element) {
element.scrollIntoView(arg);
}
}
function getScrollingElement(element) {
if (!element)
return null;
if (element.clientHeight && element.scrollHeight > element.clientHeight) {
const { overflowY } = getComputedStyle(element);
const isScrollable = overflowY !== "visible" && overflowY !== "hidden";
if (isScrollable)
return element;
} else if (element.clientWidth && element.scrollWidth > element.clientWidth) {
const { overflowX } = getComputedStyle(element);
const isScrollable = overflowX !== "visible" && overflowX !== "hidden";
if (isScrollable)
return element;
}
return getScrollingElement(element.parentElement) || document.scrollingElement || document.body;
}
function isPartiallyHidden(element) {
const elementRect = element.getBoundingClientRect();
const scroller = getScrollingElement(element);
if (!scroller)
return false;
const scrollerRect = scroller.getBoundingClientRect();
const isHTML = scroller.tagName === "HTML";
const scrollerTop = isHTML ? scrollerRect.top + scroller.scrollTop : scrollerRect.top;
const scrollerBottom = isHTML ? scroller.clientHeight : scrollerRect.bottom;
const scrollerLeft = isHTML ? scrollerRect.left + scroller.scrollLeft : scrollerRect.left;
const scrollerRight = isHTML ? scroller.clientWidth : scrollerRect.right;
const top = elementRect.top < scrollerTop;
const left = elementRect.left < scrollerLeft;
const bottom = elementRect.bottom > scrollerBottom;
const right = elementRect.right > scrollerRight;
return top || left || bottom || right;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/J7Q2EO23.js
// src/utils/hooks.ts
var _React = PNRLI7OV_spreadValues({}, external_React_namespaceObject);
var useReactId = _React.useId;
var useReactDeferredValue = _React.useDeferredValue;
var useReactInsertionEffect = _React.useInsertionEffect;
var useSafeLayoutEffect = O35LWD4W_canUseDOM ? external_React_.useLayoutEffect : external_React_.useEffect;
function useInitialValue(value) {
const [initialValue] = useState(value);
return initialValue;
}
function useLazyValue(init) {
const ref = (0,external_React_.useRef)();
if (ref.current === void 0) {
ref.current = init();
}
return ref.current;
}
function J7Q2EO23_useLiveRef(value) {
const ref = (0,external_React_.useRef)(value);
useSafeLayoutEffect(() => {
ref.current = value;
});
return ref;
}
function usePreviousValue(value) {
const [previousValue, setPreviousValue] = useState(value);
if (value !== previousValue) {
setPreviousValue(value);
}
return previousValue;
}
function useEvent(callback) {
const ref = (0,external_React_.useRef)(() => {
throw new Error("Cannot call an event handler while rendering.");
});
if (useReactInsertionEffect) {
useReactInsertionEffect(() => {
ref.current = callback;
});
} else {
ref.current = callback;
}
return (0,external_React_.useCallback)((...args) => {
var _a;
return (_a = ref.current) == null ? void 0 : _a.call(ref, ...args);
}, []);
}
function useMergeRefs(...refs) {
return (0,external_React_.useMemo)(() => {
if (!refs.some(Boolean))
return;
return (value) => {
refs.forEach((ref) => CP3U4HPL_setRef(ref, value));
};
}, refs);
}
function useRefId(ref, deps) {
const [id, setId] = useState(void 0);
useSafeLayoutEffect(() => {
var _a;
setId((_a = ref == null ? void 0 : ref.current) == null ? void 0 : _a.id);
}, deps);
return id;
}
function useId(defaultId) {
if (useReactId) {
const reactId = useReactId();
if (defaultId)
return defaultId;
return reactId;
}
const [id, setId] = (0,external_React_.useState)(defaultId);
useSafeLayoutEffect(() => {
if (defaultId || id)
return;
const random = Math.random().toString(36).substr(2, 6);
setId(`id-${random}`);
}, [defaultId, id]);
return defaultId || id;
}
function useDeferredValue(value) {
if (useReactDeferredValue) {
return useReactDeferredValue(value);
}
const [deferredValue, setDeferredValue] = useState(value);
useEffect(() => {
const raf = requestAnimationFrame(() => setDeferredValue(value));
return () => cancelAnimationFrame(raf);
}, [value]);
return deferredValue;
}
function useTagName(refOrElement, type) {
const stringOrUndefined = (type2) => {
if (typeof type2 !== "string")
return;
return type2;
};
const [tagName, setTagName] = (0,external_React_.useState)(() => stringOrUndefined(type));
useSafeLayoutEffect(() => {
const element = refOrElement && "current" in refOrElement ? refOrElement.current : refOrElement;
setTagName((element == null ? void 0 : element.tagName.toLowerCase()) || stringOrUndefined(type));
}, [refOrElement, type]);
return tagName;
}
function useAttribute(refOrElement, attributeName, defaultValue) {
const [attribute, setAttribute] = useState(defaultValue);
useSafeLayoutEffect(() => {
const element = refOrElement && "current" in refOrElement ? refOrElement.current : refOrElement;
const value = element == null ? void 0 : element.getAttribute(attributeName);
if (value == null)
return;
setAttribute(value);
}, [refOrElement, attributeName]);
return attribute;
}
function J7Q2EO23_useUpdateEffect(effect, deps) {
const mounted = useRef(false);
useEffect(() => {
if (mounted.current) {
return effect();
}
mounted.current = true;
}, deps);
useEffect(
() => () => {
mounted.current = false;
},
[]
);
}
function useUpdateLayoutEffect(effect, deps) {
const mounted = useRef(false);
useSafeLayoutEffect(() => {
if (mounted.current) {
return effect();
}
mounted.current = true;
}, deps);
useSafeLayoutEffect(
() => () => {
mounted.current = false;
},
[]
);
}
function J7Q2EO23_useControlledState(defaultState, state, setState) {
const [localState, setLocalState] = useState(defaultState);
const nextState = state !== void 0 ? state : localState;
const stateRef = J7Q2EO23_useLiveRef(state);
const setStateRef = J7Q2EO23_useLiveRef(setState);
const nextStateRef = J7Q2EO23_useLiveRef(nextState);
const setNextState = useCallback((prevValue) => {
const setStateProp = setStateRef.current;
if (setStateProp) {
if (isSetNextState(setStateProp)) {
setStateProp(prevValue);
} else {
const nextValue = applyState(prevValue, nextStateRef.current);
nextStateRef.current = nextValue;
setStateProp(nextValue);
}
}
if (stateRef.current === void 0) {
setLocalState(prevValue);
}
}, []);
defineSetNextState(setNextState);
return [nextState, setNextState];
}
var SET_NEXT_STATE = Symbol("setNextState");
function isSetNextState(arg) {
return arg[SET_NEXT_STATE] === true;
}
function defineSetNextState(arg) {
if (!isSetNextState(arg)) {
Object.defineProperty(arg, SET_NEXT_STATE, { value: true });
}
}
function J7Q2EO23_useForceUpdate() {
return useReducer(() => [], []);
}
function useBooleanEvent(booleanOrCallback) {
return useEvent(
typeof booleanOrCallback === "function" ? booleanOrCallback : () => booleanOrCallback
);
}
function useWrapElement(props, callback, deps = []) {
const wrapElement = (0,external_React_.useCallback)(
(element) => {
if (props.wrapElement) {
element = props.wrapElement(element);
}
return callback(element);
},
[...deps, props.wrapElement]
);
return PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, props), { wrapElement });
}
function usePortalRef(portalProp = false, portalRefProp) {
const [portalNode, setPortalNode] = useState(null);
const portalRef = useMergeRefs(setPortalNode, portalRefProp);
const domReady = !portalProp || portalNode;
return { portalRef, portalNode, domReady };
}
function useIsMouseMoving() {
useEffect(() => {
addGlobalEventListener("mousemove", setMouseMoving, true);
addGlobalEventListener("mousedown", resetMouseMoving, true);
addGlobalEventListener("mouseup", resetMouseMoving, true);
addGlobalEventListener("keydown", resetMouseMoving, true);
addGlobalEventListener("scroll", resetMouseMoving, true);
}, []);
const isMouseMoving = useEvent(() => mouseMoving);
return isMouseMoving;
}
var mouseMoving = false;
var previousScreenX = 0;
var previousScreenY = 0;
function hasMouseMovement(event) {
const movementX = event.movementX || event.screenX - previousScreenX;
const movementY = event.movementY || event.screenY - previousScreenY;
previousScreenX = event.screenX;
previousScreenY = event.screenY;
return movementX || movementY || "production" === "test";
}
function setMouseMoving(event) {
if (!hasMouseMovement(event))
return;
mouseMoving = true;
}
function resetMouseMoving() {
mouseMoving = false;
}
// EXTERNAL MODULE: ./node_modules/react/jsx-runtime.js
var jsx_runtime = __webpack_require__(7557);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/NQJBHION.js
// src/utils/system.tsx
function NQJBHION_isRenderProp(children) {
return typeof children === "function";
}
function forwardRef2(render) {
const Role = React.forwardRef((props, ref) => render(__spreadProps(__spreadValues({}, props), { ref })));
Role.displayName = render.displayName || render.name;
return Role;
}
function memo2(Component, propsAreEqual) {
const Role = React.memo(Component, propsAreEqual);
Role.displayName = Component.displayName || Component.name;
return Role;
}
function NQJBHION_createComponent(render) {
const Role = (props, ref) => render(PNRLI7OV_spreadValues({ ref }, props));
return external_React_.forwardRef(Role);
}
function createMemoComponent(render) {
const Role = NQJBHION_createComponent(render);
return external_React_.memo(Role);
}
function NQJBHION_createElement(Type, props) {
const _a = props, { as: As, wrapElement, render } = _a, rest = __objRest(_a, ["as", "wrapElement", "render"]);
let element;
const mergedRef = useMergeRefs(props.ref, getRefProperty(render));
if (As && typeof As !== "string") {
element = /* @__PURE__ */ (0,jsx_runtime.jsx)(As, PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, rest), { render }));
} else if (external_React_.isValidElement(render)) {
const renderProps = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, render.props), { ref: mergedRef });
element = external_React_.cloneElement(render, CP3U4HPL_mergeProps(rest, renderProps));
} else if (render) {
element = render(rest);
} else if (NQJBHION_isRenderProp(props.children)) {
const _b = rest, { children } = _b, otherProps = __objRest(_b, ["children"]);
element = props.children(otherProps);
} else if (As) {
element = /* @__PURE__ */ (0,jsx_runtime.jsx)(As, PNRLI7OV_spreadValues({}, rest));
} else {
element = /* @__PURE__ */ (0,jsx_runtime.jsx)(Type, PNRLI7OV_spreadValues({}, rest));
}
if (wrapElement) {
return wrapElement(element);
}
return element;
}
function NQJBHION_createHook(useProps) {
const useRole = (props = {}) => {
const htmlProps = useProps(props);
const copy = {};
for (const prop in htmlProps) {
if (WVTCK5PV_hasOwnProperty(htmlProps, prop) && htmlProps[prop] !== void 0) {
copy[prop] = htmlProps[prop];
}
}
return copy;
};
return useRole;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/utils/events.js
// src/utils/events.ts
function events_isPortalEvent(event) {
return Boolean(
event.currentTarget && !O35LWD4W_contains(event.currentTarget, event.target)
);
}
function events_isSelfTarget(event) {
return event.target === event.currentTarget;
}
function isOpeningInNewTab(event) {
const element = event.currentTarget;
if (!element)
return false;
const isAppleDevice = isApple();
if (isAppleDevice && !event.metaKey)
return false;
if (!isAppleDevice && !event.ctrlKey)
return false;
const tagName = element.tagName.toLowerCase();
if (tagName === "a")
return true;
if (tagName === "button" && element.type === "submit")
return true;
if (tagName === "input" && element.type === "submit")
return true;
return false;
}
function isDownloading(event) {
const element = event.currentTarget;
if (!element)
return false;
const tagName = element.tagName.toLowerCase();
if (!event.altKey)
return false;
if (tagName === "a")
return true;
if (tagName === "button" && element.type === "submit")
return true;
if (tagName === "input" && element.type === "submit")
return true;
return false;
}
function events_fireEvent(element, type, eventInit) {
const event = new Event(type, eventInit);
return element.dispatchEvent(event);
}
function events_fireBlurEvent(element, eventInit) {
const event = new FocusEvent("blur", eventInit);
const defaultAllowed = element.dispatchEvent(event);
const bubbleInit = _chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, eventInit), { bubbles: true });
element.dispatchEvent(new FocusEvent("focusout", bubbleInit));
return defaultAllowed;
}
function fireFocusEvent(element, eventInit) {
const event = new FocusEvent("focus", eventInit);
const defaultAllowed = element.dispatchEvent(event);
const bubbleInit = _chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, eventInit), { bubbles: true });
element.dispatchEvent(new FocusEvent("focusin", bubbleInit));
return defaultAllowed;
}
function events_fireKeyboardEvent(element, type, eventInit) {
const event = new KeyboardEvent(type, eventInit);
return element.dispatchEvent(event);
}
function fireClickEvent(element, eventInit) {
const event = new MouseEvent("click", eventInit);
return element.dispatchEvent(event);
}
function isFocusEventOutside(event, container) {
const containerElement = container || event.currentTarget;
const relatedTarget = event.relatedTarget;
return !relatedTarget || !O35LWD4W_contains(containerElement, relatedTarget);
}
function queueBeforeEvent(element, type, callback) {
const raf = requestAnimationFrame(() => {
element.removeEventListener(type, callImmediately, true);
callback();
});
const callImmediately = () => {
cancelAnimationFrame(raf);
callback();
};
element.addEventListener(type, callImmediately, {
once: true,
capture: true
});
return raf;
}
function events_addGlobalEventListener(type, listener, options, scope = window) {
var _a;
try {
scope.document.addEventListener(type, listener, options);
} catch (e) {
}
const listeners = [];
for (let i = 0; i < ((_a = scope.frames) == null ? void 0 : _a.length); i += 1) {
const frameWindow = scope.frames[i];
if (frameWindow) {
listeners.push(
events_addGlobalEventListener(type, listener, options, frameWindow)
);
}
}
const removeEventListener = () => {
try {
scope.document.removeEventListener(type, listener, options);
} catch (e) {
}
listeners.forEach((listener2) => listener2());
};
return removeEventListener;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/utils/focus.js
// src/utils/focus.ts
var focus_selector = "input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], iframe, object, embed, area[href], audio[controls], video[controls], [contenteditable]:not([contenteditable='false'])";
function focus_hasNegativeTabIndex(element) {
const tabIndex = parseInt(element.getAttribute("tabindex") || "0", 10);
return tabIndex < 0;
}
function focus_isFocusable(element) {
if (!O35LWD4W_matches(element, focus_selector))
return false;
if (!O35LWD4W_isVisible(element))
return false;
if (O35LWD4W_closest(element, "[inert]"))
return false;
return true;
}
function focus_isTabbable(element) {
if (!focus_isFocusable(element))
return false;
if (focus_hasNegativeTabIndex(element))
return false;
if (!("form" in element))
return true;
if (!element.form)
return true;
if (element.checked)
return true;
if (element.type !== "radio")
return true;
const radioGroup = element.form.elements.namedItem(element.name);
if (!radioGroup)
return true;
if (!("length" in radioGroup))
return true;
const activeElement = getActiveElement(element);
if (!activeElement)
return true;
if (activeElement === element)
return true;
if (!("form" in activeElement))
return true;
if (activeElement.form !== element.form)
return true;
if (activeElement.name !== element.name)
return true;
return false;
}
function focus_getAllFocusableIn(container, includeContainer) {
const elements = Array.from(
container.querySelectorAll(focus_selector)
);
if (includeContainer) {
elements.unshift(container);
}
const focusableElements = elements.filter(focus_isFocusable);
focusableElements.forEach((element, i) => {
if (isFrame(element) && element.contentDocument) {
const frameBody = element.contentDocument.body;
focusableElements.splice(i, 1, ...focus_getAllFocusableIn(frameBody));
}
});
return focusableElements;
}
function getAllFocusable(includeBody) {
return focus_getAllFocusableIn(document.body, includeBody);
}
function focus_getFirstFocusableIn(container, includeContainer) {
const [first] = focus_getAllFocusableIn(container, includeContainer);
return first || null;
}
function getFirstFocusable(includeBody) {
return focus_getFirstFocusableIn(document.body, includeBody);
}
function focus_getAllTabbableIn(container, includeContainer, fallbackToFocusable) {
const elements = Array.from(
container.querySelectorAll(focus_selector)
);
const tabbableElements = elements.filter(focus_isTabbable);
if (includeContainer && focus_isTabbable(container)) {
tabbableElements.unshift(container);
}
tabbableElements.forEach((element, i) => {
if (isFrame(element) && element.contentDocument) {
const frameBody = element.contentDocument.body;
const allFrameTabbable = focus_getAllTabbableIn(
frameBody,
false,
fallbackToFocusable
);
tabbableElements.splice(i, 1, ...allFrameTabbable);
}
});
if (!tabbableElements.length && fallbackToFocusable) {
return elements;
}
return tabbableElements;
}
function getAllTabbable(fallbackToFocusable) {
return focus_getAllTabbableIn(document.body, false, fallbackToFocusable);
}
function focus_getFirstTabbableIn(container, includeContainer, fallbackToFocusable) {
const [first] = focus_getAllTabbableIn(
container,
includeContainer,
fallbackToFocusable
);
return first || null;
}
function getFirstTabbable(fallbackToFocusable) {
return focus_getFirstTabbableIn(document.body, false, fallbackToFocusable);
}
function focus_getLastTabbableIn(container, includeContainer, fallbackToFocusable) {
const allTabbable = focus_getAllTabbableIn(
container,
includeContainer,
fallbackToFocusable
);
return allTabbable[allTabbable.length - 1] || null;
}
function getLastTabbable(fallbackToFocusable) {
return focus_getLastTabbableIn(document.body, false, fallbackToFocusable);
}
function focus_getNextTabbableIn(container, includeContainer, fallbackToFirst, fallbackToFocusable) {
const activeElement = getActiveElement(container);
const allFocusable = focus_getAllFocusableIn(container, includeContainer);
const activeIndex = allFocusable.indexOf(activeElement);
const nextFocusableElements = allFocusable.slice(activeIndex + 1);
return nextFocusableElements.find(focus_isTabbable) || (fallbackToFirst ? allFocusable.find(focus_isTabbable) : null) || (fallbackToFocusable ? nextFocusableElements[0] : null) || null;
}
function getNextTabbable(fallbackToFirst, fallbackToFocusable) {
return focus_getNextTabbableIn(
document.body,
false,
fallbackToFirst,
fallbackToFocusable
);
}
function focus_getPreviousTabbableIn(container, includeContainer, fallbackToLast, fallbackToFocusable) {
const activeElement = getActiveElement(container);
const allFocusable = focus_getAllFocusableIn(container, includeContainer).reverse();
const activeIndex = allFocusable.indexOf(activeElement);
const previousFocusableElements = allFocusable.slice(activeIndex + 1);
return previousFocusableElements.find(focus_isTabbable) || (fallbackToLast ? allFocusable.find(focus_isTabbable) : null) || (fallbackToFocusable ? previousFocusableElements[0] : null) || null;
}
function getPreviousTabbable(fallbackToFirst, fallbackToFocusable) {
return focus_getPreviousTabbableIn(
document.body,
false,
fallbackToFirst,
fallbackToFocusable
);
}
function focus_getClosestFocusable(element) {
while (element && !focus_isFocusable(element)) {
element = closest(element, focus_selector);
}
return element || null;
}
function focus_hasFocus(element) {
const activeElement = O35LWD4W_getActiveElement(element);
if (!activeElement)
return false;
if (activeElement === element)
return true;
const activeDescendant = activeElement.getAttribute("aria-activedescendant");
if (!activeDescendant)
return false;
return activeDescendant === element.id;
}
function focus_hasFocusWithin(element) {
const activeElement = O35LWD4W_getActiveElement(element);
if (!activeElement)
return false;
if (O35LWD4W_contains(element, activeElement))
return true;
const activeDescendant = activeElement.getAttribute("aria-activedescendant");
if (!activeDescendant)
return false;
if (!("id" in element))
return false;
if (activeDescendant === element.id)
return true;
return !!element.querySelector(`#${CSS.escape(activeDescendant)}`);
}
function focus_focusIfNeeded(element) {
if (!focus_hasFocusWithin(element) && focus_isFocusable(element)) {
element.focus();
}
}
function disableFocus(element) {
var _a;
const currentTabindex = (_a = element.getAttribute("tabindex")) != null ? _a : "";
element.setAttribute("data-tabindex", currentTabindex);
element.setAttribute("tabindex", "-1");
}
function disableFocusIn(container, includeContainer) {
const tabbableElements = focus_getAllTabbableIn(container, includeContainer);
tabbableElements.forEach(disableFocus);
}
function restoreFocusIn(container) {
const elements = container.querySelectorAll("[data-tabindex]");
const restoreTabIndex = (element) => {
const tabindex = element.getAttribute("data-tabindex");
element.removeAttribute("data-tabindex");
if (tabindex) {
element.setAttribute("tabindex", tabindex);
} else {
element.removeAttribute("tabindex");
}
};
if (container.hasAttribute("data-tabindex")) {
restoreTabIndex(container);
}
elements.forEach(restoreTabIndex);
}
function focusIntoView(element, options) {
if (!("scrollIntoView" in element)) {
element.focus();
} else {
element.focus({ preventScroll: true });
element.scrollIntoView(_chunks_PNRLI7OV_spreadValues({ block: "nearest", inline: "nearest" }, options));
}
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/UCFCIHEU.js
// src/utils/platform.ts
function isTouchDevice() {
return canUseDOM && !!navigator.maxTouchPoints;
}
function UCFCIHEU_isApple() {
if (!O35LWD4W_canUseDOM)
return false;
return /mac|iphone|ipad|ipod/i.test(navigator.platform);
}
function UCFCIHEU_isSafari() {
return O35LWD4W_canUseDOM && UCFCIHEU_isApple() && /apple/i.test(navigator.vendor);
}
function isFirefox() {
return O35LWD4W_canUseDOM && /firefox\//i.test(navigator.userAgent);
}
function isMac() {
return canUseDOM && navigator.platform.startsWith("Mac") && !isTouchDevice();
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/MYID4V27.js
// src/focusable/focusable.ts
var isSafariBrowser = UCFCIHEU_isSafari();
var alwaysFocusVisibleInputTypes = [
"text",
"search",
"url",
"tel",
"email",
"password",
"number",
"date",
"month",
"week",
"time",
"datetime",
"datetime-local"
];
function isAlwaysFocusVisible(element) {
const { tagName, readOnly, type } = element;
if (tagName === "TEXTAREA" && !readOnly)
return true;
if (tagName === "SELECT" && !readOnly)
return true;
if (tagName === "INPUT" && !readOnly) {
return alwaysFocusVisibleInputTypes.includes(type);
}
if (element.isContentEditable)
return true;
return false;
}
function isAlwaysFocusVisibleDelayed(element) {
const role = element.getAttribute("role");
if (role !== "combobox")
return false;
return !!element.dataset.name;
}
function getLabels(element) {
if ("labels" in element) {
return element.labels;
}
return null;
}
function isNativeCheckboxOrRadio(element) {
const tagName = element.tagName.toLowerCase();
if (tagName === "input" && element.type) {
return element.type === "radio" || element.type === "checkbox";
}
return false;
}
function MYID4V27_isNativeTabbable(tagName) {
if (!tagName)
return true;
return tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea" || tagName === "a";
}
function MYID4V27_supportsDisabledAttribute(tagName) {
if (!tagName)
return true;
return tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea";
}
function MYID4V27_getTabIndex(focusable, trulyDisabled, nativeTabbable, supportsDisabled, tabIndexProp) {
if (!focusable) {
return tabIndexProp;
}
if (trulyDisabled) {
if (nativeTabbable && !supportsDisabled) {
return -1;
}
return;
}
if (nativeTabbable) {
return tabIndexProp;
}
return tabIndexProp || 0;
}
function MYID4V27_useDisableEvent(onEvent, disabled) {
return useEvent((event) => {
onEvent == null ? void 0 : onEvent(event);
if (event.defaultPrevented)
return;
if (disabled) {
event.stopPropagation();
event.preventDefault();
}
});
}
var isKeyboardModality = true;
function onGlobalMouseDown(event) {
const target = event.target;
if (target && "hasAttribute" in target) {
if (!target.hasAttribute("data-focus-visible")) {
isKeyboardModality = false;
}
}
}
function onGlobalKeyDown(event) {
if (event.metaKey)
return;
if (event.ctrlKey)
return;
if (event.altKey)
return;
isKeyboardModality = true;
}
var useFocusable = NQJBHION_createHook(
(_a) => {
var _b = _a, {
focusable = true,
accessibleWhenDisabled,
autoFocus,
onFocusVisible
} = _b, props = __objRest(_b, [
"focusable",
"accessibleWhenDisabled",
"autoFocus",
"onFocusVisible"
]);
const ref = (0,external_React_.useRef)(null);
(0,external_React_.useEffect)(() => {
if (!focusable)
return;
events_addGlobalEventListener("mousedown", onGlobalMouseDown, true);
events_addGlobalEventListener("keydown", onGlobalKeyDown, true);
}, [focusable]);
if (isSafariBrowser) {
(0,external_React_.useEffect)(() => {
if (!focusable)
return;
const element = ref.current;
if (!element)
return;
if (!isNativeCheckboxOrRadio(element))
return;
const labels = getLabels(element);
if (!labels)
return;
const onMouseUp = () => queueMicrotask(() => element.focus());
labels.forEach((label) => label.addEventListener("mouseup", onMouseUp));
return () => {
labels.forEach(
(label) => label.removeEventListener("mouseup", onMouseUp)
);
};
}, [focusable]);
}
const disabled = focusable && props.disabled;
const trulyDisabled = !!disabled && !accessibleWhenDisabled;
const [focusVisible, setFocusVisible] = (0,external_React_.useState)(false);
(0,external_React_.useEffect)(() => {
if (!focusable)
return;
if (trulyDisabled && focusVisible) {
setFocusVisible(false);
}
}, [focusable, trulyDisabled, focusVisible]);
(0,external_React_.useEffect)(() => {
if (!focusable)
return;
if (!focusVisible)
return;
const element = ref.current;
if (!element)
return;
if (typeof IntersectionObserver === "undefined")
return;
const observer = new IntersectionObserver(() => {
if (!focus_isFocusable(element)) {
setFocusVisible(false);
}
});
observer.observe(element);
return () => observer.disconnect();
}, [focusable, focusVisible]);
const onKeyPressCapture = MYID4V27_useDisableEvent(
props.onKeyPressCapture,
disabled
);
const onMouseDownCapture = MYID4V27_useDisableEvent(
props.onMouseDownCapture,
disabled
);
const onClickCapture = MYID4V27_useDisableEvent(props.onClickCapture, disabled);
const onMouseDownProp = props.onMouseDown;
const onMouseDown = useEvent((event) => {
onMouseDownProp == null ? void 0 : onMouseDownProp(event);
if (event.defaultPrevented)
return;
if (!focusable)
return;
const element = event.currentTarget;
if (!isSafariBrowser)
return;
if (events_isPortalEvent(event))
return;
if (!O35LWD4W_isButton(element) && !isNativeCheckboxOrRadio(element))
return;
let receivedFocus = false;
const onFocus = () => {
receivedFocus = true;
};
const options = { capture: true, once: true };
element.addEventListener("focusin", onFocus, options);
queueBeforeEvent(element, "mouseup", () => {
element.removeEventListener("focusin", onFocus, true);
if (receivedFocus)
return;
focus_focusIfNeeded(element);
});
});
const handleFocusVisible = (event, currentTarget) => {
if (currentTarget) {
event.currentTarget = currentTarget;
}
onFocusVisible == null ? void 0 : onFocusVisible(event);
if (event.defaultPrevented)
return;
if (!focusable)
return;
const element = event.currentTarget;
if (!element)
return;
if (!focus_hasFocus(element))
return;
setFocusVisible(true);
};
const onKeyDownCaptureProp = props.onKeyDownCapture;
const onKeyDownCapture = useEvent(
(event) => {
onKeyDownCaptureProp == null ? void 0 : onKeyDownCaptureProp(event);
if (event.defaultPrevented)
return;
if (!focusable)
return;
if (focusVisible)
return;
if (event.metaKey)
return;
if (event.altKey)
return;
if (event.ctrlKey)
return;
if (!events_isSelfTarget(event))
return;
const element = event.currentTarget;
queueMicrotask(() => handleFocusVisible(event, element));
}
);
const onFocusCaptureProp = props.onFocusCapture;
const onFocusCapture = useEvent((event) => {
onFocusCaptureProp == null ? void 0 : onFocusCaptureProp(event);
if (event.defaultPrevented)
return;
if (!focusable)
return;
if (!events_isSelfTarget(event)) {
setFocusVisible(false);
return;
}
const element = event.currentTarget;
const applyFocusVisible = () => handleFocusVisible(event, element);
if (isKeyboardModality || isAlwaysFocusVisible(event.target)) {
queueMicrotask(applyFocusVisible);
} else if (isAlwaysFocusVisibleDelayed(event.target)) {
queueBeforeEvent(event.target, "focusout", applyFocusVisible);
} else {
setFocusVisible(false);
}
});
const onBlurProp = props.onBlur;
const onBlur = useEvent((event) => {
onBlurProp == null ? void 0 : onBlurProp(event);
if (!focusable)
return;
if (!isFocusEventOutside(event))
return;
setFocusVisible(false);
});
const autoFocusOnShow = (0,external_React_.useContext)(FocusableContext);
const autoFocusRef = useEvent((element) => {
if (!focusable)
return;
if (!autoFocus)
return;
if (!element)
return;
if (!autoFocusOnShow)
return;
queueMicrotask(() => {
if (focus_hasFocus(element))
return;
if (!focus_isFocusable(element))
return;
element.focus();
});
});
const tagName = useTagName(ref, props.as);
const nativeTabbable = focusable && MYID4V27_isNativeTabbable(tagName);
const supportsDisabled = focusable && MYID4V27_supportsDisabledAttribute(tagName);
const style = trulyDisabled ? PNRLI7OV_spreadValues({ pointerEvents: "none" }, props.style) : props.style;
props = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({
"data-focus-visible": focusable && focusVisible ? "" : void 0,
"data-autofocus": autoFocus ? true : void 0,
"aria-disabled": disabled ? true : void 0
}, props), {
ref: useMergeRefs(ref, autoFocusRef, props.ref),
style,
tabIndex: MYID4V27_getTabIndex(
focusable,
trulyDisabled,
nativeTabbable,
supportsDisabled,
props.tabIndex
),
disabled: supportsDisabled && trulyDisabled ? true : void 0,
// TODO: Test Focusable contentEditable.
contentEditable: disabled ? void 0 : props.contentEditable,
onKeyPressCapture,
onClickCapture,
onMouseDownCapture,
onMouseDown,
onKeyDownCapture,
onFocusCapture,
onBlur
});
return props;
}
);
var Focusable = NQJBHION_createComponent((props) => {
props = useFocusable(props);
return NQJBHION_createElement("div", props);
});
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/P4RGQGTG.js
// src/command/command.ts
function P4RGQGTG_isNativeClick(event) {
if (!event.isTrusted)
return false;
const element = event.currentTarget;
if (event.key === "Enter") {
return O35LWD4W_isButton(element) || element.tagName === "SUMMARY" || element.tagName === "A";
}
if (event.key === " ") {
return O35LWD4W_isButton(element) || element.tagName === "SUMMARY" || element.tagName === "INPUT" || element.tagName === "SELECT";
}
return false;
}
var useCommand = NQJBHION_createHook(
(_a) => {
var _b = _a, { clickOnEnter = true, clickOnSpace = true } = _b, props = __objRest(_b, ["clickOnEnter", "clickOnSpace"]);
const ref = (0,external_React_.useRef)(null);
const tagName = useTagName(ref, props.as);
const type = props.type;
const [isNativeButton, setIsNativeButton] = (0,external_React_.useState)(
() => !!tagName && O35LWD4W_isButton({ tagName, type })
);
(0,external_React_.useEffect)(() => {
if (!ref.current)
return;
setIsNativeButton(O35LWD4W_isButton(ref.current));
}, []);
const [active, setActive] = (0,external_React_.useState)(false);
const activeRef = (0,external_React_.useRef)(false);
const isDuplicate = "data-command" in props;
const onKeyDownProp = props.onKeyDown;
const onKeyDown = useEvent((event) => {
onKeyDownProp == null ? void 0 : onKeyDownProp(event);
const element = event.currentTarget;
if (event.defaultPrevented)
return;
if (isDuplicate)
return;
if (props.disabled)
return;
if (!events_isSelfTarget(event))
return;
if (O35LWD4W_isTextField(element))
return;
if (element.isContentEditable)
return;
const isEnter = clickOnEnter && event.key === "Enter";
const isSpace = clickOnSpace && event.key === " ";
const shouldPreventEnter = event.key === "Enter" && !clickOnEnter;
const shouldPreventSpace = event.key === " " && !clickOnSpace;
if (shouldPreventEnter || shouldPreventSpace) {
event.preventDefault();
return;
}
if (isEnter || isSpace) {
const nativeClick = P4RGQGTG_isNativeClick(event);
if (isEnter) {
if (!nativeClick) {
event.preventDefault();
const _a2 = event, { view } = _a2, eventInit = __objRest(_a2, ["view"]);
const click = () => fireClickEvent(element, eventInit);
if (isFirefox()) {
queueBeforeEvent(element, "keyup", click);
} else {
queueMicrotask(click);
}
}
} else if (isSpace) {
activeRef.current = true;
if (!nativeClick) {
event.preventDefault();
setActive(true);
}
}
}
});
const onKeyUpProp = props.onKeyUp;
const onKeyUp = useEvent((event) => {
onKeyUpProp == null ? void 0 : onKeyUpProp(event);
if (event.defaultPrevented)
return;
if (isDuplicate)
return;
if (props.disabled)
return;
if (event.metaKey)
return;
const isSpace = clickOnSpace && event.key === " ";
if (activeRef.current && isSpace) {
activeRef.current = false;
if (!P4RGQGTG_isNativeClick(event)) {
setActive(false);
const element = event.currentTarget;
const _a2 = event, { view } = _a2, eventInit = __objRest(_a2, ["view"]);
queueMicrotask(() => fireClickEvent(element, eventInit));
}
}
});
props = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({
"data-command": "",
"data-active": active ? "" : void 0,
type: isNativeButton ? "button" : void 0
}, props), {
ref: useMergeRefs(ref, props.ref),
onKeyDown,
onKeyUp
});
props = useFocusable(props);
return props;
}
);
var Command = NQJBHION_createComponent((props) => {
props = useCommand(props);
return NQJBHION_createElement("button", props);
});
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/T3DJZG63.js
// src/collection/collection-context.ts
var CollectionContext = (0,external_React_.createContext)(
void 0
);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/HGFTMLQ7.js
// src/collection/collection-item.ts
var useCollectionItem = NQJBHION_createHook(
(_a) => {
var _b = _a, {
store,
shouldRegisterItem = true,
getItem = WVTCK5PV_identity,
element: element
} = _b, props = __objRest(_b, [
"store",
"shouldRegisterItem",
"getItem",
// @ts-expect-error This prop may come from a collection renderer.
"element"
]);
const context = (0,external_React_.useContext)(CollectionContext);
store = store || context;
const id = useId(props.id);
const unrenderItem = (0,external_React_.useRef)();
const ref = (0,external_React_.useCallback)(
(element2) => {
var _a2;
if (!element2 || !id || !shouldRegisterItem) {
return (_a2 = unrenderItem.current) == null ? void 0 : _a2.call(unrenderItem);
}
const item = getItem({ id, element: element2 });
unrenderItem.current = store == null ? void 0 : store.renderItem(item);
},
[id, shouldRegisterItem, getItem, store]
);
props = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, props), {
ref: useMergeRefs(ref, props.ref)
});
return props;
}
);
var CollectionItem = NQJBHION_createComponent(
(props) => {
const htmlProps = useCollectionItem(props);
return NQJBHION_createElement("div", htmlProps);
}
);
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/OXPV2NBK.js
// src/composite/utils.ts
var NULL_ITEM = { id: null };
function flipItems(items, activeId, shouldInsertNullItem = false) {
const index = items.findIndex((item) => item.id === activeId);
return [
...items.slice(index + 1),
...shouldInsertNullItem ? [NULL_ITEM] : [],
...items.slice(0, index)
];
}
function OXPV2NBK_findFirstEnabledItem(items, excludeId) {
return items.find((item) => {
if (excludeId) {
return !item.disabled && item.id !== excludeId;
}
return !item.disabled;
});
}
function getEnabledItem(store, id) {
if (!id)
return null;
return store.item(id) || null;
}
function groupItemsByRows(items) {
const rows = [];
for (const item of items) {
const row = rows.find((currentRow) => {
var _a;
return ((_a = currentRow[0]) == null ? void 0 : _a.rowId) === item.rowId;
});
if (row) {
row.push(item);
} else {
rows.push([item]);
}
}
return rows;
}
function selectTextField(element, collapseToEnd = false) {
if (isTextField(element)) {
element.setSelectionRange(
collapseToEnd ? element.value.length : 0,
element.value.length
);
} else if (element.isContentEditable) {
const selection = getDocument(element).getSelection();
selection == null ? void 0 : selection.selectAllChildren(element);
if (collapseToEnd) {
selection == null ? void 0 : selection.collapseToEnd();
}
}
}
var FOCUS_SILENTLY = Symbol("FOCUS_SILENTLY");
function focusSilently(element) {
element[FOCUS_SILENTLY] = true;
element.focus();
}
function silentlyFocused(element) {
const isSilentlyFocused = element[FOCUS_SILENTLY];
delete element[FOCUS_SILENTLY];
return isSilentlyFocused;
}
function OXPV2NBK_isItem(store, element, exclude) {
if (!element)
return false;
if (element === exclude)
return false;
const item = store.item(element.id);
if (!item)
return false;
if (exclude && item.element === exclude)
return false;
return true;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/WJ37OVG2.js
// src/composite/composite-context.ts
var CompositeItemContext = (0,external_React_.createContext)(
void 0
);
var CompositeRowContext = (0,external_React_.createContext)(
void 0
);
var CompositeContext = (0,external_React_.createContext)(
void 0
);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/OOWNFOTF.js
// src/utils/store.tsx
var noopSubscribe = () => () => {
};
function useStoreState(store, keyOrSelector = WVTCK5PV_identity) {
const getSnapshot = () => {
if (!store)
return;
const state = store.getState();
const selector = typeof keyOrSelector === "function" ? keyOrSelector : null;
const key = typeof keyOrSelector === "string" ? keyOrSelector : null;
if (selector)
return selector(state);
if (!key)
return;
if (!WVTCK5PV_hasOwnProperty(state, key))
return;
return state[key];
};
return (0,shim.useSyncExternalStore)(
(store == null ? void 0 : store.subscribe) || noopSubscribe,
getSnapshot,
getSnapshot
);
}
function useStoreProps(store, props, key, setKey) {
const value = WVTCK5PV_hasOwnProperty(props, key) ? props[key] : void 0;
const propsRef = J7Q2EO23_useLiveRef({
value,
setValue: setKey ? props[setKey] : void 0
});
useSafeLayoutEffect(() => {
let canFlushSync = false;
queueMicrotask(() => {
canFlushSync = true;
});
return store.sync(
(state, prev) => {
const { value: value2, setValue } = propsRef.current;
if (!setValue)
return;
if (state[key] === prev[key])
return;
if (state[key] === value2)
return;
if (canFlushSync) {
(0,external_ReactDOM_namespaceObject.flushSync)(() => setValue(state[key]));
} else {
setValue(state[key]);
}
},
[key]
);
}, [store, key]);
useSafeLayoutEffect(() => {
return store.sync(() => {
if (value === void 0)
return;
store.setState(key, value);
}, [key]);
}, [store, key, value]);
}
function OOWNFOTF_useStore(createStore) {
const store = useLazyValue(createStore);
useSafeLayoutEffect(() => store.init(), [store]);
const useState = (0,external_React_.useCallback)(
(keyOrSelector) => useStoreState(store, keyOrSelector),
[store]
);
return (0,external_React_.useMemo)(() => PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, store), { useState }), [store, useState]);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/DCG3EYDE.js
// src/composite/composite-item.tsx
function isEditableElement(element) {
if (element.isContentEditable)
return true;
if (O35LWD4W_isTextField(element))
return true;
return element.tagName === "INPUT" && !O35LWD4W_isButton(element);
}
function getNextPageOffset(scrollingElement, pageUp = false) {
const height = scrollingElement.clientHeight;
const { top } = scrollingElement.getBoundingClientRect();
const pageSize = Math.max(height * 0.875, height - 40) * 1.5;
const pageOffset = pageUp ? height - pageSize + top : pageSize + top;
if (scrollingElement.tagName === "HTML") {
return pageOffset + scrollingElement.scrollTop;
}
return pageOffset;
}
function getItemOffset(itemElement, pageUp = false) {
const { top } = itemElement.getBoundingClientRect();
if (pageUp) {
return top + itemElement.clientHeight;
}
return top;
}
function findNextPageItemId(element, store, next, pageUp = false) {
var _a;
if (!store)
return;
if (!next)
return;
const { renderedItems } = store.getState();
const scrollingElement = getScrollingElement(element);
if (!scrollingElement)
return;
const nextPageOffset = getNextPageOffset(scrollingElement, pageUp);
let id;
let prevDifference;
for (let i = 0; i < renderedItems.length; i += 1) {
const previousId = id;
id = next(i);
if (!id)
break;
if (id === previousId)
continue;
const itemElement = (_a = getEnabledItem(store, id)) == null ? void 0 : _a.element;
if (!itemElement)
continue;
const itemOffset = getItemOffset(itemElement, pageUp);
const difference = itemOffset - nextPageOffset;
const absDifference = Math.abs(difference);
if (pageUp && difference <= 0 || !pageUp && difference >= 0) {
if (prevDifference !== void 0 && prevDifference < absDifference) {
id = previousId;
}
break;
}
prevDifference = absDifference;
}
return id;
}
function DCG3EYDE_targetIsAnotherItem(event, store) {
if (events_isSelfTarget(event))
return false;
return OXPV2NBK_isItem(store, event.target);
}
function DCG3EYDE_useRole(ref, props) {
const roleProp = props.role;
const [role, setRole] = (0,external_React_.useState)(roleProp);
useSafeLayoutEffect(() => {
const element = ref.current;
if (!element)
return;
setRole(element.getAttribute("role") || roleProp);
}, [roleProp]);
return role;
}
function requiresAriaSelected(role) {
return role === "option" || role === "treeitem";
}
function supportsAriaSelected(role) {
if (role === "option")
return true;
if (role === "tab")
return true;
if (role === "treeitem")
return true;
if (role === "gridcell")
return true;
if (role === "row")
return true;
if (role === "columnheader")
return true;
if (role === "rowheader")
return true;
return false;
}
var DCG3EYDE_useCompositeItem = NQJBHION_createHook(
(_a) => {
var _b = _a, {
store,
rowId: rowIdProp,
preventScrollOnKeyDown = false,
moveOnKeyPress = true,
getItem: getItemProp,
"aria-setsize": ariaSetSizeProp,
"aria-posinset": ariaPosInSetProp
} = _b, props = __objRest(_b, [
"store",
"rowId",
"preventScrollOnKeyDown",
"moveOnKeyPress",
"getItem",
"aria-setsize",
"aria-posinset"
]);
var _a2;
const context = (0,external_React_.useContext)(CompositeContext);
store = store || context;
const id = useId(props.id);
const ref = (0,external_React_.useRef)(null);
const row = (0,external_React_.useContext)(CompositeRowContext);
const rowId = useStoreState(store, (state) => {
if (rowIdProp)
return rowIdProp;
if (!(row == null ? void 0 : row.baseElement))
return;
if (row.baseElement !== state.baseElement)
return;
return row.id;
});
const trulyDisabled = props.disabled && !props.accessibleWhenDisabled;
const getItem = (0,external_React_.useCallback)(
(item) => {
const nextItem = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, item), {
id: id || item.id,
rowId,
disabled: !!trulyDisabled
});
if (getItemProp) {
return getItemProp(nextItem);
}
return nextItem;
},
[id, rowId, trulyDisabled, getItemProp]
);
const onFocusProp = props.onFocus;
const hasFocusedComposite = (0,external_React_.useRef)(false);
const onFocus = useEvent((event) => {
onFocusProp == null ? void 0 : onFocusProp(event);
if (event.defaultPrevented)
return;
if (events_isPortalEvent(event))
return;
if (!id)
return;
if (!store)
return;
const { activeId, virtualFocus: virtualFocus2, baseElement: baseElement2 } = store.getState();
if (DCG3EYDE_targetIsAnotherItem(event, store))
return;
if (activeId !== id) {
store.setActiveId(id);
}
if (!virtualFocus2)
return;
if (!events_isSelfTarget(event))
return;
if (isEditableElement(event.currentTarget))
return;
if (!baseElement2)
return;
hasFocusedComposite.current = true;
const fromComposite = event.relatedTarget === baseElement2 || OXPV2NBK_isItem(store, event.relatedTarget);
if (fromComposite) {
focusSilently(baseElement2);
} else {
baseElement2.focus();
}
});
const onBlurCaptureProp = props.onBlurCapture;
const onBlurCapture = useEvent((event) => {
onBlurCaptureProp == null ? void 0 : onBlurCaptureProp(event);
if (event.defaultPrevented)
return;
const state = store == null ? void 0 : store.getState();
if ((state == null ? void 0 : state.virtualFocus) && hasFocusedComposite.current) {
hasFocusedComposite.current = false;
event.preventDefault();
event.stopPropagation();
}
});
const onKeyDownProp = props.onKeyDown;
const preventScrollOnKeyDownProp = useBooleanEvent(preventScrollOnKeyDown);
const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
const onKeyDown = useEvent((event) => {
onKeyDownProp == null ? void 0 : onKeyDownProp(event);
if (event.defaultPrevented)
return;
if (!events_isSelfTarget(event))
return;
if (!store)
return;
const { currentTarget } = event;
const state = store.getState();
const item = store.item(id);
const isGrid = !!(item == null ? void 0 : item.rowId);
const isVertical = state.orientation !== "horizontal";
const isHorizontal = state.orientation !== "vertical";
const keyMap = {
ArrowUp: (isGrid || isVertical) && store.up,
ArrowRight: (isGrid || isHorizontal) && store.next,
ArrowDown: (isGrid || isVertical) && store.down,
ArrowLeft: (isGrid || isHorizontal) && store.previous,
Home: () => {
if (!isGrid || event.ctrlKey) {
return store == null ? void 0 : store.first();
}
return store == null ? void 0 : store.previous(-1);
},
End: () => {
if (!isGrid || event.ctrlKey) {
return store == null ? void 0 : store.last();
}
return store == null ? void 0 : store.next(-1);
},
PageUp: () => {
return findNextPageItemId(currentTarget, store, store == null ? void 0 : store.up, true);
},
PageDown: () => {
return findNextPageItemId(currentTarget, store, store == null ? void 0 : store.down);
}
};
const action = keyMap[event.key];
if (action) {
const nextId = action();
if (preventScrollOnKeyDownProp(event) || nextId !== void 0) {
if (!moveOnKeyPressProp(event))
return;
event.preventDefault();
store.move(nextId);
}
}
});
const baseElement = useStoreState(
store,
(state) => state.baseElement || void 0
);
const providerValue = (0,external_React_.useMemo)(
() => ({ id, baseElement }),
[id, baseElement]
);
props = useWrapElement(
props,
(element) => /* @__PURE__ */ (0,jsx_runtime.jsx)(CompositeItemContext.Provider, { value: providerValue, children: element }),
[providerValue]
);
const isActiveItem = useStoreState(store, (state) => state.activeId === id);
const virtualFocus = useStoreState(store, "virtualFocus");
const role = DCG3EYDE_useRole(ref, props);
let ariaSelected;
if (isActiveItem) {
if (requiresAriaSelected(role)) {
ariaSelected = true;
} else if (virtualFocus && supportsAriaSelected(role)) {
ariaSelected = true;
}
}
const ariaSetSize = useStoreState(store, (state) => {
if (ariaSetSizeProp != null)
return ariaSetSizeProp;
if (!(row == null ? void 0 : row.ariaSetSize))
return;
if (row.baseElement !== state.baseElement)
return;
return row.ariaSetSize;
});
const ariaPosInSet = useStoreState(store, (state) => {
if (ariaPosInSetProp != null)
return ariaPosInSetProp;
if (!(row == null ? void 0 : row.ariaPosInSet))
return;
if (row.baseElement !== state.baseElement)
return;
const itemsInRow = state.renderedItems.filter(
(item) => item.rowId === rowId
);
return row.ariaPosInSet + itemsInRow.findIndex((item) => item.id === id);
});
const isTabbable = (_a2 = useStoreState(store, (state) => {
if (!state.renderedItems.length)
return true;
return !state.virtualFocus && state.activeId === id;
})) != null ? _a2 : true;
props = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({
id,
"aria-selected": ariaSelected,
"data-active-item": isActiveItem ? "" : void 0
}, props), {
ref: useMergeRefs(ref, props.ref),
tabIndex: isTabbable ? props.tabIndex : -1,
onFocus,
onBlurCapture,
onKeyDown
});
props = useCommand(props);
props = useCollectionItem(PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({
store
}, props), {
getItem,
shouldRegisterItem: !!id ? props.shouldRegisterItem : false
}));
return PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({}, props), {
"aria-setsize": ariaSetSize,
"aria-posinset": ariaPosInSet
});
}
);
var DCG3EYDE_CompositeItem = createMemoComponent(
(props) => {
const htmlProps = DCG3EYDE_useCompositeItem(props);
return NQJBHION_createElement("button", htmlProps);
}
);
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/HCTED3MY.js
// src/toolbar/toolbar-item.ts
var useToolbarItem = NQJBHION_createHook(
(_a) => {
var _b = _a, { store } = _b, props = __objRest(_b, ["store"]);
props = DCG3EYDE_useCompositeItem(PNRLI7OV_spreadValues({ store }, props));
return props;
}
);
var ToolbarItem = createMemoComponent((props) => {
const htmlProps = useToolbarItem(props);
return NQJBHION_createElement("button", htmlProps);
});
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-context/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const ToolbarContext = (0,external_wp_element_namespaceObject.createContext)(undefined);
/* harmony default export */ var toolbar_context = (ToolbarContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-item/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function toolbar_item_ToolbarItem({
children,
as: Component,
...props
}, ref) {
const accessibleToolbarStore = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
const isRenderProp = typeof children === 'function';
if (!isRenderProp && !Component) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
return null;
}
const allProps = { ...props,
ref,
'data-toolbar-item': true
};
if (!accessibleToolbarStore) {
if (Component) {
return (0,external_wp_element_namespaceObject.createElement)(Component, { ...allProps
}, children);
}
if (!isRenderProp) {
return null;
}
return children(allProps);
}
const render = isRenderProp ? children : Component && (0,external_wp_element_namespaceObject.createElement)(Component, null);
return (0,external_wp_element_namespaceObject.createElement)(ToolbarItem, { ...allProps,
store: accessibleToolbarStore,
render: render
});
}
/* harmony default export */ var toolbar_item = ((0,external_wp_element_namespaceObject.forwardRef)(toolbar_item_ToolbarItem));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-button/toolbar-button-container.js
/**
* Internal dependencies
*/
const ToolbarButtonContainer = ({
children,
className
}) => (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, children);
/* harmony default export */ var toolbar_button_container = (ToolbarButtonContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToolbarButton({
children,
className,
containerClassName,
extraProps,
isActive,
isDisabled,
title,
...props
}, ref) {
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if (!accessibleToolbarState) {
return (0,external_wp_element_namespaceObject.createElement)(toolbar_button_container, {
className: containerClassName
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
ref: ref,
icon: props.icon,
label: title,
shortcut: props.shortcut,
"data-subscript": props.subscript,
onClick: event => {
event.stopPropagation(); // TODO: Possible bug; maybe use onClick instead of props.onClick.
if (props.onClick) {
props.onClick(event);
}
},
className: classnames_default()('components-toolbar__control', className),
isPressed: isActive,
disabled: isDisabled,
"data-toolbar-item": true,
...extraProps,
...props
}, children));
} // ToobarItem will pass all props to the render prop child, which will pass
// all props to Button. This means that ToolbarButton has the same API as
// Button.
return (0,external_wp_element_namespaceObject.createElement)(toolbar_item, {
className: classnames_default()('components-toolbar-button', className),
...extraProps,
...props,
ref: ref
}, toolbarItemProps => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
label: title,
isPressed: isActive,
disabled: isDisabled,
...toolbarItemProps
}, children));
}
/**
* ToolbarButton can be used to add actions to a toolbar, usually inside a Toolbar
* or ToolbarGroup when used to create general interfaces.
*
* ```jsx
* import { Toolbar, ToolbarButton } from '@wordpress/components';
* import { edit } from '@wordpress/icons';
*
* function MyToolbar() {
* return (
* <Toolbar label="Options">
* <ToolbarButton
* icon={ edit }
* label="Edit"
* onClick={ () => alert( 'Editing' ) }
* />
* </Toolbar>
* );
* }
* ```
*/
const ToolbarButton = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToolbarButton);
/* harmony default export */ var toolbar_button = (ToolbarButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-group/toolbar-group-container.js
// @ts-nocheck
const ToolbarGroupContainer = ({
className,
children,
...props
}) => (0,external_wp_element_namespaceObject.createElement)("div", {
className: className,
...props
}, children);
/* harmony default export */ var toolbar_group_container = (ToolbarGroupContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-group/toolbar-group-collapsed.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToolbarGroupCollapsed({
controls = [],
toggleProps,
...props
}) {
// It'll contain state if `ToolbarGroup` is being used within
// `<Toolbar label="label" />`
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
const renderDropdownMenu = internalToggleProps => (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, {
controls: controls,
toggleProps: { ...internalToggleProps,
'data-toolbar-item': true
},
...props
});
if (accessibleToolbarState) {
return (0,external_wp_element_namespaceObject.createElement)(toolbar_item, { ...toggleProps
}, renderDropdownMenu);
}
return renderDropdownMenu(toggleProps);
}
/* harmony default export */ var toolbar_group_collapsed = (ToolbarGroupCollapsed);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-group/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Renders a collapsible group of controls
*
* The `controls` prop accepts an array of sets. A set is an array of controls.
* Controls have the following shape:
*
* ```
* {
* icon: string,
* title: string,
* subscript: string,
* onClick: Function,
* isActive: boolean,
* isDisabled: boolean
* }
* ```
*
* For convenience it is also possible to pass only an array of controls. It is
* then assumed this is the only set.
*
* Either `controls` or `children` is required, otherwise this components
* renders nothing.
*
* @param {Object} props Component props.
* @param {Array} [props.controls] The controls to render in this toolbar.
* @param {WPElement} [props.children] Any other things to render inside the toolbar besides the controls.
* @param {string} [props.className] Class to set on the container div.
* @param {boolean} [props.isCollapsed] Turns ToolbarGroup into a dropdown menu.
* @param {string} [props.title] ARIA label for dropdown menu if is collapsed.
*/
function ToolbarGroup({
controls = [],
children,
className,
isCollapsed,
title,
...props
}) {
// It'll contain state if `ToolbarGroup` is being used within
// `<Toolbar label="label" />`
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if ((!controls || !controls.length) && !children) {
return null;
}
const finalClassName = classnames_default()( // Unfortunately, there's legacy code referencing to `.components-toolbar`
// So we can't get rid of it
accessibleToolbarState ? 'components-toolbar-group' : 'components-toolbar', className); // Normalize controls to nested array of objects (sets of controls)
let controlSets = controls;
if (!Array.isArray(controlSets[0])) {
controlSets = [controlSets];
}
if (isCollapsed) {
return (0,external_wp_element_namespaceObject.createElement)(toolbar_group_collapsed, {
label: title,
controls: controlSets,
className: finalClassName,
children: children,
...props
});
}
return (0,external_wp_element_namespaceObject.createElement)(toolbar_group_container, {
className: finalClassName,
...props
}, controlSets?.flatMap((controlSet, indexOfSet) => controlSet.map((control, indexOfControl) => (0,external_wp_element_namespaceObject.createElement)(toolbar_button, {
key: [indexOfSet, indexOfControl].join(),
containerClassName: indexOfSet > 0 && indexOfControl === 0 ? 'has-left-divider' : null,
...control
}))), children);
}
/* harmony default export */ var toolbar_group = (ToolbarGroup);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/WKNTOKYS.js
// src/collection/collection-store.ts
function useCollectionStoreOptions(_props) {
return {};
}
function useCollectionStoreProps(store, props) {
useStoreProps(store, props, "items", "setItems");
return store;
}
function useCollectionStore(props = {}) {
const options = useCollectionStoreOptions(props);
const store = useStore(
() => Core.createCollectionStore(__spreadValues(__spreadValues({}, props), options))
);
return useCollectionStoreProps(store, props);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/5PLAJI33.js
// src/composite/composite-store.ts
function useCompositeStoreOptions(props) {
return useCollectionStoreOptions(props);
}
function useCompositeStoreProps(store, props) {
store = useCollectionStoreProps(store, props);
useStoreProps(store, props, "activeId", "setActiveId");
useStoreProps(store, props, "includesBaseElement");
useStoreProps(store, props, "virtualFocus");
useStoreProps(store, props, "orientation");
useStoreProps(store, props, "rtl");
useStoreProps(store, props, "focusLoop");
useStoreProps(store, props, "focusWrap");
useStoreProps(store, props, "focusShift");
return store;
}
function useCompositeStore(props = {}) {
const options = useCompositeStoreOptions(props);
const store = useStore(
() => Core.createCompositeStore(__spreadValues(__spreadValues({}, props), options))
);
return useCompositeStoreProps(store, props);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/FQL4TRMX.js
// src/utils/store.ts
function createStore(initialState, ...stores) {
let state = initialState;
let prevStateBatch = state;
let lastUpdate = Symbol();
let initialized = false;
const updatedKeys = /* @__PURE__ */ new Set();
const setups = /* @__PURE__ */ new Set();
const listeners = /* @__PURE__ */ new Set();
const listenersBatch = /* @__PURE__ */ new Set();
const disposables = /* @__PURE__ */ new WeakMap();
const listenerKeys = /* @__PURE__ */ new WeakMap();
const setup = (callback) => {
setups.add(callback);
return () => setups.delete(callback);
};
const init = () => {
if (initialized)
return WVTCK5PV_noop;
if (!stores.length)
return WVTCK5PV_noop;
initialized = true;
const desyncs = getKeys(state).map(
(key) => WVTCK5PV_chain(
...stores.map((store) => {
var _a, _b;
const storeState = (_a = store == null ? void 0 : store.getState) == null ? void 0 : _a.call(store);
if (!storeState)
return;
if (!WVTCK5PV_hasOwnProperty(storeState, key))
return;
return (_b = store == null ? void 0 : store.sync) == null ? void 0 : _b.call(store, (state2) => setState(key, state2[key]), [key]);
})
)
);
const teardowns = [];
setups.forEach((setup2) => teardowns.push(setup2()));
const cleanups = stores.map((store) => {
var _a;
return (_a = store == null ? void 0 : store.init) == null ? void 0 : _a.call(store);
});
return WVTCK5PV_chain(...desyncs, ...teardowns, ...cleanups, () => {
initialized = false;
});
};
const sub = (listener, keys, batch = false) => {
const set = batch ? listenersBatch : listeners;
set.add(listener);
listenerKeys.set(listener, keys);
return () => {
var _a;
(_a = disposables.get(listener)) == null ? void 0 : _a();
disposables.delete(listener);
listenerKeys.delete(listener);
set.delete(listener);
};
};
const subscribe = (listener, keys) => sub(listener, keys);
const sync = (listener, keys) => {
disposables.set(listener, listener(state, state));
return sub(listener, keys);
};
const syncBatch = (listener, keys) => {
disposables.set(listener, listener(state, prevStateBatch));
return sub(listener, keys, true);
};
const getState = () => state;
const setState = (key, value) => {
if (!WVTCK5PV_hasOwnProperty(state, key))
return;
const nextValue = WVTCK5PV_applyState(value, state[key]);
if (nextValue === state[key])
return;
stores.forEach((store) => {
var _a;
(_a = store == null ? void 0 : store.setState) == null ? void 0 : _a.call(store, key, nextValue);
});
const prevState = state;
state = _chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, state), { [key]: nextValue });
const thisUpdate = Symbol();
lastUpdate = thisUpdate;
updatedKeys.add(key);
const run = (listener, prev, uKeys) => {
var _a;
const keys = listenerKeys.get(listener);
const updated = (k) => uKeys ? uKeys.has(k) : k === key;
if (!keys || keys.some(updated)) {
(_a = disposables.get(listener)) == null ? void 0 : _a();
disposables.set(listener, listener(state, prev));
}
};
listeners.forEach((listener) => run(listener, prevState));
queueMicrotask(() => {
if (lastUpdate !== thisUpdate)
return;
const snapshot = state;
listenersBatch.forEach((listener) => {
run(listener, prevStateBatch, updatedKeys);
});
prevStateBatch = snapshot;
updatedKeys.clear();
});
};
const pick2 = (...keys) => createStore(pick(state, keys), finalStore);
const omit2 = (...keys) => createStore(omit(state, keys), finalStore);
const finalStore = {
setup,
init,
subscribe,
sync,
syncBatch,
getState,
setState,
pick: pick2,
omit: omit2
};
return finalStore;
}
function mergeStore(...stores) {
const initialState = stores.reduce((state, store2) => {
var _a;
const nextState = (_a = store2 == null ? void 0 : store2.getState) == null ? void 0 : _a.call(store2);
if (!nextState)
return state;
return __spreadValues(__spreadValues({}, state), nextState);
}, {});
const store = createStore(initialState, ...stores);
return store;
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/SHUO6V52.js
// src/collection/collection-store.ts
function SHUO6V52_isElementPreceding(a, b) {
return Boolean(
b.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_PRECEDING
);
}
function SHUO6V52_sortBasedOnDOMPosition(items) {
const pairs = items.map((item, index) => [index, item]);
let isOrderDifferent = false;
pairs.sort(([indexA, a], [indexB, b]) => {
const elementA = a.element;
const elementB = b.element;
if (elementA === elementB)
return 0;
if (!elementA || !elementB)
return 0;
if (SHUO6V52_isElementPreceding(elementA, elementB)) {
if (indexA > indexB) {
isOrderDifferent = true;
}
return -1;
}
if (indexA < indexB) {
isOrderDifferent = true;
}
return 1;
});
if (isOrderDifferent) {
return pairs.map(([_, item]) => item);
}
return items;
}
function SHUO6V52_getCommonParent(items) {
var _a;
const firstItem = items.find((item) => !!item.element);
const lastItem = [...items].reverse().find((item) => !!item.element);
let parentElement = (_a = firstItem == null ? void 0 : firstItem.element) == null ? void 0 : _a.parentElement;
while (parentElement && (lastItem == null ? void 0 : lastItem.element)) {
const parent = parentElement;
if (lastItem && parent.contains(lastItem.element)) {
return parentElement;
}
parentElement = parentElement.parentElement;
}
return O35LWD4W_getDocument(parentElement).body;
}
function createCollectionStore(props = {}) {
var _a;
const syncState = (_a = props.store) == null ? void 0 : _a.getState();
const items = defaultValue(
props.items,
syncState == null ? void 0 : syncState.items,
props.defaultItems,
[]
);
const itemsMap = new Map(items.map((item) => [item.id, item]));
const initialState = {
items,
renderedItems: defaultValue(syncState == null ? void 0 : syncState.renderedItems, [])
};
const privateStore = createStore({
renderedItems: initialState.renderedItems
});
const collection = createStore(initialState, props.store);
const sortItems = () => {
const state = privateStore.getState();
const renderedItems = SHUO6V52_sortBasedOnDOMPosition(state.renderedItems);
privateStore.setState("renderedItems", renderedItems);
collection.setState("renderedItems", renderedItems);
};
collection.setup(() => {
return privateStore.syncBatch(
(state) => {
let firstRun = true;
let raf = requestAnimationFrame(sortItems);
if (typeof IntersectionObserver !== "function")
return;
const callback = () => {
if (firstRun) {
firstRun = false;
return;
}
cancelAnimationFrame(raf);
raf = requestAnimationFrame(sortItems);
};
const root = SHUO6V52_getCommonParent(state.renderedItems);
const observer = new IntersectionObserver(callback, { root });
state.renderedItems.forEach((item) => {
if (!item.element)
return;
observer.observe(item.element);
});
return () => {
cancelAnimationFrame(raf);
observer.disconnect();
};
},
["renderedItems"]
);
});
const mergeItem = (item, setItems, canDeleteFromMap = false) => {
let prevItem;
setItems((items2) => {
const index = items2.findIndex(({ id }) => id === item.id);
const nextItems = items2.slice();
if (index !== -1) {
prevItem = items2[index];
const nextItem = _chunks_PNRLI7OV_spreadValues(_chunks_PNRLI7OV_spreadValues({}, prevItem), item);
nextItems[index] = nextItem;
itemsMap.set(item.id, nextItem);
} else {
nextItems.push(item);
itemsMap.set(item.id, item);
}
return nextItems;
});
const unmergeItem = () => {
setItems((items2) => {
if (!prevItem) {
if (canDeleteFromMap) {
itemsMap.delete(item.id);
}
return items2.filter(({ id }) => id !== item.id);
}
const index = items2.findIndex(({ id }) => id === item.id);
if (index === -1)
return items2;
const nextItems = items2.slice();
nextItems[index] = prevItem;
itemsMap.set(item.id, prevItem);
return nextItems;
});
};
return unmergeItem;
};
const registerItem = (item) => mergeItem(item, (getItems) => collection.setState("items", getItems), true);
return _chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, collection), {
registerItem,
renderItem: (item) => WVTCK5PV_chain(
registerItem(item),
mergeItem(
item,
(getItems) => privateStore.setState("renderedItems", getItems)
)
),
item: (id) => {
if (!id)
return null;
let item = itemsMap.get(id);
if (!item) {
const { items: items2 } = collection.getState();
item = items2.find((item2) => item2.id === id);
if (item) {
itemsMap.set(id, item);
}
}
return item || null;
}
});
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/5XEKIOCW.js
// src/utils/array.ts
function _5XEKIOCW_toArray(arg) {
if (Array.isArray(arg)) {
return arg;
}
return typeof arg !== "undefined" ? [arg] : [];
}
function addItemToArray(array, item, index = -1) {
if (!(index in array)) {
return [...array, item];
}
return [...array.slice(0, index), item, ...array.slice(index)];
}
function flatten2DArray(array) {
const flattened = [];
for (const row of array) {
flattened.push(...row);
}
return flattened;
}
function reverseArray(array) {
return array.slice().reverse();
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/NRXA5QTV.js
// src/composite/composite-store.ts
var NRXA5QTV_NULL_ITEM = { id: null };
function NRXA5QTV_findFirstEnabledItem(items, excludeId) {
return items.find((item) => {
if (excludeId) {
return !item.disabled && item.id !== excludeId;
}
return !item.disabled;
});
}
function getEnabledItems(items, excludeId) {
return items.filter((item) => {
if (excludeId) {
return !item.disabled && item.id !== excludeId;
}
return !item.disabled;
});
}
function NRXA5QTV_getOppositeOrientation(orientation) {
if (orientation === "vertical")
return "horizontal";
if (orientation === "horizontal")
return "vertical";
return;
}
function getItemsInRow(items, rowId) {
return items.filter((item) => item.rowId === rowId);
}
function NRXA5QTV_flipItems(items, activeId, shouldInsertNullItem = false) {
const index = items.findIndex((item) => item.id === activeId);
return [
...items.slice(index + 1),
...shouldInsertNullItem ? [NRXA5QTV_NULL_ITEM] : [],
...items.slice(0, index)
];
}
function NRXA5QTV_groupItemsByRows(items) {
const rows = [];
for (const item of items) {
const row = rows.find((currentRow) => {
var _a;
return ((_a = currentRow[0]) == null ? void 0 : _a.rowId) === item.rowId;
});
if (row) {
row.push(item);
} else {
rows.push([item]);
}
}
return rows;
}
function getMaxRowLength(array) {
let maxLength = 0;
for (const { length } of array) {
if (length > maxLength) {
maxLength = length;
}
}
return maxLength;
}
function NRXA5QTV_createEmptyItem(rowId) {
return {
id: "__EMPTY_ITEM__",
disabled: true,
rowId
};
}
function normalizeRows(rows, activeId, focusShift) {
const maxLength = getMaxRowLength(rows);
for (const row of rows) {
for (let i = 0; i < maxLength; i += 1) {
const item = row[i];
if (!item || focusShift && item.disabled) {
const isFirst = i === 0;
const previousItem = isFirst && focusShift ? NRXA5QTV_findFirstEnabledItem(row) : row[i - 1];
row[i] = previousItem && activeId !== previousItem.id && focusShift ? previousItem : NRXA5QTV_createEmptyItem(previousItem == null ? void 0 : previousItem.rowId);
}
}
}
return rows;
}
function NRXA5QTV_verticalizeItems(items) {
const rows = NRXA5QTV_groupItemsByRows(items);
const maxLength = getMaxRowLength(rows);
const verticalized = [];
for (let i = 0; i < maxLength; i += 1) {
for (const row of rows) {
const item = row[i];
if (item) {
verticalized.push(_chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, item), {
// If there's no rowId, it means that it's not a grid composite, but
// a single row instead. So, instead of verticalizing it, that is,
// assigning a different rowId based on the column index, we keep it
// undefined so they will be part of the same row. This is useful
// when using up/down on one-dimensional composites.
rowId: item.rowId ? `${i}` : void 0
}));
}
}
}
return verticalized;
}
function createCompositeStore(props = {}) {
var _a;
const syncState = (_a = props.store) == null ? void 0 : _a.getState();
const collection = createCollectionStore(props);
const activeId = defaultValue(
props.activeId,
syncState == null ? void 0 : syncState.activeId,
props.defaultActiveId
);
const initialState = _chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, collection.getState()), {
activeId,
baseElement: defaultValue(syncState == null ? void 0 : syncState.baseElement, null),
includesBaseElement: defaultValue(
props.includesBaseElement,
syncState == null ? void 0 : syncState.includesBaseElement,
activeId === null
),
moves: defaultValue(syncState == null ? void 0 : syncState.moves, 0),
orientation: defaultValue(
props.orientation,
syncState == null ? void 0 : syncState.orientation,
"both"
),
rtl: defaultValue(props.rtl, syncState == null ? void 0 : syncState.rtl, false),
virtualFocus: defaultValue(
props.virtualFocus,
syncState == null ? void 0 : syncState.virtualFocus,
false
),
focusLoop: defaultValue(props.focusLoop, syncState == null ? void 0 : syncState.focusLoop, false),
focusWrap: defaultValue(props.focusWrap, syncState == null ? void 0 : syncState.focusWrap, false),
focusShift: defaultValue(props.focusShift, syncState == null ? void 0 : syncState.focusShift, false)
});
const composite = createStore(initialState, collection, props.store);
composite.setup(
() => composite.sync(
(state) => {
composite.setState("activeId", (activeId2) => {
var _a2;
if (activeId2 !== void 0)
return activeId2;
return (_a2 = NRXA5QTV_findFirstEnabledItem(state.renderedItems)) == null ? void 0 : _a2.id;
});
},
["renderedItems", "activeId"]
)
);
const getNextId = (items, orientation, hasNullItem, skip) => {
var _a2, _b;
const { activeId: activeId2, rtl, focusLoop, focusWrap, includesBaseElement } = composite.getState();
const isHorizontal = orientation !== "vertical";
const isRTL = rtl && isHorizontal;
const allItems = isRTL ? reverseArray(items) : items;
if (activeId2 == null) {
return (_a2 = NRXA5QTV_findFirstEnabledItem(allItems)) == null ? void 0 : _a2.id;
}
const activeItem = allItems.find((item) => item.id === activeId2);
if (!activeItem) {
return (_b = NRXA5QTV_findFirstEnabledItem(allItems)) == null ? void 0 : _b.id;
}
const isGrid = !!activeItem.rowId;
const activeIndex = allItems.indexOf(activeItem);
const nextItems = allItems.slice(activeIndex + 1);
const nextItemsInRow = getItemsInRow(nextItems, activeItem.rowId);
if (skip !== void 0) {
const nextEnabledItemsInRow = getEnabledItems(nextItemsInRow, activeId2);
const nextItem2 = nextEnabledItemsInRow.slice(skip)[0] || // If we can't find an item, just return the last one.
nextEnabledItemsInRow[nextEnabledItemsInRow.length - 1];
return nextItem2 == null ? void 0 : nextItem2.id;
}
const oppositeOrientation = NRXA5QTV_getOppositeOrientation(
// If it's a grid and orientation is not set, it's a next/previous call,
// which is inherently horizontal. up/down will call next with orientation
// set to vertical by default (see below on up/down methods).
isGrid ? orientation || "horizontal" : orientation
);
const canLoop = focusLoop && focusLoop !== oppositeOrientation;
const canWrap = isGrid && focusWrap && focusWrap !== oppositeOrientation;
hasNullItem = hasNullItem || !isGrid && canLoop && includesBaseElement;
if (canLoop) {
const loopItems = canWrap && !hasNullItem ? allItems : getItemsInRow(allItems, activeItem.rowId);
const sortedItems = NRXA5QTV_flipItems(loopItems, activeId2, hasNullItem);
const nextItem2 = NRXA5QTV_findFirstEnabledItem(sortedItems, activeId2);
return nextItem2 == null ? void 0 : nextItem2.id;
}
if (canWrap) {
const nextItem2 = NRXA5QTV_findFirstEnabledItem(
// We can use nextItems, which contains all the next items, including
// items from other rows, to wrap between rows. However, if there is a
// null item (the composite container), we'll only use the next items in
// the row. So moving next from the last item will focus on the
// composite container. On grid composites, horizontal navigation never
// focuses on the composite container, only vertical.
hasNullItem ? nextItemsInRow : nextItems,
activeId2
);
const nextId = hasNullItem ? (nextItem2 == null ? void 0 : nextItem2.id) || null : nextItem2 == null ? void 0 : nextItem2.id;
return nextId;
}
const nextItem = NRXA5QTV_findFirstEnabledItem(nextItemsInRow, activeId2);
if (!nextItem && hasNullItem) {
return null;
}
return nextItem == null ? void 0 : nextItem.id;
};
return _chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues(_chunks_PNRLI7OV_spreadValues({}, collection), composite), {
setBaseElement: (element) => composite.setState("baseElement", element),
setActiveId: (id) => composite.setState("activeId", id),
move: (id) => {
if (id === void 0)
return;
composite.setState("activeId", id);
composite.setState("moves", (moves) => moves + 1);
},
first: () => {
var _a2;
return (_a2 = NRXA5QTV_findFirstEnabledItem(composite.getState().renderedItems)) == null ? void 0 : _a2.id;
},
last: () => {
var _a2;
return (_a2 = NRXA5QTV_findFirstEnabledItem(reverseArray(composite.getState().renderedItems))) == null ? void 0 : _a2.id;
},
next: (skip) => {
const { renderedItems, orientation } = composite.getState();
return getNextId(renderedItems, orientation, false, skip);
},
previous: (skip) => {
var _a2;
const { renderedItems, orientation, includesBaseElement } = composite.getState();
const isGrid = !!((_a2 = NRXA5QTV_findFirstEnabledItem(renderedItems)) == null ? void 0 : _a2.rowId);
const hasNullItem = !isGrid && includesBaseElement;
return getNextId(
reverseArray(renderedItems),
orientation,
hasNullItem,
skip
);
},
down: (skip) => {
const {
activeId: activeId2,
renderedItems,
focusShift,
focusLoop,
includesBaseElement
} = composite.getState();
const shouldShift = focusShift && !skip;
const verticalItems = NRXA5QTV_verticalizeItems(
flatten2DArray(
normalizeRows(NRXA5QTV_groupItemsByRows(renderedItems), activeId2, shouldShift)
)
);
const canLoop = focusLoop && focusLoop !== "horizontal";
const hasNullItem = canLoop && includesBaseElement;
return getNextId(verticalItems, "vertical", hasNullItem, skip);
},
up: (skip) => {
const { activeId: activeId2, renderedItems, focusShift, includesBaseElement } = composite.getState();
const shouldShift = focusShift && !skip;
const verticalItems = NRXA5QTV_verticalizeItems(
reverseArray(
flatten2DArray(
normalizeRows(
NRXA5QTV_groupItemsByRows(renderedItems),
activeId2,
shouldShift
)
)
)
);
const hasNullItem = includesBaseElement;
return getNextId(verticalItems, "vertical", hasNullItem, skip);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/toolbar/toolbar-store.js
// src/toolbar/toolbar-store.ts
function createToolbarStore(props = {}) {
var _a;
const syncState = (_a = props.store) == null ? void 0 : _a.getState();
return createCompositeStore(_chunks_PNRLI7OV_spreadProps(_chunks_PNRLI7OV_spreadValues({}, props), {
orientation: defaultValue(
props.orientation,
syncState == null ? void 0 : syncState.orientation,
"horizontal"
),
focusLoop: defaultValue(props.focusLoop, syncState == null ? void 0 : syncState.focusLoop, true)
}));
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/toolbar/toolbar-store.js
// src/toolbar/toolbar-store.ts
function useToolbarStoreOptions(props) {
return useCompositeStoreOptions(props);
}
function useToolbarStoreProps(store, props) {
return useCompositeStoreProps(store, props);
}
function useToolbarStore(props = {}) {
const options = useToolbarStoreOptions(props);
const store = OOWNFOTF_useStore(
() => createToolbarStore(PNRLI7OV_spreadValues(PNRLI7OV_spreadValues({}, props), options))
);
return useToolbarStoreProps(store, props);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/DFUIIKXE.js
// src/toolbar/toolbar-context.ts
var DFUIIKXE_ToolbarContext = (0,external_React_.createContext)(
void 0
);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/AAVDGJD5.js
// src/composite/composite.tsx
function isGrid(items) {
return items.some((item) => !!item.rowId);
}
function isPrintableKey(event) {
return event.key.length === 1 && !event.ctrlKey && !event.metaKey;
}
function isModifierKey(event) {
return event.key === "Shift" || event.key === "Control" || event.key === "Alt" || event.key === "Meta";
}
function AAVDGJD5_canProxyKeyboardEvent(event, state) {
if (!events_isSelfTarget(event))
return false;
if (isModifierKey(event))
return false;
const target = event.target;
if (!target)
return true;
if (O35LWD4W_isTextField(target)) {
if (isPrintableKey(event))
return false;
const grid = isGrid(state.renderedItems);
const focusingInputOnly = state.activeId === null;
const allowHorizontalNavigationOnItems = grid && !focusingInputOnly;
const isHomeOrEnd = event.key === "Home" || event.key === "End";
if (!allowHorizontalNavigationOnItems && isHomeOrEnd)
return false;
}
return !event.isPropagationStopped();
}
function AAVDGJD5_useKeyboardEventProxy(store, onKeyboardEvent, previousElementRef) {
return useEvent((event) => {
var _a;
onKeyboardEvent == null ? void 0 : onKeyboardEvent(event);
if (event.defaultPrevented)
return;
const state = store.getState();
const activeElement = (_a = getEnabledItem(store, state.activeId)) == null ? void 0 : _a.element;
if (!activeElement)
return;
if (!AAVDGJD5_canProxyKeyboardEvent(event, state))
return;
const _b = event, { view } = _b, eventInit = __objRest(_b, ["view"]);
const previousElement = previousElementRef == null ? void 0 : previousElementRef.current;
if (activeElement !== previousElement) {
activeElement.focus();
}
if (!events_fireKeyboardEvent(activeElement, event.type, eventInit)) {
event.preventDefault();
}
if (event.currentTarget.contains(activeElement)) {
event.stopPropagation();
}
});
}
function AAVDGJD5_findFirstEnabledItemInTheLastRow(items) {
return OXPV2NBK_findFirstEnabledItem(
flatten2DArray(reverseArray(groupItemsByRows(items)))
);
}
function useScheduleFocus(store) {
const [scheduled, setScheduled] = (0,external_React_.useState)(false);
const schedule = (0,external_React_.useCallback)(() => setScheduled(true), []);
const activeItem = store.useState(
(state) => getEnabledItem(store, state.activeId)
);
(0,external_React_.useEffect)(() => {
const activeElement = activeItem == null ? void 0 : activeItem.element;
if (!scheduled)
return;
if (!activeElement)
return;
setScheduled(false);
activeElement.focus({ preventScroll: true });
}, [activeItem, scheduled]);
return schedule;
}
var AAVDGJD5_useComposite = NQJBHION_createHook(
(_a) => {
var _b = _a, {
store,
composite = true,
focusOnMove = composite,
moveOnKeyPress = true
} = _b, props = __objRest(_b, [
"store",
"composite",
"focusOnMove",
"moveOnKeyPress"
]);
const previousElementRef = (0,external_React_.useRef)(null);
const scheduleFocus = useScheduleFocus(store);
const moves = store.useState("moves");
(0,external_React_.useEffect)(() => {
var _a2;
if (!moves)
return;
if (!composite)
return;
if (!focusOnMove)
return;
const { activeId: activeId2 } = store.getState();
const itemElement = (_a2 = getEnabledItem(store, activeId2)) == null ? void 0 : _a2.element;
if (!itemElement)
return;
focusIntoView(itemElement);
}, [moves, composite, focusOnMove]);
useSafeLayoutEffect(() => {
if (!composite)
return;
if (!moves)
return;
const { baseElement, activeId: activeId2 } = store.getState();
const isSelfAcive = activeId2 === null;
if (!isSelfAcive)
return;
if (!baseElement)
return;
const previousElement = previousElementRef.current;
previousElementRef.current = null;
if (previousElement) {
events_fireBlurEvent(previousElement, { relatedTarget: baseElement });
}
if (focus_hasFocus(baseElement)) {
fireFocusEvent(baseElement, { relatedTarget: previousElement });
} else {
baseElement.focus();
}
}, [moves, composite]);
const activeId = store.useState("activeId");
const virtualFocus = store.useState("virtualFocus");
useSafeLayoutEffect(() => {
var _a2;
if (!composite)
return;
if (!virtualFocus)
return;
const previousElement = previousElementRef.current;
previousElementRef.current = null;
if (!previousElement)
return;
const activeElement = (_a2 = getEnabledItem(store, activeId)) == null ? void 0 : _a2.element;
const relatedTarget = activeElement || O35LWD4W_getActiveElement(previousElement);
events_fireBlurEvent(previousElement, { relatedTarget });
}, [activeId, virtualFocus, composite]);
const onKeyDownCapture = AAVDGJD5_useKeyboardEventProxy(
store,
props.onKeyDownCapture,
previousElementRef
);
const onKeyUpCapture = AAVDGJD5_useKeyboardEventProxy(
store,
props.onKeyUpCapture,
previousElementRef
);
const onFocusCaptureProp = props.onFocusCapture;
const onFocusCapture = useEvent((event) => {
onFocusCaptureProp == null ? void 0 : onFocusCaptureProp(event);
if (event.defaultPrevented)
return;
const { virtualFocus: virtualFocus2 } = store.getState();
if (!virtualFocus2)
return;
const previousActiveElement = event.relatedTarget;
const isSilentlyFocused = silentlyFocused(event.currentTarget);
if (events_isSelfTarget(event) && isSilentlyFocused) {
event.stopPropagation();
previousElementRef.current = previousActiveElement;
}
});
const onFocusProp = props.onFocus;
const onFocus = useEvent((event) => {
onFocusProp == null ? void 0 : onFocusProp(event);
if (event.defaultPrevented)
return;
if (!composite)
return;
const { relatedTarget } = event;
const { virtualFocus: virtualFocus2 } = store.getState();
if (virtualFocus2) {
if (events_isSelfTarget(event) && !OXPV2NBK_isItem(store, relatedTarget)) {
queueMicrotask(scheduleFocus);
}
} else if (events_isSelfTarget(event)) {
store.setActiveId(null);
}
});
const onBlurCaptureProp = props.onBlurCapture;
const onBlurCapture = useEvent((event) => {
var _a2;
onBlurCaptureProp == null ? void 0 : onBlurCaptureProp(event);
if (event.defaultPrevented)
return;
const { virtualFocus: virtualFocus2, activeId: activeId2 } = store.getState();
if (!virtualFocus2)
return;
const activeElement = (_a2 = getEnabledItem(store, activeId2)) == null ? void 0 : _a2.element;
const nextActiveElement = event.relatedTarget;
const nextActiveElementIsItem = OXPV2NBK_isItem(store, nextActiveElement);
const previousElement = previousElementRef.current;
previousElementRef.current = null;
if (events_isSelfTarget(event) && nextActiveElementIsItem) {
if (nextActiveElement === activeElement) {
if (previousElement && previousElement !== nextActiveElement) {
events_fireBlurEvent(previousElement, event);
}
} else if (activeElement) {
events_fireBlurEvent(activeElement, event);
}
event.stopPropagation();
} else {
const targetIsItem = OXPV2NBK_isItem(store, event.target);
if (!targetIsItem && activeElement) {
events_fireBlurEvent(activeElement, event);
}
}
});
const onKeyDownProp = props.onKeyDown;
const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
const onKeyDown = useEvent((event) => {
var _a2;
onKeyDownProp == null ? void 0 : onKeyDownProp(event);
if (event.defaultPrevented)
return;
if (!events_isSelfTarget(event))
return;
const { orientation, items, renderedItems, activeId: activeId2 } = store.getState();
const activeItem = getEnabledItem(store, activeId2);
if ((_a2 = activeItem == null ? void 0 : activeItem.element) == null ? void 0 : _a2.isConnected)
return;
const isVertical = orientation !== "horizontal";
const isHorizontal = orientation !== "vertical";
const grid = isGrid(renderedItems);
const up = () => {
if (grid) {
const item = items && AAVDGJD5_findFirstEnabledItemInTheLastRow(items);
return item == null ? void 0 : item.id;
}
return store.last();
};
const keyMap = {
ArrowUp: (grid || isVertical) && up,
ArrowRight: (grid || isHorizontal) && store.first,
ArrowDown: (grid || isVertical) && store.first,
ArrowLeft: (grid || isHorizontal) && store.last,
Home: store.first,
End: store.last,
PageUp: store.first,
PageDown: store.last
};
const action = keyMap[event.key];
if (action) {
const id = action();
if (id !== void 0) {
if (!moveOnKeyPressProp(event))
return;
event.preventDefault();
store.move(id);
}
}
});
props = useWrapElement(
props,
(element) => /* @__PURE__ */ (0,jsx_runtime.jsx)(CompositeContext.Provider, { value: store, children: element }),
[store]
);
const activeDescendant = store.useState(
(state) => {
var _a2;
return composite && state.virtualFocus ? (_a2 = getEnabledItem(store, state.activeId)) == null ? void 0 : _a2.id : void 0;
}
);
props = PNRLI7OV_spreadProps(PNRLI7OV_spreadValues({
"aria-activedescendant": activeDescendant
}, props), {
ref: useMergeRefs(composite ? store.setBaseElement : null, props.ref),
onKeyDownCapture,
onKeyUpCapture,
onFocusCapture,
onFocus,
onBlurCapture,
onKeyDown
});
const focusable = store.useState(
(state) => composite && (state.virtualFocus || state.activeId === null)
);
props = useFocusable(PNRLI7OV_spreadValues({ focusable }, props));
return props;
}
);
var AAVDGJD5_Composite = NQJBHION_createComponent((props) => {
const htmlProps = AAVDGJD5_useComposite(props);
return NQJBHION_createElement("div", htmlProps);
});
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/toolbar/toolbar.js
// src/toolbar/toolbar.tsx
var useToolbar = NQJBHION_createHook((_a) => {
var _b = _a, { store } = _b, props = __objRest(_b, ["store"]);
const orientation = store.useState(
(state) => state.orientation === "both" ? void 0 : state.orientation
);
props = useWrapElement(
props,
(element) => /* @__PURE__ */ (0,jsx_runtime.jsx)(DFUIIKXE_ToolbarContext.Provider, { value: store, children: element }),
[store]
);
props = PNRLI7OV_spreadValues({
role: "toolbar",
"aria-orientation": orientation
}, props);
props = AAVDGJD5_useComposite(PNRLI7OV_spreadValues({ store }, props));
return props;
});
var Toolbar = NQJBHION_createComponent((props) => {
const htmlProps = useToolbar(props);
return NQJBHION_createElement("div", htmlProps);
});
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar/toolbar-container.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToolbarContainer({
label,
...props
}, ref) {
const toolbarStore = useToolbarStore({
focusLoop: true,
rtl: (0,external_wp_i18n_namespaceObject.isRTL)()
});
return (// This will provide state for `ToolbarButton`'s
(0,external_wp_element_namespaceObject.createElement)(toolbar_context.Provider, {
value: toolbarStore
}, (0,external_wp_element_namespaceObject.createElement)(Toolbar, {
ref: ref,
"aria-label": label,
store: toolbarStore,
...props
}))
);
}
const ToolbarContainer = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToolbarContainer);
/* harmony default export */ var toolbar_container = (ToolbarContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const CONTEXT_SYSTEM_VALUE = {
DropdownMenu: {
variant: 'toolbar'
},
Dropdown: {
variant: 'toolbar'
}
};
function UnforwardedToolbar({
className,
label,
...props
}, ref) {
if (!label) {
external_wp_deprecated_default()('Using Toolbar without label prop', {
since: '5.6',
alternative: 'ToolbarGroup component',
link: 'https://developer.wordpress.org/block-editor/components/toolbar/'
});
return (0,external_wp_element_namespaceObject.createElement)(toolbar_group, { ...props,
className: className
});
} // `ToolbarGroup` already uses components-toolbar for compatibility reasons.
const finalClassName = classnames_default()('components-accessible-toolbar', className);
return (0,external_wp_element_namespaceObject.createElement)(ContextSystemProvider, {
value: CONTEXT_SYSTEM_VALUE
}, (0,external_wp_element_namespaceObject.createElement)(toolbar_container, {
className: finalClassName,
label: label,
ref: ref,
...props
}));
}
/**
* Renders a toolbar.
*
* To add controls, simply pass `ToolbarButton` components as children.
*
* ```jsx
* import { Toolbar, ToolbarButton } from '@wordpress/components';
* import { formatBold, formatItalic, link } from '@wordpress/icons';
*
* function MyToolbar() {
* return (
* <Toolbar label="Options">
* <ToolbarButton icon={ formatBold } label="Bold" />
* <ToolbarButton icon={ formatItalic } label="Italic" />
* <ToolbarButton icon={ link } label="Link" />
* </Toolbar>
* );
* }
* ```
*/
const toolbar_Toolbar = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToolbar);
/* harmony default export */ var toolbar = (toolbar_Toolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-dropdown-menu/index.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToolbarDropdownMenu(props, ref) {
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if (!accessibleToolbarState) {
return (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, { ...props
});
} // ToobarItem will pass all props to the render prop child, which will pass
// all props to the toggle of DropdownMenu. This means that ToolbarDropdownMenu
// has the same API as DropdownMenu.
return (0,external_wp_element_namespaceObject.createElement)(toolbar_item, {
ref: ref,
...props.toggleProps
}, toolbarItemProps => (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, { ...props,
popoverProps: { ...props.popoverProps
},
toggleProps: toolbarItemProps
}));
}
/* harmony default export */ var toolbar_dropdown_menu = ((0,external_wp_element_namespaceObject.forwardRef)(ToolbarDropdownMenu));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/styles.js
function tools_panel_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const toolsPanelGrid = {
columns: columns => /*#__PURE__*/emotion_react_browser_esm_css("grid-template-columns:", `repeat( ${columns}, minmax(0, 1fr) )`, ";" + ( true ? "" : 0), true ? "" : 0),
spacing: /*#__PURE__*/emotion_react_browser_esm_css("column-gap:", space(2), ";row-gap:", space(4), ";" + ( true ? "" : 0), true ? "" : 0),
item: {
fullWidth: true ? {
name: "18iuzk9",
styles: "grid-column:1/-1"
} : 0
}
};
const ToolsPanel = columns => /*#__PURE__*/emotion_react_browser_esm_css(toolsPanelGrid.columns(columns), " ", toolsPanelGrid.spacing, " border-top:", config_values.borderWidth, " solid ", COLORS.gray[300], ";margin-top:-1px;padding:", space(4), ";" + ( true ? "" : 0), true ? "" : 0);
/**
* Items injected into a ToolsPanel via a virtual bubbling slot will require
* an inner dom element to be injected. The following rule allows for the
* CSS grid display to be re-established.
*/
const ToolsPanelWithInnerWrapper = columns => {
return /*#__PURE__*/emotion_react_browser_esm_css(">div:not( :first-of-type ){display:grid;", toolsPanelGrid.columns(columns), " ", toolsPanelGrid.spacing, " ", toolsPanelGrid.item.fullWidth, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const ToolsPanelHiddenInnerWrapper = true ? {
name: "huufmu",
styles: ">div:not( :first-of-type ){display:none;}"
} : 0;
const ToolsPanelHeader = /*#__PURE__*/emotion_react_browser_esm_css(toolsPanelGrid.item.fullWidth, " gap:", space(2), ";.components-dropdown-menu{margin:", space(-1), " 0;line-height:0;}&&&& .components-dropdown-menu__toggle{padding:0;min-width:", space(6), ";}" + ( true ? "" : 0), true ? "" : 0);
const ToolsPanelHeading = true ? {
name: "1pmxm02",
styles: "font-size:inherit;font-weight:500;line-height:normal;&&{margin:0;}"
} : 0;
const ToolsPanelItem = /*#__PURE__*/emotion_react_browser_esm_css(toolsPanelGrid.item.fullWidth, "&>div,&>fieldset{padding-bottom:0;margin-bottom:0;max-width:100%;}&& ", base_control_styles_Wrapper, "{margin-bottom:0;", StyledField, ":last-child{margin-bottom:0;}}", StyledHelp, "{margin-bottom:0;}&& ", LabelWrapper, "{label{line-height:1.4em;}}" + ( true ? "" : 0), true ? "" : 0);
const ToolsPanelItemPlaceholder = true ? {
name: "eivff4",
styles: "display:none"
} : 0;
const styles_DropdownMenu = true ? {
name: "16gsvie",
styles: "min-width:200px"
} : 0;
const ResetLabel = createStyled("span", true ? {
target: "ews648u0"
} : 0)("color:", COLORS.ui.themeDark10, ";font-size:11px;font-weight:500;line-height:1.4;", rtl({
marginLeft: space(3)
}), " text-transform:uppercase;" + ( true ? "" : 0));
const DefaultControlsItem = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";&&[aria-disabled='true']{color:", COLORS.gray[700], ";opacity:1;&:hover{color:", COLORS.gray[700], ";}", ResetLabel, "{opacity:0.3;}}" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const tools_panel_context_noop = () => undefined;
const ToolsPanelContext = (0,external_wp_element_namespaceObject.createContext)({
menuItems: {
default: {},
optional: {}
},
hasMenuItems: false,
isResetting: false,
shouldRenderPlaceholderItems: false,
registerPanelItem: tools_panel_context_noop,
deregisterPanelItem: tools_panel_context_noop,
flagItemCustomization: tools_panel_context_noop,
registerResetAllFilter: tools_panel_context_noop,
deregisterResetAllFilter: tools_panel_context_noop,
areAllOptionalControlsHidden: true
});
const useToolsPanelContext = () => (0,external_wp_element_namespaceObject.useContext)(ToolsPanelContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-header/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useToolsPanelHeader(props) {
const {
className,
headingLevel = 2,
...otherProps
} = useContextSystem(props, 'ToolsPanelHeader');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(ToolsPanelHeader, className);
}, [className, cx]);
const dropdownMenuClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(styles_DropdownMenu);
}, [cx]);
const headingClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(ToolsPanelHeading);
}, [cx]);
const defaultControlsItemClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(DefaultControlsItem);
}, [cx]);
const {
menuItems,
hasMenuItems,
areAllOptionalControlsHidden
} = useToolsPanelContext();
return { ...otherProps,
areAllOptionalControlsHidden,
defaultControlsItemClassName,
dropdownMenuClassName,
hasMenuItems,
headingClassName,
headingLevel,
menuItems,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-header/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DefaultControlsGroup = ({
itemClassName,
items,
toggleItem
}) => {
if (!items.length) {
return null;
}
const resetSuffix = (0,external_wp_element_namespaceObject.createElement)(ResetLabel, {
"aria-hidden": true
}, (0,external_wp_i18n_namespaceObject.__)('Reset'));
return (0,external_wp_element_namespaceObject.createElement)(menu_group, {
label: (0,external_wp_i18n_namespaceObject.__)('Defaults')
}, items.map(([label, hasValue]) => {
if (hasValue) {
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: label,
className: itemClassName,
role: "menuitem",
label: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('Reset %s'), label),
onClick: () => {
toggleItem(label);
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('%s reset to default'), label), 'assertive');
},
suffix: resetSuffix
}, label);
}
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: label,
className: itemClassName,
role: "menuitemcheckbox",
isSelected: true,
"aria-disabled": true
}, label);
}));
};
const OptionalControlsGroup = ({
items,
toggleItem
}) => {
if (!items.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(menu_group, {
label: (0,external_wp_i18n_namespaceObject.__)('Tools')
}, items.map(([label, isSelected]) => {
const itemLabel = isSelected ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being hidden and reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('Hide and reset %s'), label) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control to display e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('Show %s'), label);
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: label,
icon: isSelected && library_check,
isSelected: isSelected,
label: itemLabel,
onClick: () => {
if (isSelected) {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('%s hidden and reset to default'), label), 'assertive');
} else {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('%s is now visible'), label), 'assertive');
}
toggleItem(label);
},
role: "menuitemcheckbox"
}, label);
}));
};
const component_ToolsPanelHeader = (props, forwardedRef) => {
const {
areAllOptionalControlsHidden,
defaultControlsItemClassName,
dropdownMenuClassName,
hasMenuItems,
headingClassName,
headingLevel = 2,
label: labelText,
menuItems,
resetAll,
toggleItem,
...headerProps
} = useToolsPanelHeader(props);
if (!labelText) {
return null;
}
const defaultItems = Object.entries(menuItems?.default || {});
const optionalItems = Object.entries(menuItems?.optional || {});
const dropDownMenuIcon = areAllOptionalControlsHidden ? library_plus : more_vertical;
const dropDownMenuLabelText = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the tool e.g. "Color" or "Typography".
(0,external_wp_i18n_namespaceObject._x)('%s options', 'Button label to reveal tool panel options'), labelText);
const dropdownMenuDescriptionText = areAllOptionalControlsHidden ? (0,external_wp_i18n_namespaceObject.__)('All options are currently hidden') : undefined;
const canResetAll = [...defaultItems, ...optionalItems].some(([, isSelected]) => isSelected);
return (0,external_wp_element_namespaceObject.createElement)(h_stack_component, { ...headerProps,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(heading_component, {
level: headingLevel,
className: headingClassName
}, labelText), hasMenuItems && (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, {
icon: dropDownMenuIcon,
label: dropDownMenuLabelText,
menuProps: {
className: dropdownMenuClassName
},
toggleProps: {
isSmall: true,
describedBy: dropdownMenuDescriptionText
}
}, () => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(DefaultControlsGroup, {
items: defaultItems,
toggleItem: toggleItem,
itemClassName: defaultControlsItemClassName
}), (0,external_wp_element_namespaceObject.createElement)(OptionalControlsGroup, {
items: optionalItems,
toggleItem: toggleItem
}), (0,external_wp_element_namespaceObject.createElement)(menu_group, null, (0,external_wp_element_namespaceObject.createElement)(menu_item, {
"aria-disabled": !canResetAll,
variant: 'tertiary',
onClick: () => {
if (canResetAll) {
resetAll();
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('All options reset'), 'assertive');
}
}
}, (0,external_wp_i18n_namespaceObject.__)('Reset all'))))));
};
const ConnectedToolsPanelHeader = contextConnect(component_ToolsPanelHeader, 'ToolsPanelHeader');
/* harmony default export */ var tools_panel_header_component = (ConnectedToolsPanelHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_COLUMNS = 2;
const generateMenuItems = ({
panelItems,
shouldReset,
currentMenuItems,
menuItemOrder
}) => {
const newMenuItems = {
default: {},
optional: {}
};
const menuItems = {
default: {},
optional: {}
};
panelItems.forEach(({
hasValue,
isShownByDefault,
label
}) => {
const group = isShownByDefault ? 'default' : 'optional'; // If a menu item for this label has already been flagged as customized
// (for default controls), or toggled on (for optional controls), do not
// overwrite its value as those controls would lose that state.
const existingItemValue = currentMenuItems?.[group]?.[label];
const value = existingItemValue ? existingItemValue : hasValue();
newMenuItems[group][label] = shouldReset ? false : value;
}); // Loop the known, previously registered items first to maintain menu order.
menuItemOrder.forEach(key => {
if (newMenuItems.default.hasOwnProperty(key)) {
menuItems.default[key] = newMenuItems.default[key];
}
if (newMenuItems.optional.hasOwnProperty(key)) {
menuItems.optional[key] = newMenuItems.optional[key];
}
}); // Loop newMenuItems object adding any that aren't in the known items order.
Object.keys(newMenuItems.default).forEach(key => {
if (!menuItems.default.hasOwnProperty(key)) {
menuItems.default[key] = newMenuItems.default[key];
}
});
Object.keys(newMenuItems.optional).forEach(key => {
if (!menuItems.optional.hasOwnProperty(key)) {
menuItems.optional[key] = newMenuItems.optional[key];
}
});
return menuItems;
};
const isMenuItemTypeEmpty = obj => obj && Object.keys(obj).length === 0;
function useToolsPanel(props) {
const {
className,
headingLevel = 2,
resetAll,
panelId,
hasInnerWrapper = false,
shouldRenderPlaceholderItems = false,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass,
...otherProps
} = useContextSystem(props, 'ToolsPanel');
const isResetting = (0,external_wp_element_namespaceObject.useRef)(false);
const wasResetting = isResetting.current; // `isResetting` is cleared via this hook to effectively batch together
// the resetAll task. Without this, the flag is cleared after the first
// control updates and forces a rerender with subsequent controls then
// believing they need to reset, unfortunately using stale data.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (wasResetting) {
isResetting.current = false;
}
}, [wasResetting]); // Allow panel items to register themselves.
const [panelItems, setPanelItems] = (0,external_wp_element_namespaceObject.useState)([]);
const [menuItemOrder, setMenuItemOrder] = (0,external_wp_element_namespaceObject.useState)([]);
const [resetAllFilters, setResetAllFilters] = (0,external_wp_element_namespaceObject.useState)([]);
const registerPanelItem = (0,external_wp_element_namespaceObject.useCallback)(item => {
// Add item to panel items.
setPanelItems(items => {
const newItems = [...items]; // If an item with this label has already been registered, remove it
// first. This can happen when an item is moved between the default
// and optional groups.
const existingIndex = newItems.findIndex(oldItem => oldItem.label === item.label);
if (existingIndex !== -1) {
newItems.splice(existingIndex, 1);
}
return [...newItems, item];
}); // Track the initial order of item registration. This is used for
// maintaining menu item order later.
setMenuItemOrder(items => {
if (items.includes(item.label)) {
return items;
}
return [...items, item.label];
});
}, [setPanelItems, setMenuItemOrder]); // Panels need to deregister on unmount to avoid orphans in menu state.
// This is an issue when panel items are being injected via SlotFills.
const deregisterPanelItem = (0,external_wp_element_namespaceObject.useCallback)(label => {
// When switching selections between components injecting matching
// controls, e.g. both panels have a "padding" control, the
// deregistration of the first panel doesn't occur until after the
// registration of the next.
setPanelItems(items => {
const newItems = [...items];
const index = newItems.findIndex(item => item.label === label);
if (index !== -1) {
newItems.splice(index, 1);
}
return newItems;
});
}, [setPanelItems]);
const registerResetAllFilter = (0,external_wp_element_namespaceObject.useCallback)(newFilter => {
setResetAllFilters(filters => {
return [...filters, newFilter];
});
}, [setResetAllFilters]);
const deregisterResetAllFilter = (0,external_wp_element_namespaceObject.useCallback)(filterToRemove => {
setResetAllFilters(filters => {
return filters.filter(filter => filter !== filterToRemove);
});
}, [setResetAllFilters]); // Manage and share display state of menu items representing child controls.
const [menuItems, setMenuItems] = (0,external_wp_element_namespaceObject.useState)({
default: {},
optional: {}
}); // Setup menuItems state as panel items register themselves.
(0,external_wp_element_namespaceObject.useEffect)(() => {
setMenuItems(prevState => {
const items = generateMenuItems({
panelItems,
shouldReset: false,
currentMenuItems: prevState,
menuItemOrder
});
return items;
});
}, [panelItems, setMenuItems, menuItemOrder]); // Force a menu item to be checked.
// This is intended for use with default panel items. They are displayed
// separately to optional items and have different display states,
// we need to update that when their value is customized.
const flagItemCustomization = (0,external_wp_element_namespaceObject.useCallback)((label, group = 'default') => {
setMenuItems(items => {
const newState = { ...items,
[group]: { ...items[group],
[label]: true
}
};
return newState;
});
}, [setMenuItems]); // Whether all optional menu items are hidden or not must be tracked
// in order to later determine if the panel display is empty and handle
// conditional display of a plus icon to indicate the presence of further
// menu items.
const [areAllOptionalControlsHidden, setAreAllOptionalControlsHidden] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isMenuItemTypeEmpty(menuItems?.default) && !isMenuItemTypeEmpty(menuItems?.optional)) {
const allControlsHidden = !Object.entries(menuItems.optional).some(([, isSelected]) => isSelected);
setAreAllOptionalControlsHidden(allControlsHidden);
}
}, [menuItems, setAreAllOptionalControlsHidden]);
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const wrapperStyle = hasInnerWrapper && ToolsPanelWithInnerWrapper(DEFAULT_COLUMNS);
const emptyStyle = isMenuItemTypeEmpty(menuItems?.default) && areAllOptionalControlsHidden && ToolsPanelHiddenInnerWrapper;
return cx(ToolsPanel(DEFAULT_COLUMNS), wrapperStyle, emptyStyle, className);
}, [areAllOptionalControlsHidden, className, cx, hasInnerWrapper, menuItems]); // Toggle the checked state of a menu item which is then used to determine
// display of the item within the panel.
const toggleItem = (0,external_wp_element_namespaceObject.useCallback)(label => {
const currentItem = panelItems.find(item => item.label === label);
if (!currentItem) {
return;
}
const menuGroup = currentItem.isShownByDefault ? 'default' : 'optional';
const newMenuItems = { ...menuItems,
[menuGroup]: { ...menuItems[menuGroup],
[label]: !menuItems[menuGroup][label]
}
};
setMenuItems(newMenuItems);
}, [menuItems, panelItems, setMenuItems]); // Resets display of children and executes resetAll callback if available.
const resetAllItems = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (typeof resetAll === 'function') {
isResetting.current = true;
resetAll(resetAllFilters);
} // Turn off display of all non-default items.
const resetMenuItems = generateMenuItems({
panelItems,
menuItemOrder,
shouldReset: true
});
setMenuItems(resetMenuItems);
}, [panelItems, resetAllFilters, resetAll, setMenuItems, menuItemOrder]); // Assist ItemGroup styling when there are potentially hidden placeholder
// items by identifying first & last items that are toggled on for display.
const getFirstVisibleItemLabel = items => {
const optionalItems = menuItems.optional || {};
const firstItem = items.find(item => item.isShownByDefault || !!optionalItems[item.label]);
return firstItem?.label;
};
const firstDisplayedItem = getFirstVisibleItemLabel(panelItems);
const lastDisplayedItem = getFirstVisibleItemLabel([...panelItems].reverse());
const panelContext = (0,external_wp_element_namespaceObject.useMemo)(() => ({
areAllOptionalControlsHidden,
deregisterPanelItem,
deregisterResetAllFilter,
firstDisplayedItem,
flagItemCustomization,
hasMenuItems: !!panelItems.length,
isResetting: isResetting.current,
lastDisplayedItem,
menuItems,
panelId,
registerPanelItem,
registerResetAllFilter,
shouldRenderPlaceholderItems,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass
}), [areAllOptionalControlsHidden, deregisterPanelItem, deregisterResetAllFilter, firstDisplayedItem, flagItemCustomization, lastDisplayedItem, menuItems, panelId, panelItems, registerResetAllFilter, registerPanelItem, shouldRenderPlaceholderItems, __experimentalFirstVisibleItemClass, __experimentalLastVisibleItemClass]);
return { ...otherProps,
headingLevel,
panelContext,
resetAllItems,
toggleItem,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const UnconnectedToolsPanel = (props, forwardedRef) => {
const {
children,
label,
panelContext,
resetAllItems,
toggleItem,
headingLevel,
...toolsPanelProps
} = useToolsPanel(props);
return (0,external_wp_element_namespaceObject.createElement)(grid_component, { ...toolsPanelProps,
columns: 2,
ref: forwardedRef
}, (0,external_wp_element_namespaceObject.createElement)(ToolsPanelContext.Provider, {
value: panelContext
}, (0,external_wp_element_namespaceObject.createElement)(tools_panel_header_component, {
label: label,
resetAll: resetAllItems,
toggleItem: toggleItem,
headingLevel: headingLevel
}), children));
};
/**
* The `ToolsPanel` is a container component that displays its children preceded
* by a header. The header includes a dropdown menu which is automatically
* generated from the panel's inner `ToolsPanelItems`.
*
* @example
* ```jsx
* import { __ } from '@wordpress/i18n';
* import {
* __experimentalToolsPanel as ToolsPanel,
* __experimentalToolsPanelItem as ToolsPanelItem,
* __experimentalUnitControl as UnitControl
* } from '@wordpress/components';
*
* function Example() {
* const [ height, setHeight ] = useState();
* const [ width, setWidth ] = useState();
*
* const resetAll = () => {
* setHeight();
* setWidth();
* }
*
* return (
* <ToolsPanel label={ __( 'Dimensions' ) } resetAll={ resetAll }>
* <ToolsPanelItem
* hasValue={ () => !! height }
* label={ __( 'Height' ) }
* onDeselect={ () => setHeight() }
* >
* <UnitControl
* label={ __( 'Height' ) }
* onChange={ setHeight }
* value={ height }
* />
* </ToolsPanelItem>
* <ToolsPanelItem
* hasValue={ () => !! width }
* label={ __( 'Width' ) }
* onDeselect={ () => setWidth() }
* >
* <UnitControl
* label={ __( 'Width' ) }
* onChange={ setWidth }
* value={ width }
* />
* </ToolsPanelItem>
* </ToolsPanel>
* );
* }
* ```
*/
const component_ToolsPanel = contextConnect(UnconnectedToolsPanel, 'ToolsPanel');
/* harmony default export */ var tools_panel_component = (component_ToolsPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-item/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const hook_noop = () => {};
function useToolsPanelItem(props) {
const {
className,
hasValue,
isShownByDefault = false,
label,
panelId,
resetAllFilter = hook_noop,
onDeselect,
onSelect,
...otherProps
} = useContextSystem(props, 'ToolsPanelItem');
const {
panelId: currentPanelId,
menuItems,
registerResetAllFilter,
deregisterResetAllFilter,
registerPanelItem,
deregisterPanelItem,
flagItemCustomization,
isResetting,
shouldRenderPlaceholderItems: shouldRenderPlaceholder,
firstDisplayedItem,
lastDisplayedItem,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass
} = useToolsPanelContext();
const hasValueCallback = (0,external_wp_element_namespaceObject.useCallback)(hasValue, [panelId, hasValue]);
const resetAllFilterCallback = (0,external_wp_element_namespaceObject.useCallback)(resetAllFilter, [panelId, resetAllFilter]);
const previousPanelId = (0,external_wp_compose_namespaceObject.usePrevious)(currentPanelId);
const hasMatchingPanel = currentPanelId === panelId || currentPanelId === null; // Registering the panel item allows the panel to include it in its
// automatically generated menu and determine its initial checked status.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasMatchingPanel && previousPanelId !== null) {
registerPanelItem({
hasValue: hasValueCallback,
isShownByDefault,
label,
panelId
});
}
return () => {
if (previousPanelId === null && !!currentPanelId || currentPanelId === panelId) {
deregisterPanelItem(label);
}
};
}, [currentPanelId, hasMatchingPanel, isShownByDefault, label, hasValueCallback, panelId, previousPanelId, registerPanelItem, deregisterPanelItem]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasMatchingPanel) {
registerResetAllFilter(resetAllFilterCallback);
}
return () => {
if (hasMatchingPanel) {
deregisterResetAllFilter(resetAllFilterCallback);
}
};
}, [registerResetAllFilter, deregisterResetAllFilter, resetAllFilterCallback, hasMatchingPanel]); // Note: `label` is used as a key when building menu item state in
// `ToolsPanel`.
const menuGroup = isShownByDefault ? 'default' : 'optional';
const isMenuItemChecked = menuItems?.[menuGroup]?.[label];
const wasMenuItemChecked = (0,external_wp_compose_namespaceObject.usePrevious)(isMenuItemChecked);
const isRegistered = menuItems?.[menuGroup]?.[label] !== undefined;
const isValueSet = hasValue();
const wasValueSet = (0,external_wp_compose_namespaceObject.usePrevious)(isValueSet);
const newValueSet = isValueSet && !wasValueSet; // Notify the panel when an item's value has been set.
//
// 1. For default controls, this is so "reset" appears beside its menu item.
// 2. For optional controls, when the panel ID is `null`, it allows the
// panel to ensure the item is toggled on for display in the menu, given the
// value has been set external to the control.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!newValueSet) {
return;
}
if (isShownByDefault || currentPanelId === null) {
flagItemCustomization(label, menuGroup);
}
}, [currentPanelId, newValueSet, isShownByDefault, menuGroup, label, flagItemCustomization]); // Determine if the panel item's corresponding menu is being toggled and
// trigger appropriate callback if it is.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We check whether this item is currently registered as items rendered
// via fills can persist through the parent panel being remounted.
// See: https://github.com/WordPress/gutenberg/pull/45673
if (!isRegistered || isResetting || !hasMatchingPanel) {
return;
}
if (isMenuItemChecked && !isValueSet && !wasMenuItemChecked) {
onSelect?.();
}
if (!isMenuItemChecked && wasMenuItemChecked) {
onDeselect?.();
}
}, [hasMatchingPanel, isMenuItemChecked, isRegistered, isResetting, isValueSet, wasMenuItemChecked, onSelect, onDeselect]); // The item is shown if it is a default control regardless of whether it
// has a value. Optional items are shown when they are checked or have
// a value.
const isShown = isShownByDefault ? menuItems?.[menuGroup]?.[label] !== undefined : isMenuItemChecked;
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const placeholderStyle = shouldRenderPlaceholder && !isShown && ToolsPanelItemPlaceholder;
const firstItemStyle = firstDisplayedItem === label && __experimentalFirstVisibleItemClass;
const lastItemStyle = lastDisplayedItem === label && __experimentalLastVisibleItemClass;
return cx(ToolsPanelItem, placeholderStyle, className, firstItemStyle, lastItemStyle);
}, [isShown, shouldRenderPlaceholder, className, cx, firstDisplayedItem, lastDisplayedItem, __experimentalFirstVisibleItemClass, __experimentalLastVisibleItemClass, label]);
return { ...otherProps,
isShown,
shouldRenderPlaceholder,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-item/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// This wraps controls to be conditionally displayed within a tools panel. It
// prevents props being applied to HTML elements that would make them invalid.
const UnconnectedToolsPanelItem = (props, forwardedRef) => {
const {
children,
isShown,
shouldRenderPlaceholder,
...toolsPanelItemProps
} = useToolsPanelItem(props);
if (!isShown) {
return shouldRenderPlaceholder ? (0,external_wp_element_namespaceObject.createElement)(component, { ...toolsPanelItemProps,
ref: forwardedRef
}) : null;
}
return (0,external_wp_element_namespaceObject.createElement)(component, { ...toolsPanelItemProps,
ref: forwardedRef
}, children);
};
const component_ToolsPanelItem = contextConnect(UnconnectedToolsPanelItem, 'ToolsPanelItem');
/* harmony default export */ var tools_panel_item_component = (component_ToolsPanelItem);
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/roving-tab-index-context.js
/**
* WordPress dependencies
*/
const RovingTabIndexContext = (0,external_wp_element_namespaceObject.createContext)(undefined);
const useRovingTabIndexContext = () => (0,external_wp_element_namespaceObject.useContext)(RovingTabIndexContext);
const RovingTabIndexProvider = RovingTabIndexContext.Provider;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/roving-tab-index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Provider for adding roving tab index behaviors to tree grid structures.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/components/src/tree-grid/README.md
*/
function RovingTabIndex({
children
}) {
const [lastFocusedElement, setLastFocusedElement] = (0,external_wp_element_namespaceObject.useState)(); // Use `useMemo` to avoid creation of a new object for the providerValue
// on every render. Only create a new object when the `lastFocusedElement`
// value changes.
const providerValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
lastFocusedElement,
setLastFocusedElement
}), [lastFocusedElement]);
return (0,external_wp_element_namespaceObject.createElement)(RovingTabIndexProvider, {
value: providerValue
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Return focusables in a row element, excluding those from other branches
* nested within the row.
*
* @param rowElement The DOM element representing the row.
*
* @return The array of focusables in the row.
*/
function getRowFocusables(rowElement) {
const focusablesInRow = external_wp_dom_namespaceObject.focus.focusable.find(rowElement, {
sequential: true
});
return focusablesInRow.filter(focusable => {
return focusable.closest('[role="row"]') === rowElement;
});
}
/**
* Renders both a table and tbody element, used to create a tree hierarchy.
*
*/
function UnforwardedTreeGrid({
children,
onExpandRow = () => {},
onCollapseRow = () => {},
onFocusRow = () => {},
applicationAriaLabel,
...props
},
/** A ref to the underlying DOM table element. */
ref) {
const onKeyDown = (0,external_wp_element_namespaceObject.useCallback)(event => {
const {
keyCode,
metaKey,
ctrlKey,
altKey
} = event; // The shift key is intentionally absent from the following list,
// to enable shift + up/down to select items from the list.
const hasModifierKeyPressed = metaKey || ctrlKey || altKey;
if (hasModifierKeyPressed || ![external_wp_keycodes_namespaceObject.UP, external_wp_keycodes_namespaceObject.DOWN, external_wp_keycodes_namespaceObject.LEFT, external_wp_keycodes_namespaceObject.RIGHT, external_wp_keycodes_namespaceObject.HOME, external_wp_keycodes_namespaceObject.END].includes(keyCode)) {
return;
} // The event will be handled, stop propagation.
event.stopPropagation();
const {
activeElement
} = document;
const {
currentTarget: treeGridElement
} = event;
if (!activeElement || !treeGridElement.contains(activeElement)) {
return;
} // Calculate the columnIndex of the active element.
const activeRow = activeElement.closest('[role="row"]');
if (!activeRow) {
return;
}
const focusablesInRow = getRowFocusables(activeRow);
const currentColumnIndex = focusablesInRow.indexOf(activeElement);
const canExpandCollapse = 0 === currentColumnIndex;
const cannotFocusNextColumn = canExpandCollapse && (activeRow.getAttribute('data-expanded') === 'false' || activeRow.getAttribute('aria-expanded') === 'false') && keyCode === external_wp_keycodes_namespaceObject.RIGHT;
if ([external_wp_keycodes_namespaceObject.LEFT, external_wp_keycodes_namespaceObject.RIGHT].includes(keyCode)) {
// Calculate to the next element.
let nextIndex;
if (keyCode === external_wp_keycodes_namespaceObject.LEFT) {
nextIndex = Math.max(0, currentColumnIndex - 1);
} else {
nextIndex = Math.min(currentColumnIndex + 1, focusablesInRow.length - 1);
} // Focus is at the left most column.
if (canExpandCollapse) {
if (keyCode === external_wp_keycodes_namespaceObject.LEFT) {
var _activeRow$getAttribu;
// Left:
// If a row is focused, and it is expanded, collapses the current row.
if (activeRow.getAttribute('data-expanded') === 'true' || activeRow.getAttribute('aria-expanded') === 'true') {
onCollapseRow(activeRow);
event.preventDefault();
return;
} // If a row is focused, and it is collapsed, moves to the parent row (if there is one).
const level = Math.max(parseInt((_activeRow$getAttribu = activeRow?.getAttribute('aria-level')) !== null && _activeRow$getAttribu !== void 0 ? _activeRow$getAttribu : '1', 10) - 1, 1);
const rows = Array.from(treeGridElement.querySelectorAll('[role="row"]'));
let parentRow = activeRow;
const currentRowIndex = rows.indexOf(activeRow);
for (let i = currentRowIndex; i >= 0; i--) {
const ariaLevel = rows[i].getAttribute('aria-level');
if (ariaLevel !== null && parseInt(ariaLevel, 10) === level) {
parentRow = rows[i];
break;
}
}
getRowFocusables(parentRow)?.[0]?.focus();
}
if (keyCode === external_wp_keycodes_namespaceObject.RIGHT) {
// Right:
// If a row is focused, and it is collapsed, expands the current row.
if (activeRow.getAttribute('data-expanded') === 'false' || activeRow.getAttribute('aria-expanded') === 'false') {
onExpandRow(activeRow);
event.preventDefault();
return;
} // If a row is focused, and it is expanded, focuses the next cell in the row.
const focusableItems = getRowFocusables(activeRow);
if (focusableItems.length > 0) {
focusableItems[nextIndex]?.focus();
}
} // Prevent key use for anything else. For example, Voiceover
// will start reading text on continued use of left/right arrow
// keys.
event.preventDefault();
return;
} // Focus the next element. If at most left column and row is collapsed, moving right is not allowed as this will expand. However, if row is collapsed, moving left is allowed.
if (cannotFocusNextColumn) {
return;
}
focusablesInRow[nextIndex].focus(); // Prevent key use for anything else. This ensures Voiceover
// doesn't try to handle key navigation.
event.preventDefault();
} else if ([external_wp_keycodes_namespaceObject.UP, external_wp_keycodes_namespaceObject.DOWN].includes(keyCode)) {
// Calculate the rowIndex of the next row.
const rows = Array.from(treeGridElement.querySelectorAll('[role="row"]'));
const currentRowIndex = rows.indexOf(activeRow);
let nextRowIndex;
if (keyCode === external_wp_keycodes_namespaceObject.UP) {
nextRowIndex = Math.max(0, currentRowIndex - 1);
} else {
nextRowIndex = Math.min(currentRowIndex + 1, rows.length - 1);
} // Focus is either at the top or bottom edge of the grid. Do nothing.
if (nextRowIndex === currentRowIndex) {
// Prevent key use for anything else. For example, Voiceover
// will start navigating horizontally when reaching the vertical
// bounds of a table.
event.preventDefault();
return;
} // Get the focusables in the next row.
const focusablesInNextRow = getRowFocusables(rows[nextRowIndex]); // If for some reason there are no focusables in the next row, do nothing.
if (!focusablesInNextRow || !focusablesInNextRow.length) {
// Prevent key use for anything else. For example, Voiceover
// will still focus text when using arrow keys, while this
// component should limit navigation to focusables.
event.preventDefault();
return;
} // Try to focus the element in the next row that's at a similar column to the activeElement.
const nextIndex = Math.min(currentColumnIndex, focusablesInNextRow.length - 1);
focusablesInNextRow[nextIndex].focus(); // Let consumers know the row that was originally focused,
// and the row that is now in focus.
onFocusRow(event, activeRow, rows[nextRowIndex]); // Prevent key use for anything else. This ensures Voiceover
// doesn't try to handle key navigation.
event.preventDefault();
} else if ([external_wp_keycodes_namespaceObject.HOME, external_wp_keycodes_namespaceObject.END].includes(keyCode)) {
// Calculate the rowIndex of the next row.
const rows = Array.from(treeGridElement.querySelectorAll('[role="row"]'));
const currentRowIndex = rows.indexOf(activeRow);
let nextRowIndex;
if (keyCode === external_wp_keycodes_namespaceObject.HOME) {
nextRowIndex = 0;
} else {
nextRowIndex = rows.length - 1;
} // Focus is either at the top or bottom edge of the grid. Do nothing.
if (nextRowIndex === currentRowIndex) {
// Prevent key use for anything else. For example, Voiceover
// will start navigating horizontally when reaching the vertical
// bounds of a table.
event.preventDefault();
return;
} // Get the focusables in the next row.
const focusablesInNextRow = getRowFocusables(rows[nextRowIndex]); // If for some reason there are no focusables in the next row, do nothing.
if (!focusablesInNextRow || !focusablesInNextRow.length) {
// Prevent key use for anything else. For example, Voiceover
// will still focus text when using arrow keys, while this
// component should limit navigation to focusables.
event.preventDefault();
return;
} // Try to focus the element in the next row that's at a similar column to the activeElement.
const nextIndex = Math.min(currentColumnIndex, focusablesInNextRow.length - 1);
focusablesInNextRow[nextIndex].focus(); // Let consumers know the row that was originally focused,
// and the row that is now in focus.
onFocusRow(event, activeRow, rows[nextRowIndex]); // Prevent key use for anything else. This ensures Voiceover
// doesn't try to handle key navigation.
event.preventDefault();
}
}, [onExpandRow, onCollapseRow, onFocusRow]);
/* Disable reason: A treegrid is implemented using a table element. */
/* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role */
return (0,external_wp_element_namespaceObject.createElement)(RovingTabIndex, null, (0,external_wp_element_namespaceObject.createElement)("div", {
role: "application",
"aria-label": applicationAriaLabel
}, (0,external_wp_element_namespaceObject.createElement)("table", { ...props,
role: "treegrid",
onKeyDown: onKeyDown,
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)("tbody", null, children))));
/* eslint-enable jsx-a11y/no-noninteractive-element-to-interactive-role */
}
/**
* `TreeGrid` is used to create a tree hierarchy.
* It is not a visually styled component, but instead helps with adding
* keyboard navigation and roving tab index behaviors to tree grid structures.
*
* A tree grid is a hierarchical 2 dimensional UI component, for example it could be
* used to implement a file system browser.
*
* A tree grid allows the user to navigate using arrow keys.
* Up/down to navigate vertically across rows, and left/right to navigate horizontally
* between focusables in a row.
*
* The `TreeGrid` renders both a `table` and `tbody` element, and is intended to be used
* with `TreeGridRow` (`tr`) and `TreeGridCell` (`td`) to build out a grid.
*
* ```jsx
* function TreeMenu() {
* return (
* <TreeGrid>
* <TreeGridRow level={ 1 } positionInSet={ 1 } setSize={ 2 }>
* <TreeGridCell>
* { ( props ) => (
* <Button onClick={ onSelect } { ...props }>Select</Button>
* ) }
* </TreeGridCell>
* <TreeGridCell>
* { ( props ) => (
* <Button onClick={ onMove } { ...props }>Move</Button>
* ) }
* </TreeGridCell>
* </TreeGridRow>
* <TreeGridRow level={ 1 } positionInSet={ 2 } setSize={ 2 }>
* <TreeGridCell>
* { ( props ) => (
* <Button onClick={ onSelect } { ...props }>Select</Button>
* ) }
* </TreeGridCell>
* <TreeGridCell>
* { ( props ) => (
* <Button onClick={ onMove } { ...props }>Move</Button>
* ) }
* </TreeGridCell>
* </TreeGridRow>
* <TreeGridRow level={ 2 } positionInSet={ 1 } setSize={ 1 }>
* <TreeGridCell>
* { ( props ) => (
* <Button onClick={ onSelect } { ...props }>Select</Button>
* ) }
* </TreeGridCell>
* <TreeGridCell>
* { ( props ) => (
* <Button onClick={ onMove } { ...props }>Move</Button>
* ) }
* </TreeGridCell>
* </TreeGridRow>
* </TreeGrid>
* );
* }
* ```
*
* @see {@link https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html}
*/
const TreeGrid = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTreeGrid);
/* harmony default export */ var tree_grid = (TreeGrid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/row.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedTreeGridRow({
children,
level,
positionInSet,
setSize,
isExpanded,
...props
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)("tr", { ...props,
ref: ref,
role: "row",
"aria-level": level,
"aria-posinset": positionInSet,
"aria-setsize": setSize,
"aria-expanded": isExpanded
}, children);
}
/**
* `TreeGridRow` is used to create a tree hierarchy.
* It is not a visually styled component, but instead helps with adding
* keyboard navigation and roving tab index behaviors to tree grid structures.
*
* @see {@link https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html}
*/
const TreeGridRow = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTreeGridRow);
/* harmony default export */ var tree_grid_row = (TreeGridRow);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/roving-tab-index-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const RovingTabIndexItem = (0,external_wp_element_namespaceObject.forwardRef)(function UnforwardedRovingTabIndexItem({
children,
as: Component,
...props
}, forwardedRef) {
const localRef = (0,external_wp_element_namespaceObject.useRef)();
const ref = forwardedRef || localRef; // @ts-expect-error - We actually want to throw an error if this is undefined.
const {
lastFocusedElement,
setLastFocusedElement
} = useRovingTabIndexContext();
let tabIndex;
if (lastFocusedElement) {
tabIndex = lastFocusedElement === ( // TODO: The original implementation simply used `ref.current` here, assuming
// that a forwarded ref would always be an object, which is not necessarily true.
// This workaround maintains the original runtime behavior in a type-safe way,
// but should be revisited.
'current' in ref ? ref.current : undefined) ? 0 : -1;
}
const onFocus = event => setLastFocusedElement?.(event.target);
const allProps = {
ref,
tabIndex,
onFocus,
...props
};
if (typeof children === 'function') {
return children(allProps);
}
if (!Component) return null;
return (0,external_wp_element_namespaceObject.createElement)(Component, { ...allProps
}, children);
});
/* harmony default export */ var roving_tab_index_item = (RovingTabIndexItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedTreeGridItem({
children,
...props
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)(roving_tab_index_item, {
ref: ref,
...props
}, children);
}
/**
* `TreeGridItem` is used to create a tree hierarchy.
* It is not a visually styled component, but instead helps with adding
* keyboard navigation and roving tab index behaviors to tree grid structures.
*
* @see {@link https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html}
*/
const TreeGridItem = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTreeGridItem);
/* harmony default export */ var tree_grid_item = (TreeGridItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/cell.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedTreeGridCell({
children,
withoutGridItem = false,
...props
}, ref) {
return (0,external_wp_element_namespaceObject.createElement)("td", { ...props,
role: "gridcell"
}, withoutGridItem ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children) : (0,external_wp_element_namespaceObject.createElement)(tree_grid_item, {
ref: ref
}, children));
}
/**
* `TreeGridCell` is used to create a tree hierarchy.
* It is not a visually styled component, but instead helps with adding
* keyboard navigation and roving tab index behaviors to tree grid structures.
*
* @see {@link https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html}
*/
const TreeGridCell = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTreeGridCell);
/* harmony default export */ var cell = (TreeGridCell);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/isolated-event-container/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function stopPropagation(event) {
event.stopPropagation();
}
const IsolatedEventContainer = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
external_wp_deprecated_default()('wp.components.IsolatedEventContainer', {
since: '5.7'
}); // Disable reason: this stops certain events from propagating outside of the component.
// - onMouseDown is disabled as this can cause interactions with other DOM elements.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)("div", { ...props,
ref: ref,
onMouseDown: stopPropagation
});
/* eslint-enable jsx-a11y/no-static-element-interactions */
});
/* harmony default export */ var isolated_event_container = (IsolatedEventContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/use-slot-fills.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSlotFills(name) {
const registry = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const fills = useSnapshot(registry.fills, {
sync: true
}); // The important bit here is that this call ensures that the hook
// only causes a re-render if the "fills" of a given slot name
// change change, not any fills.
return fills.get(name);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/z-stack/styles.js
function z_stack_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const ZStackChildView = createStyled("div", true ? {
target: "ebn2ljm1"
} : 0)("&:not( :first-of-type ){", ({
offsetAmount
}) => /*#__PURE__*/emotion_react_browser_esm_css({
marginInlineStart: offsetAmount
}, true ? "" : 0, true ? "" : 0), ";}", ({
zIndex
}) => /*#__PURE__*/emotion_react_browser_esm_css({
zIndex
}, true ? "" : 0, true ? "" : 0), ";" + ( true ? "" : 0));
var z_stack_styles_ref = true ? {
name: "rs0gp6",
styles: "grid-row-start:1;grid-column-start:1"
} : 0;
const ZStackView = createStyled("div", true ? {
target: "ebn2ljm0"
} : 0)("display:inline-grid;grid-auto-flow:column;position:relative;&>", ZStackChildView, "{position:relative;justify-self:start;", ({
isLayered
}) => isLayered ? // When `isLayered` is true, all items overlap in the same grid cell
z_stack_styles_ref : undefined, ";}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/z-stack/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedZStack(props, forwardedRef) {
const {
children,
className,
isLayered = true,
isReversed = false,
offset = 0,
...otherProps
} = useContextSystem(props, 'ZStack');
const validChildren = getValidChildren(children);
const childrenLastIndex = validChildren.length - 1;
const clonedChildren = validChildren.map((child, index) => {
const zIndex = isReversed ? childrenLastIndex - index : index; // Only when the component is layered, the offset needs to be multiplied by
// the item's index, so that items can correctly stack at the right distance
const offsetAmount = isLayered ? offset * index : offset;
const key = (0,external_wp_element_namespaceObject.isValidElement)(child) ? child.key : index;
return (0,external_wp_element_namespaceObject.createElement)(ZStackChildView, {
offsetAmount: offsetAmount,
zIndex: zIndex,
key: key
}, child);
});
return (0,external_wp_element_namespaceObject.createElement)(ZStackView, { ...otherProps,
className: className,
isLayered: isLayered,
ref: forwardedRef
}, clonedChildren);
}
/**
* `ZStack` allows you to stack things along the Z-axis.
*
* ```jsx
* import { __experimentalZStack as ZStack } from '@wordpress/components';
*
* function Example() {
* return (
* <ZStack offset={ 20 } isLayered>
* <ExampleImage />
* <ExampleImage />
* <ExampleImage />
* </ZStack>
* );
* }
* ```
*/
const ZStack = contextConnect(UnconnectedZStack, 'ZStack');
/* harmony default export */ var z_stack_component = (ZStack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/navigate-regions/index.js
/**
* WordPress dependencies
*/
const defaultShortcuts = {
previous: [{
modifier: 'ctrlShift',
character: '`'
}, {
modifier: 'ctrlShift',
character: '~'
}, {
modifier: 'access',
character: 'p'
}],
next: [{
modifier: 'ctrl',
character: '`'
}, {
modifier: 'access',
character: 'n'
}]
};
function useNavigateRegions(shortcuts = defaultShortcuts) {
const ref = (0,external_wp_element_namespaceObject.useRef)(null);
const [isFocusingRegions, setIsFocusingRegions] = (0,external_wp_element_namespaceObject.useState)(false);
function focusRegion(offset) {
var _ref$current$querySel;
const regions = Array.from((_ref$current$querySel = ref.current?.querySelectorAll('[role="region"][tabindex="-1"]')) !== null && _ref$current$querySel !== void 0 ? _ref$current$querySel : []);
if (!regions.length) {
return;
}
let nextRegion = regions[0]; // Based off the current element, use closest to determine the wrapping region since this operates up the DOM. Also, match tabindex to avoid edge cases with regions we do not want.
const wrappingRegion = ref.current?.ownerDocument?.activeElement?.closest('[role="region"][tabindex="-1"]');
const selectedIndex = wrappingRegion ? regions.indexOf(wrappingRegion) : -1;
if (selectedIndex !== -1) {
let nextIndex = selectedIndex + offset;
nextIndex = nextIndex === -1 ? regions.length - 1 : nextIndex;
nextIndex = nextIndex === regions.length ? 0 : nextIndex;
nextRegion = regions[nextIndex];
}
nextRegion.focus();
setIsFocusingRegions(true);
}
const clickRef = (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onClick() {
setIsFocusingRegions(false);
}
element.addEventListener('click', onClick);
return () => {
element.removeEventListener('click', onClick);
};
}, [setIsFocusingRegions]);
return {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, clickRef]),
className: isFocusingRegions ? 'is-focusing-regions' : '',
onKeyDown(event) {
if (shortcuts.previous.some(({
modifier,
character
}) => {
return external_wp_keycodes_namespaceObject.isKeyboardEvent[modifier](event, character);
})) {
focusRegion(-1);
} else if (shortcuts.next.some(({
modifier,
character
}) => {
return external_wp_keycodes_namespaceObject.isKeyboardEvent[modifier](event, character);
})) {
focusRegion(1);
}
}
};
}
/**
* `navigateRegions` is a React [higher-order component](https://facebook.github.io/react/docs/higher-order-components.html)
* adding keyboard navigation to switch between the different DOM elements marked as "regions" (role="region").
* These regions should be focusable (By adding a tabIndex attribute for example). For better accessibility,
* these elements must be properly labelled to briefly describe the purpose of the content in the region.
* For more details, see "Landmark Roles" in the [WAI-ARIA specification](https://www.w3.org/TR/wai-aria/)
* and "Landmark Regions" in the [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/practices/landmark-regions/).
*
* ```jsx
* import { navigateRegions } from '@wordpress/components';
*
* const MyComponentWithNavigateRegions = navigateRegions( () => (
* <div>
* <div role="region" tabIndex="-1" aria-label="Header">
* Header
* </div>
* <div role="region" tabIndex="-1" aria-label="Content">
* Content
* </div>
* <div role="region" tabIndex="-1" aria-label="Sidebar">
* Sidebar
* </div>
* </div>
* ) );
* ```
*/
/* harmony default export */ var navigate_regions = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(Component => ({
shortcuts,
...props
}) => (0,external_wp_element_namespaceObject.createElement)("div", { ...useNavigateRegions(shortcuts)
}, (0,external_wp_element_namespaceObject.createElement)(Component, { ...props
})), 'navigateRegions'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-constrained-tabbing/index.js
/**
* WordPress dependencies
*/
/**
* `withConstrainedTabbing` is a React [higher-order component](https://facebook.github.io/react/docs/higher-order-components.html)
* adding the ability to constrain keyboard navigation with the Tab key within a component.
* For accessibility reasons, some UI components need to constrain Tab navigation, for example
* modal dialogs or similar UI. Use of this component is recommended only in cases where a way to
* navigate away from the wrapped component is implemented by other means, usually by pressing
* the Escape key or using a specific UI control, e.g. a "Close" button.
*/
const withConstrainedTabbing = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => function ComponentWithConstrainedTabbing(props) {
const ref = (0,external_wp_compose_namespaceObject.useConstrainedTabbing)();
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
tabIndex: -1
}, (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, { ...props
}));
}, 'withConstrainedTabbing');
/* harmony default export */ var with_constrained_tabbing = (withConstrainedTabbing);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-fallback-styles/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/* harmony default export */ var with_fallback_styles = (mapNodeToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => {
return class extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.nodeRef = this.props.node;
this.state = {
fallbackStyles: undefined,
grabStylesCompleted: false
};
this.bindRef = this.bindRef.bind(this);
}
bindRef(node) {
if (!node) {
return;
}
this.nodeRef = node;
}
componentDidMount() {
this.grabFallbackStyles();
}
componentDidUpdate() {
this.grabFallbackStyles();
}
grabFallbackStyles() {
const {
grabStylesCompleted,
fallbackStyles
} = this.state;
if (this.nodeRef && !grabStylesCompleted) {
const newFallbackStyles = mapNodeToProps(this.nodeRef, this.props);
if (!es6_default()(newFallbackStyles, fallbackStyles)) {
this.setState({
fallbackStyles: newFallbackStyles,
grabStylesCompleted: Object.values(newFallbackStyles).every(Boolean)
});
}
}
}
render() {
const wrappedComponent = (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, { ...this.props,
...this.state.fallbackStyles
});
return this.props.node ? wrappedComponent : (0,external_wp_element_namespaceObject.createElement)("div", {
ref: this.bindRef
}, " ", wrappedComponent, " ");
}
};
}, 'withFallbackStyles'));
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-filters/index.js
/**
* WordPress dependencies
*/
const ANIMATION_FRAME_PERIOD = 16;
/**
* Creates a higher-order component which adds filtering capability to the
* wrapped component. Filters get applied when the original component is about
* to be mounted. When a filter is added or removed that matches the hook name,
* the wrapped component re-renders.
*
* @param hookName Hook name exposed to be used by filters.
*
* @return Higher-order component factory.
*
* ```jsx
* import { withFilters } from '@wordpress/components';
* import { addFilter } from '@wordpress/hooks';
*
* const MyComponent = ( { title } ) => <h1>{ title }</h1>;
*
* const ComponentToAppend = () => <div>Appended component</div>;
*
* function withComponentAppended( FilteredComponent ) {
* return ( props ) => (
* <>
* <FilteredComponent { ...props } />
* <ComponentToAppend />
* </>
* );
* }
*
* addFilter(
* 'MyHookName',
* 'my-plugin/with-component-appended',
* withComponentAppended
* );
*
* const MyComponentWithFilters = withFilters( 'MyHookName' )( MyComponent );
* ```
*/
function withFilters(hookName) {
return (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => {
const namespace = 'core/with-filters/' + hookName;
/**
* The component definition with current filters applied. Each instance
* reuse this shared reference as an optimization to avoid excessive
* calls to `applyFilters` when many instances exist.
*/
let FilteredComponent;
/**
* Initializes the FilteredComponent variable once, if not already
* assigned. Subsequent calls are effectively a noop.
*/
function ensureFilteredComponent() {
if (FilteredComponent === undefined) {
FilteredComponent = (0,external_wp_hooks_namespaceObject.applyFilters)(hookName, OriginalComponent);
}
}
class FilteredComponentRenderer extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
ensureFilteredComponent();
}
componentDidMount() {
FilteredComponentRenderer.instances.push(this); // If there were previously no mounted instances for components
// filtered on this hook, add the hook handler.
if (FilteredComponentRenderer.instances.length === 1) {
(0,external_wp_hooks_namespaceObject.addAction)('hookRemoved', namespace, onHooksUpdated);
(0,external_wp_hooks_namespaceObject.addAction)('hookAdded', namespace, onHooksUpdated);
}
}
componentWillUnmount() {
FilteredComponentRenderer.instances = FilteredComponentRenderer.instances.filter(instance => instance !== this); // If this was the last of the mounted components filtered on
// this hook, remove the hook handler.
if (FilteredComponentRenderer.instances.length === 0) {
(0,external_wp_hooks_namespaceObject.removeAction)('hookRemoved', namespace);
(0,external_wp_hooks_namespaceObject.removeAction)('hookAdded', namespace);
}
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(FilteredComponent, { ...this.props
});
}
}
FilteredComponentRenderer.instances = [];
/**
* Updates the FilteredComponent definition, forcing a render for each
* mounted instance. This occurs a maximum of once per animation frame.
*/
const throttledForceUpdate = (0,external_wp_compose_namespaceObject.debounce)(() => {
// Recreate the filtered component, only after delay so that it's
// computed once, even if many filters added.
FilteredComponent = (0,external_wp_hooks_namespaceObject.applyFilters)(hookName, OriginalComponent); // Force each instance to render.
FilteredComponentRenderer.instances.forEach(instance => {
instance.forceUpdate();
});
}, ANIMATION_FRAME_PERIOD);
/**
* When a filter is added or removed for the matching hook name, each
* mounted instance should re-render with the new filters having been
* applied to the original component.
*
* @param updatedHookName Name of the hook that was updated.
*/
function onHooksUpdated(updatedHookName) {
if (updatedHookName === hookName) {
throttledForceUpdate();
}
}
return FilteredComponentRenderer;
}, 'withFilters');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-focus-return/index.js
/**
* WordPress dependencies
*/
/**
* Returns true if the given object is component-like. An object is component-
* like if it is an instance of wp.element.Component, or is a function.
*
* @param object Object to test.
*
* @return Whether object is component-like.
*/
function isComponentLike(object) {
return object instanceof external_wp_element_namespaceObject.Component || typeof object === 'function';
}
/**
* Higher Order Component used to be used to wrap disposable elements like
* sidebars, modals, dropdowns. When mounting the wrapped component, we track a
* reference to the current active element so we know where to restore focus
* when the component is unmounted.
*
* @param options The component to be enhanced with
* focus return behavior, or an object
* describing the component and the
* focus return characteristics.
*
* @return Higher Order Component with the focus restauration behaviour.
*/
/* harmony default export */ var with_focus_return = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)( // @ts-expect-error TODO: Reconcile with intended `createHigherOrderComponent` types
options => {
const HoC = ({
onFocusReturn
} = {}) => WrappedComponent => {
const WithFocusReturn = props => {
const ref = (0,external_wp_compose_namespaceObject.useFocusReturn)(onFocusReturn);
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, { ...props
}));
};
return WithFocusReturn;
};
if (isComponentLike(options)) {
const WrappedComponent = options;
return HoC()(WrappedComponent);
}
return HoC(options);
}, 'withFocusReturn'));
const with_focus_return_Provider = ({
children
}) => {
external_wp_deprecated_default()('wp.components.FocusReturnProvider component', {
since: '5.7',
hint: 'This provider is not used anymore. You can just remove it from your codebase'
});
return children;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-notices/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Override the default edit UI to include notices if supported.
*
* Wrapping the original component with `withNotices` encapsulates the component
* with the additional props `noticeOperations` and `noticeUI`.
*
* ```jsx
* import { withNotices, Button } from '@wordpress/components';
*
* const MyComponentWithNotices = withNotices(
* ( { noticeOperations, noticeUI } ) => {
* const addError = () =>
* noticeOperations.createErrorNotice( 'Error message' );
* return (
* <div>
* { noticeUI }
* <Button variant="secondary" onClick={ addError }>
* Add error
* </Button>
* </div>
* );
* }
* );
* ```
*
* @param OriginalComponent Original component.
*
* @return Wrapped component.
*/
/* harmony default export */ var with_notices = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => {
function Component(props, ref) {
const [noticeList, setNoticeList] = (0,external_wp_element_namespaceObject.useState)([]);
const noticeOperations = (0,external_wp_element_namespaceObject.useMemo)(() => {
const createNotice = notice => {
const noticeToAdd = notice.id ? notice : { ...notice,
id: esm_browser_v4()
};
setNoticeList(current => [...current, noticeToAdd]);
};
return {
createNotice,
createErrorNotice: msg => {
// @ts-expect-error TODO: Missing `id`, potentially a bug
createNotice({
status: 'error',
content: msg
});
},
removeNotice: id => {
setNoticeList(current => current.filter(notice => notice.id !== id));
},
removeAllNotices: () => {
setNoticeList([]);
}
};
}, []);
const propsOut = { ...props,
noticeList,
noticeOperations,
noticeUI: noticeList.length > 0 && (0,external_wp_element_namespaceObject.createElement)(list, {
className: "components-with-notices-ui",
notices: noticeList,
onRemove: noticeOperations.removeNotice
})
};
return isForwardRef ? (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, { ...propsOut,
ref: ref
}) : (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, { ...propsOut
});
}
let isForwardRef; // @ts-expect-error - `render` will only be present when OriginalComponent was wrapped with forwardRef().
const {
render
} = OriginalComponent; // Returns a forwardRef if OriginalComponent appears to be a forwardRef.
if (typeof render === 'function') {
isForwardRef = true;
return (0,external_wp_element_namespaceObject.forwardRef)(Component);
}
return Component;
}, 'withNotices'));
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@radix-ui/primitive/dist/index.module.js
function $e42e1063c40fb3ef$export$b9ecd428b558ff10(originalEventHandler, ourEventHandler, { checkForDefaultPrevented: checkForDefaultPrevented = true } = {}) {
return function handleEvent(event) {
originalEventHandler === null || originalEventHandler === void 0 || originalEventHandler(event);
if (checkForDefaultPrevented === false || !event.defaultPrevented) return ourEventHandler === null || ourEventHandler === void 0 ? void 0 : ourEventHandler(event);
};
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-compose-refs/dist/index.module.js
/**
* Set a given ref to a given value
* This utility takes care of different types of refs: callback refs and RefObject(s)
*/ function $6ed0406888f73fc4$var$setRef(ref, value) {
if (typeof ref === 'function') ref(value);
else if (ref !== null && ref !== undefined) ref.current = value;
}
/**
* A utility to compose multiple refs together
* Accepts callback refs and RefObject(s)
*/ function $6ed0406888f73fc4$export$43e446d32b3d21af(...refs) {
return (node)=>refs.forEach((ref)=>$6ed0406888f73fc4$var$setRef(ref, node)
)
;
}
/**
* A custom hook that composes multiple refs
* Accepts callback refs and RefObject(s)
*/ function $6ed0406888f73fc4$export$c7b2cbe3552a0d05(...refs) {
// eslint-disable-next-line react-hooks/exhaustive-deps
return (0,external_React_.useCallback)($6ed0406888f73fc4$export$43e446d32b3d21af(...refs), refs);
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-context/dist/index.module.js
function $c512c27ab02ef895$export$fd42f52fd3ae1109(rootComponentName, defaultContext) {
const Context = /*#__PURE__*/ $3bkAK$createContext(defaultContext);
function Provider(props) {
const { children: children , ...context } = props; // Only re-memoize when prop values change
// eslint-disable-next-line react-hooks/exhaustive-deps
const value = $3bkAK$useMemo(()=>context
, Object.values(context));
return /*#__PURE__*/ $3bkAK$createElement(Context.Provider, {
value: value
}, children);
}
function useContext(consumerName) {
const context = $3bkAK$useContext(Context);
if (context) return context;
if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context.
throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
}
Provider.displayName = rootComponentName + 'Provider';
return [
Provider,
useContext
];
}
/* -------------------------------------------------------------------------------------------------
* createContextScope
* -----------------------------------------------------------------------------------------------*/ function $c512c27ab02ef895$export$50c7b4e9d9f19c1(scopeName, createContextScopeDeps = []) {
let defaultContexts = [];
/* -----------------------------------------------------------------------------------------------
* createContext
* ---------------------------------------------------------------------------------------------*/ function $c512c27ab02ef895$export$fd42f52fd3ae1109(rootComponentName, defaultContext) {
const BaseContext = /*#__PURE__*/ (0,external_React_.createContext)(defaultContext);
const index = defaultContexts.length;
defaultContexts = [
...defaultContexts,
defaultContext
];
function Provider(props) {
const { scope: scope , children: children , ...context } = props;
const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index]) || BaseContext; // Only re-memoize when prop values change
// eslint-disable-next-line react-hooks/exhaustive-deps
const value = (0,external_React_.useMemo)(()=>context
, Object.values(context));
return /*#__PURE__*/ (0,external_React_.createElement)(Context.Provider, {
value: value
}, children);
}
function useContext(consumerName, scope) {
const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index]) || BaseContext;
const context = (0,external_React_.useContext)(Context);
if (context) return context;
if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context.
throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
}
Provider.displayName = rootComponentName + 'Provider';
return [
Provider,
useContext
];
}
/* -----------------------------------------------------------------------------------------------
* createScope
* ---------------------------------------------------------------------------------------------*/ const createScope = ()=>{
const scopeContexts = defaultContexts.map((defaultContext)=>{
return /*#__PURE__*/ (0,external_React_.createContext)(defaultContext);
});
return function useScope(scope) {
const contexts = (scope === null || scope === void 0 ? void 0 : scope[scopeName]) || scopeContexts;
return (0,external_React_.useMemo)(()=>({
[`__scope${scopeName}`]: {
...scope,
[scopeName]: contexts
}
})
, [
scope,
contexts
]);
};
};
createScope.scopeName = scopeName;
return [
$c512c27ab02ef895$export$fd42f52fd3ae1109,
$c512c27ab02ef895$var$composeContextScopes(createScope, ...createContextScopeDeps)
];
}
/* -------------------------------------------------------------------------------------------------
* composeContextScopes
* -----------------------------------------------------------------------------------------------*/ function $c512c27ab02ef895$var$composeContextScopes(...scopes) {
const baseScope = scopes[0];
if (scopes.length === 1) return baseScope;
const createScope1 = ()=>{
const scopeHooks = scopes.map((createScope)=>({
useScope: createScope(),
scopeName: createScope.scopeName
})
);
return function useComposedScopes(overrideScopes) {
const nextScopes1 = scopeHooks.reduce((nextScopes, { useScope: useScope , scopeName: scopeName })=>{
// We are calling a hook inside a callback which React warns against to avoid inconsistent
// renders, however, scoping doesn't have render side effects so we ignore the rule.
// eslint-disable-next-line react-hooks/rules-of-hooks
const scopeProps = useScope(overrideScopes);
const currentScope = scopeProps[`__scope${scopeName}`];
return {
...nextScopes,
...currentScope
};
}, {});
return (0,external_React_.useMemo)(()=>({
[`__scope${baseScope.scopeName}`]: nextScopes1
})
, [
nextScopes1
]);
};
};
createScope1.scopeName = baseScope.scopeName;
return createScope1;
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-use-callback-ref/dist/index.module.js
/**
* A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a
* prop or avoid re-executing effects when passed as a dependency
*/ function $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(callback) {
const callbackRef = (0,external_React_.useRef)(callback);
(0,external_React_.useEffect)(()=>{
callbackRef.current = callback;
}); // https://github.com/facebook/react/issues/19240
return (0,external_React_.useMemo)(()=>(...args)=>{
var _callbackRef$current;
return (_callbackRef$current = callbackRef.current) === null || _callbackRef$current === void 0 ? void 0 : _callbackRef$current.call(callbackRef, ...args);
}
, []);
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-use-controllable-state/dist/index.module.js
function $71cd76cc60e0454e$export$6f32135080cb4c3({ prop: prop , defaultProp: defaultProp , onChange: onChange = ()=>{} }) {
const [uncontrolledProp, setUncontrolledProp] = $71cd76cc60e0454e$var$useUncontrolledState({
defaultProp: defaultProp,
onChange: onChange
});
const isControlled = prop !== undefined;
const value1 = isControlled ? prop : uncontrolledProp;
const handleChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onChange);
const setValue = (0,external_React_.useCallback)((nextValue)=>{
if (isControlled) {
const setter = nextValue;
const value = typeof nextValue === 'function' ? setter(prop) : nextValue;
if (value !== prop) handleChange(value);
} else setUncontrolledProp(nextValue);
}, [
isControlled,
prop,
setUncontrolledProp,
handleChange
]);
return [
value1,
setValue
];
}
function $71cd76cc60e0454e$var$useUncontrolledState({ defaultProp: defaultProp , onChange: onChange }) {
const uncontrolledState = (0,external_React_.useState)(defaultProp);
const [value] = uncontrolledState;
const prevValueRef = (0,external_React_.useRef)(value);
const handleChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onChange);
(0,external_React_.useEffect)(()=>{
if (prevValueRef.current !== value) {
handleChange(value);
prevValueRef.current = value;
}
}, [
value,
prevValueRef,
handleChange
]);
return uncontrolledState;
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-slot/dist/index.module.js
/* -------------------------------------------------------------------------------------------------
* Slot
* -----------------------------------------------------------------------------------------------*/ const $5e63c961fc1ce211$export$8c6ed5c666ac1360 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { children: children , ...slotProps } = props;
const childrenArray = external_React_.Children.toArray(children);
const slottable = childrenArray.find($5e63c961fc1ce211$var$isSlottable);
if (slottable) {
// the new element to render is the one passed as a child of `Slottable`
const newElement = slottable.props.children;
const newChildren = childrenArray.map((child)=>{
if (child === slottable) {
// because the new element will be the one rendered, we are only interested
// in grabbing its children (`newElement.props.children`)
if (external_React_.Children.count(newElement) > 1) return external_React_.Children.only(null);
return /*#__PURE__*/ (0,external_React_.isValidElement)(newElement) ? newElement.props.children : null;
} else return child;
});
return /*#__PURE__*/ (0,external_React_.createElement)($5e63c961fc1ce211$var$SlotClone, extends_extends({}, slotProps, {
ref: forwardedRef
}), /*#__PURE__*/ (0,external_React_.isValidElement)(newElement) ? /*#__PURE__*/ (0,external_React_.cloneElement)(newElement, undefined, newChildren) : null);
}
return /*#__PURE__*/ (0,external_React_.createElement)($5e63c961fc1ce211$var$SlotClone, extends_extends({}, slotProps, {
ref: forwardedRef
}), children);
});
$5e63c961fc1ce211$export$8c6ed5c666ac1360.displayName = 'Slot';
/* -------------------------------------------------------------------------------------------------
* SlotClone
* -----------------------------------------------------------------------------------------------*/ const $5e63c961fc1ce211$var$SlotClone = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { children: children , ...slotProps } = props;
if (/*#__PURE__*/ (0,external_React_.isValidElement)(children)) return /*#__PURE__*/ (0,external_React_.cloneElement)(children, {
...$5e63c961fc1ce211$var$mergeProps(slotProps, children.props),
ref: $6ed0406888f73fc4$export$43e446d32b3d21af(forwardedRef, children.ref)
});
return external_React_.Children.count(children) > 1 ? external_React_.Children.only(null) : null;
});
$5e63c961fc1ce211$var$SlotClone.displayName = 'SlotClone';
/* -------------------------------------------------------------------------------------------------
* Slottable
* -----------------------------------------------------------------------------------------------*/ const $5e63c961fc1ce211$export$d9f1ccf0bdb05d45 = ({ children: children })=>{
return /*#__PURE__*/ (0,external_React_.createElement)(external_React_.Fragment, null, children);
};
/* ---------------------------------------------------------------------------------------------- */ function $5e63c961fc1ce211$var$isSlottable(child) {
return /*#__PURE__*/ (0,external_React_.isValidElement)(child) && child.type === $5e63c961fc1ce211$export$d9f1ccf0bdb05d45;
}
function $5e63c961fc1ce211$var$mergeProps(slotProps, childProps) {
// all child props should override
const overrideProps = {
...childProps
};
for(const propName in childProps){
const slotPropValue = slotProps[propName];
const childPropValue = childProps[propName];
const isHandler = /^on[A-Z]/.test(propName);
if (isHandler) {
// if the handler exists on both, we compose them
if (slotPropValue && childPropValue) overrideProps[propName] = (...args)=>{
childPropValue(...args);
slotPropValue(...args);
};
else if (slotPropValue) overrideProps[propName] = slotPropValue;
} else if (propName === 'style') overrideProps[propName] = {
...slotPropValue,
...childPropValue
};
else if (propName === 'className') overrideProps[propName] = [
slotPropValue,
childPropValue
].filter(Boolean).join(' ');
}
return {
...slotProps,
...overrideProps
};
}
const $5e63c961fc1ce211$export$be92b6f5f03c0fe9 = (/* unused pure expression or super */ null && ($5e63c961fc1ce211$export$8c6ed5c666ac1360));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-primitive/dist/index.module.js
const $8927f6f2acc4f386$var$NODES = [
'a',
'button',
'div',
'form',
'h2',
'h3',
'img',
'input',
'label',
'li',
'nav',
'ol',
'p',
'span',
'svg',
'ul'
]; // Temporary while we await merge of this fix:
// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/55396
// prettier-ignore
/* -------------------------------------------------------------------------------------------------
* Primitive
* -----------------------------------------------------------------------------------------------*/ const $8927f6f2acc4f386$export$250ffa63cdc0d034 = $8927f6f2acc4f386$var$NODES.reduce((primitive, node)=>{
const Node = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { asChild: asChild , ...primitiveProps } = props;
const Comp = asChild ? $5e63c961fc1ce211$export$8c6ed5c666ac1360 : node;
(0,external_React_.useEffect)(()=>{
window[Symbol.for('radix-ui')] = true;
}, []);
return /*#__PURE__*/ (0,external_React_.createElement)(Comp, extends_extends({}, primitiveProps, {
ref: forwardedRef
}));
});
Node.displayName = `Primitive.${node}`;
return {
...primitive,
[node]: Node
};
}, {});
/* -------------------------------------------------------------------------------------------------
* Utils
* -----------------------------------------------------------------------------------------------*/ /**
* Flush custom event dispatch
* https://github.com/radix-ui/primitives/pull/1378
*
* React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types.
*
* Internally, React prioritises events in the following order:
* - discrete
* - continuous
* - default
*
* https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350
*
* `discrete` is an important distinction as updates within these events are applied immediately.
* React however, is not able to infer the priority of custom event types due to how they are detected internally.
* Because of this, it's possible for updates from custom events to be unexpectedly batched when
* dispatched by another `discrete` event.
*
* In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch.
* This utility should be used when dispatching a custom event from within another `discrete` event, this utility
* is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event.
* For example:
*
* dispatching a known click 👎
* target.dispatchEvent(new Event(click))
*
* dispatching a custom type within a non-discrete event 👎
* onScroll={(event) => event.target.dispatchEvent(new CustomEvent(customType))}
*
* dispatching a custom type within a `discrete` event 👍
* onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(customType))}
*
* Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use
* this utility with them. This is because it's possible for those handlers to be called implicitly during render
* e.g. when focus is within a component as it is unmounted, or when managing focus on mount.
*/ function $8927f6f2acc4f386$export$6d1a0317bde7de7f(target, event) {
if (target) (0,external_ReactDOM_namespaceObject.flushSync)(()=>target.dispatchEvent(event)
);
}
/* -----------------------------------------------------------------------------------------------*/ const $8927f6f2acc4f386$export$be92b6f5f03c0fe9 = (/* unused pure expression or super */ null && ($8927f6f2acc4f386$export$250ffa63cdc0d034));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-collection/dist/index.module.js
// We have resorted to returning slots directly rather than exposing primitives that can then
// be slotted like `<CollectionItem as={Slot}>…</CollectionItem>`.
// This is because we encountered issues with generic types that cannot be statically analysed
// due to creating them dynamically via createCollection.
function $e02a7d9cb1dc128c$export$c74125a8e3af6bb2(name) {
/* -----------------------------------------------------------------------------------------------
* CollectionProvider
* ---------------------------------------------------------------------------------------------*/ const PROVIDER_NAME = name + 'CollectionProvider';
const [createCollectionContext, createCollectionScope] = $c512c27ab02ef895$export$50c7b4e9d9f19c1(PROVIDER_NAME);
const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(PROVIDER_NAME, {
collectionRef: {
current: null
},
itemMap: new Map()
});
const CollectionProvider = (props)=>{
const { scope: scope , children: children } = props;
const ref = external_React_default().useRef(null);
const itemMap = external_React_default().useRef(new Map()).current;
return /*#__PURE__*/ external_React_default().createElement(CollectionProviderImpl, {
scope: scope,
itemMap: itemMap,
collectionRef: ref
}, children);
};
/*#__PURE__*/ Object.assign(CollectionProvider, {
displayName: PROVIDER_NAME
});
/* -----------------------------------------------------------------------------------------------
* CollectionSlot
* ---------------------------------------------------------------------------------------------*/ const COLLECTION_SLOT_NAME = name + 'CollectionSlot';
const CollectionSlot = /*#__PURE__*/ external_React_default().forwardRef((props, forwardedRef)=>{
const { scope: scope , children: children } = props;
const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.collectionRef);
return /*#__PURE__*/ external_React_default().createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, {
ref: composedRefs
}, children);
});
/*#__PURE__*/ Object.assign(CollectionSlot, {
displayName: COLLECTION_SLOT_NAME
});
/* -----------------------------------------------------------------------------------------------
* CollectionItem
* ---------------------------------------------------------------------------------------------*/ const ITEM_SLOT_NAME = name + 'CollectionItemSlot';
const ITEM_DATA_ATTR = 'data-radix-collection-item';
const CollectionItemSlot = /*#__PURE__*/ external_React_default().forwardRef((props, forwardedRef)=>{
const { scope: scope , children: children , ...itemData } = props;
const ref = external_React_default().useRef(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
const context = useCollectionContext(ITEM_SLOT_NAME, scope);
external_React_default().useEffect(()=>{
context.itemMap.set(ref, {
ref: ref,
...itemData
});
return ()=>void context.itemMap.delete(ref)
;
});
return /*#__PURE__*/ external_React_default().createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, {
[ITEM_DATA_ATTR]: '',
ref: composedRefs
}, children);
});
/*#__PURE__*/ Object.assign(CollectionItemSlot, {
displayName: ITEM_SLOT_NAME
});
/* -----------------------------------------------------------------------------------------------
* useCollection
* ---------------------------------------------------------------------------------------------*/ function useCollection(scope) {
const context = useCollectionContext(name + 'CollectionConsumer', scope);
const getItems = external_React_default().useCallback(()=>{
const collectionNode = context.collectionRef.current;
if (!collectionNode) return [];
const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
const items = Array.from(context.itemMap.values());
const orderedItems = items.sort((a, b)=>orderedNodes.indexOf(a.ref.current) - orderedNodes.indexOf(b.ref.current)
);
return orderedItems;
}, [
context.collectionRef,
context.itemMap
]);
return getItems;
}
return [
{
Provider: CollectionProvider,
Slot: CollectionSlot,
ItemSlot: CollectionItemSlot
},
useCollection,
createCollectionScope
];
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-direction/dist/index.module.js
const $f631663db3294ace$var$DirectionContext = /*#__PURE__*/ (0,external_React_.createContext)(undefined);
/* -------------------------------------------------------------------------------------------------
* Direction
* -----------------------------------------------------------------------------------------------*/ const $f631663db3294ace$export$c760c09fdd558351 = (props)=>{
const { dir: dir , children: children } = props;
return /*#__PURE__*/ $7Gjcd$createElement($f631663db3294ace$var$DirectionContext.Provider, {
value: dir
}, children);
};
/* -----------------------------------------------------------------------------------------------*/ function $f631663db3294ace$export$b39126d51d94e6f3(localDir) {
const globalDir = (0,external_React_.useContext)($f631663db3294ace$var$DirectionContext);
return localDir || globalDir || 'ltr';
}
const $f631663db3294ace$export$2881499e37b75b9a = (/* unused pure expression or super */ null && ($f631663db3294ace$export$c760c09fdd558351));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-use-escape-keydown/dist/index.module.js
/**
* Listens for when the escape key is down
*/ function $addc16e1bbe58fd0$export$3a72a57244d6e765(onEscapeKeyDownProp, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) {
const onEscapeKeyDown = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onEscapeKeyDownProp);
(0,external_React_.useEffect)(()=>{
const handleKeyDown = (event)=>{
if (event.key === 'Escape') onEscapeKeyDown(event);
};
ownerDocument.addEventListener('keydown', handleKeyDown);
return ()=>ownerDocument.removeEventListener('keydown', handleKeyDown)
;
}, [
onEscapeKeyDown,
ownerDocument
]);
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-dismissable-layer/dist/index.module.js
/* -------------------------------------------------------------------------------------------------
* DismissableLayer
* -----------------------------------------------------------------------------------------------*/ const $5cb92bef7577960e$var$DISMISSABLE_LAYER_NAME = 'DismissableLayer';
const $5cb92bef7577960e$var$CONTEXT_UPDATE = 'dismissableLayer.update';
const $5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside';
const $5cb92bef7577960e$var$FOCUS_OUTSIDE = 'dismissableLayer.focusOutside';
let $5cb92bef7577960e$var$originalBodyPointerEvents;
const $5cb92bef7577960e$var$DismissableLayerContext = /*#__PURE__*/ (0,external_React_.createContext)({
layers: new Set(),
layersWithOutsidePointerEventsDisabled: new Set(),
branches: new Set()
});
const $5cb92bef7577960e$export$177fb62ff3ec1f22 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
var _node$ownerDocument;
const { disableOutsidePointerEvents: disableOutsidePointerEvents = false , onEscapeKeyDown: onEscapeKeyDown , onPointerDownOutside: onPointerDownOutside , onFocusOutside: onFocusOutside , onInteractOutside: onInteractOutside , onDismiss: onDismiss , ...layerProps } = props;
const context = (0,external_React_.useContext)($5cb92bef7577960e$var$DismissableLayerContext);
const [node1, setNode] = (0,external_React_.useState)(null);
const ownerDocument = (_node$ownerDocument = node1 === null || node1 === void 0 ? void 0 : node1.ownerDocument) !== null && _node$ownerDocument !== void 0 ? _node$ownerDocument : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document;
const [, force] = (0,external_React_.useState)({});
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, (node)=>setNode(node)
);
const layers = Array.from(context.layers);
const [highestLayerWithOutsidePointerEventsDisabled] = [
...context.layersWithOutsidePointerEventsDisabled
].slice(-1); // prettier-ignore
const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore
const index = node1 ? layers.indexOf(node1) : -1;
const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex;
const pointerDownOutside = $5cb92bef7577960e$var$usePointerDownOutside((event)=>{
const target = event.target;
const isPointerDownOnBranch = [
...context.branches
].some((branch)=>branch.contains(target)
);
if (!isPointerEventsEnabled || isPointerDownOnBranch) return;
onPointerDownOutside === null || onPointerDownOutside === void 0 || onPointerDownOutside(event);
onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event);
if (!event.defaultPrevented) onDismiss === null || onDismiss === void 0 || onDismiss();
}, ownerDocument);
const focusOutside = $5cb92bef7577960e$var$useFocusOutside((event)=>{
const target = event.target;
const isFocusInBranch = [
...context.branches
].some((branch)=>branch.contains(target)
);
if (isFocusInBranch) return;
onFocusOutside === null || onFocusOutside === void 0 || onFocusOutside(event);
onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event);
if (!event.defaultPrevented) onDismiss === null || onDismiss === void 0 || onDismiss();
}, ownerDocument);
$addc16e1bbe58fd0$export$3a72a57244d6e765((event)=>{
const isHighestLayer = index === context.layers.size - 1;
if (!isHighestLayer) return;
onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event);
if (!event.defaultPrevented && onDismiss) {
event.preventDefault();
onDismiss();
}
}, ownerDocument);
(0,external_React_.useEffect)(()=>{
if (!node1) return;
if (disableOutsidePointerEvents) {
if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
$5cb92bef7577960e$var$originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;
ownerDocument.body.style.pointerEvents = 'none';
}
context.layersWithOutsidePointerEventsDisabled.add(node1);
}
context.layers.add(node1);
$5cb92bef7577960e$var$dispatchUpdate();
return ()=>{
if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) ownerDocument.body.style.pointerEvents = $5cb92bef7577960e$var$originalBodyPointerEvents;
};
}, [
node1,
ownerDocument,
disableOutsidePointerEvents,
context
]);
/**
* We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect
* because a change to `disableOutsidePointerEvents` would remove this layer from the stack
* and add it to the end again so the layering order wouldn't be _creation order_.
* We only want them to be removed from context stacks when unmounted.
*/ (0,external_React_.useEffect)(()=>{
return ()=>{
if (!node1) return;
context.layers.delete(node1);
context.layersWithOutsidePointerEventsDisabled.delete(node1);
$5cb92bef7577960e$var$dispatchUpdate();
};
}, [
node1,
context
]);
(0,external_React_.useEffect)(()=>{
const handleUpdate = ()=>force({})
;
document.addEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE, handleUpdate);
return ()=>document.removeEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE, handleUpdate)
;
}, []);
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({}, layerProps, {
ref: composedRefs,
style: {
pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? 'auto' : 'none' : undefined,
...props.style
},
onFocusCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocusCapture, focusOutside.onFocusCapture),
onBlurCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlurCapture, focusOutside.onBlurCapture),
onPointerDownCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture)
}));
});
/*#__PURE__*/ Object.assign($5cb92bef7577960e$export$177fb62ff3ec1f22, {
displayName: $5cb92bef7577960e$var$DISMISSABLE_LAYER_NAME
});
/* -------------------------------------------------------------------------------------------------
* DismissableLayerBranch
* -----------------------------------------------------------------------------------------------*/ const $5cb92bef7577960e$var$BRANCH_NAME = 'DismissableLayerBranch';
const $5cb92bef7577960e$export$4d5eb2109db14228 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const context = (0,external_React_.useContext)($5cb92bef7577960e$var$DismissableLayerContext);
const ref = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
(0,external_React_.useEffect)(()=>{
const node = ref.current;
if (node) {
context.branches.add(node);
return ()=>{
context.branches.delete(node);
};
}
}, [
context.branches
]);
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({}, props, {
ref: composedRefs
}));
});
/*#__PURE__*/ Object.assign($5cb92bef7577960e$export$4d5eb2109db14228, {
displayName: $5cb92bef7577960e$var$BRANCH_NAME
});
/* -----------------------------------------------------------------------------------------------*/ /**
* Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup`
* to mimic layer dismissing behaviour present in OS.
* Returns props to pass to the node we want to check for outside events.
*/ function $5cb92bef7577960e$var$usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) {
const handlePointerDownOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onPointerDownOutside);
const isPointerInsideReactTreeRef = (0,external_React_.useRef)(false);
const handleClickRef = (0,external_React_.useRef)(()=>{});
(0,external_React_.useEffect)(()=>{
const handlePointerDown = (event)=>{
if (event.target && !isPointerInsideReactTreeRef.current) {
const eventDetail = {
originalEvent: event
};
function handleAndDispatchPointerDownOutsideEvent() {
$5cb92bef7577960e$var$handleAndDispatchCustomEvent($5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, {
discrete: true
});
}
/**
* On touch devices, we need to wait for a click event because browsers implement
* a ~350ms delay between the time the user stops touching the display and when the
* browser executres events. We need to ensure we don't reactivate pointer-events within
* this timeframe otherwise the browser may execute events that should have been prevented.
*
* Additionally, this also lets us deal automatically with cancellations when a click event
* isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc.
*
* This is why we also continuously remove the previous listener, because we cannot be
* certain that it was raised, and therefore cleaned-up.
*/ if (event.pointerType === 'touch') {
ownerDocument.removeEventListener('click', handleClickRef.current);
handleClickRef.current = handleAndDispatchPointerDownOutsideEvent;
ownerDocument.addEventListener('click', handleClickRef.current, {
once: true
});
} else handleAndDispatchPointerDownOutsideEvent();
}
isPointerInsideReactTreeRef.current = false;
};
/**
* if this hook executes in a component that mounts via a `pointerdown` event, the event
* would bubble up to the document and trigger a `pointerDownOutside` event. We avoid
* this by delaying the event listener registration on the document.
* This is not React specific, but rather how the DOM works, ie:
* ```
* button.addEventListener('pointerdown', () => {
* console.log('I will log');
* document.addEventListener('pointerdown', () => {
* console.log('I will also log');
* })
* });
*/ const timerId = window.setTimeout(()=>{
ownerDocument.addEventListener('pointerdown', handlePointerDown);
}, 0);
return ()=>{
window.clearTimeout(timerId);
ownerDocument.removeEventListener('pointerdown', handlePointerDown);
ownerDocument.removeEventListener('click', handleClickRef.current);
};
}, [
ownerDocument,
handlePointerDownOutside
]);
return {
// ensures we check React component tree (not just DOM tree)
onPointerDownCapture: ()=>isPointerInsideReactTreeRef.current = true
};
}
/**
* Listens for when focus happens outside a react subtree.
* Returns props to pass to the root (node) of the subtree we want to check.
*/ function $5cb92bef7577960e$var$useFocusOutside(onFocusOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) {
const handleFocusOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onFocusOutside);
const isFocusInsideReactTreeRef = (0,external_React_.useRef)(false);
(0,external_React_.useEffect)(()=>{
const handleFocus = (event)=>{
if (event.target && !isFocusInsideReactTreeRef.current) {
const eventDetail = {
originalEvent: event
};
$5cb92bef7577960e$var$handleAndDispatchCustomEvent($5cb92bef7577960e$var$FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {
discrete: false
});
}
};
ownerDocument.addEventListener('focusin', handleFocus);
return ()=>ownerDocument.removeEventListener('focusin', handleFocus)
;
}, [
ownerDocument,
handleFocusOutside
]);
return {
onFocusCapture: ()=>isFocusInsideReactTreeRef.current = true
,
onBlurCapture: ()=>isFocusInsideReactTreeRef.current = false
};
}
function $5cb92bef7577960e$var$dispatchUpdate() {
const event = new CustomEvent($5cb92bef7577960e$var$CONTEXT_UPDATE);
document.dispatchEvent(event);
}
function $5cb92bef7577960e$var$handleAndDispatchCustomEvent(name, handler, detail, { discrete: discrete }) {
const target = detail.originalEvent.target;
const event = new CustomEvent(name, {
bubbles: false,
cancelable: true,
detail: detail
});
if (handler) target.addEventListener(name, handler, {
once: true
});
if (discrete) $8927f6f2acc4f386$export$6d1a0317bde7de7f(target, event);
else target.dispatchEvent(event);
}
const $5cb92bef7577960e$export$be92b6f5f03c0fe9 = (/* unused pure expression or super */ null && ($5cb92bef7577960e$export$177fb62ff3ec1f22));
const $5cb92bef7577960e$export$aecb2ddcb55c95be = (/* unused pure expression or super */ null && ($5cb92bef7577960e$export$4d5eb2109db14228));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-focus-guards/dist/index.module.js
/** Number of components which have requested interest to have focus guards */ let $3db38b7d1fb3fe6a$var$count = 0;
function $3db38b7d1fb3fe6a$export$ac5b58043b79449b(props) {
$3db38b7d1fb3fe6a$export$b7ece24a22aeda8c();
return props.children;
}
/**
* Injects a pair of focus guards at the edges of the whole DOM tree
* to ensure `focusin` & `focusout` events can be caught consistently.
*/ function $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c() {
(0,external_React_.useEffect)(()=>{
var _edgeGuards$, _edgeGuards$2;
const edgeGuards = document.querySelectorAll('[data-radix-focus-guard]');
document.body.insertAdjacentElement('afterbegin', (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 ? _edgeGuards$ : $3db38b7d1fb3fe6a$var$createFocusGuard());
document.body.insertAdjacentElement('beforeend', (_edgeGuards$2 = edgeGuards[1]) !== null && _edgeGuards$2 !== void 0 ? _edgeGuards$2 : $3db38b7d1fb3fe6a$var$createFocusGuard());
$3db38b7d1fb3fe6a$var$count++;
return ()=>{
if ($3db38b7d1fb3fe6a$var$count === 1) document.querySelectorAll('[data-radix-focus-guard]').forEach((node)=>node.remove()
);
$3db38b7d1fb3fe6a$var$count--;
};
}, []);
}
function $3db38b7d1fb3fe6a$var$createFocusGuard() {
const element = document.createElement('span');
element.setAttribute('data-radix-focus-guard', '');
element.tabIndex = 0;
element.style.cssText = 'outline: none; opacity: 0; position: fixed; pointer-events: none';
return element;
}
const $3db38b7d1fb3fe6a$export$be92b6f5f03c0fe9 = (/* unused pure expression or super */ null && ($3db38b7d1fb3fe6a$export$ac5b58043b79449b));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-focus-scope/dist/index.module.js
const $d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';
const $d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';
const $d3863c46a17e8a28$var$EVENT_OPTIONS = {
bubbles: false,
cancelable: true
};
/* -------------------------------------------------------------------------------------------------
* FocusScope
* -----------------------------------------------------------------------------------------------*/ const $d3863c46a17e8a28$var$FOCUS_SCOPE_NAME = 'FocusScope';
const $d3863c46a17e8a28$export$20e40289641fbbb6 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { loop: loop = false , trapped: trapped = false , onMountAutoFocus: onMountAutoFocusProp , onUnmountAutoFocus: onUnmountAutoFocusProp , ...scopeProps } = props;
const [container1, setContainer] = (0,external_React_.useState)(null);
const onMountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onMountAutoFocusProp);
const onUnmountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onUnmountAutoFocusProp);
const lastFocusedElementRef = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, (node)=>setContainer(node)
);
const focusScope = (0,external_React_.useRef)({
paused: false,
pause () {
this.paused = true;
},
resume () {
this.paused = false;
}
}).current; // Takes care of trapping focus if focus is moved outside programmatically for example
(0,external_React_.useEffect)(()=>{
if (trapped) {
function handleFocusIn(event) {
if (focusScope.paused || !container1) return;
const target = event.target;
if (container1.contains(target)) lastFocusedElementRef.current = target;
else $d3863c46a17e8a28$var$focus(lastFocusedElementRef.current, {
select: true
});
}
function handleFocusOut(event) {
if (focusScope.paused || !container1) return;
if (!container1.contains(event.relatedTarget)) $d3863c46a17e8a28$var$focus(lastFocusedElementRef.current, {
select: true
});
}
document.addEventListener('focusin', handleFocusIn);
document.addEventListener('focusout', handleFocusOut);
return ()=>{
document.removeEventListener('focusin', handleFocusIn);
document.removeEventListener('focusout', handleFocusOut);
};
}
}, [
trapped,
container1,
focusScope.paused
]);
(0,external_React_.useEffect)(()=>{
if (container1) {
$d3863c46a17e8a28$var$focusScopesStack.add(focusScope);
const previouslyFocusedElement = document.activeElement;
const hasFocusedCandidate = container1.contains(previouslyFocusedElement);
if (!hasFocusedCandidate) {
const mountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, $d3863c46a17e8a28$var$EVENT_OPTIONS);
container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
container1.dispatchEvent(mountEvent);
if (!mountEvent.defaultPrevented) {
$d3863c46a17e8a28$var$focusFirst($d3863c46a17e8a28$var$removeLinks($d3863c46a17e8a28$var$getTabbableCandidates(container1)), {
select: true
});
if (document.activeElement === previouslyFocusedElement) $d3863c46a17e8a28$var$focus(container1);
}
}
return ()=>{
container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); // We hit a react bug (fixed in v17) with focusing in unmount.
// We need to delay the focus a little to get around it for now.
// See: https://github.com/facebook/react/issues/17894
setTimeout(()=>{
const unmountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, $d3863c46a17e8a28$var$EVENT_OPTIONS);
container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
container1.dispatchEvent(unmountEvent);
if (!unmountEvent.defaultPrevented) $d3863c46a17e8a28$var$focus(previouslyFocusedElement !== null && previouslyFocusedElement !== void 0 ? previouslyFocusedElement : document.body, {
select: true
});
// we need to remove the listener after we `dispatchEvent`
container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
$d3863c46a17e8a28$var$focusScopesStack.remove(focusScope);
}, 0);
};
}
}, [
container1,
onMountAutoFocus,
onUnmountAutoFocus,
focusScope
]); // Takes care of looping focus (when tabbing whilst at the edges)
const handleKeyDown = (0,external_React_.useCallback)((event)=>{
if (!loop && !trapped) return;
if (focusScope.paused) return;
const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;
const focusedElement = document.activeElement;
if (isTabKey && focusedElement) {
const container = event.currentTarget;
const [first, last] = $d3863c46a17e8a28$var$getTabbableEdges(container);
const hasTabbableElementsInside = first && last; // we can only wrap focus if we have tabbable edges
if (!hasTabbableElementsInside) {
if (focusedElement === container) event.preventDefault();
} else {
if (!event.shiftKey && focusedElement === last) {
event.preventDefault();
if (loop) $d3863c46a17e8a28$var$focus(first, {
select: true
});
} else if (event.shiftKey && focusedElement === first) {
event.preventDefault();
if (loop) $d3863c46a17e8a28$var$focus(last, {
select: true
});
}
}
}
}, [
loop,
trapped,
focusScope.paused
]);
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({
tabIndex: -1
}, scopeProps, {
ref: composedRefs,
onKeyDown: handleKeyDown
}));
});
/*#__PURE__*/ Object.assign($d3863c46a17e8a28$export$20e40289641fbbb6, {
displayName: $d3863c46a17e8a28$var$FOCUS_SCOPE_NAME
});
/* -------------------------------------------------------------------------------------------------
* Utils
* -----------------------------------------------------------------------------------------------*/ /**
* Attempts focusing the first element in a list of candidates.
* Stops when focus has actually moved.
*/ function $d3863c46a17e8a28$var$focusFirst(candidates, { select: select = false } = {}) {
const previouslyFocusedElement = document.activeElement;
for (const candidate of candidates){
$d3863c46a17e8a28$var$focus(candidate, {
select: select
});
if (document.activeElement !== previouslyFocusedElement) return;
}
}
/**
* Returns the first and last tabbable elements inside a container.
*/ function $d3863c46a17e8a28$var$getTabbableEdges(container) {
const candidates = $d3863c46a17e8a28$var$getTabbableCandidates(container);
const first = $d3863c46a17e8a28$var$findVisible(candidates, container);
const last = $d3863c46a17e8a28$var$findVisible(candidates.reverse(), container);
return [
first,
last
];
}
/**
* Returns a list of potential tabbable candidates.
*
* NOTE: This is only a close approximation. For example it doesn't take into account cases like when
* elements are not visible. This cannot be worked out easily by just reading a property, but rather
* necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.
*
* See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
* Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1
*/ function $d3863c46a17e8a28$var$getTabbableCandidates(container) {
const nodes = [];
const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
acceptNode: (node)=>{
const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden';
if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP; // `.tabIndex` is not the same as the `tabindex` attribute. It works on the
// runtime's understanding of tabbability, so this automatically accounts
// for any kind of element that could be tabbed to.
return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
});
while(walker.nextNode())nodes.push(walker.currentNode); // we do not take into account the order of nodes with positive `tabIndex` as it
// hinders accessibility to have tab order different from visual order.
return nodes;
}
/**
* Returns the first visible element in a list.
* NOTE: Only checks visibility up to the `container`.
*/ function $d3863c46a17e8a28$var$findVisible(elements, container) {
for (const element of elements){
// we stop checking if it's hidden at the `container` level (excluding)
if (!$d3863c46a17e8a28$var$isHidden(element, {
upTo: container
})) return element;
}
}
function $d3863c46a17e8a28$var$isHidden(node, { upTo: upTo }) {
if (getComputedStyle(node).visibility === 'hidden') return true;
while(node){
// we stop at `upTo` (excluding it)
if (upTo !== undefined && node === upTo) return false;
if (getComputedStyle(node).display === 'none') return true;
node = node.parentElement;
}
return false;
}
function $d3863c46a17e8a28$var$isSelectableInput(element) {
return element instanceof HTMLInputElement && 'select' in element;
}
function $d3863c46a17e8a28$var$focus(element, { select: select = false } = {}) {
// only focus if that element is focusable
if (element && element.focus) {
const previouslyFocusedElement = document.activeElement; // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users
element.focus({
preventScroll: true
}); // only select if its not the same element, it supports selection and we need to select
if (element !== previouslyFocusedElement && $d3863c46a17e8a28$var$isSelectableInput(element) && select) element.select();
}
}
/* -------------------------------------------------------------------------------------------------
* FocusScope stack
* -----------------------------------------------------------------------------------------------*/ const $d3863c46a17e8a28$var$focusScopesStack = $d3863c46a17e8a28$var$createFocusScopesStack();
function $d3863c46a17e8a28$var$createFocusScopesStack() {
/** A stack of focus scopes, with the active one at the top */ let stack = [];
return {
add (focusScope) {
// pause the currently active focus scope (at the top of the stack)
const activeFocusScope = stack[0];
if (focusScope !== activeFocusScope) activeFocusScope === null || activeFocusScope === void 0 || activeFocusScope.pause();
// remove in case it already exists (because we'll re-add it at the top of the stack)
stack = $d3863c46a17e8a28$var$arrayRemove(stack, focusScope);
stack.unshift(focusScope);
},
remove (focusScope) {
var _stack$;
stack = $d3863c46a17e8a28$var$arrayRemove(stack, focusScope);
(_stack$ = stack[0]) === null || _stack$ === void 0 || _stack$.resume();
}
};
}
function $d3863c46a17e8a28$var$arrayRemove(array, item) {
const updatedArray = [
...array
];
const index = updatedArray.indexOf(item);
if (index !== -1) updatedArray.splice(index, 1);
return updatedArray;
}
function $d3863c46a17e8a28$var$removeLinks(items) {
return items.filter((item)=>item.tagName !== 'A'
);
}
const $d3863c46a17e8a28$export$be92b6f5f03c0fe9 = (/* unused pure expression or super */ null && ($d3863c46a17e8a28$export$20e40289641fbbb6));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-use-layout-effect/dist/index.module.js
/**
* On the server, React emits a warning when calling `useLayoutEffect`.
* This is because neither `useLayoutEffect` nor `useEffect` run on the server.
* We use this safe version which suppresses the warning by replacing it with a noop on the server.
*
* See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
*/ const $9f79659886946c16$export$e5c5a5f917a5871c = Boolean(globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) ? external_React_.useLayoutEffect : ()=>{};
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-id/dist/index.module.js
const $1746a345f3d73bb7$var$useReactId = external_React_['useId'.toString()] || (()=>undefined
);
let $1746a345f3d73bb7$var$count = 0;
function $1746a345f3d73bb7$export$f680877a34711e37(deterministicId) {
const [id, setId] = external_React_.useState($1746a345f3d73bb7$var$useReactId()); // React versions older than 18 will have client-side ids only.
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
if (!deterministicId) setId((reactId)=>reactId !== null && reactId !== void 0 ? reactId : String($1746a345f3d73bb7$var$count++)
);
}, [
deterministicId
]);
return deterministicId || (id ? `radix-${id}` : '');
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-popper/node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs
function floating_ui_core_browser_min_t(t){return t.split("-")[0]}function dist_floating_ui_core_browser_min_e(t){return t.split("-")[1]}function dist_floating_ui_core_browser_min_n(e){return["top","bottom"].includes(floating_ui_core_browser_min_t(e))?"x":"y"}function dist_floating_ui_core_browser_min_r(t){return"y"===t?"height":"width"}function floating_ui_core_browser_min_i(i,o,a){let{reference:l,floating:s}=i;const c=l.x+l.width/2-s.width/2,f=l.y+l.height/2-s.height/2,u=dist_floating_ui_core_browser_min_n(o),m=dist_floating_ui_core_browser_min_r(u),g=l[m]/2-s[m]/2,d="x"===u;let p;switch(floating_ui_core_browser_min_t(o)){case"top":p={x:c,y:l.y-s.height};break;case"bottom":p={x:c,y:l.y+l.height};break;case"right":p={x:l.x+l.width,y:f};break;case"left":p={x:l.x-s.width,y:f};break;default:p={x:l.x,y:l.y}}switch(dist_floating_ui_core_browser_min_e(o)){case"start":p[u]-=g*(a&&d?-1:1);break;case"end":p[u]+=g*(a&&d?-1:1)}return p}const dist_floating_ui_core_browser_min_o=async(t,e,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:a=[],platform:l}=n,s=await(null==l.isRTL?void 0:l.isRTL(e));let c=await l.getElementRects({reference:t,floating:e,strategy:o}),{x:f,y:u}=floating_ui_core_browser_min_i(c,r,s),m=r,g={},d=0;for(let n=0;n<a.length;n++){const{name:p,fn:h}=a[n],{x:y,y:x,data:w,reset:v}=await h({x:f,y:u,initialPlacement:r,placement:m,strategy:o,middlewareData:g,rects:c,platform:l,elements:{reference:t,floating:e}});f=null!=y?y:f,u=null!=x?x:u,g={...g,[p]:{...g[p],...w}},v&&d<=50&&(d++,"object"==typeof v&&(v.placement&&(m=v.placement),v.rects&&(c=!0===v.rects?await l.getElementRects({reference:t,floating:e,strategy:o}):v.rects),({x:f,y:u}=floating_ui_core_browser_min_i(c,m,s))),n=-1)}return{x:f,y:u,placement:m,strategy:o,middlewareData:g}};function dist_floating_ui_core_browser_min_a(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}function floating_ui_core_browser_min_l(t){return{...t,top:t.y,left:t.x,right:t.x+t.width,bottom:t.y+t.height}}async function dist_floating_ui_core_browser_min_s(t,e){var n;void 0===e&&(e={});const{x:r,y:i,platform:o,rects:s,elements:c,strategy:f}=t,{boundary:u="clippingAncestors",rootBoundary:m="viewport",elementContext:g="floating",altBoundary:d=!1,padding:p=0}=e,h=dist_floating_ui_core_browser_min_a(p),y=c[d?"floating"===g?"reference":"floating":g],x=floating_ui_core_browser_min_l(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(y)))||n?y:y.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(c.floating)),boundary:u,rootBoundary:m,strategy:f})),w=floating_ui_core_browser_min_l(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({rect:"floating"===g?{...s.floating,x:r,y:i}:s.reference,offsetParent:await(null==o.getOffsetParent?void 0:o.getOffsetParent(c.floating)),strategy:f}):s[g]);return{top:x.top-w.top+h.top,bottom:w.bottom-x.bottom+h.bottom,left:x.left-w.left+h.left,right:w.right-x.right+h.right}}const floating_ui_core_browser_min_c=Math.min,floating_ui_core_browser_min_f=Math.max;function floating_ui_core_browser_min_u(t,e,n){return floating_ui_core_browser_min_f(t,floating_ui_core_browser_min_c(e,n))}const floating_ui_core_browser_min_m=t=>({name:"arrow",options:t,async fn(i){const{element:o,padding:l=0}=null!=t?t:{},{x:s,y:c,placement:f,rects:m,platform:g}=i;if(null==o)return{};const d=dist_floating_ui_core_browser_min_a(l),p={x:s,y:c},h=dist_floating_ui_core_browser_min_n(f),y=dist_floating_ui_core_browser_min_e(f),x=dist_floating_ui_core_browser_min_r(h),w=await g.getDimensions(o),v="y"===h?"top":"left",b="y"===h?"bottom":"right",R=m.reference[x]+m.reference[h]-p[h]-m.floating[x],A=p[h]-m.reference[h],P=await(null==g.getOffsetParent?void 0:g.getOffsetParent(o));let T=P?"y"===h?P.clientHeight||0:P.clientWidth||0:0;0===T&&(T=m.floating[x]);const O=R/2-A/2,D=d[v],L=T-w[x]-d[b],k=T/2-w[x]/2+O,E=floating_ui_core_browser_min_u(D,k,L),C=("start"===y?d[v]:d[b])>0&&k!==E&&m.reference[x]<=m.floating[x];return{[h]:p[h]-(C?k<D?D-k:L-k:0),data:{[h]:E,centerOffset:k-E}}}}),floating_ui_core_browser_min_g={left:"right",right:"left",bottom:"top",top:"bottom"};function floating_ui_core_browser_min_d(t){return t.replace(/left|right|bottom|top/g,(t=>floating_ui_core_browser_min_g[t]))}function floating_ui_core_browser_min_p(t,i,o){void 0===o&&(o=!1);const a=dist_floating_ui_core_browser_min_e(t),l=dist_floating_ui_core_browser_min_n(t),s=dist_floating_ui_core_browser_min_r(l);let c="x"===l?a===(o?"end":"start")?"right":"left":"start"===a?"bottom":"top";return i.reference[s]>i.floating[s]&&(c=floating_ui_core_browser_min_d(c)),{main:c,cross:floating_ui_core_browser_min_d(c)}}const floating_ui_core_browser_min_h={start:"end",end:"start"};function floating_ui_core_browser_min_y(t){return t.replace(/start|end/g,(t=>floating_ui_core_browser_min_h[t]))}const floating_ui_core_browser_min_x=["top","right","bottom","left"],floating_ui_core_browser_min_w=floating_ui_core_browser_min_x.reduce(((t,e)=>t.concat(e,e+"-start",e+"-end")),[]);const floating_ui_core_browser_min_v=function(n){return void 0===n&&(n={}),{name:"autoPlacement",options:n,async fn(r){var i,o,a,l,c;const{x:f,y:u,rects:m,middlewareData:g,placement:d,platform:h,elements:x}=r,{alignment:v=null,allowedPlacements:b=floating_ui_core_browser_min_w,autoAlignment:R=!0,...A}=n,P=function(n,r,i){return(n?[...i.filter((t=>dist_floating_ui_core_browser_min_e(t)===n)),...i.filter((t=>dist_floating_ui_core_browser_min_e(t)!==n))]:i.filter((e=>floating_ui_core_browser_min_t(e)===e))).filter((t=>!n||dist_floating_ui_core_browser_min_e(t)===n||!!r&&floating_ui_core_browser_min_y(t)!==t))}(v,R,b),T=await dist_floating_ui_core_browser_min_s(r,A),O=null!=(i=null==(o=g.autoPlacement)?void 0:o.index)?i:0,D=P[O];if(null==D)return{};const{main:L,cross:k}=floating_ui_core_browser_min_p(D,m,await(null==h.isRTL?void 0:h.isRTL(x.floating)));if(d!==D)return{x:f,y:u,reset:{placement:P[0]}};const E=[T[floating_ui_core_browser_min_t(D)],T[L],T[k]],C=[...null!=(a=null==(l=g.autoPlacement)?void 0:l.overflows)?a:[],{placement:D,overflows:E}],H=P[O+1];if(H)return{data:{index:O+1,overflows:C},reset:{placement:H}};const B=C.slice().sort(((t,e)=>t.overflows[0]-e.overflows[0])),V=null==(c=B.find((t=>{let{overflows:e}=t;return e.every((t=>t<=0))})))?void 0:c.placement,F=null!=V?V:B[0].placement;return F!==d?{data:{index:O+1,overflows:C},reset:{placement:F}}:{}}}};const floating_ui_core_browser_min_b=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(n){var r;const{placement:i,middlewareData:o,rects:a,initialPlacement:l,platform:c,elements:f}=n,{mainAxis:u=!0,crossAxis:m=!0,fallbackPlacements:g,fallbackStrategy:h="bestFit",flipAlignment:x=!0,...w}=e,v=floating_ui_core_browser_min_t(i),b=g||(v===l||!x?[floating_ui_core_browser_min_d(l)]:function(t){const e=floating_ui_core_browser_min_d(t);return[floating_ui_core_browser_min_y(t),e,floating_ui_core_browser_min_y(e)]}(l)),R=[l,...b],A=await dist_floating_ui_core_browser_min_s(n,w),P=[];let T=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&P.push(A[v]),m){const{main:t,cross:e}=floating_ui_core_browser_min_p(i,a,await(null==c.isRTL?void 0:c.isRTL(f.floating)));P.push(A[t],A[e])}if(T=[...T,{placement:i,overflows:P}],!P.every((t=>t<=0))){var O,D;const t=(null!=(O=null==(D=o.flip)?void 0:D.index)?O:0)+1,e=R[t];if(e)return{data:{index:t,overflows:T},reset:{placement:e}};let n="bottom";switch(h){case"bestFit":{var L;const t=null==(L=T.map((t=>[t,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:L[0].placement;t&&(n=t);break}case"initialPlacement":n=l}if(i!==n)return{reset:{placement:n}}}return{}}}};function floating_ui_core_browser_min_R(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function floating_ui_core_browser_min_A(t){return floating_ui_core_browser_min_x.some((e=>t[e]>=0))}const floating_ui_core_browser_min_P=function(t){let{strategy:e="referenceHidden",...n}=void 0===t?{}:t;return{name:"hide",async fn(t){const{rects:r}=t;switch(e){case"referenceHidden":{const e=floating_ui_core_browser_min_R(await dist_floating_ui_core_browser_min_s(t,{...n,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:floating_ui_core_browser_min_A(e)}}}case"escaped":{const e=floating_ui_core_browser_min_R(await dist_floating_ui_core_browser_min_s(t,{...n,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:floating_ui_core_browser_min_A(e)}}}default:return{}}}}};const floating_ui_core_browser_min_T=function(r){return void 0===r&&(r=0),{name:"offset",options:r,async fn(i){const{x:o,y:a}=i,l=await async function(r,i){const{placement:o,platform:a,elements:l}=r,s=await(null==a.isRTL?void 0:a.isRTL(l.floating)),c=floating_ui_core_browser_min_t(o),f=dist_floating_ui_core_browser_min_e(o),u="x"===dist_floating_ui_core_browser_min_n(o),m=["left","top"].includes(c)?-1:1,g=s&&u?-1:1,d="function"==typeof i?i(r):i;let{mainAxis:p,crossAxis:h,alignmentAxis:y}="number"==typeof d?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...d};return f&&"number"==typeof y&&(h="end"===f?-1*y:y),u?{x:h*g,y:p*m}:{x:p*m,y:h*g}}(i,r);return{x:o+l.x,y:a+l.y,data:l}}}};function floating_ui_core_browser_min_O(t){return"x"===t?"y":"x"}const floating_ui_core_browser_min_D=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(r){const{x:i,y:o,placement:a}=r,{mainAxis:l=!0,crossAxis:c=!1,limiter:f={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...m}=e,g={x:i,y:o},d=await dist_floating_ui_core_browser_min_s(r,m),p=dist_floating_ui_core_browser_min_n(floating_ui_core_browser_min_t(a)),h=floating_ui_core_browser_min_O(p);let y=g[p],x=g[h];if(l){const t="y"===p?"bottom":"right";y=floating_ui_core_browser_min_u(y+d["y"===p?"top":"left"],y,y-d[t])}if(c){const t="y"===h?"bottom":"right";x=floating_ui_core_browser_min_u(x+d["y"===h?"top":"left"],x,x-d[t])}const w=f.fn({...r,[p]:y,[h]:x});return{...w,data:{x:w.x-i,y:w.y-o}}}}},floating_ui_core_browser_min_L=function(e){return void 0===e&&(e={}),{options:e,fn(r){const{x:i,y:o,placement:a,rects:l,middlewareData:s}=r,{offset:c=0,mainAxis:f=!0,crossAxis:u=!0}=e,m={x:i,y:o},g=dist_floating_ui_core_browser_min_n(a),d=floating_ui_core_browser_min_O(g);let p=m[g],h=m[d];const y="function"==typeof c?c({...l,placement:a}):c,x="number"==typeof y?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(f){const t="y"===g?"height":"width",e=l.reference[g]-l.floating[t]+x.mainAxis,n=l.reference[g]+l.reference[t]-x.mainAxis;p<e?p=e:p>n&&(p=n)}if(u){var w,v,b,R;const e="y"===g?"width":"height",n=["top","left"].includes(floating_ui_core_browser_min_t(a)),r=l.reference[d]-l.floating[e]+(n&&null!=(w=null==(v=s.offset)?void 0:v[d])?w:0)+(n?0:x.crossAxis),i=l.reference[d]+l.reference[e]+(n?0:null!=(b=null==(R=s.offset)?void 0:R[d])?b:0)-(n?x.crossAxis:0);h<r?h=r:h>i&&(h=i)}return{[g]:p,[d]:h}}}},floating_ui_core_browser_min_k=function(n){return void 0===n&&(n={}),{name:"size",options:n,async fn(r){const{placement:i,rects:o,platform:a,elements:l}=r,{apply:c,...u}=n,m=await dist_floating_ui_core_browser_min_s(r,u),g=floating_ui_core_browser_min_t(i),d=dist_floating_ui_core_browser_min_e(i);let p,h;"top"===g||"bottom"===g?(p=g,h=d===(await(null==a.isRTL?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(h=g,p="end"===d?"top":"bottom");const y=floating_ui_core_browser_min_f(m.left,0),x=floating_ui_core_browser_min_f(m.right,0),w=floating_ui_core_browser_min_f(m.top,0),v=floating_ui_core_browser_min_f(m.bottom,0),b={availableHeight:o.floating.height-(["left","right"].includes(i)?2*(0!==w||0!==v?w+v:floating_ui_core_browser_min_f(m.top,m.bottom)):m[p]),availableWidth:o.floating.width-(["top","bottom"].includes(i)?2*(0!==y||0!==x?y+x:floating_ui_core_browser_min_f(m.left,m.right)):m[h])},R=await a.getDimensions(l.floating);null==c||c({...r,...b});const A=await a.getDimensions(l.floating);return R.width!==A.width||R.height!==A.height?{reset:{rects:!0}}:{}}}},floating_ui_core_browser_min_E=function(e){return void 0===e&&(e={}),{name:"inline",options:e,async fn(r){var i;const{placement:o,elements:s,rects:u,platform:m,strategy:g}=r,{padding:d=2,x:p,y:h}=e,y=floating_ui_core_browser_min_l(m.convertOffsetParentRelativeRectToViewportRelativeRect?await m.convertOffsetParentRelativeRectToViewportRelativeRect({rect:u.reference,offsetParent:await(null==m.getOffsetParent?void 0:m.getOffsetParent(s.floating)),strategy:g}):u.reference),x=null!=(i=await(null==m.getClientRects?void 0:m.getClientRects(s.reference)))?i:[],w=dist_floating_ui_core_browser_min_a(d);const v=await m.getElementRects({reference:{getBoundingClientRect:function(){var e;if(2===x.length&&x[0].left>x[1].right&&null!=p&&null!=h)return null!=(e=x.find((t=>p>t.left-w.left&&p<t.right+w.right&&h>t.top-w.top&&h<t.bottom+w.bottom)))?e:y;if(x.length>=2){if("x"===dist_floating_ui_core_browser_min_n(o)){const e=x[0],n=x[x.length-1],r="top"===floating_ui_core_browser_min_t(o),i=e.top,a=n.bottom,l=r?e.left:n.left,s=r?e.right:n.right;return{top:i,bottom:a,left:l,right:s,width:s-l,height:a-i,x:l,y:i}}const e="left"===floating_ui_core_browser_min_t(o),r=floating_ui_core_browser_min_f(...x.map((t=>t.right))),i=floating_ui_core_browser_min_c(...x.map((t=>t.left))),a=x.filter((t=>e?t.left===i:t.right===r)),l=a[0].top,s=a[a.length-1].bottom;return{top:l,bottom:s,left:i,right:r,width:r-i,height:s-l,x:i,y:l}}return y}},floating:s.floating,strategy:g});return u.reference.x!==v.reference.x||u.reference.y!==v.reference.y||u.reference.width!==v.reference.width||u.reference.height!==v.reference.height?{reset:{rects:v}}:{}}}};
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-popper/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs
function dist_floating_ui_dom_browser_min_n(t){return t&&t.document&&t.location&&t.alert&&t.setInterval}function dist_floating_ui_dom_browser_min_o(t){if(null==t)return window;if(!dist_floating_ui_dom_browser_min_n(t)){const e=t.ownerDocument;return e&&e.defaultView||window}return t}function dist_floating_ui_dom_browser_min_i(t){return dist_floating_ui_dom_browser_min_o(t).getComputedStyle(t)}function floating_ui_dom_browser_min_r(t){return dist_floating_ui_dom_browser_min_n(t)?"":t?(t.nodeName||"").toLowerCase():""}function dist_floating_ui_dom_browser_min_l(){const t=navigator.userAgentData;return null!=t&&t.brands?t.brands.map((t=>t.brand+"/"+t.version)).join(" "):navigator.userAgent}function dist_floating_ui_dom_browser_min_c(t){return t instanceof dist_floating_ui_dom_browser_min_o(t).HTMLElement}function dist_floating_ui_dom_browser_min_f(t){return t instanceof dist_floating_ui_dom_browser_min_o(t).Element}function floating_ui_dom_browser_min_s(t){if("undefined"==typeof ShadowRoot)return!1;return t instanceof dist_floating_ui_dom_browser_min_o(t).ShadowRoot||t instanceof ShadowRoot}function dist_floating_ui_dom_browser_min_u(t){const{overflow:e,overflowX:n,overflowY:o}=dist_floating_ui_dom_browser_min_i(t);return/auto|scroll|overlay|hidden/.test(e+o+n)}function dist_floating_ui_dom_browser_min_d(t){return["table","td","th"].includes(floating_ui_dom_browser_min_r(t))}function dist_floating_ui_dom_browser_min_h(t){const e=/firefox/i.test(dist_floating_ui_dom_browser_min_l()),n=dist_floating_ui_dom_browser_min_i(t);return"none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||["transform","perspective"].includes(n.willChange)||e&&"filter"===n.willChange||e&&!!n.filter&&"none"!==n.filter}function dist_floating_ui_dom_browser_min_a(){return!/^((?!chrome|android).)*safari/i.test(dist_floating_ui_dom_browser_min_l())}const dist_floating_ui_dom_browser_min_g=Math.min,dist_floating_ui_dom_browser_min_p=Math.max,dist_floating_ui_dom_browser_min_m=Math.round;function dist_floating_ui_dom_browser_min_w(t,e,n){var i,r,l,s;void 0===e&&(e=!1),void 0===n&&(n=!1);const u=t.getBoundingClientRect();let d=1,h=1;e&&dist_floating_ui_dom_browser_min_c(t)&&(d=t.offsetWidth>0&&dist_floating_ui_dom_browser_min_m(u.width)/t.offsetWidth||1,h=t.offsetHeight>0&&dist_floating_ui_dom_browser_min_m(u.height)/t.offsetHeight||1);const g=dist_floating_ui_dom_browser_min_f(t)?dist_floating_ui_dom_browser_min_o(t):window,p=!dist_floating_ui_dom_browser_min_a()&&n,w=(u.left+(p&&null!=(i=null==(r=g.visualViewport)?void 0:r.offsetLeft)?i:0))/d,v=(u.top+(p&&null!=(l=null==(s=g.visualViewport)?void 0:s.offsetTop)?l:0))/h,y=u.width/d,x=u.height/h;return{width:y,height:x,top:v,right:w+y,bottom:v+x,left:w,x:w,y:v}}function dist_floating_ui_dom_browser_min_v(t){return(e=t,(e instanceof dist_floating_ui_dom_browser_min_o(e).Node?t.ownerDocument:t.document)||window.document).documentElement;var e}function dist_floating_ui_dom_browser_min_y(t){return dist_floating_ui_dom_browser_min_f(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.pageXOffset,scrollTop:t.pageYOffset}}function dist_floating_ui_dom_browser_min_x(t){return dist_floating_ui_dom_browser_min_w(dist_floating_ui_dom_browser_min_v(t)).left+dist_floating_ui_dom_browser_min_y(t).scrollLeft}function dist_floating_ui_dom_browser_min_b(t,e,n){const o=dist_floating_ui_dom_browser_min_c(e),i=dist_floating_ui_dom_browser_min_v(e),l=dist_floating_ui_dom_browser_min_w(t,o&&function(t){const e=dist_floating_ui_dom_browser_min_w(t);return dist_floating_ui_dom_browser_min_m(e.width)!==t.offsetWidth||dist_floating_ui_dom_browser_min_m(e.height)!==t.offsetHeight}(e),"fixed"===n);let f={scrollLeft:0,scrollTop:0};const s={x:0,y:0};if(o||!o&&"fixed"!==n)if(("body"!==floating_ui_dom_browser_min_r(e)||dist_floating_ui_dom_browser_min_u(i))&&(f=dist_floating_ui_dom_browser_min_y(e)),dist_floating_ui_dom_browser_min_c(e)){const t=dist_floating_ui_dom_browser_min_w(e,!0);s.x=t.x+e.clientLeft,s.y=t.y+e.clientTop}else i&&(s.x=dist_floating_ui_dom_browser_min_x(i));return{x:l.left+f.scrollLeft-s.x,y:l.top+f.scrollTop-s.y,width:l.width,height:l.height}}function dist_floating_ui_dom_browser_min_L(t){return"html"===floating_ui_dom_browser_min_r(t)?t:t.assignedSlot||t.parentNode||(floating_ui_dom_browser_min_s(t)?t.host:null)||dist_floating_ui_dom_browser_min_v(t)}function dist_floating_ui_dom_browser_min_R(t){return dist_floating_ui_dom_browser_min_c(t)&&"fixed"!==getComputedStyle(t).position?t.offsetParent:null}function dist_floating_ui_dom_browser_min_T(t){const e=dist_floating_ui_dom_browser_min_o(t);let n=dist_floating_ui_dom_browser_min_R(t);for(;n&&dist_floating_ui_dom_browser_min_d(n)&&"static"===getComputedStyle(n).position;)n=dist_floating_ui_dom_browser_min_R(n);return n&&("html"===floating_ui_dom_browser_min_r(n)||"body"===floating_ui_dom_browser_min_r(n)&&"static"===getComputedStyle(n).position&&!dist_floating_ui_dom_browser_min_h(n))?e:n||function(t){let e=dist_floating_ui_dom_browser_min_L(t);for(floating_ui_dom_browser_min_s(e)&&(e=e.host);dist_floating_ui_dom_browser_min_c(e)&&!["html","body"].includes(floating_ui_dom_browser_min_r(e));){if(dist_floating_ui_dom_browser_min_h(e))return e;e=e.parentNode}return null}(t)||e}function floating_ui_dom_browser_min_W(t){if(dist_floating_ui_dom_browser_min_c(t))return{width:t.offsetWidth,height:t.offsetHeight};const e=dist_floating_ui_dom_browser_min_w(t);return{width:e.width,height:e.height}}function dist_floating_ui_dom_browser_min_E(t){const e=dist_floating_ui_dom_browser_min_L(t);return["html","body","#document"].includes(floating_ui_dom_browser_min_r(e))?t.ownerDocument.body:dist_floating_ui_dom_browser_min_c(e)&&dist_floating_ui_dom_browser_min_u(e)?e:dist_floating_ui_dom_browser_min_E(e)}function floating_ui_dom_browser_min_H(t,e){var n;void 0===e&&(e=[]);const i=dist_floating_ui_dom_browser_min_E(t),r=i===(null==(n=t.ownerDocument)?void 0:n.body),l=dist_floating_ui_dom_browser_min_o(i),c=r?[l].concat(l.visualViewport||[],dist_floating_ui_dom_browser_min_u(i)?i:[]):i,f=e.concat(c);return r?f:f.concat(floating_ui_dom_browser_min_H(c))}function dist_floating_ui_dom_browser_min_C(e,n,r){return"viewport"===n?floating_ui_core_browser_min_l(function(t,e){const n=dist_floating_ui_dom_browser_min_o(t),i=dist_floating_ui_dom_browser_min_v(t),r=n.visualViewport;let l=i.clientWidth,c=i.clientHeight,f=0,s=0;if(r){l=r.width,c=r.height;const t=dist_floating_ui_dom_browser_min_a();(t||!t&&"fixed"===e)&&(f=r.offsetLeft,s=r.offsetTop)}return{width:l,height:c,x:f,y:s}}(e,r)):dist_floating_ui_dom_browser_min_f(n)?function(t,e){const n=dist_floating_ui_dom_browser_min_w(t,!1,"fixed"===e),o=n.top+t.clientTop,i=n.left+t.clientLeft;return{top:o,left:i,x:i,y:o,right:i+t.clientWidth,bottom:o+t.clientHeight,width:t.clientWidth,height:t.clientHeight}}(n,r):floating_ui_core_browser_min_l(function(t){var e;const n=dist_floating_ui_dom_browser_min_v(t),o=dist_floating_ui_dom_browser_min_y(t),r=null==(e=t.ownerDocument)?void 0:e.body,l=dist_floating_ui_dom_browser_min_p(n.scrollWidth,n.clientWidth,r?r.scrollWidth:0,r?r.clientWidth:0),c=dist_floating_ui_dom_browser_min_p(n.scrollHeight,n.clientHeight,r?r.scrollHeight:0,r?r.clientHeight:0);let f=-o.scrollLeft+dist_floating_ui_dom_browser_min_x(t);const s=-o.scrollTop;return"rtl"===dist_floating_ui_dom_browser_min_i(r||n).direction&&(f+=dist_floating_ui_dom_browser_min_p(n.clientWidth,r?r.clientWidth:0)-l),{width:l,height:c,x:f,y:s}}(dist_floating_ui_dom_browser_min_v(e)))}function floating_ui_dom_browser_min_S(t){const e=floating_ui_dom_browser_min_H(t),n=["absolute","fixed"].includes(dist_floating_ui_dom_browser_min_i(t).position)&&dist_floating_ui_dom_browser_min_c(t)?dist_floating_ui_dom_browser_min_T(t):t;return dist_floating_ui_dom_browser_min_f(n)?e.filter((t=>dist_floating_ui_dom_browser_min_f(t)&&function(t,e){const n=null==e.getRootNode?void 0:e.getRootNode();if(t.contains(e))return!0;if(n&&floating_ui_dom_browser_min_s(n)){let n=e;do{if(n&&t===n)return!0;n=n.parentNode||n.host}while(n)}return!1}(t,n)&&"body"!==floating_ui_dom_browser_min_r(t))):[]}const dist_floating_ui_dom_browser_min_D={getClippingRect:function(t){let{element:e,boundary:n,rootBoundary:o,strategy:i}=t;const r=[..."clippingAncestors"===n?floating_ui_dom_browser_min_S(e):[].concat(n),o],l=r[0],c=r.reduce(((t,n)=>{const o=dist_floating_ui_dom_browser_min_C(e,n,i);return t.top=dist_floating_ui_dom_browser_min_p(o.top,t.top),t.right=dist_floating_ui_dom_browser_min_g(o.right,t.right),t.bottom=dist_floating_ui_dom_browser_min_g(o.bottom,t.bottom),t.left=dist_floating_ui_dom_browser_min_p(o.left,t.left),t}),dist_floating_ui_dom_browser_min_C(e,l,i));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},convertOffsetParentRelativeRectToViewportRelativeRect:function(t){let{rect:e,offsetParent:n,strategy:o}=t;const i=dist_floating_ui_dom_browser_min_c(n),l=dist_floating_ui_dom_browser_min_v(n);if(n===l)return e;let f={scrollLeft:0,scrollTop:0};const s={x:0,y:0};if((i||!i&&"fixed"!==o)&&(("body"!==floating_ui_dom_browser_min_r(n)||dist_floating_ui_dom_browser_min_u(l))&&(f=dist_floating_ui_dom_browser_min_y(n)),dist_floating_ui_dom_browser_min_c(n))){const t=dist_floating_ui_dom_browser_min_w(n,!0);s.x=t.x+n.clientLeft,s.y=t.y+n.clientTop}return{...e,x:e.x-f.scrollLeft+s.x,y:e.y-f.scrollTop+s.y}},isElement:dist_floating_ui_dom_browser_min_f,getDimensions:floating_ui_dom_browser_min_W,getOffsetParent:dist_floating_ui_dom_browser_min_T,getDocumentElement:dist_floating_ui_dom_browser_min_v,getElementRects:t=>{let{reference:e,floating:n,strategy:o}=t;return{reference:dist_floating_ui_dom_browser_min_b(e,dist_floating_ui_dom_browser_min_T(n),o),floating:{...floating_ui_dom_browser_min_W(n),x:0,y:0}}},getClientRects:t=>Array.from(t.getClientRects()),isRTL:t=>"rtl"===dist_floating_ui_dom_browser_min_i(t).direction};function floating_ui_dom_browser_min_N(t,e,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:l=!0,animationFrame:c=!1}=o,s=i&&!c,u=r&&!c,d=s||u?[...dist_floating_ui_dom_browser_min_f(t)?floating_ui_dom_browser_min_H(t):[],...floating_ui_dom_browser_min_H(e)]:[];d.forEach((t=>{s&&t.addEventListener("scroll",n,{passive:!0}),u&&t.addEventListener("resize",n)}));let h,a=null;if(l){let o=!0;a=new ResizeObserver((()=>{o||n(),o=!1})),dist_floating_ui_dom_browser_min_f(t)&&!c&&a.observe(t),a.observe(e)}let g=c?dist_floating_ui_dom_browser_min_w(t):null;return c&&function e(){const o=dist_floating_ui_dom_browser_min_w(t);!g||o.x===g.x&&o.y===g.y&&o.width===g.width&&o.height===g.height||n();g=o,h=requestAnimationFrame(e)}(),n(),()=>{var t;d.forEach((t=>{s&&t.removeEventListener("scroll",n),u&&t.removeEventListener("resize",n)})),null==(t=a)||t.disconnect(),a=null,c&&cancelAnimationFrame(h)}}const floating_ui_dom_browser_min_z=(t,n,o)=>dist_floating_ui_core_browser_min_o(t,n,{platform:dist_floating_ui_dom_browser_min_D,...o});
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-popper/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js
var floating_ui_react_dom_esm_index = typeof document !== 'undefined' ? external_React_.useLayoutEffect : external_React_.useEffect;
// Fork of `fast-deep-equal` that only does the comparisons we need and compares
// functions
function floating_ui_react_dom_esm_deepEqual(a, b) {
if (a === b) {
return true;
}
if (typeof a !== typeof b) {
return false;
}
if (typeof a === 'function' && a.toString() === b.toString()) {
return true;
}
let length, i, keys;
if (a && b && typeof a == 'object') {
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;) {
if (!floating_ui_react_dom_esm_deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) {
return false;
}
for (i = length; i-- !== 0;) {
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
return false;
}
}
for (i = length; i-- !== 0;) {
const key = keys[i];
if (key === '_owner' && a.$$typeof) {
continue;
}
if (!floating_ui_react_dom_esm_deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
return a !== a && b !== b;
}
function floating_ui_react_dom_esm_useLatestRef(value) {
const ref = external_React_.useRef(value);
floating_ui_react_dom_esm_index(() => {
ref.current = value;
});
return ref;
}
function floating_ui_react_dom_esm_useFloating(_temp) {
let {
middleware,
placement = 'bottom',
strategy = 'absolute',
whileElementsMounted
} = _temp === void 0 ? {} : _temp;
const reference = external_React_.useRef(null);
const floating = external_React_.useRef(null);
const whileElementsMountedRef = floating_ui_react_dom_esm_useLatestRef(whileElementsMounted);
const cleanupRef = external_React_.useRef(null);
const [data, setData] = external_React_.useState({
// Setting these to `null` will allow the consumer to determine if
// `computePosition()` has run yet
x: null,
y: null,
strategy,
placement,
middlewareData: {}
});
const [latestMiddleware, setLatestMiddleware] = external_React_.useState(middleware);
if (!floating_ui_react_dom_esm_deepEqual(latestMiddleware == null ? void 0 : latestMiddleware.map(_ref => {
let {
options
} = _ref;
return options;
}), middleware == null ? void 0 : middleware.map(_ref2 => {
let {
options
} = _ref2;
return options;
}))) {
setLatestMiddleware(middleware);
}
const update = external_React_.useCallback(() => {
if (!reference.current || !floating.current) {
return;
}
floating_ui_dom_browser_min_z(reference.current, floating.current, {
middleware: latestMiddleware,
placement,
strategy
}).then(data => {
if (isMountedRef.current) {
external_ReactDOM_namespaceObject.flushSync(() => {
setData(data);
});
}
});
}, [latestMiddleware, placement, strategy]);
floating_ui_react_dom_esm_index(() => {
// Skip first update
if (isMountedRef.current) {
update();
}
}, [update]);
const isMountedRef = external_React_.useRef(false);
floating_ui_react_dom_esm_index(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
const runElementMountCallback = external_React_.useCallback(() => {
if (typeof cleanupRef.current === 'function') {
cleanupRef.current();
cleanupRef.current = null;
}
if (reference.current && floating.current) {
if (whileElementsMountedRef.current) {
const cleanupFn = whileElementsMountedRef.current(reference.current, floating.current, update);
cleanupRef.current = cleanupFn;
} else {
update();
}
}
}, [update, whileElementsMountedRef]);
const setReference = external_React_.useCallback(node => {
reference.current = node;
runElementMountCallback();
}, [runElementMountCallback]);
const setFloating = external_React_.useCallback(node => {
floating.current = node;
runElementMountCallback();
}, [runElementMountCallback]);
const refs = external_React_.useMemo(() => ({
reference,
floating
}), []);
return external_React_.useMemo(() => ({ ...data,
update,
refs,
reference: setReference,
floating: setFloating
}), [data, update, refs, setReference, setFloating]);
}
/**
* Positions an inner element of the floating element such that it is centered
* to the reference element.
* This wraps the core `arrow` middleware to allow React refs as the element.
* @see https://floating-ui.com/docs/arrow
*/
const floating_ui_react_dom_esm_arrow = options => {
const {
element,
padding
} = options;
function isRef(value) {
return Object.prototype.hasOwnProperty.call(value, 'current');
}
return {
name: 'arrow',
options,
fn(args) {
if (isRef(element)) {
if (element.current != null) {
return floating_ui_core_browser_min_m({
element: element.current,
padding
}).fn(args);
}
return {};
} else if (element) {
return floating_ui_core_browser_min_m({
element,
padding
}).fn(args);
}
return {};
}
};
};
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-arrow/dist/index.module.js
/* -------------------------------------------------------------------------------------------------
* Arrow
* -----------------------------------------------------------------------------------------------*/ const $7e8f5cd07187803e$var$NAME = 'Arrow';
const $7e8f5cd07187803e$export$21b07c8f274aebd5 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { children: children , width: width = 10 , height: height = 5 , ...arrowProps } = props;
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.svg, extends_extends({}, arrowProps, {
ref: forwardedRef,
width: width,
height: height,
viewBox: "0 0 30 10",
preserveAspectRatio: "none"
}), props.asChild ? children : /*#__PURE__*/ (0,external_React_.createElement)("polygon", {
points: "0,0 30,0 15,10"
}));
});
/*#__PURE__*/ Object.assign($7e8f5cd07187803e$export$21b07c8f274aebd5, {
displayName: $7e8f5cd07187803e$var$NAME
});
/* -----------------------------------------------------------------------------------------------*/ const $7e8f5cd07187803e$export$be92b6f5f03c0fe9 = $7e8f5cd07187803e$export$21b07c8f274aebd5;
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-use-size/dist/index.module.js
function $db6c3485150b8e66$export$1ab7ae714698c4b8(element) {
const [size, setSize] = (0,external_React_.useState)(undefined);
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
if (element) {
// provide size as early as possible
setSize({
width: element.offsetWidth,
height: element.offsetHeight
});
const resizeObserver = new ResizeObserver((entries)=>{
if (!Array.isArray(entries)) return;
// Since we only observe the one element, we don't need to loop over the
// array
if (!entries.length) return;
const entry = entries[0];
let width;
let height;
if ('borderBoxSize' in entry) {
const borderSizeEntry = entry['borderBoxSize']; // iron out differences between browsers
const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;
width = borderSize['inlineSize'];
height = borderSize['blockSize'];
} else {
// for browsers that don't support `borderBoxSize`
// we calculate it ourselves to get the correct border box.
width = element.offsetWidth;
height = element.offsetHeight;
}
setSize({
width: width,
height: height
});
});
resizeObserver.observe(element, {
box: 'border-box'
});
return ()=>resizeObserver.unobserve(element)
;
} else // We only want to reset to `undefined` when the element becomes `null`,
// not if it changes to another element.
setSize(undefined);
}, [
element
]);
return size;
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-popper/dist/index.module.js
const $cf1ac5d9fe0e8206$export$36f0086da09c4b9f = (/* unused pure expression or super */ null && ([
'top',
'right',
'bottom',
'left'
]));
const $cf1ac5d9fe0e8206$export$3671ffab7b302fc9 = (/* unused pure expression or super */ null && ([
'start',
'center',
'end'
]));
/* -------------------------------------------------------------------------------------------------
* Popper
* -----------------------------------------------------------------------------------------------*/ const $cf1ac5d9fe0e8206$var$POPPER_NAME = 'Popper';
const [$cf1ac5d9fe0e8206$var$createPopperContext, $cf1ac5d9fe0e8206$export$722aac194ae923] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($cf1ac5d9fe0e8206$var$POPPER_NAME);
const [$cf1ac5d9fe0e8206$var$PopperProvider, $cf1ac5d9fe0e8206$var$usePopperContext] = $cf1ac5d9fe0e8206$var$createPopperContext($cf1ac5d9fe0e8206$var$POPPER_NAME);
const $cf1ac5d9fe0e8206$export$badac9ada3a0bdf9 = (props)=>{
const { __scopePopper: __scopePopper , children: children } = props;
const [anchor, setAnchor] = (0,external_React_.useState)(null);
return /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$var$PopperProvider, {
scope: __scopePopper,
anchor: anchor,
onAnchorChange: setAnchor
}, children);
};
/*#__PURE__*/ Object.assign($cf1ac5d9fe0e8206$export$badac9ada3a0bdf9, {
displayName: $cf1ac5d9fe0e8206$var$POPPER_NAME
});
/* -------------------------------------------------------------------------------------------------
* PopperAnchor
* -----------------------------------------------------------------------------------------------*/ const $cf1ac5d9fe0e8206$var$ANCHOR_NAME = 'PopperAnchor';
const $cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopePopper: __scopePopper , virtualRef: virtualRef , ...anchorProps } = props;
const context = $cf1ac5d9fe0e8206$var$usePopperContext($cf1ac5d9fe0e8206$var$ANCHOR_NAME, __scopePopper);
const ref = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
(0,external_React_.useEffect)(()=>{
// Consumer can anchor the popper to something that isn't
// a DOM node e.g. pointer position, so we override the
// `anchorRef` with their virtual ref in this case.
context.onAnchorChange((virtualRef === null || virtualRef === void 0 ? void 0 : virtualRef.current) || ref.current);
});
return virtualRef ? null : /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({}, anchorProps, {
ref: composedRefs
}));
});
/*#__PURE__*/ Object.assign($cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d, {
displayName: $cf1ac5d9fe0e8206$var$ANCHOR_NAME
});
/* -------------------------------------------------------------------------------------------------
* PopperContent
* -----------------------------------------------------------------------------------------------*/ const $cf1ac5d9fe0e8206$var$CONTENT_NAME = 'PopperContent';
const [$cf1ac5d9fe0e8206$var$PopperContentProvider, $cf1ac5d9fe0e8206$var$useContentContext] = $cf1ac5d9fe0e8206$var$createPopperContext($cf1ac5d9fe0e8206$var$CONTENT_NAME);
const [$cf1ac5d9fe0e8206$var$PositionContextProvider, $cf1ac5d9fe0e8206$var$usePositionContext] = $cf1ac5d9fe0e8206$var$createPopperContext($cf1ac5d9fe0e8206$var$CONTENT_NAME, {
hasParent: false,
positionUpdateFns: new Set()
});
const $cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
var _arrowSize$width, _arrowSize$height, _middlewareData$arrow, _middlewareData$arrow2, _middlewareData$arrow3, _middlewareData$hide, _middlewareData$trans, _middlewareData$trans2;
const { __scopePopper: __scopePopper , side: side = 'bottom' , sideOffset: sideOffset = 0 , align: align = 'center' , alignOffset: alignOffset = 0 , arrowPadding: arrowPadding = 0 , collisionBoundary: collisionBoundary = [] , collisionPadding: collisionPaddingProp = 0 , sticky: sticky = 'partial' , hideWhenDetached: hideWhenDetached = false , avoidCollisions: avoidCollisions = true , onPlaced: onPlaced , ...contentProps } = props;
const context = $cf1ac5d9fe0e8206$var$usePopperContext($cf1ac5d9fe0e8206$var$CONTENT_NAME, __scopePopper);
const [content, setContent] = (0,external_React_.useState)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, (node)=>setContent(node)
);
const [arrow, setArrow] = (0,external_React_.useState)(null);
const arrowSize = $db6c3485150b8e66$export$1ab7ae714698c4b8(arrow);
const arrowWidth = (_arrowSize$width = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.width) !== null && _arrowSize$width !== void 0 ? _arrowSize$width : 0;
const arrowHeight = (_arrowSize$height = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.height) !== null && _arrowSize$height !== void 0 ? _arrowSize$height : 0;
const desiredPlacement = side + (align !== 'center' ? '-' + align : '');
const collisionPadding = typeof collisionPaddingProp === 'number' ? collisionPaddingProp : {
top: 0,
right: 0,
bottom: 0,
left: 0,
...collisionPaddingProp
};
const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [
collisionBoundary
];
const hasExplicitBoundaries = boundary.length > 0;
const detectOverflowOptions = {
padding: collisionPadding,
boundary: boundary.filter($cf1ac5d9fe0e8206$var$isNotNull),
// with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
altBoundary: hasExplicitBoundaries
};
const { reference: reference , floating: floating , strategy: strategy , x: x , y: y , placement: placement , middlewareData: middlewareData , update: update } = floating_ui_react_dom_esm_useFloating({
// default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
strategy: 'fixed',
placement: desiredPlacement,
whileElementsMounted: floating_ui_dom_browser_min_N,
middleware: [
$cf1ac5d9fe0e8206$var$anchorCssProperties(),
floating_ui_core_browser_min_T({
mainAxis: sideOffset + arrowHeight,
alignmentAxis: alignOffset
}),
avoidCollisions ? floating_ui_core_browser_min_D({
mainAxis: true,
crossAxis: false,
limiter: sticky === 'partial' ? floating_ui_core_browser_min_L() : undefined,
...detectOverflowOptions
}) : undefined,
arrow ? floating_ui_react_dom_esm_arrow({
element: arrow,
padding: arrowPadding
}) : undefined,
avoidCollisions ? floating_ui_core_browser_min_b({
...detectOverflowOptions
}) : undefined,
floating_ui_core_browser_min_k({
...detectOverflowOptions,
apply: ({ elements: elements , availableWidth: width , availableHeight: height })=>{
elements.floating.style.setProperty('--radix-popper-available-width', `${width}px`);
elements.floating.style.setProperty('--radix-popper-available-height', `${height}px`);
}
}),
$cf1ac5d9fe0e8206$var$transformOrigin({
arrowWidth: arrowWidth,
arrowHeight: arrowHeight
}),
hideWhenDetached ? floating_ui_core_browser_min_P({
strategy: 'referenceHidden'
}) : undefined
].filter($cf1ac5d9fe0e8206$var$isDefined)
}); // assign the reference dynamically once `Content` has mounted so we can collocate the logic
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
reference(context.anchor);
}, [
reference,
context.anchor
]);
const isPlaced = x !== null && y !== null;
const [placedSide, placedAlign] = $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement(placement);
const handlePlaced = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onPlaced);
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
if (isPlaced) handlePlaced === null || handlePlaced === void 0 || handlePlaced();
}, [
isPlaced,
handlePlaced
]);
const arrowX = (_middlewareData$arrow = middlewareData.arrow) === null || _middlewareData$arrow === void 0 ? void 0 : _middlewareData$arrow.x;
const arrowY = (_middlewareData$arrow2 = middlewareData.arrow) === null || _middlewareData$arrow2 === void 0 ? void 0 : _middlewareData$arrow2.y;
const cannotCenterArrow = ((_middlewareData$arrow3 = middlewareData.arrow) === null || _middlewareData$arrow3 === void 0 ? void 0 : _middlewareData$arrow3.centerOffset) !== 0;
const [contentZIndex, setContentZIndex] = (0,external_React_.useState)();
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
if (content) setContentZIndex(window.getComputedStyle(content).zIndex);
}, [
content
]);
const { hasParent: hasParent , positionUpdateFns: positionUpdateFns } = $cf1ac5d9fe0e8206$var$usePositionContext($cf1ac5d9fe0e8206$var$CONTENT_NAME, __scopePopper);
const isRoot = !hasParent;
(0,external_React_.useLayoutEffect)(()=>{
if (!isRoot) {
positionUpdateFns.add(update);
return ()=>{
positionUpdateFns.delete(update);
};
}
}, [
isRoot,
positionUpdateFns,
update
]); // when nested contents are rendered in portals, they are appended out of order causing
// children to be positioned incorrectly if initially open.
// we need to re-compute the positioning once the parent has finally been placed.
// https://github.com/floating-ui/floating-ui/issues/1531
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
if (isRoot && isPlaced) Array.from(positionUpdateFns).reverse().forEach((fn)=>requestAnimationFrame(fn)
);
}, [
isRoot,
isPlaced,
positionUpdateFns
]);
const commonProps = {
'data-side': placedSide,
'data-align': placedAlign,
...contentProps,
ref: composedRefs,
style: {
...contentProps.style,
// if the PopperContent hasn't been placed yet (not all measurements done)
// we prevent animations so that users's animation don't kick in too early referring wrong sides
animation: !isPlaced ? 'none' : undefined,
// hide the content if using the hide middleware and should be hidden
opacity: (_middlewareData$hide = middlewareData.hide) !== null && _middlewareData$hide !== void 0 && _middlewareData$hide.referenceHidden ? 0 : undefined
}
};
return /*#__PURE__*/ (0,external_React_.createElement)("div", {
ref: floating,
"data-radix-popper-content-wrapper": "",
style: {
position: strategy,
left: 0,
top: 0,
transform: isPlaced ? `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)` : 'translate3d(0, -200%, 0)',
// keep off the page when measuring
minWidth: 'max-content',
zIndex: contentZIndex,
['--radix-popper-transform-origin']: [
(_middlewareData$trans = middlewareData.transformOrigin) === null || _middlewareData$trans === void 0 ? void 0 : _middlewareData$trans.x,
(_middlewareData$trans2 = middlewareData.transformOrigin) === null || _middlewareData$trans2 === void 0 ? void 0 : _middlewareData$trans2.y
].join(' ')
} // Floating UI interally calculates logical alignment based the `dir` attribute on
,
dir: props.dir
}, /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$var$PopperContentProvider, {
scope: __scopePopper,
placedSide: placedSide,
onArrowChange: setArrow,
arrowX: arrowX,
arrowY: arrowY,
shouldHideArrow: cannotCenterArrow
}, isRoot ? /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$var$PositionContextProvider, {
scope: __scopePopper,
hasParent: true,
positionUpdateFns: positionUpdateFns
}, /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, commonProps)) : /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, commonProps)));
});
/*#__PURE__*/ Object.assign($cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc, {
displayName: $cf1ac5d9fe0e8206$var$CONTENT_NAME
});
/* -------------------------------------------------------------------------------------------------
* PopperArrow
* -----------------------------------------------------------------------------------------------*/ const $cf1ac5d9fe0e8206$var$ARROW_NAME = 'PopperArrow';
const $cf1ac5d9fe0e8206$var$OPPOSITE_SIDE = {
top: 'bottom',
right: 'left',
bottom: 'top',
left: 'right'
};
const $cf1ac5d9fe0e8206$export$79d62cd4e10a3fd0 = /*#__PURE__*/ (0,external_React_.forwardRef)(function $cf1ac5d9fe0e8206$export$79d62cd4e10a3fd0(props, forwardedRef) {
const { __scopePopper: __scopePopper , ...arrowProps } = props;
const contentContext = $cf1ac5d9fe0e8206$var$useContentContext($cf1ac5d9fe0e8206$var$ARROW_NAME, __scopePopper);
const baseSide = $cf1ac5d9fe0e8206$var$OPPOSITE_SIDE[contentContext.placedSide];
return(/*#__PURE__*/ // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)
// doesn't report size as we'd expect on SVG elements.
// it reports their bounding box which is effectively the largest path inside the SVG.
(0,external_React_.createElement)("span", {
ref: contentContext.onArrowChange,
style: {
position: 'absolute',
left: contentContext.arrowX,
top: contentContext.arrowY,
[baseSide]: 0,
transformOrigin: {
top: '',
right: '0 0',
bottom: 'center 0',
left: '100% 0'
}[contentContext.placedSide],
transform: {
top: 'translateY(100%)',
right: 'translateY(50%) rotate(90deg) translateX(-50%)',
bottom: `rotate(180deg)`,
left: 'translateY(50%) rotate(-90deg) translateX(50%)'
}[contentContext.placedSide],
visibility: contentContext.shouldHideArrow ? 'hidden' : undefined
}
}, /*#__PURE__*/ (0,external_React_.createElement)($7e8f5cd07187803e$export$be92b6f5f03c0fe9, extends_extends({}, arrowProps, {
ref: forwardedRef,
style: {
...arrowProps.style,
// ensures the element can be measured correctly (mostly for if SVG)
display: 'block'
}
}))));
});
/*#__PURE__*/ Object.assign($cf1ac5d9fe0e8206$export$79d62cd4e10a3fd0, {
displayName: $cf1ac5d9fe0e8206$var$ARROW_NAME
});
/* -----------------------------------------------------------------------------------------------*/ function $cf1ac5d9fe0e8206$var$isDefined(value) {
return value !== undefined;
}
function $cf1ac5d9fe0e8206$var$isNotNull(value) {
return value !== null;
}
const $cf1ac5d9fe0e8206$var$anchorCssProperties = ()=>({
name: 'anchorCssProperties',
fn (data) {
const { rects: rects , elements: elements } = data;
const { width: width , height: height } = rects.reference;
elements.floating.style.setProperty('--radix-popper-anchor-width', `${width}px`);
elements.floating.style.setProperty('--radix-popper-anchor-height', `${height}px`);
return {};
}
})
;
const $cf1ac5d9fe0e8206$var$transformOrigin = (options)=>({
name: 'transformOrigin',
options: options,
fn (data) {
var _middlewareData$arrow4, _middlewareData$arrow5, _middlewareData$arrow6, _middlewareData$arrow7, _middlewareData$arrow8;
const { placement: placement , rects: rects , middlewareData: middlewareData } = data;
const cannotCenterArrow = ((_middlewareData$arrow4 = middlewareData.arrow) === null || _middlewareData$arrow4 === void 0 ? void 0 : _middlewareData$arrow4.centerOffset) !== 0;
const isArrowHidden = cannotCenterArrow;
const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;
const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;
const [placedSide, placedAlign] = $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement(placement);
const noArrowAlign = {
start: '0%',
center: '50%',
end: '100%'
}[placedAlign];
const arrowXCenter = ((_middlewareData$arrow5 = (_middlewareData$arrow6 = middlewareData.arrow) === null || _middlewareData$arrow6 === void 0 ? void 0 : _middlewareData$arrow6.x) !== null && _middlewareData$arrow5 !== void 0 ? _middlewareData$arrow5 : 0) + arrowWidth / 2;
const arrowYCenter = ((_middlewareData$arrow7 = (_middlewareData$arrow8 = middlewareData.arrow) === null || _middlewareData$arrow8 === void 0 ? void 0 : _middlewareData$arrow8.y) !== null && _middlewareData$arrow7 !== void 0 ? _middlewareData$arrow7 : 0) + arrowHeight / 2;
let x = '';
let y = '';
if (placedSide === 'bottom') {
x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
y = `${-arrowHeight}px`;
} else if (placedSide === 'top') {
x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
y = `${rects.floating.height + arrowHeight}px`;
} else if (placedSide === 'right') {
x = `${-arrowHeight}px`;
y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
} else if (placedSide === 'left') {
x = `${rects.floating.width + arrowHeight}px`;
y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
}
return {
data: {
x: x,
y: y
}
};
}
})
;
function $cf1ac5d9fe0e8206$var$getSideAndAlignFromPlacement(placement) {
const [side, align = 'center'] = placement.split('-');
return [
side,
align
];
}
const $cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9 = $cf1ac5d9fe0e8206$export$badac9ada3a0bdf9;
const $cf1ac5d9fe0e8206$export$b688253958b8dfe7 = $cf1ac5d9fe0e8206$export$ecd4e1ccab6ed6d;
const $cf1ac5d9fe0e8206$export$7c6e2c02157bb7d2 = $cf1ac5d9fe0e8206$export$bc4ae5855d3c4fc;
const $cf1ac5d9fe0e8206$export$21b07c8f274aebd5 = $cf1ac5d9fe0e8206$export$79d62cd4e10a3fd0;
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-portal/dist/index.module.js
/* -------------------------------------------------------------------------------------------------
* Portal
* -----------------------------------------------------------------------------------------------*/ const $f1701beae083dbae$var$PORTAL_NAME = 'Portal';
const $f1701beae083dbae$export$602eac185826482c = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
var _globalThis$document;
const { container: container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body , ...portalProps } = props;
return container ? /*#__PURE__*/ external_ReactDOM_default().createPortal(/*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({}, portalProps, {
ref: forwardedRef
})), container) : null;
});
/*#__PURE__*/ Object.assign($f1701beae083dbae$export$602eac185826482c, {
displayName: $f1701beae083dbae$var$PORTAL_NAME
});
/* -----------------------------------------------------------------------------------------------*/ const $f1701beae083dbae$export$be92b6f5f03c0fe9 = (/* unused pure expression or super */ null && ($f1701beae083dbae$export$602eac185826482c));
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-presence/dist/index.module.js
function $fe963b355347cc68$export$3e6543de14f8614f(initialState, machine) {
return (0,external_React_.useReducer)((state, event)=>{
const nextState = machine[state][event];
return nextState !== null && nextState !== void 0 ? nextState : state;
}, initialState);
}
const $921a889cee6df7e8$export$99c2b779aa4e8b8b = (props)=>{
const { present: present , children: children } = props;
const presence = $921a889cee6df7e8$var$usePresence(present);
const child = typeof children === 'function' ? children({
present: presence.isPresent
}) : external_React_.Children.only(children);
const ref = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(presence.ref, child.ref);
const forceMount = typeof children === 'function';
return forceMount || presence.isPresent ? /*#__PURE__*/ (0,external_React_.cloneElement)(child, {
ref: ref
}) : null;
};
$921a889cee6df7e8$export$99c2b779aa4e8b8b.displayName = 'Presence';
/* -------------------------------------------------------------------------------------------------
* usePresence
* -----------------------------------------------------------------------------------------------*/ function $921a889cee6df7e8$var$usePresence(present) {
const [node1, setNode] = (0,external_React_.useState)();
const stylesRef = (0,external_React_.useRef)({});
const prevPresentRef = (0,external_React_.useRef)(present);
const prevAnimationNameRef = (0,external_React_.useRef)('none');
const initialState = present ? 'mounted' : 'unmounted';
const [state, send] = $fe963b355347cc68$export$3e6543de14f8614f(initialState, {
mounted: {
UNMOUNT: 'unmounted',
ANIMATION_OUT: 'unmountSuspended'
},
unmountSuspended: {
MOUNT: 'mounted',
ANIMATION_END: 'unmounted'
},
unmounted: {
MOUNT: 'mounted'
}
});
(0,external_React_.useEffect)(()=>{
const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(stylesRef.current);
prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none';
}, [
state
]);
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
const styles = stylesRef.current;
const wasPresent = prevPresentRef.current;
const hasPresentChanged = wasPresent !== present;
if (hasPresentChanged) {
const prevAnimationName = prevAnimationNameRef.current;
const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(styles);
if (present) send('MOUNT');
else if (currentAnimationName === 'none' || (styles === null || styles === void 0 ? void 0 : styles.display) === 'none') // If there is no exit animation or the element is hidden, animations won't run
// so we unmount instantly
send('UNMOUNT');
else {
/**
* When `present` changes to `false`, we check changes to animation-name to
* determine whether an animation has started. We chose this approach (reading
* computed styles) because there is no `animationrun` event and `animationstart`
* fires after `animation-delay` has expired which would be too late.
*/ const isAnimating = prevAnimationName !== currentAnimationName;
if (wasPresent && isAnimating) send('ANIMATION_OUT');
else send('UNMOUNT');
}
prevPresentRef.current = present;
}
}, [
present,
send
]);
$9f79659886946c16$export$e5c5a5f917a5871c(()=>{
if (node1) {
/**
* Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel`
* event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we
* make sure we only trigger ANIMATION_END for the currently active animation.
*/ const handleAnimationEnd = (event)=>{
const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(stylesRef.current);
const isCurrentAnimation = currentAnimationName.includes(event.animationName);
if (event.target === node1 && isCurrentAnimation) // With React 18 concurrency this update is applied
// a frame after the animation ends, creating a flash of visible content.
// By manually flushing we ensure they sync within a frame, removing the flash.
(0,external_ReactDOM_namespaceObject.flushSync)(()=>send('ANIMATION_END')
);
};
const handleAnimationStart = (event)=>{
if (event.target === node1) // if animation occurred, store its name as the previous animation.
prevAnimationNameRef.current = $921a889cee6df7e8$var$getAnimationName(stylesRef.current);
};
node1.addEventListener('animationstart', handleAnimationStart);
node1.addEventListener('animationcancel', handleAnimationEnd);
node1.addEventListener('animationend', handleAnimationEnd);
return ()=>{
node1.removeEventListener('animationstart', handleAnimationStart);
node1.removeEventListener('animationcancel', handleAnimationEnd);
node1.removeEventListener('animationend', handleAnimationEnd);
};
} else // Transition to the unmounted state if the node is removed prematurely.
// We avoid doing so during cleanup as the node may change but still exist.
send('ANIMATION_END');
}, [
node1,
send
]);
return {
isPresent: [
'mounted',
'unmountSuspended'
].includes(state),
ref: (0,external_React_.useCallback)((node)=>{
if (node) stylesRef.current = getComputedStyle(node);
setNode(node);
}, [])
};
}
/* -----------------------------------------------------------------------------------------------*/ function $921a889cee6df7e8$var$getAnimationName(styles) {
return (styles === null || styles === void 0 ? void 0 : styles.animationName) || 'none';
}
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-roving-focus/dist/index.module.js
const $d7bdfb9eb0fdf311$var$ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus';
const $d7bdfb9eb0fdf311$var$EVENT_OPTIONS = {
bubbles: false,
cancelable: true
};
/* -------------------------------------------------------------------------------------------------
* RovingFocusGroup
* -----------------------------------------------------------------------------------------------*/ const $d7bdfb9eb0fdf311$var$GROUP_NAME = 'RovingFocusGroup';
const [$d7bdfb9eb0fdf311$var$Collection, $d7bdfb9eb0fdf311$var$useCollection, $d7bdfb9eb0fdf311$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2($d7bdfb9eb0fdf311$var$GROUP_NAME);
const [$d7bdfb9eb0fdf311$var$createRovingFocusGroupContext, $d7bdfb9eb0fdf311$export$c7109489551a4f4] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($d7bdfb9eb0fdf311$var$GROUP_NAME, [
$d7bdfb9eb0fdf311$var$createCollectionScope
]);
const [$d7bdfb9eb0fdf311$var$RovingFocusProvider, $d7bdfb9eb0fdf311$var$useRovingFocusContext] = $d7bdfb9eb0fdf311$var$createRovingFocusGroupContext($d7bdfb9eb0fdf311$var$GROUP_NAME);
const $d7bdfb9eb0fdf311$export$8699f7c8af148338 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
return /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$var$Collection.Provider, {
scope: props.__scopeRovingFocusGroup
}, /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$var$Collection.Slot, {
scope: props.__scopeRovingFocusGroup
}, /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$var$RovingFocusGroupImpl, extends_extends({}, props, {
ref: forwardedRef
}))));
});
/*#__PURE__*/ Object.assign($d7bdfb9eb0fdf311$export$8699f7c8af148338, {
displayName: $d7bdfb9eb0fdf311$var$GROUP_NAME
});
/* -----------------------------------------------------------------------------------------------*/ const $d7bdfb9eb0fdf311$var$RovingFocusGroupImpl = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeRovingFocusGroup: __scopeRovingFocusGroup , orientation: orientation , loop: loop = false , dir: dir , currentTabStopId: currentTabStopIdProp , defaultCurrentTabStopId: defaultCurrentTabStopId , onCurrentTabStopIdChange: onCurrentTabStopIdChange , onEntryFocus: onEntryFocus , ...groupProps } = props;
const ref = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir);
const [currentTabStopId = null, setCurrentTabStopId] = $71cd76cc60e0454e$export$6f32135080cb4c3({
prop: currentTabStopIdProp,
defaultProp: defaultCurrentTabStopId,
onChange: onCurrentTabStopIdChange
});
const [isTabbingBackOut, setIsTabbingBackOut] = (0,external_React_.useState)(false);
const handleEntryFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onEntryFocus);
const getItems = $d7bdfb9eb0fdf311$var$useCollection(__scopeRovingFocusGroup);
const isClickFocusRef = (0,external_React_.useRef)(false);
const [focusableItemsCount, setFocusableItemsCount] = (0,external_React_.useState)(0);
(0,external_React_.useEffect)(()=>{
const node = ref.current;
if (node) {
node.addEventListener($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, handleEntryFocus);
return ()=>node.removeEventListener($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, handleEntryFocus)
;
}
}, [
handleEntryFocus
]);
return /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$var$RovingFocusProvider, {
scope: __scopeRovingFocusGroup,
orientation: orientation,
dir: direction,
loop: loop,
currentTabStopId: currentTabStopId,
onItemFocus: (0,external_React_.useCallback)((tabStopId)=>setCurrentTabStopId(tabStopId)
, [
setCurrentTabStopId
]),
onItemShiftTab: (0,external_React_.useCallback)(()=>setIsTabbingBackOut(true)
, []),
onFocusableItemAdd: (0,external_React_.useCallback)(()=>setFocusableItemsCount((prevCount)=>prevCount + 1
)
, []),
onFocusableItemRemove: (0,external_React_.useCallback)(()=>setFocusableItemsCount((prevCount)=>prevCount - 1
)
, [])
}, /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({
tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0,
"data-orientation": orientation
}, groupProps, {
ref: composedRefs,
style: {
outline: 'none',
...props.style
},
onMouseDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onMouseDown, ()=>{
isClickFocusRef.current = true;
}),
onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, (event)=>{
// We normally wouldn't need this check, because we already check
// that the focus is on the current target and not bubbling to it.
// We do this because Safari doesn't focus buttons when clicked, and
// instead, the wrapper will get focused and not through a bubbling event.
const isKeyboardFocus = !isClickFocusRef.current;
if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) {
const entryFocusEvent = new CustomEvent($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, $d7bdfb9eb0fdf311$var$EVENT_OPTIONS);
event.currentTarget.dispatchEvent(entryFocusEvent);
if (!entryFocusEvent.defaultPrevented) {
const items = getItems().filter((item)=>item.focusable
);
const activeItem = items.find((item)=>item.active
);
const currentItem = items.find((item)=>item.id === currentTabStopId
);
const candidateItems = [
activeItem,
currentItem,
...items
].filter(Boolean);
const candidateNodes = candidateItems.map((item)=>item.ref.current
);
$d7bdfb9eb0fdf311$var$focusFirst(candidateNodes);
}
}
isClickFocusRef.current = false;
}),
onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlur, ()=>setIsTabbingBackOut(false)
)
})));
});
/* -------------------------------------------------------------------------------------------------
* RovingFocusGroupItem
* -----------------------------------------------------------------------------------------------*/ const $d7bdfb9eb0fdf311$var$ITEM_NAME = 'RovingFocusGroupItem';
const $d7bdfb9eb0fdf311$export$ab9df7c53fe8454 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeRovingFocusGroup: __scopeRovingFocusGroup , focusable: focusable = true , active: active = false , tabStopId: tabStopId , ...itemProps } = props;
const autoId = $1746a345f3d73bb7$export$f680877a34711e37();
const id = tabStopId || autoId;
const context = $d7bdfb9eb0fdf311$var$useRovingFocusContext($d7bdfb9eb0fdf311$var$ITEM_NAME, __scopeRovingFocusGroup);
const isCurrentTabStop = context.currentTabStopId === id;
const getItems = $d7bdfb9eb0fdf311$var$useCollection(__scopeRovingFocusGroup);
const { onFocusableItemAdd: onFocusableItemAdd , onFocusableItemRemove: onFocusableItemRemove } = context;
(0,external_React_.useEffect)(()=>{
if (focusable) {
onFocusableItemAdd();
return ()=>onFocusableItemRemove()
;
}
}, [
focusable,
onFocusableItemAdd,
onFocusableItemRemove
]);
return /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$var$Collection.ItemSlot, {
scope: __scopeRovingFocusGroup,
id: id,
focusable: focusable,
active: active
}, /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, extends_extends({
tabIndex: isCurrentTabStop ? 0 : -1,
"data-orientation": context.orientation
}, itemProps, {
ref: forwardedRef,
onMouseDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onMouseDown, (event)=>{
// We prevent focusing non-focusable items on `mousedown`.
// Even though the item has tabIndex={-1}, that only means take it out of the tab order.
if (!focusable) event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also
else context.onItemFocus(id);
}),
onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, ()=>context.onItemFocus(id)
),
onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event)=>{
if (event.key === 'Tab' && event.shiftKey) {
context.onItemShiftTab();
return;
}
if (event.target !== event.currentTarget) return;
const focusIntent = $d7bdfb9eb0fdf311$var$getFocusIntent(event, context.orientation, context.dir);
if (focusIntent !== undefined) {
event.preventDefault();
const items = getItems().filter((item)=>item.focusable
);
let candidateNodes = items.map((item)=>item.ref.current
);
if (focusIntent === 'last') candidateNodes.reverse();
else if (focusIntent === 'prev' || focusIntent === 'next') {
if (focusIntent === 'prev') candidateNodes.reverse();
const currentIndex = candidateNodes.indexOf(event.currentTarget);
candidateNodes = context.loop ? $d7bdfb9eb0fdf311$var$wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1);
}
/**
* Imperative focus during keydown is risky so we prevent React's batching updates
* to avoid potential bugs. See: https://github.com/facebook/react/issues/20332
*/ setTimeout(()=>$d7bdfb9eb0fdf311$var$focusFirst(candidateNodes)
);
}
})
})));
});
/*#__PURE__*/ Object.assign($d7bdfb9eb0fdf311$export$ab9df7c53fe8454, {
displayName: $d7bdfb9eb0fdf311$var$ITEM_NAME
});
/* -----------------------------------------------------------------------------------------------*/ // prettier-ignore
const $d7bdfb9eb0fdf311$var$MAP_KEY_TO_FOCUS_INTENT = {
ArrowLeft: 'prev',
ArrowUp: 'prev',
ArrowRight: 'next',
ArrowDown: 'next',
PageUp: 'first',
Home: 'first',
PageDown: 'last',
End: 'last'
};
function $d7bdfb9eb0fdf311$var$getDirectionAwareKey(key, dir) {
if (dir !== 'rtl') return key;
return key === 'ArrowLeft' ? 'ArrowRight' : key === 'ArrowRight' ? 'ArrowLeft' : key;
}
function $d7bdfb9eb0fdf311$var$getFocusIntent(event, orientation, dir) {
const key = $d7bdfb9eb0fdf311$var$getDirectionAwareKey(event.key, dir);
if (orientation === 'vertical' && [
'ArrowLeft',
'ArrowRight'
].includes(key)) return undefined;
if (orientation === 'horizontal' && [
'ArrowUp',
'ArrowDown'
].includes(key)) return undefined;
return $d7bdfb9eb0fdf311$var$MAP_KEY_TO_FOCUS_INTENT[key];
}
function $d7bdfb9eb0fdf311$var$focusFirst(candidates) {
const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
for (const candidate of candidates){
// if focus is already where we want to go, we don't want to keep going through the candidates
if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
candidate.focus();
if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
}
}
/**
* Wraps an array around itself at a given start index
* Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`
*/ function $d7bdfb9eb0fdf311$var$wrapArray(array, startIndex) {
return array.map((_, index)=>array[(startIndex + index) % array.length]
);
}
const $d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9 = $d7bdfb9eb0fdf311$export$8699f7c8af148338;
const $d7bdfb9eb0fdf311$export$6d08773d2e66f8f2 = $d7bdfb9eb0fdf311$export$ab9df7c53fe8454;
;// CONCATENATED MODULE: ./node_modules/aria-hidden/dist/es2015/index.js
var getDefaultParent = function (originalTarget) {
if (typeof document === 'undefined') {
return null;
}
var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;
return sampleTarget.ownerDocument.body;
};
var counterMap = new WeakMap();
var uncontrolledNodes = new WeakMap();
var markerMap = {};
var lockCount = 0;
var unwrapHost = function (node) {
return node && (node.host || unwrapHost(node.parentNode));
};
var correctTargets = function (parent, targets) {
return targets
.map(function (target) {
if (parent.contains(target)) {
return target;
}
var correctedTarget = unwrapHost(target);
if (correctedTarget && parent.contains(correctedTarget)) {
return correctedTarget;
}
console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing');
return null;
})
.filter(function (x) { return Boolean(x); });
};
/**
* Marks everything except given node(or nodes) as aria-hidden
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @param {String} [controlAttribute] - html Attribute to control
* @return {Undo} undo command
*/
var applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) {
var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
if (!markerMap[markerName]) {
markerMap[markerName] = new WeakMap();
}
var markerCounter = markerMap[markerName];
var hiddenNodes = [];
var elementsToKeep = new Set();
var elementsToStop = new Set(targets);
var keep = function (el) {
if (!el || elementsToKeep.has(el)) {
return;
}
elementsToKeep.add(el);
keep(el.parentNode);
};
targets.forEach(keep);
var deep = function (parent) {
if (!parent || elementsToStop.has(parent)) {
return;
}
Array.prototype.forEach.call(parent.children, function (node) {
if (elementsToKeep.has(node)) {
deep(node);
}
else {
var attr = node.getAttribute(controlAttribute);
var alreadyHidden = attr !== null && attr !== 'false';
var counterValue = (counterMap.get(node) || 0) + 1;
var markerValue = (markerCounter.get(node) || 0) + 1;
counterMap.set(node, counterValue);
markerCounter.set(node, markerValue);
hiddenNodes.push(node);
if (counterValue === 1 && alreadyHidden) {
uncontrolledNodes.set(node, true);
}
if (markerValue === 1) {
node.setAttribute(markerName, 'true');
}
if (!alreadyHidden) {
node.setAttribute(controlAttribute, 'true');
}
}
});
};
deep(parentNode);
elementsToKeep.clear();
lockCount++;
return function () {
hiddenNodes.forEach(function (node) {
var counterValue = counterMap.get(node) - 1;
var markerValue = markerCounter.get(node) - 1;
counterMap.set(node, counterValue);
markerCounter.set(node, markerValue);
if (!counterValue) {
if (!uncontrolledNodes.has(node)) {
node.removeAttribute(controlAttribute);
}
uncontrolledNodes.delete(node);
}
if (!markerValue) {
node.removeAttribute(markerName);
}
});
lockCount--;
if (!lockCount) {
// clear
counterMap = new WeakMap();
counterMap = new WeakMap();
uncontrolledNodes = new WeakMap();
markerMap = {};
}
};
};
/**
* Marks everything except given node(or nodes) as aria-hidden
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @return {Undo} undo command
*/
var hideOthers = function (originalTarget, parentNode, markerName) {
if (markerName === void 0) { markerName = 'data-aria-hidden'; }
var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
var activeParentNode = parentNode || getDefaultParent(originalTarget);
if (!activeParentNode) {
return function () { return null; };
}
// we should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10
targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live]')));
return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden');
};
/**
* Marks everything except given node(or nodes) as inert
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @return {Undo} undo command
*/
var inertOthers = function (originalTarget, parentNode, markerName) {
if (markerName === void 0) { markerName = 'data-inert-ed'; }
var activeParentNode = parentNode || getDefaultParent(originalTarget);
if (!activeParentNode) {
return function () { return null; };
}
return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert');
};
/**
* @returns if current browser supports inert
*/
var supportsInert = function () {
return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert');
};
/**
* Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @return {Undo} undo command
*/
var suppressOthers = function (originalTarget, parentNode, markerName) {
if (markerName === void 0) { markerName = 'data-suppressed'; }
return (supportsInert() ? inertOthers : hideOthers)(originalTarget, parentNode, markerName);
};
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll-bar/dist/es2015/constants.js
var zeroRightClassName = 'right-scroll-bar-position';
var fullWidthClassName = 'width-before-scroll-bar';
var noScrollbarsClassName = 'with-scroll-bars-hidden';
/**
* Name of a CSS variable containing the amount of "hidden" scrollbar
* ! might be undefined ! use will fallback!
*/
var removedBarSizeVariable = '--removed-body-scroll-bar-size';
;// CONCATENATED MODULE: ./node_modules/use-callback-ref/dist/es2015/assignRef.js
/**
* Assigns a value for a given ref, no matter of the ref format
* @param {RefObject} ref - a callback function or ref object
* @param value - a new value
*
* @see https://github.com/theKashey/use-callback-ref#assignref
* @example
* const refObject = useRef();
* const refFn = (ref) => {....}
*
* assignRef(refObject, "refValue");
* assignRef(refFn, "refValue");
*/
function assignRef(ref, value) {
if (typeof ref === 'function') {
ref(value);
}
else if (ref) {
ref.current = value;
}
return ref;
}
;// CONCATENATED MODULE: ./node_modules/use-callback-ref/dist/es2015/useRef.js
/**
* creates a MutableRef with ref change callback
* @param initialValue - initial ref value
* @param {Function} callback - a callback to run when value changes
*
* @example
* const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue);
* ref.current = 1;
* // prints 0 -> 1
*
* @see https://reactjs.org/docs/hooks-reference.html#useref
* @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref
* @returns {MutableRefObject}
*/
function useCallbackRef(initialValue, callback) {
var ref = (0,external_React_.useState)(function () { return ({
// value
value: initialValue,
// last callback
callback: callback,
// "memoized" public interface
facade: {
get current() {
return ref.value;
},
set current(value) {
var last = ref.value;
if (last !== value) {
ref.value = value;
ref.callback(value, last);
}
},
},
}); })[0];
// update callback
ref.callback = callback;
return ref.facade;
}
;// CONCATENATED MODULE: ./node_modules/use-callback-ref/dist/es2015/useMergeRef.js
/**
* Merges two or more refs together providing a single interface to set their value
* @param {RefObject|Ref} refs
* @returns {MutableRefObject} - a new ref, which translates all changes to {refs}
*
* @see {@link mergeRefs} a version without buit-in memoization
* @see https://github.com/theKashey/use-callback-ref#usemergerefs
* @example
* const Component = React.forwardRef((props, ref) => {
* const ownRef = useRef();
* const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together
* return <div ref={domRef}>...</div>
* }
*/
function useMergeRef_useMergeRefs(refs, defaultValue) {
return useCallbackRef(defaultValue || null, function (newValue) { return refs.forEach(function (ref) { return assignRef(ref, newValue); }); });
}
;// CONCATENATED MODULE: ./node_modules/use-sidecar/dist/es2015/medium.js
function ItoI(a) {
return a;
}
function innerCreateMedium(defaults, middleware) {
if (middleware === void 0) { middleware = ItoI; }
var buffer = [];
var assigned = false;
var medium = {
read: function () {
if (assigned) {
throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.');
}
if (buffer.length) {
return buffer[buffer.length - 1];
}
return defaults;
},
useMedium: function (data) {
var item = middleware(data, assigned);
buffer.push(item);
return function () {
buffer = buffer.filter(function (x) { return x !== item; });
};
},
assignSyncMedium: function (cb) {
assigned = true;
while (buffer.length) {
var cbs = buffer;
buffer = [];
cbs.forEach(cb);
}
buffer = {
push: function (x) { return cb(x); },
filter: function () { return buffer; },
};
},
assignMedium: function (cb) {
assigned = true;
var pendingQueue = [];
if (buffer.length) {
var cbs = buffer;
buffer = [];
cbs.forEach(cb);
pendingQueue = buffer;
}
var executeQueue = function () {
var cbs = pendingQueue;
pendingQueue = [];
cbs.forEach(cb);
};
var cycle = function () { return Promise.resolve().then(executeQueue); };
cycle();
buffer = {
push: function (x) {
pendingQueue.push(x);
cycle();
},
filter: function (filter) {
pendingQueue = pendingQueue.filter(filter);
return buffer;
},
};
},
};
return medium;
}
function createMedium(defaults, middleware) {
if (middleware === void 0) { middleware = ItoI; }
return innerCreateMedium(defaults, middleware);
}
// eslint-disable-next-line @typescript-eslint/ban-types
function createSidecarMedium(options) {
if (options === void 0) { options = {}; }
var medium = innerCreateMedium(null);
medium.options = __assign({ async: true, ssr: false }, options);
return medium;
}
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/medium.js
var effectCar = createSidecarMedium();
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/UI.js
var nothing = function () {
return;
};
/**
* Removes scrollbar from the page and contain the scroll within the Lock
*/
var RemoveScroll = external_React_.forwardRef(function (props, parentRef) {
var ref = external_React_.useRef(null);
var _a = external_React_.useState({
onScrollCapture: nothing,
onWheelCapture: nothing,
onTouchMoveCapture: nothing,
}), callbacks = _a[0], setCallbacks = _a[1];
var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? 'div' : _b, rest = __rest(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]);
var SideCar = sideCar;
var containerRef = useMergeRef_useMergeRefs([ref, parentRef]);
var containerProps = __assign(__assign({}, rest), callbacks);
return (external_React_.createElement(external_React_.Fragment, null,
enabled && (external_React_.createElement(SideCar, { sideCar: effectCar, removeScrollBar: removeScrollBar, shards: shards, noIsolation: noIsolation, inert: inert, setCallbacks: setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref })),
forwardProps ? (external_React_.cloneElement(external_React_.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef }))) : (external_React_.createElement(Container, __assign({}, containerProps, { className: className, ref: containerRef }), children))));
});
RemoveScroll.defaultProps = {
enabled: true,
removeScrollBar: true,
inert: false,
};
RemoveScroll.classNames = {
fullWidth: fullWidthClassName,
zeroRight: zeroRightClassName,
};
;// CONCATENATED MODULE: ./node_modules/use-sidecar/dist/es2015/exports.js
var SideCar = function (_a) {
var sideCar = _a.sideCar, rest = __rest(_a, ["sideCar"]);
if (!sideCar) {
throw new Error('Sidecar: please provide `sideCar` property to import the right car');
}
var Target = sideCar.read();
if (!Target) {
throw new Error('Sidecar medium not found');
}
return external_React_.createElement(Target, __assign({}, rest));
};
SideCar.isSideCarExport = true;
function exportSidecar(medium, exported) {
medium.useMedium(exported);
return SideCar;
}
;// CONCATENATED MODULE: ./node_modules/get-nonce/dist/es2015/index.js
var currentNonce;
var setNonce = function (nonce) {
currentNonce = nonce;
};
var getNonce = function () {
if (currentNonce) {
return currentNonce;
}
if (true) {
return __webpack_require__.nc;
}
return undefined;
};
;// CONCATENATED MODULE: ./node_modules/react-style-singleton/dist/es2015/singleton.js
function makeStyleTag() {
if (!document)
return null;
var tag = document.createElement('style');
tag.type = 'text/css';
var nonce = getNonce();
if (nonce) {
tag.setAttribute('nonce', nonce);
}
return tag;
}
function injectStyles(tag, css) {
// @ts-ignore
if (tag.styleSheet) {
// @ts-ignore
tag.styleSheet.cssText = css;
}
else {
tag.appendChild(document.createTextNode(css));
}
}
function insertStyleTag(tag) {
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(tag);
}
var stylesheetSingleton = function () {
var counter = 0;
var stylesheet = null;
return {
add: function (style) {
if (counter == 0) {
if ((stylesheet = makeStyleTag())) {
injectStyles(stylesheet, style);
insertStyleTag(stylesheet);
}
}
counter++;
},
remove: function () {
counter--;
if (!counter && stylesheet) {
stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);
stylesheet = null;
}
},
};
};
;// CONCATENATED MODULE: ./node_modules/react-style-singleton/dist/es2015/hook.js
/**
* creates a hook to control style singleton
* @see {@link styleSingleton} for a safer component version
* @example
* ```tsx
* const useStyle = styleHookSingleton();
* ///
* useStyle('body { overflow: hidden}');
*/
var styleHookSingleton = function () {
var sheet = stylesheetSingleton();
return function (styles, isDynamic) {
external_React_.useEffect(function () {
sheet.add(styles);
return function () {
sheet.remove();
};
}, [styles && isDynamic]);
};
};
;// CONCATENATED MODULE: ./node_modules/react-style-singleton/dist/es2015/component.js
/**
* create a Component to add styles on demand
* - styles are added when first instance is mounted
* - styles are removed when the last instance is unmounted
* - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior
*/
var styleSingleton = function () {
var useStyle = styleHookSingleton();
var Sheet = function (_a) {
var styles = _a.styles, dynamic = _a.dynamic;
useStyle(styles, dynamic);
return null;
};
return Sheet;
};
;// CONCATENATED MODULE: ./node_modules/react-style-singleton/dist/es2015/index.js
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll-bar/dist/es2015/utils.js
var zeroGap = {
left: 0,
top: 0,
right: 0,
gap: 0,
};
var utils_parse = function (x) { return parseInt(x || '', 10) || 0; };
var getOffset = function (gapMode) {
var cs = window.getComputedStyle(document.body);
var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft'];
var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop'];
var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight'];
return [utils_parse(left), utils_parse(top), utils_parse(right)];
};
var getGapWidth = function (gapMode) {
if (gapMode === void 0) { gapMode = 'margin'; }
if (typeof window === 'undefined') {
return zeroGap;
}
var offsets = getOffset(gapMode);
var documentWidth = document.documentElement.clientWidth;
var windowWidth = window.innerWidth;
return {
left: offsets[0],
top: offsets[1],
right: offsets[2],
gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]),
};
};
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll-bar/dist/es2015/component.js
var Style = styleSingleton();
// important tip - once we measure scrollBar width and remove them
// we could not repeat this operation
// thus we are using style-singleton - only the first "yet correct" style will be applied.
var getStyles = function (_a, allowRelative, gapMode, important) {
var left = _a.left, top = _a.top, right = _a.right, gap = _a.gap;
if (gapMode === void 0) { gapMode = 'margin'; }
return "\n .".concat(noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([
allowRelative && "position: relative ".concat(important, ";"),
gapMode === 'margin' &&
"\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "),
gapMode === 'padding' && "padding-right: ".concat(gap, "px ").concat(important, ";"),
]
.filter(Boolean)
.join(''), "\n }\n \n .").concat(zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body {\n ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n }\n");
};
/**
* Removes page scrollbar and blocks page scroll when mounted
*/
var RemoveScrollBar = function (props) {
var noRelative = props.noRelative, noImportant = props.noImportant, _a = props.gapMode, gapMode = _a === void 0 ? 'margin' : _a;
/*
gap will be measured on every component mount
however it will be used only by the "first" invocation
due to singleton nature of <Style
*/
var gap = external_React_.useMemo(function () { return getGapWidth(gapMode); }, [gapMode]);
return external_React_.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') });
};
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll-bar/dist/es2015/index.js
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js
var passiveSupported = false;
if (typeof window !== 'undefined') {
try {
var aggresiveCapture_options = Object.defineProperty({}, 'passive', {
get: function () {
passiveSupported = true;
return true;
},
});
// @ts-ignore
window.addEventListener('test', aggresiveCapture_options, aggresiveCapture_options);
// @ts-ignore
window.removeEventListener('test', aggresiveCapture_options, aggresiveCapture_options);
}
catch (err) {
passiveSupported = false;
}
}
var nonPassive = passiveSupported ? { passive: false } : false;
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/handleScroll.js
var alwaysContainsScroll = function (node) {
// textarea will always _contain_ scroll inside self. It only can be hidden
return node.tagName === 'TEXTAREA';
};
var elementCanBeScrolled = function (node, overflow) {
var styles = window.getComputedStyle(node);
return (
// not-not-scrollable
styles[overflow] !== 'hidden' &&
// contains scroll inside self
!(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible'));
};
var elementCouldBeVScrolled = function (node) { return elementCanBeScrolled(node, 'overflowY'); };
var elementCouldBeHScrolled = function (node) { return elementCanBeScrolled(node, 'overflowX'); };
var locationCouldBeScrolled = function (axis, node) {
var current = node;
do {
// Skip over shadow root
if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) {
current = current.host;
}
var isScrollable = elementCouldBeScrolled(axis, current);
if (isScrollable) {
var _a = getScrollVariables(axis, current), s = _a[1], d = _a[2];
if (s > d) {
return true;
}
}
current = current.parentNode;
} while (current && current !== document.body);
return false;
};
var getVScrollVariables = function (_a) {
var scrollTop = _a.scrollTop, scrollHeight = _a.scrollHeight, clientHeight = _a.clientHeight;
return [
scrollTop,
scrollHeight,
clientHeight,
];
};
var getHScrollVariables = function (_a) {
var scrollLeft = _a.scrollLeft, scrollWidth = _a.scrollWidth, clientWidth = _a.clientWidth;
return [
scrollLeft,
scrollWidth,
clientWidth,
];
};
var elementCouldBeScrolled = function (axis, node) {
return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node);
};
var getScrollVariables = function (axis, node) {
return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node);
};
var getDirectionFactor = function (axis, direction) {
/**
* If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position,
* and then increasingly negative as you scroll towards the end of the content.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft
*/
return axis === 'h' && direction === 'rtl' ? -1 : 1;
};
var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) {
var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction);
var delta = directionFactor * sourceDelta;
// find scrollable target
var target = event.target;
var targetInLock = endTarget.contains(target);
var shouldCancelScroll = false;
var isDeltaPositive = delta > 0;
var availableScroll = 0;
var availableScrollTop = 0;
do {
var _a = getScrollVariables(axis, target), position = _a[0], scroll_1 = _a[1], capacity = _a[2];
var elementScroll = scroll_1 - capacity - directionFactor * position;
if (position || elementScroll) {
if (elementCouldBeScrolled(axis, target)) {
availableScroll += elementScroll;
availableScrollTop += position;
}
}
target = target.parentNode;
} while (
// portaled content
(!targetInLock && target !== document.body) ||
// self content
(targetInLock && (endTarget.contains(target) || endTarget === target)));
if (isDeltaPositive && ((noOverscroll && availableScroll === 0) || (!noOverscroll && delta > availableScroll))) {
shouldCancelScroll = true;
}
else if (!isDeltaPositive &&
((noOverscroll && availableScrollTop === 0) || (!noOverscroll && -delta > availableScrollTop))) {
shouldCancelScroll = true;
}
return shouldCancelScroll;
};
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var getTouchXY = function (event) {
return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];
};
var getDeltaXY = function (event) { return [event.deltaX, event.deltaY]; };
var extractRef = function (ref) {
return ref && 'current' in ref ? ref.current : ref;
};
var deltaCompare = function (x, y) { return x[0] === y[0] && x[1] === y[1]; };
var generateStyle = function (id) { return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); };
var SideEffect_idCounter = 0;
var lockStack = [];
function RemoveScrollSideCar(props) {
var shouldPreventQueue = external_React_.useRef([]);
var touchStartRef = external_React_.useRef([0, 0]);
var activeAxis = external_React_.useRef();
var id = external_React_.useState(SideEffect_idCounter++)[0];
var Style = external_React_.useState(function () { return styleSingleton(); })[0];
var lastProps = external_React_.useRef(props);
external_React_.useEffect(function () {
lastProps.current = props;
}, [props]);
external_React_.useEffect(function () {
if (props.inert) {
document.body.classList.add("block-interactivity-".concat(id));
var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean);
allow_1.forEach(function (el) { return el.classList.add("allow-interactivity-".concat(id)); });
return function () {
document.body.classList.remove("block-interactivity-".concat(id));
allow_1.forEach(function (el) { return el.classList.remove("allow-interactivity-".concat(id)); });
};
}
return;
}, [props.inert, props.lockRef.current, props.shards]);
var shouldCancelEvent = external_React_.useCallback(function (event, parent) {
if ('touches' in event && event.touches.length === 2) {
return !lastProps.current.allowPinchZoom;
}
var touch = getTouchXY(event);
var touchStart = touchStartRef.current;
var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0];
var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1];
var currentAxis;
var target = event.target;
var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v';
// allow horizontal touch move on Range inputs. They will not cause any scroll
if ('touches' in event && moveDirection === 'h' && target.type === 'range') {
return false;
}
var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
if (!canBeScrolledInMainDirection) {
return true;
}
if (canBeScrolledInMainDirection) {
currentAxis = moveDirection;
}
else {
currentAxis = moveDirection === 'v' ? 'h' : 'v';
canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
// other axis might be not scrollable
}
if (!canBeScrolledInMainDirection) {
return false;
}
if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) {
activeAxis.current = currentAxis;
}
if (!currentAxis) {
return true;
}
var cancelingAxis = activeAxis.current || currentAxis;
return handleScroll(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true);
}, []);
var shouldPrevent = external_React_.useCallback(function (_event) {
var event = _event;
if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) {
// not the last active
return;
}
var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event);
var sourceEvent = shouldPreventQueue.current.filter(function (e) { return e.name === event.type && e.target === event.target && deltaCompare(e.delta, delta); })[0];
// self event, and should be canceled
if (sourceEvent && sourceEvent.should) {
if (event.cancelable) {
event.preventDefault();
}
return;
}
// outside or shard event
if (!sourceEvent) {
var shardNodes = (lastProps.current.shards || [])
.map(extractRef)
.filter(Boolean)
.filter(function (node) { return node.contains(event.target); });
var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;
if (shouldStop) {
if (event.cancelable) {
event.preventDefault();
}
}
}
}, []);
var shouldCancel = external_React_.useCallback(function (name, delta, target, should) {
var event = { name: name, delta: delta, target: target, should: should };
shouldPreventQueue.current.push(event);
setTimeout(function () {
shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { return e !== event; });
}, 1);
}, []);
var scrollTouchStart = external_React_.useCallback(function (event) {
touchStartRef.current = getTouchXY(event);
activeAxis.current = undefined;
}, []);
var scrollWheel = external_React_.useCallback(function (event) {
shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
}, []);
var scrollTouchMove = external_React_.useCallback(function (event) {
shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
}, []);
external_React_.useEffect(function () {
lockStack.push(Style);
props.setCallbacks({
onScrollCapture: scrollWheel,
onWheelCapture: scrollWheel,
onTouchMoveCapture: scrollTouchMove,
});
document.addEventListener('wheel', shouldPrevent, nonPassive);
document.addEventListener('touchmove', shouldPrevent, nonPassive);
document.addEventListener('touchstart', scrollTouchStart, nonPassive);
return function () {
lockStack = lockStack.filter(function (inst) { return inst !== Style; });
document.removeEventListener('wheel', shouldPrevent, nonPassive);
document.removeEventListener('touchmove', shouldPrevent, nonPassive);
document.removeEventListener('touchstart', scrollTouchStart, nonPassive);
};
}, []);
var removeScrollBar = props.removeScrollBar, inert = props.inert;
return (external_React_.createElement(external_React_.Fragment, null,
inert ? external_React_.createElement(Style, { styles: generateStyle(id) }) : null,
removeScrollBar ? external_React_.createElement(RemoveScrollBar, { gapMode: "margin" }) : null));
}
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/sidecar.js
/* harmony default export */ var sidecar = (exportSidecar(effectCar, RemoveScrollSideCar));
;// CONCATENATED MODULE: ./node_modules/react-remove-scroll/dist/es2015/Combination.js
var ReactRemoveScroll = external_React_.forwardRef(function (props, ref) { return (external_React_.createElement(RemoveScroll, __assign({}, props, { ref: ref, sideCar: sidecar }))); });
ReactRemoveScroll.classNames = RemoveScroll.classNames;
/* harmony default export */ var Combination = (ReactRemoveScroll);
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-menu/dist/index.module.js
const $6cc32821e9371a1c$var$SELECTION_KEYS = [
'Enter',
' '
];
const $6cc32821e9371a1c$var$FIRST_KEYS = [
'ArrowDown',
'PageUp',
'Home'
];
const $6cc32821e9371a1c$var$LAST_KEYS = [
'ArrowUp',
'PageDown',
'End'
];
const $6cc32821e9371a1c$var$FIRST_LAST_KEYS = [
...$6cc32821e9371a1c$var$FIRST_KEYS,
...$6cc32821e9371a1c$var$LAST_KEYS
];
const $6cc32821e9371a1c$var$SUB_OPEN_KEYS = {
ltr: [
...$6cc32821e9371a1c$var$SELECTION_KEYS,
'ArrowRight'
],
rtl: [
...$6cc32821e9371a1c$var$SELECTION_KEYS,
'ArrowLeft'
]
};
const $6cc32821e9371a1c$var$SUB_CLOSE_KEYS = {
ltr: [
'ArrowLeft'
],
rtl: [
'ArrowRight'
]
};
/* -------------------------------------------------------------------------------------------------
* Menu
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$MENU_NAME = 'Menu';
const [$6cc32821e9371a1c$var$Collection, $6cc32821e9371a1c$var$useCollection, $6cc32821e9371a1c$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2($6cc32821e9371a1c$var$MENU_NAME);
const [$6cc32821e9371a1c$var$createMenuContext, $6cc32821e9371a1c$export$4027731b685e72eb] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($6cc32821e9371a1c$var$MENU_NAME, [
$6cc32821e9371a1c$var$createCollectionScope,
$cf1ac5d9fe0e8206$export$722aac194ae923,
$d7bdfb9eb0fdf311$export$c7109489551a4f4
]);
const $6cc32821e9371a1c$var$usePopperScope = $cf1ac5d9fe0e8206$export$722aac194ae923();
const $6cc32821e9371a1c$var$useRovingFocusGroupScope = $d7bdfb9eb0fdf311$export$c7109489551a4f4();
const [$6cc32821e9371a1c$var$MenuProvider, $6cc32821e9371a1c$var$useMenuContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$MENU_NAME);
const [$6cc32821e9371a1c$var$MenuRootProvider, $6cc32821e9371a1c$var$useMenuRootContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$MENU_NAME);
const $6cc32821e9371a1c$export$d9b273488cd8ce6f = (props)=>{
const { __scopeMenu: __scopeMenu , open: open = false , children: children , dir: dir , onOpenChange: onOpenChange , modal: modal = true } = props;
const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu);
const [content, setContent] = (0,external_React_.useState)(null);
const isUsingKeyboardRef = (0,external_React_.useRef)(false);
const handleOpenChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onOpenChange);
const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir);
(0,external_React_.useEffect)(()=>{
// Capture phase ensures we set the boolean before any side effects execute
// in response to the key or pointer event as they might depend on this value.
const handleKeyDown = ()=>{
isUsingKeyboardRef.current = true;
document.addEventListener('pointerdown', handlePointer, {
capture: true,
once: true
});
document.addEventListener('pointermove', handlePointer, {
capture: true,
once: true
});
};
const handlePointer = ()=>isUsingKeyboardRef.current = false
;
document.addEventListener('keydown', handleKeyDown, {
capture: true
});
return ()=>{
document.removeEventListener('keydown', handleKeyDown, {
capture: true
});
document.removeEventListener('pointerdown', handlePointer, {
capture: true
});
document.removeEventListener('pointermove', handlePointer, {
capture: true
});
};
}, []);
return /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9, popperScope, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuProvider, {
scope: __scopeMenu,
open: open,
onOpenChange: handleOpenChange,
content: content,
onContentChange: setContent
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuRootProvider, {
scope: __scopeMenu,
onClose: (0,external_React_.useCallback)(()=>handleOpenChange(false)
, [
handleOpenChange
]),
isUsingKeyboardRef: isUsingKeyboardRef,
dir: direction,
modal: modal
}, children)));
};
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$d9b273488cd8ce6f, {
displayName: $6cc32821e9371a1c$var$MENU_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuAnchor
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$ANCHOR_NAME = 'MenuAnchor';
const $6cc32821e9371a1c$export$9fa5ebd18bee4d43 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , ...anchorProps } = props;
const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$export$b688253958b8dfe7, extends_extends({}, popperScope, anchorProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$9fa5ebd18bee4d43, {
displayName: $6cc32821e9371a1c$var$ANCHOR_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuPortal
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$PORTAL_NAME = 'MenuPortal';
const [$6cc32821e9371a1c$var$PortalProvider, $6cc32821e9371a1c$var$usePortalContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$PORTAL_NAME, {
forceMount: undefined
});
const $6cc32821e9371a1c$export$793392f970497feb = (props)=>{
const { __scopeMenu: __scopeMenu , forceMount: forceMount , children: children , container: container } = props;
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$PORTAL_NAME, __scopeMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$PortalProvider, {
scope: __scopeMenu,
forceMount: forceMount
}, /*#__PURE__*/ (0,external_React_.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
present: forceMount || context.open
}, /*#__PURE__*/ (0,external_React_.createElement)($f1701beae083dbae$export$602eac185826482c, {
asChild: true,
container: container
}, children)));
};
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$793392f970497feb, {
displayName: $6cc32821e9371a1c$var$PORTAL_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuContent
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$CONTENT_NAME = 'MenuContent';
const [$6cc32821e9371a1c$var$MenuContentProvider, $6cc32821e9371a1c$var$useMenuContentContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$CONTENT_NAME);
const $6cc32821e9371a1c$export$479f0f2f71193efe = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const portalContext = $6cc32821e9371a1c$var$usePortalContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
const { forceMount: forceMount = portalContext.forceMount , ...contentProps } = props;
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$Collection.Provider, {
scope: props.__scopeMenu
}, /*#__PURE__*/ (0,external_React_.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
present: forceMount || context.open
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$Collection.Slot, {
scope: props.__scopeMenu
}, rootContext.modal ? /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuRootContentModal, extends_extends({}, contentProps, {
ref: forwardedRef
})) : /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuRootContentNonModal, extends_extends({}, contentProps, {
ref: forwardedRef
})))));
});
/* ---------------------------------------------------------------------------------------------- */ const $6cc32821e9371a1c$var$MenuRootContentModal = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
const ref = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref); // Hide everything from ARIA except the `MenuContent`
(0,external_React_.useEffect)(()=>{
const content = ref.current;
if (content) return hideOthers(content);
}, []);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuContentImpl, extends_extends({}, props, {
ref: composedRefs // we make sure we're not trapping once it's been closed
,
trapFocus: context.open // make sure to only disable pointer events when open
,
disableOutsidePointerEvents: context.open,
disableOutsideScroll: true // When focus is trapped, a `focusout` event may still happen.
,
onFocusOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocusOutside, (event)=>event.preventDefault()
, {
checkForDefaultPrevented: false
}),
onDismiss: ()=>context.onOpenChange(false)
}));
});
const $6cc32821e9371a1c$var$MenuRootContentNonModal = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuContentImpl, extends_extends({}, props, {
ref: forwardedRef,
trapFocus: false,
disableOutsidePointerEvents: false,
disableOutsideScroll: false,
onDismiss: ()=>context.onOpenChange(false)
}));
});
/* ---------------------------------------------------------------------------------------------- */ const $6cc32821e9371a1c$var$MenuContentImpl = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , loop: loop = false , trapFocus: trapFocus , onOpenAutoFocus: onOpenAutoFocus , onCloseAutoFocus: onCloseAutoFocus , disableOutsidePointerEvents: disableOutsidePointerEvents , onEntryFocus: onEntryFocus , onEscapeKeyDown: onEscapeKeyDown , onPointerDownOutside: onPointerDownOutside , onFocusOutside: onFocusOutside , onInteractOutside: onInteractOutside , onDismiss: onDismiss , disableOutsideScroll: disableOutsideScroll , ...contentProps } = props;
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, __scopeMenu);
const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$CONTENT_NAME, __scopeMenu);
const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu);
const rovingFocusGroupScope = $6cc32821e9371a1c$var$useRovingFocusGroupScope(__scopeMenu);
const getItems = $6cc32821e9371a1c$var$useCollection(__scopeMenu);
const [currentItemId, setCurrentItemId] = (0,external_React_.useState)(null);
const contentRef = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, contentRef, context.onContentChange);
const timerRef = (0,external_React_.useRef)(0);
const searchRef = (0,external_React_.useRef)('');
const pointerGraceTimerRef = (0,external_React_.useRef)(0);
const pointerGraceIntentRef = (0,external_React_.useRef)(null);
const pointerDirRef = (0,external_React_.useRef)('right');
const lastPointerXRef = (0,external_React_.useRef)(0);
const ScrollLockWrapper = disableOutsideScroll ? Combination : external_React_.Fragment;
const scrollLockWrapperProps = disableOutsideScroll ? {
as: $5e63c961fc1ce211$export$8c6ed5c666ac1360,
allowPinchZoom: true
} : undefined;
const handleTypeaheadSearch = (key)=>{
var _items$find, _items$find2;
const search = searchRef.current + key;
const items = getItems().filter((item)=>!item.disabled
);
const currentItem = document.activeElement;
const currentMatch = (_items$find = items.find((item)=>item.ref.current === currentItem
)) === null || _items$find === void 0 ? void 0 : _items$find.textValue;
const values = items.map((item)=>item.textValue
);
const nextMatch = $6cc32821e9371a1c$var$getNextMatch(values, search, currentMatch);
const newItem = (_items$find2 = items.find((item)=>item.textValue === nextMatch
)) === null || _items$find2 === void 0 ? void 0 : _items$find2.ref.current; // Reset `searchRef` 1 second after it was last updated
(function updateSearch(value) {
searchRef.current = value;
window.clearTimeout(timerRef.current);
if (value !== '') timerRef.current = window.setTimeout(()=>updateSearch('')
, 1000);
})(search);
if (newItem) /**
* Imperative focus during keydown is risky so we prevent React's batching updates
* to avoid potential bugs. See: https://github.com/facebook/react/issues/20332
*/ setTimeout(()=>newItem.focus()
);
};
(0,external_React_.useEffect)(()=>{
return ()=>window.clearTimeout(timerRef.current)
;
}, []); // Make sure the whole tree has focus guards as our `MenuContent` may be
// the last element in the DOM (beacuse of the `Portal`)
$3db38b7d1fb3fe6a$export$b7ece24a22aeda8c();
const isPointerMovingToSubmenu = (0,external_React_.useCallback)((event)=>{
var _pointerGraceIntentRe, _pointerGraceIntentRe2;
const isMovingTowards = pointerDirRef.current === ((_pointerGraceIntentRe = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe === void 0 ? void 0 : _pointerGraceIntentRe.side);
return isMovingTowards && $6cc32821e9371a1c$var$isPointerInGraceArea(event, (_pointerGraceIntentRe2 = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe2 === void 0 ? void 0 : _pointerGraceIntentRe2.area);
}, []);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuContentProvider, {
scope: __scopeMenu,
searchRef: searchRef,
onItemEnter: (0,external_React_.useCallback)((event)=>{
if (isPointerMovingToSubmenu(event)) event.preventDefault();
}, [
isPointerMovingToSubmenu
]),
onItemLeave: (0,external_React_.useCallback)((event)=>{
var _contentRef$current;
if (isPointerMovingToSubmenu(event)) return;
(_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 || _contentRef$current.focus();
setCurrentItemId(null);
}, [
isPointerMovingToSubmenu
]),
onTriggerLeave: (0,external_React_.useCallback)((event)=>{
if (isPointerMovingToSubmenu(event)) event.preventDefault();
}, [
isPointerMovingToSubmenu
]),
pointerGraceTimerRef: pointerGraceTimerRef,
onPointerGraceIntentChange: (0,external_React_.useCallback)((intent)=>{
pointerGraceIntentRef.current = intent;
}, [])
}, /*#__PURE__*/ (0,external_React_.createElement)(ScrollLockWrapper, scrollLockWrapperProps, /*#__PURE__*/ (0,external_React_.createElement)($d3863c46a17e8a28$export$20e40289641fbbb6, {
asChild: true,
trapped: trapFocus,
onMountAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(onOpenAutoFocus, (event)=>{
var _contentRef$current2;
// when opening, explicitly focus the content area only and leave
// `onEntryFocus` in control of focusing first item
event.preventDefault();
(_contentRef$current2 = contentRef.current) === null || _contentRef$current2 === void 0 || _contentRef$current2.focus();
}),
onUnmountAutoFocus: onCloseAutoFocus
}, /*#__PURE__*/ (0,external_React_.createElement)($5cb92bef7577960e$export$177fb62ff3ec1f22, {
asChild: true,
disableOutsidePointerEvents: disableOutsidePointerEvents,
onEscapeKeyDown: onEscapeKeyDown,
onPointerDownOutside: onPointerDownOutside,
onFocusOutside: onFocusOutside,
onInteractOutside: onInteractOutside,
onDismiss: onDismiss
}, /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9, extends_extends({
asChild: true
}, rovingFocusGroupScope, {
dir: rootContext.dir,
orientation: "vertical",
loop: loop,
currentTabStopId: currentItemId,
onCurrentTabStopIdChange: setCurrentItemId,
onEntryFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(onEntryFocus, (event)=>{
// only focus first item when using keyboard
if (!rootContext.isUsingKeyboardRef.current) event.preventDefault();
})
}), /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$export$7c6e2c02157bb7d2, extends_extends({
role: "menu",
"aria-orientation": "vertical",
"data-state": $6cc32821e9371a1c$var$getOpenState(context.open),
"data-radix-menu-content": "",
dir: rootContext.dir
}, popperScope, contentProps, {
ref: composedRefs,
style: {
outline: 'none',
...contentProps.style
},
onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(contentProps.onKeyDown, (event)=>{
// submenu key events bubble through portals. We only care about keys in this menu.
const target = event.target;
const isKeyDownInside = target.closest('[data-radix-menu-content]') === event.currentTarget;
const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
const isCharacterKey = event.key.length === 1;
if (isKeyDownInside) {
// menus should not be navigated using tab key so we prevent it
if (event.key === 'Tab') event.preventDefault();
if (!isModifierKey && isCharacterKey) handleTypeaheadSearch(event.key);
} // focus first/last item based on key pressed
const content = contentRef.current;
if (event.target !== content) return;
if (!$6cc32821e9371a1c$var$FIRST_LAST_KEYS.includes(event.key)) return;
event.preventDefault();
const items = getItems().filter((item)=>!item.disabled
);
const candidateNodes = items.map((item)=>item.ref.current
);
if ($6cc32821e9371a1c$var$LAST_KEYS.includes(event.key)) candidateNodes.reverse();
$6cc32821e9371a1c$var$focusFirst(candidateNodes);
}),
onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlur, (event)=>{
// clear search buffer when leaving the menu
if (!event.currentTarget.contains(event.target)) {
window.clearTimeout(timerRef.current);
searchRef.current = '';
}
}),
onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, $6cc32821e9371a1c$var$whenMouse((event)=>{
const target = event.target;
const pointerXHasChanged = lastPointerXRef.current !== event.clientX; // We don't use `event.movementX` for this check because Safari will
// always return `0` on a pointer event.
if (event.currentTarget.contains(target) && pointerXHasChanged) {
const newDir = event.clientX > lastPointerXRef.current ? 'right' : 'left';
pointerDirRef.current = newDir;
lastPointerXRef.current = event.clientX;
}
}))
})))))));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$479f0f2f71193efe, {
displayName: $6cc32821e9371a1c$var$CONTENT_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuGroup
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$GROUP_NAME = 'MenuGroup';
const $6cc32821e9371a1c$export$22a631d1f72787bb = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , ...groupProps } = props;
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({
role: "group"
}, groupProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$22a631d1f72787bb, {
displayName: $6cc32821e9371a1c$var$GROUP_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuLabel
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$LABEL_NAME = 'MenuLabel';
const $6cc32821e9371a1c$export$dd37bec0e8a99143 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , ...labelProps } = props;
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({}, labelProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$dd37bec0e8a99143, {
displayName: $6cc32821e9371a1c$var$LABEL_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuItem
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$ITEM_NAME = 'MenuItem';
const $6cc32821e9371a1c$var$ITEM_SELECT = 'menu.itemSelect';
const $6cc32821e9371a1c$export$2ce376c2cc3355c8 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { disabled: disabled = false , onSelect: onSelect , ...itemProps } = props;
const ref = (0,external_React_.useRef)(null);
const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$ITEM_NAME, props.__scopeMenu);
const contentContext = $6cc32821e9371a1c$var$useMenuContentContext($6cc32821e9371a1c$var$ITEM_NAME, props.__scopeMenu);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
const isPointerDownRef = (0,external_React_.useRef)(false);
const handleSelect = ()=>{
const menuItem = ref.current;
if (!disabled && menuItem) {
const itemSelectEvent = new CustomEvent($6cc32821e9371a1c$var$ITEM_SELECT, {
bubbles: true,
cancelable: true
});
menuItem.addEventListener($6cc32821e9371a1c$var$ITEM_SELECT, (event)=>onSelect === null || onSelect === void 0 ? void 0 : onSelect(event)
, {
once: true
});
$8927f6f2acc4f386$export$6d1a0317bde7de7f(menuItem, itemSelectEvent);
if (itemSelectEvent.defaultPrevented) isPointerDownRef.current = false;
else rootContext.onClose();
}
};
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuItemImpl, extends_extends({}, itemProps, {
ref: composedRefs,
disabled: disabled,
onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, handleSelect),
onPointerDown: (event)=>{
var _props$onPointerDown;
(_props$onPointerDown = props.onPointerDown) === null || _props$onPointerDown === void 0 || _props$onPointerDown.call(props, event);
isPointerDownRef.current = true;
},
onPointerUp: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerUp, (event)=>{
var _event$currentTarget;
// Pointer down can move to a different menu item which should activate it on pointer up.
// We dispatch a click for selection to allow composition with click based triggers and to
// prevent Firefox from getting stuck in text selection mode when the menu closes.
if (!isPointerDownRef.current) (_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 || _event$currentTarget.click();
}),
onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event)=>{
const isTypingAhead = contentContext.searchRef.current !== '';
if (disabled || isTypingAhead && event.key === ' ') return;
if ($6cc32821e9371a1c$var$SELECTION_KEYS.includes(event.key)) {
event.currentTarget.click();
/**
* We prevent default browser behaviour for selection keys as they should trigger
* a selection only:
* - prevents space from scrolling the page.
* - if keydown causes focus to move, prevents keydown from firing on the new target.
*/ event.preventDefault();
}
})
}));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$2ce376c2cc3355c8, {
displayName: $6cc32821e9371a1c$var$ITEM_NAME
});
/* ---------------------------------------------------------------------------------------------- */ const $6cc32821e9371a1c$var$MenuItemImpl = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , disabled: disabled = false , textValue: textValue , ...itemProps } = props;
const contentContext = $6cc32821e9371a1c$var$useMenuContentContext($6cc32821e9371a1c$var$ITEM_NAME, __scopeMenu);
const rovingFocusGroupScope = $6cc32821e9371a1c$var$useRovingFocusGroupScope(__scopeMenu);
const ref = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
const [isFocused, setIsFocused] = (0,external_React_.useState)(false); // get the item's `.textContent` as default strategy for typeahead `textValue`
const [textContent, setTextContent] = (0,external_React_.useState)('');
(0,external_React_.useEffect)(()=>{
const menuItem = ref.current;
if (menuItem) {
var _menuItem$textContent;
setTextContent(((_menuItem$textContent = menuItem.textContent) !== null && _menuItem$textContent !== void 0 ? _menuItem$textContent : '').trim());
}
}, [
itemProps.children
]);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$Collection.ItemSlot, {
scope: __scopeMenu,
disabled: disabled,
textValue: textValue !== null && textValue !== void 0 ? textValue : textContent
}, /*#__PURE__*/ (0,external_React_.createElement)($d7bdfb9eb0fdf311$export$6d08773d2e66f8f2, extends_extends({
asChild: true
}, rovingFocusGroupScope, {
focusable: !disabled
}), /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({
role: "menuitem",
"data-highlighted": isFocused ? '' : undefined,
"aria-disabled": disabled || undefined,
"data-disabled": disabled ? '' : undefined
}, itemProps, {
ref: composedRefs,
onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, $6cc32821e9371a1c$var$whenMouse((event)=>{
if (disabled) contentContext.onItemLeave(event);
else {
contentContext.onItemEnter(event);
if (!event.defaultPrevented) {
const item = event.currentTarget;
item.focus();
}
}
})),
onPointerLeave: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerLeave, $6cc32821e9371a1c$var$whenMouse((event)=>contentContext.onItemLeave(event)
)),
onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, ()=>setIsFocused(true)
),
onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlur, ()=>setIsFocused(false)
)
}))));
});
/* -------------------------------------------------------------------------------------------------
* MenuCheckboxItem
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$CHECKBOX_ITEM_NAME = 'MenuCheckboxItem';
const $6cc32821e9371a1c$export$f6f243521332502d = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { checked: checked = false , onCheckedChange: onCheckedChange , ...checkboxItemProps } = props;
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$ItemIndicatorProvider, {
scope: props.__scopeMenu,
checked: checked
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$2ce376c2cc3355c8, extends_extends({
role: "menuitemcheckbox",
"aria-checked": $6cc32821e9371a1c$var$isIndeterminate(checked) ? 'mixed' : checked
}, checkboxItemProps, {
ref: forwardedRef,
"data-state": $6cc32821e9371a1c$var$getCheckedState(checked),
onSelect: $e42e1063c40fb3ef$export$b9ecd428b558ff10(checkboxItemProps.onSelect, ()=>onCheckedChange === null || onCheckedChange === void 0 ? void 0 : onCheckedChange($6cc32821e9371a1c$var$isIndeterminate(checked) ? true : !checked)
, {
checkForDefaultPrevented: false
})
})));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$f6f243521332502d, {
displayName: $6cc32821e9371a1c$var$CHECKBOX_ITEM_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuRadioGroup
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$RADIO_GROUP_NAME = 'MenuRadioGroup';
const [$6cc32821e9371a1c$var$RadioGroupProvider, $6cc32821e9371a1c$var$useRadioGroupContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$RADIO_GROUP_NAME, {
value: undefined,
onValueChange: ()=>{}
});
const $6cc32821e9371a1c$export$ea2200c9eee416b3 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { value: value , onValueChange: onValueChange , ...groupProps } = props;
const handleValueChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onValueChange);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$RadioGroupProvider, {
scope: props.__scopeMenu,
value: value,
onValueChange: handleValueChange
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$22a631d1f72787bb, extends_extends({}, groupProps, {
ref: forwardedRef
})));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$ea2200c9eee416b3, {
displayName: $6cc32821e9371a1c$var$RADIO_GROUP_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuRadioItem
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$RADIO_ITEM_NAME = 'MenuRadioItem';
const $6cc32821e9371a1c$export$69bd225e9817f6d0 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { value: value , ...radioItemProps } = props;
const context = $6cc32821e9371a1c$var$useRadioGroupContext($6cc32821e9371a1c$var$RADIO_ITEM_NAME, props.__scopeMenu);
const checked = value === context.value;
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$ItemIndicatorProvider, {
scope: props.__scopeMenu,
checked: checked
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$2ce376c2cc3355c8, extends_extends({
role: "menuitemradio",
"aria-checked": checked
}, radioItemProps, {
ref: forwardedRef,
"data-state": $6cc32821e9371a1c$var$getCheckedState(checked),
onSelect: $e42e1063c40fb3ef$export$b9ecd428b558ff10(radioItemProps.onSelect, ()=>{
var _context$onValueChang;
return (_context$onValueChang = context.onValueChange) === null || _context$onValueChang === void 0 ? void 0 : _context$onValueChang.call(context, value);
}, {
checkForDefaultPrevented: false
})
})));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$69bd225e9817f6d0, {
displayName: $6cc32821e9371a1c$var$RADIO_ITEM_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuItemIndicator
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$ITEM_INDICATOR_NAME = 'MenuItemIndicator';
const [$6cc32821e9371a1c$var$ItemIndicatorProvider, $6cc32821e9371a1c$var$useItemIndicatorContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$ITEM_INDICATOR_NAME, {
checked: false
});
const $6cc32821e9371a1c$export$a2593e23056970a3 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , forceMount: forceMount , ...itemIndicatorProps } = props;
const indicatorContext = $6cc32821e9371a1c$var$useItemIndicatorContext($6cc32821e9371a1c$var$ITEM_INDICATOR_NAME, __scopeMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
present: forceMount || $6cc32821e9371a1c$var$isIndeterminate(indicatorContext.checked) || indicatorContext.checked === true
}, /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.span, extends_extends({}, itemIndicatorProps, {
ref: forwardedRef,
"data-state": $6cc32821e9371a1c$var$getCheckedState(indicatorContext.checked)
})));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$a2593e23056970a3, {
displayName: $6cc32821e9371a1c$var$ITEM_INDICATOR_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuSeparator
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$SEPARATOR_NAME = 'MenuSeparator';
const $6cc32821e9371a1c$export$1cec7dcdd713e220 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , ...separatorProps } = props;
return /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.div, extends_extends({
role: "separator",
"aria-orientation": "horizontal"
}, separatorProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$1cec7dcdd713e220, {
displayName: $6cc32821e9371a1c$var$SEPARATOR_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuArrow
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$ARROW_NAME = 'MenuArrow';
const $6cc32821e9371a1c$export$bcdda4773debf5fa = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeMenu: __scopeMenu , ...arrowProps } = props;
const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$export$21b07c8f274aebd5, extends_extends({}, popperScope, arrowProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$bcdda4773debf5fa, {
displayName: $6cc32821e9371a1c$var$ARROW_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuSub
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$SUB_NAME = 'MenuSub';
const [$6cc32821e9371a1c$var$MenuSubProvider, $6cc32821e9371a1c$var$useMenuSubContext] = $6cc32821e9371a1c$var$createMenuContext($6cc32821e9371a1c$var$SUB_NAME);
const $6cc32821e9371a1c$export$71bdb9d1e2909932 = (props)=>{
const { __scopeMenu: __scopeMenu , children: children , open: open = false , onOpenChange: onOpenChange } = props;
const parentMenuContext = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$SUB_NAME, __scopeMenu);
const popperScope = $6cc32821e9371a1c$var$usePopperScope(__scopeMenu);
const [trigger, setTrigger] = (0,external_React_.useState)(null);
const [content, setContent] = (0,external_React_.useState)(null);
const handleOpenChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onOpenChange); // Prevent the parent menu from reopening with open submenus.
(0,external_React_.useEffect)(()=>{
if (parentMenuContext.open === false) handleOpenChange(false);
return ()=>handleOpenChange(false)
;
}, [
parentMenuContext.open,
handleOpenChange
]);
return /*#__PURE__*/ (0,external_React_.createElement)($cf1ac5d9fe0e8206$export$be92b6f5f03c0fe9, popperScope, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuProvider, {
scope: __scopeMenu,
open: open,
onOpenChange: handleOpenChange,
content: content,
onContentChange: setContent
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuSubProvider, {
scope: __scopeMenu,
contentId: $1746a345f3d73bb7$export$f680877a34711e37(),
triggerId: $1746a345f3d73bb7$export$f680877a34711e37(),
trigger: trigger,
onTriggerChange: setTrigger
}, children)));
};
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$71bdb9d1e2909932, {
displayName: $6cc32821e9371a1c$var$SUB_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuSubTrigger
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$SUB_TRIGGER_NAME = 'MenuSubTrigger';
const $6cc32821e9371a1c$export$5fbbb3ba7297405f = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$SUB_TRIGGER_NAME, props.__scopeMenu);
const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$SUB_TRIGGER_NAME, props.__scopeMenu);
const subContext = $6cc32821e9371a1c$var$useMenuSubContext($6cc32821e9371a1c$var$SUB_TRIGGER_NAME, props.__scopeMenu);
const contentContext = $6cc32821e9371a1c$var$useMenuContentContext($6cc32821e9371a1c$var$SUB_TRIGGER_NAME, props.__scopeMenu);
const openTimerRef = (0,external_React_.useRef)(null);
const { pointerGraceTimerRef: pointerGraceTimerRef , onPointerGraceIntentChange: onPointerGraceIntentChange } = contentContext;
const scope = {
__scopeMenu: props.__scopeMenu
};
const clearOpenTimer = (0,external_React_.useCallback)(()=>{
if (openTimerRef.current) window.clearTimeout(openTimerRef.current);
openTimerRef.current = null;
}, []);
(0,external_React_.useEffect)(()=>clearOpenTimer
, [
clearOpenTimer
]);
(0,external_React_.useEffect)(()=>{
const pointerGraceTimer = pointerGraceTimerRef.current;
return ()=>{
window.clearTimeout(pointerGraceTimer);
onPointerGraceIntentChange(null);
};
}, [
pointerGraceTimerRef,
onPointerGraceIntentChange
]);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$9fa5ebd18bee4d43, extends_extends({
asChild: true
}, scope), /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuItemImpl, extends_extends({
id: subContext.triggerId,
"aria-haspopup": "menu",
"aria-expanded": context.open,
"aria-controls": subContext.contentId,
"data-state": $6cc32821e9371a1c$var$getOpenState(context.open)
}, props, {
ref: $6ed0406888f73fc4$export$43e446d32b3d21af(forwardedRef, subContext.onTriggerChange) // This is redundant for mouse users but we cannot determine pointer type from
,
onClick: (event)=>{
var _props$onClick;
(_props$onClick = props.onClick) === null || _props$onClick === void 0 || _props$onClick.call(props, event);
if (props.disabled || event.defaultPrevented) return;
/**
* We manually focus because iOS Safari doesn't always focus on click (e.g. buttons)
* and we rely heavily on `onFocusOutside` for submenus to close when switching
* between separate submenus.
*/ event.currentTarget.focus();
if (!context.open) context.onOpenChange(true);
},
onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, $6cc32821e9371a1c$var$whenMouse((event)=>{
contentContext.onItemEnter(event);
if (event.defaultPrevented) return;
if (!props.disabled && !context.open && !openTimerRef.current) {
contentContext.onPointerGraceIntentChange(null);
openTimerRef.current = window.setTimeout(()=>{
context.onOpenChange(true);
clearOpenTimer();
}, 100);
}
})),
onPointerLeave: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerLeave, $6cc32821e9371a1c$var$whenMouse((event)=>{
var _context$content;
clearOpenTimer();
const contentRect = (_context$content = context.content) === null || _context$content === void 0 ? void 0 : _context$content.getBoundingClientRect();
if (contentRect) {
var _context$content2;
// TODO: make sure to update this when we change positioning logic
const side = (_context$content2 = context.content) === null || _context$content2 === void 0 ? void 0 : _context$content2.dataset.side;
const rightSide = side === 'right';
const bleed = rightSide ? -5 : 5;
const contentNearEdge = contentRect[rightSide ? 'left' : 'right'];
const contentFarEdge = contentRect[rightSide ? 'right' : 'left'];
contentContext.onPointerGraceIntentChange({
area: [
// consistently within polygon bounds
{
x: event.clientX + bleed,
y: event.clientY
},
{
x: contentNearEdge,
y: contentRect.top
},
{
x: contentFarEdge,
y: contentRect.top
},
{
x: contentFarEdge,
y: contentRect.bottom
},
{
x: contentNearEdge,
y: contentRect.bottom
}
],
side: side
});
window.clearTimeout(pointerGraceTimerRef.current);
pointerGraceTimerRef.current = window.setTimeout(()=>contentContext.onPointerGraceIntentChange(null)
, 300);
} else {
contentContext.onTriggerLeave(event);
if (event.defaultPrevented) return; // There's 100ms where the user may leave an item before the submenu was opened.
contentContext.onPointerGraceIntentChange(null);
}
})),
onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event)=>{
const isTypingAhead = contentContext.searchRef.current !== '';
if (props.disabled || isTypingAhead && event.key === ' ') return;
if ($6cc32821e9371a1c$var$SUB_OPEN_KEYS[rootContext.dir].includes(event.key)) {
var _context$content3;
context.onOpenChange(true); // The trigger may hold focus if opened via pointer interaction
// so we ensure content is given focus again when switching to keyboard.
(_context$content3 = context.content) === null || _context$content3 === void 0 || _context$content3.focus(); // prevent window from scrolling
event.preventDefault();
}
})
})));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$5fbbb3ba7297405f, {
displayName: $6cc32821e9371a1c$var$SUB_TRIGGER_NAME
});
/* -------------------------------------------------------------------------------------------------
* MenuSubContent
* -----------------------------------------------------------------------------------------------*/ const $6cc32821e9371a1c$var$SUB_CONTENT_NAME = 'MenuSubContent';
const $6cc32821e9371a1c$export$e7142ab31822bde6 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const portalContext = $6cc32821e9371a1c$var$usePortalContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
const { forceMount: forceMount = portalContext.forceMount , ...subContentProps } = props;
const context = $6cc32821e9371a1c$var$useMenuContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
const rootContext = $6cc32821e9371a1c$var$useMenuRootContext($6cc32821e9371a1c$var$CONTENT_NAME, props.__scopeMenu);
const subContext = $6cc32821e9371a1c$var$useMenuSubContext($6cc32821e9371a1c$var$SUB_CONTENT_NAME, props.__scopeMenu);
const ref = (0,external_React_.useRef)(null);
const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$Collection.Provider, {
scope: props.__scopeMenu
}, /*#__PURE__*/ (0,external_React_.createElement)($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
present: forceMount || context.open
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$Collection.Slot, {
scope: props.__scopeMenu
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$var$MenuContentImpl, extends_extends({
id: subContext.contentId,
"aria-labelledby": subContext.triggerId
}, subContentProps, {
ref: composedRefs,
align: "start",
side: rootContext.dir === 'rtl' ? 'left' : 'right',
disableOutsidePointerEvents: false,
disableOutsideScroll: false,
trapFocus: false,
onOpenAutoFocus: (event)=>{
var _ref$current;
// when opening a submenu, focus content for keyboard users only
if (rootContext.isUsingKeyboardRef.current) (_ref$current = ref.current) === null || _ref$current === void 0 || _ref$current.focus();
event.preventDefault();
} // The menu might close because of focusing another menu item in the parent menu. We
,
onCloseAutoFocus: (event)=>event.preventDefault()
,
onFocusOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocusOutside, (event)=>{
// We prevent closing when the trigger is focused to avoid triggering a re-open animation
// on pointer interaction.
if (event.target !== subContext.trigger) context.onOpenChange(false);
}),
onEscapeKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onEscapeKeyDown, (event)=>{
rootContext.onClose(); // ensure pressing escape in submenu doesn't escape full screen mode
event.preventDefault();
}),
onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event)=>{
// Submenu key events bubble through portals. We only care about keys in this menu.
const isKeyDownInside = event.currentTarget.contains(event.target);
const isCloseKey = $6cc32821e9371a1c$var$SUB_CLOSE_KEYS[rootContext.dir].includes(event.key);
if (isKeyDownInside && isCloseKey) {
var _subContext$trigger;
context.onOpenChange(false); // We focus manually because we prevented it in `onCloseAutoFocus`
(_subContext$trigger = subContext.trigger) === null || _subContext$trigger === void 0 || _subContext$trigger.focus(); // prevent window from scrolling
event.preventDefault();
}
})
})))));
});
/*#__PURE__*/ Object.assign($6cc32821e9371a1c$export$e7142ab31822bde6, {
displayName: $6cc32821e9371a1c$var$SUB_CONTENT_NAME
});
/* -----------------------------------------------------------------------------------------------*/ function $6cc32821e9371a1c$var$getOpenState(open) {
return open ? 'open' : 'closed';
}
function $6cc32821e9371a1c$var$isIndeterminate(checked) {
return checked === 'indeterminate';
}
function $6cc32821e9371a1c$var$getCheckedState(checked) {
return $6cc32821e9371a1c$var$isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked';
}
function $6cc32821e9371a1c$var$focusFirst(candidates) {
const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
for (const candidate of candidates){
// if focus is already where we want to go, we don't want to keep going through the candidates
if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
candidate.focus();
if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
}
}
/**
* Wraps an array around itself at a given start index
* Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`
*/ function $6cc32821e9371a1c$var$wrapArray(array, startIndex) {
return array.map((_, index)=>array[(startIndex + index) % array.length]
);
}
/**
* This is the "meat" of the typeahead matching logic. It takes in all the values,
* the search and the current match, and returns the next match (or `undefined`).
*
* We normalize the search because if a user has repeatedly pressed a character,
* we want the exact same behavior as if we only had that one character
* (ie. cycle through options starting with that character)
*
* We also reorder the values by wrapping the array around the current match.
* This is so we always look forward from the current match, and picking the first
* match will always be the correct one.
*
* Finally, if the normalized search is exactly one character, we exclude the
* current match from the values because otherwise it would be the first to match always
* and focus would never move. This is as opposed to the regular case, where we
* don't want focus to move if the current match still matches.
*/ function $6cc32821e9371a1c$var$getNextMatch(values, search, currentMatch) {
const isRepeated = search.length > 1 && Array.from(search).every((char)=>char === search[0]
);
const normalizedSearch = isRepeated ? search[0] : search;
const currentMatchIndex = currentMatch ? values.indexOf(currentMatch) : -1;
let wrappedValues = $6cc32821e9371a1c$var$wrapArray(values, Math.max(currentMatchIndex, 0));
const excludeCurrentMatch = normalizedSearch.length === 1;
if (excludeCurrentMatch) wrappedValues = wrappedValues.filter((v)=>v !== currentMatch
);
const nextMatch = wrappedValues.find((value)=>value.toLowerCase().startsWith(normalizedSearch.toLowerCase())
);
return nextMatch !== currentMatch ? nextMatch : undefined;
}
// Determine if a point is inside of a polygon.
// Based on https://github.com/substack/point-in-polygon
function $6cc32821e9371a1c$var$isPointInPolygon(point, polygon) {
const { x: x , y: y } = point;
let inside = false;
for(let i = 0, j = polygon.length - 1; i < polygon.length; j = i++){
const xi = polygon[i].x;
const yi = polygon[i].y;
const xj = polygon[j].x;
const yj = polygon[j].y; // prettier-ignore
const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
function $6cc32821e9371a1c$var$isPointerInGraceArea(event, area) {
if (!area) return false;
const cursorPos = {
x: event.clientX,
y: event.clientY
};
return $6cc32821e9371a1c$var$isPointInPolygon(cursorPos, area);
}
function $6cc32821e9371a1c$var$whenMouse(handler) {
return (event)=>event.pointerType === 'mouse' ? handler(event) : undefined
;
}
const $6cc32821e9371a1c$export$be92b6f5f03c0fe9 = $6cc32821e9371a1c$export$d9b273488cd8ce6f;
const $6cc32821e9371a1c$export$b688253958b8dfe7 = $6cc32821e9371a1c$export$9fa5ebd18bee4d43;
const $6cc32821e9371a1c$export$602eac185826482c = $6cc32821e9371a1c$export$793392f970497feb;
const $6cc32821e9371a1c$export$7c6e2c02157bb7d2 = $6cc32821e9371a1c$export$479f0f2f71193efe;
const $6cc32821e9371a1c$export$eb2fcfdbd7ba97d4 = $6cc32821e9371a1c$export$22a631d1f72787bb;
const $6cc32821e9371a1c$export$b04be29aa201d4f5 = $6cc32821e9371a1c$export$dd37bec0e8a99143;
const $6cc32821e9371a1c$export$6d08773d2e66f8f2 = $6cc32821e9371a1c$export$2ce376c2cc3355c8;
const $6cc32821e9371a1c$export$16ce288f89fa631c = $6cc32821e9371a1c$export$f6f243521332502d;
const $6cc32821e9371a1c$export$a98f0dcb43a68a25 = $6cc32821e9371a1c$export$ea2200c9eee416b3;
const $6cc32821e9371a1c$export$371ab307eab489c0 = $6cc32821e9371a1c$export$69bd225e9817f6d0;
const $6cc32821e9371a1c$export$c3468e2714d175fa = $6cc32821e9371a1c$export$a2593e23056970a3;
const $6cc32821e9371a1c$export$1ff3c3f08ae963c0 = $6cc32821e9371a1c$export$1cec7dcdd713e220;
const $6cc32821e9371a1c$export$21b07c8f274aebd5 = $6cc32821e9371a1c$export$bcdda4773debf5fa;
const $6cc32821e9371a1c$export$d7a01e11500dfb6f = $6cc32821e9371a1c$export$71bdb9d1e2909932;
const $6cc32821e9371a1c$export$2ea8a7a591ac5eac = $6cc32821e9371a1c$export$5fbbb3ba7297405f;
const $6cc32821e9371a1c$export$6d4de93b380beddf = $6cc32821e9371a1c$export$e7142ab31822bde6;
;// CONCATENATED MODULE: ./node_modules/@radix-ui/react-dropdown-menu/dist/index.module.js
/* -------------------------------------------------------------------------------------------------
* DropdownMenu
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$DROPDOWN_MENU_NAME = 'DropdownMenu';
const [$d08ef79370b62062$var$createDropdownMenuContext, $d08ef79370b62062$export$c0623cd925aeb687] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($d08ef79370b62062$var$DROPDOWN_MENU_NAME, [
$6cc32821e9371a1c$export$4027731b685e72eb
]);
const $d08ef79370b62062$var$useMenuScope = $6cc32821e9371a1c$export$4027731b685e72eb();
const [$d08ef79370b62062$var$DropdownMenuProvider, $d08ef79370b62062$var$useDropdownMenuContext] = $d08ef79370b62062$var$createDropdownMenuContext($d08ef79370b62062$var$DROPDOWN_MENU_NAME);
const $d08ef79370b62062$export$e44a253a59704894 = (props)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , children: children , dir: dir , open: openProp , defaultOpen: defaultOpen , onOpenChange: onOpenChange , modal: modal = true } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
const triggerRef = (0,external_React_.useRef)(null);
const [open = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({
prop: openProp,
defaultProp: defaultOpen,
onChange: onOpenChange
});
return /*#__PURE__*/ (0,external_React_.createElement)($d08ef79370b62062$var$DropdownMenuProvider, {
scope: __scopeDropdownMenu,
triggerId: $1746a345f3d73bb7$export$f680877a34711e37(),
triggerRef: triggerRef,
contentId: $1746a345f3d73bb7$export$f680877a34711e37(),
open: open,
onOpenChange: setOpen,
onOpenToggle: (0,external_React_.useCallback)(()=>setOpen((prevOpen)=>!prevOpen
)
, [
setOpen
]),
modal: modal
}, /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$be92b6f5f03c0fe9, extends_extends({}, menuScope, {
open: open,
onOpenChange: setOpen,
dir: dir,
modal: modal
}), children));
};
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$e44a253a59704894, {
displayName: $d08ef79370b62062$var$DROPDOWN_MENU_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuTrigger
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$TRIGGER_NAME = 'DropdownMenuTrigger';
const $d08ef79370b62062$export$d2469213b3befba9 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , disabled: disabled = false , ...triggerProps } = props;
const context = $d08ef79370b62062$var$useDropdownMenuContext($d08ef79370b62062$var$TRIGGER_NAME, __scopeDropdownMenu);
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$b688253958b8dfe7, extends_extends({
asChild: true
}, menuScope), /*#__PURE__*/ (0,external_React_.createElement)($8927f6f2acc4f386$export$250ffa63cdc0d034.button, extends_extends({
type: "button",
id: context.triggerId,
"aria-haspopup": "menu",
"aria-expanded": context.open,
"aria-controls": context.open ? context.contentId : undefined,
"data-state": context.open ? 'open' : 'closed',
"data-disabled": disabled ? '' : undefined,
disabled: disabled
}, triggerProps, {
ref: $6ed0406888f73fc4$export$43e446d32b3d21af(forwardedRef, context.triggerRef),
onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDown, (event)=>{
// only call handler if it's the left button (mousedown gets triggered by all mouse buttons)
// but not when the control key is pressed (avoiding MacOS right click)
if (!disabled && event.button === 0 && event.ctrlKey === false) {
context.onOpenToggle(); // prevent trigger focusing when opening
// this allows the content to be given focus without competition
if (!context.open) event.preventDefault();
}
}),
onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event)=>{
if (disabled) return;
if ([
'Enter',
' '
].includes(event.key)) context.onOpenToggle();
if (event.key === 'ArrowDown') context.onOpenChange(true); // prevent keydown from scrolling window / first focused item to execute
// that keydown (inadvertently closing the menu)
if ([
'Enter',
' ',
'ArrowDown'
].includes(event.key)) event.preventDefault();
})
})));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$d2469213b3befba9, {
displayName: $d08ef79370b62062$var$TRIGGER_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuPortal
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$PORTAL_NAME = 'DropdownMenuPortal';
const $d08ef79370b62062$export$cd369b4d4d54efc9 = (props)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...portalProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$602eac185826482c, extends_extends({}, menuScope, portalProps));
};
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$cd369b4d4d54efc9, {
displayName: $d08ef79370b62062$var$PORTAL_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuContent
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$CONTENT_NAME = 'DropdownMenuContent';
const $d08ef79370b62062$export$6e76d93a37c01248 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...contentProps } = props;
const context = $d08ef79370b62062$var$useDropdownMenuContext($d08ef79370b62062$var$CONTENT_NAME, __scopeDropdownMenu);
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
const hasInteractedOutsideRef = (0,external_React_.useRef)(false);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$7c6e2c02157bb7d2, extends_extends({
id: context.contentId,
"aria-labelledby": context.triggerId
}, menuScope, contentProps, {
ref: forwardedRef,
onCloseAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onCloseAutoFocus, (event)=>{
var _context$triggerRef$c;
if (!hasInteractedOutsideRef.current) (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus();
hasInteractedOutsideRef.current = false; // Always prevent auto focus because we either focus manually or want user agent focus
event.preventDefault();
}),
onInteractOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onInteractOutside, (event)=>{
const originalEvent = event.detail.originalEvent;
const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
if (!context.modal || isRightClick) hasInteractedOutsideRef.current = true;
}),
style: {
...props.style,
'--radix-dropdown-menu-content-transform-origin': 'var(--radix-popper-transform-origin)',
'--radix-dropdown-menu-content-available-width': 'var(--radix-popper-available-width)',
'--radix-dropdown-menu-content-available-height': 'var(--radix-popper-available-height)',
'--radix-dropdown-menu-trigger-width': 'var(--radix-popper-anchor-width)',
'--radix-dropdown-menu-trigger-height': 'var(--radix-popper-anchor-height)'
}
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$6e76d93a37c01248, {
displayName: $d08ef79370b62062$var$CONTENT_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuGroup
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$GROUP_NAME = 'DropdownMenuGroup';
const $d08ef79370b62062$export$246bebaba3a2f70e = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...groupProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$eb2fcfdbd7ba97d4, extends_extends({}, menuScope, groupProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$246bebaba3a2f70e, {
displayName: $d08ef79370b62062$var$GROUP_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuLabel
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$LABEL_NAME = 'DropdownMenuLabel';
const $d08ef79370b62062$export$76e48c5b57f24495 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...labelProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$b04be29aa201d4f5, extends_extends({}, menuScope, labelProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$76e48c5b57f24495, {
displayName: $d08ef79370b62062$var$LABEL_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuItem
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$ITEM_NAME = 'DropdownMenuItem';
const $d08ef79370b62062$export$ed97964d1871885d = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...itemProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$6d08773d2e66f8f2, extends_extends({}, menuScope, itemProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$ed97964d1871885d, {
displayName: $d08ef79370b62062$var$ITEM_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuCheckboxItem
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$CHECKBOX_ITEM_NAME = 'DropdownMenuCheckboxItem';
const $d08ef79370b62062$export$53a69729da201fa9 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...checkboxItemProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$16ce288f89fa631c, extends_extends({}, menuScope, checkboxItemProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$53a69729da201fa9, {
displayName: $d08ef79370b62062$var$CHECKBOX_ITEM_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuRadioGroup
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$RADIO_GROUP_NAME = 'DropdownMenuRadioGroup';
const $d08ef79370b62062$export$3323ad73d55f587e = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...radioGroupProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$a98f0dcb43a68a25, extends_extends({}, menuScope, radioGroupProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$3323ad73d55f587e, {
displayName: $d08ef79370b62062$var$RADIO_GROUP_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuRadioItem
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$RADIO_ITEM_NAME = 'DropdownMenuRadioItem';
const $d08ef79370b62062$export$e4f69b41b1637536 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...radioItemProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$371ab307eab489c0, extends_extends({}, menuScope, radioItemProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$e4f69b41b1637536, {
displayName: $d08ef79370b62062$var$RADIO_ITEM_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuItemIndicator
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$INDICATOR_NAME = 'DropdownMenuItemIndicator';
const $d08ef79370b62062$export$42355ae145153fb6 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...itemIndicatorProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$c3468e2714d175fa, extends_extends({}, menuScope, itemIndicatorProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$42355ae145153fb6, {
displayName: $d08ef79370b62062$var$INDICATOR_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuSeparator
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$SEPARATOR_NAME = 'DropdownMenuSeparator';
const $d08ef79370b62062$export$da160178fd3bc7e9 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...separatorProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$1ff3c3f08ae963c0, extends_extends({}, menuScope, separatorProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$da160178fd3bc7e9, {
displayName: $d08ef79370b62062$var$SEPARATOR_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuArrow
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$ARROW_NAME = 'DropdownMenuArrow';
const $d08ef79370b62062$export$34b8980744021ec5 = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...arrowProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$21b07c8f274aebd5, extends_extends({}, menuScope, arrowProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$34b8980744021ec5, {
displayName: $d08ef79370b62062$var$ARROW_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuSub
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$export$2f307d81a64f5442 = (props)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , children: children , open: openProp , onOpenChange: onOpenChange , defaultOpen: defaultOpen } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
const [open = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({
prop: openProp,
defaultProp: defaultOpen,
onChange: onOpenChange
});
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$d7a01e11500dfb6f, extends_extends({}, menuScope, {
open: open,
onOpenChange: setOpen
}), children);
};
/* -------------------------------------------------------------------------------------------------
* DropdownMenuSubTrigger
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$SUB_TRIGGER_NAME = 'DropdownMenuSubTrigger';
const $d08ef79370b62062$export$21dcb7ec56f874cf = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...subTriggerProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$2ea8a7a591ac5eac, extends_extends({}, menuScope, subTriggerProps, {
ref: forwardedRef
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$21dcb7ec56f874cf, {
displayName: $d08ef79370b62062$var$SUB_TRIGGER_NAME
});
/* -------------------------------------------------------------------------------------------------
* DropdownMenuSubContent
* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$var$SUB_CONTENT_NAME = 'DropdownMenuSubContent';
const $d08ef79370b62062$export$f34ec8bc2482cc5f = /*#__PURE__*/ (0,external_React_.forwardRef)((props, forwardedRef)=>{
const { __scopeDropdownMenu: __scopeDropdownMenu , ...subContentProps } = props;
const menuScope = $d08ef79370b62062$var$useMenuScope(__scopeDropdownMenu);
return /*#__PURE__*/ (0,external_React_.createElement)($6cc32821e9371a1c$export$6d4de93b380beddf, extends_extends({}, menuScope, subContentProps, {
ref: forwardedRef,
style: {
...props.style,
'--radix-dropdown-menu-content-transform-origin': 'var(--radix-popper-transform-origin)',
'--radix-dropdown-menu-content-available-width': 'var(--radix-popper-available-width)',
'--radix-dropdown-menu-content-available-height': 'var(--radix-popper-available-height)',
'--radix-dropdown-menu-trigger-width': 'var(--radix-popper-anchor-width)',
'--radix-dropdown-menu-trigger-height': 'var(--radix-popper-anchor-height)'
}
}));
});
/*#__PURE__*/ Object.assign($d08ef79370b62062$export$f34ec8bc2482cc5f, {
displayName: $d08ef79370b62062$var$SUB_CONTENT_NAME
});
/* -----------------------------------------------------------------------------------------------*/ const $d08ef79370b62062$export$be92b6f5f03c0fe9 = $d08ef79370b62062$export$e44a253a59704894;
const $d08ef79370b62062$export$41fb9f06171c75f4 = $d08ef79370b62062$export$d2469213b3befba9;
const $d08ef79370b62062$export$602eac185826482c = $d08ef79370b62062$export$cd369b4d4d54efc9;
const $d08ef79370b62062$export$7c6e2c02157bb7d2 = $d08ef79370b62062$export$6e76d93a37c01248;
const $d08ef79370b62062$export$eb2fcfdbd7ba97d4 = $d08ef79370b62062$export$246bebaba3a2f70e;
const $d08ef79370b62062$export$b04be29aa201d4f5 = $d08ef79370b62062$export$76e48c5b57f24495;
const $d08ef79370b62062$export$6d08773d2e66f8f2 = $d08ef79370b62062$export$ed97964d1871885d;
const $d08ef79370b62062$export$16ce288f89fa631c = $d08ef79370b62062$export$53a69729da201fa9;
const $d08ef79370b62062$export$a98f0dcb43a68a25 = $d08ef79370b62062$export$3323ad73d55f587e;
const $d08ef79370b62062$export$371ab307eab489c0 = $d08ef79370b62062$export$e4f69b41b1637536;
const $d08ef79370b62062$export$c3468e2714d175fa = $d08ef79370b62062$export$42355ae145153fb6;
const $d08ef79370b62062$export$1ff3c3f08ae963c0 = $d08ef79370b62062$export$da160178fd3bc7e9;
const $d08ef79370b62062$export$21b07c8f274aebd5 = (/* unused pure expression or super */ null && ($d08ef79370b62062$export$34b8980744021ec5));
const $d08ef79370b62062$export$d7a01e11500dfb6f = $d08ef79370b62062$export$2f307d81a64f5442;
const $d08ef79370b62062$export$2ea8a7a591ac5eac = $d08ef79370b62062$export$21dcb7ec56f874cf;
const $d08ef79370b62062$export$6d4de93b380beddf = $d08ef79370b62062$export$f34ec8bc2482cc5f;
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-right-small.js
/**
* WordPress dependencies
*/
const chevronRightSmall = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M10.8622 8.04053L14.2805 12.0286L10.8622 16.0167L9.72327 15.0405L12.3049 12.0286L9.72327 9.01672L10.8622 8.04053Z"
}));
/* harmony default export */ var chevron_right_small = (chevronRightSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown-menu-v2/styles.js
function dropdown_menu_v2_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ANIMATION_PARAMS = {
SLIDE_AMOUNT: '2px',
DURATION: '400ms',
EASING: 'cubic-bezier( 0.16, 1, 0.3, 1 )'
};
const CONTENT_WRAPPER_PADDING = space(2);
const ITEM_PREFIX_WIDTH = space(7);
const ITEM_PADDING_INLINE_START = space(2);
const ITEM_PADDING_INLINE_END = space(2.5); // TODO: should bring this into the config, and make themeable
const DEFAULT_BORDER_COLOR = COLORS.ui.borderDisabled;
const TOOLBAR_VARIANT_BORDER_COLOR = COLORS.gray[900];
const DEFAULT_BOX_SHADOW = `0 0 0 ${config_values.borderWidth} ${DEFAULT_BORDER_COLOR}, ${config_values.popoverShadow}`;
const TOOLBAR_VARIANT_BOX_SHADOW = `0 0 0 ${config_values.borderWidth} ${TOOLBAR_VARIANT_BORDER_COLOR}`;
const slideUpAndFade = emotion_react_browser_esm_keyframes({
'0%': {
opacity: 0,
transform: `translateY(${ANIMATION_PARAMS.SLIDE_AMOUNT})`
},
'100%': {
opacity: 1,
transform: 'translateY(0)'
}
});
const slideRightAndFade = emotion_react_browser_esm_keyframes({
'0%': {
opacity: 0,
transform: `translateX(-${ANIMATION_PARAMS.SLIDE_AMOUNT})`
},
'100%': {
opacity: 1,
transform: 'translateX(0)'
}
});
const slideDownAndFade = emotion_react_browser_esm_keyframes({
'0%': {
opacity: 0,
transform: `translateY(-${ANIMATION_PARAMS.SLIDE_AMOUNT})`
},
'100%': {
opacity: 1,
transform: 'translateY(0)'
}
});
const slideLeftAndFade = emotion_react_browser_esm_keyframes({
'0%': {
opacity: 0,
transform: `translateX(${ANIMATION_PARAMS.SLIDE_AMOUNT})`
},
'100%': {
opacity: 1,
transform: 'translateX(0)'
}
});
const baseContent = variant => /*#__PURE__*/emotion_react_browser_esm_css("min-width:220px;background-color:", COLORS.ui.background, ";border-radius:", config_values.radiusBlockUi, ";padding:", CONTENT_WRAPPER_PADDING, ";box-shadow:", variant === 'toolbar' ? TOOLBAR_VARIANT_BOX_SHADOW : DEFAULT_BOX_SHADOW, ";animation-duration:", ANIMATION_PARAMS.DURATION, ";animation-timing-function:", ANIMATION_PARAMS.EASING, ";will-change:transform,opacity;&[data-side='top']{animation-name:", slideDownAndFade, ";}&[data-side='right']{animation-name:", slideLeftAndFade, ";}&[data-side='bottom']{animation-name:", slideUpAndFade, ";}&[data-side='left']{animation-name:", slideRightAndFade, ";}@media ( prefers-reduced-motion ){animation-duration:0s;}" + ( true ? "" : 0), true ? "" : 0);
const itemPrefix = /*#__PURE__*/emotion_react_browser_esm_css("width:", ITEM_PREFIX_WIDTH, ";display:inline-flex;align-items:center;justify-content:center;margin-inline-start:calc( -1 * ", ITEM_PADDING_INLINE_START, " );margin-top:", space(-2), ";margin-bottom:", space(-2), ";" + ( true ? "" : 0), true ? "" : 0);
const itemSuffix = /*#__PURE__*/emotion_react_browser_esm_css("width:max-content;display:inline-flex;align-items:center;justify-content:center;margin-inline-start:auto;padding-inline-start:", space(6), ";margin-top:", space(-2), ";margin-bottom:", space(-2), ";opacity:0.6;[data-highlighted]>&,[data-state='open']>&,[data-disabled]>&{opacity:1;}" + ( true ? "" : 0), true ? "" : 0);
const ItemPrefixWrapper = createStyled("span", true ? {
target: "e1kdzosf11"
} : 0)(itemPrefix, ";" + ( true ? "" : 0));
const ItemSuffixWrapper = createStyled("span", true ? {
target: "e1kdzosf10"
} : 0)(itemSuffix, ";" + ( true ? "" : 0));
const baseItem = /*#__PURE__*/emotion_react_browser_esm_css("all:unset;font-size:", font('default.fontSize'), ";font-family:inherit;font-weight:normal;line-height:20px;color:", COLORS.gray[900], ";border-radius:", config_values.radiusBlockUi, ";display:flex;align-items:center;padding:", space(2), " ", ITEM_PADDING_INLINE_END, " ", space(2), " ", ITEM_PADDING_INLINE_START, ";position:relative;user-select:none;outline:none;&[data-disabled]{opacity:0.5;pointer-events:none;}&[data-highlighted]{background-color:", COLORS.gray[100], ";outline:2px solid transparent;}svg{fill:currentColor;}&:not( :has( ", ItemPrefixWrapper, " ) ){padding-inline-start:", ITEM_PREFIX_WIDTH, ";}" + ( true ? "" : 0), true ? "" : 0);
const dropdown_menu_v2_styles_Content = /*#__PURE__*/createStyled($d08ef79370b62062$export$7c6e2c02157bb7d2, true ? {
target: "e1kdzosf9"
} : 0)(props => baseContent(props.variant), ";" + ( true ? "" : 0));
const SubContent = /*#__PURE__*/createStyled($d08ef79370b62062$export$6d4de93b380beddf, true ? {
target: "e1kdzosf8"
} : 0)(props => baseContent(props.variant), ";" + ( true ? "" : 0));
const styles_Item = /*#__PURE__*/createStyled($d08ef79370b62062$export$6d08773d2e66f8f2, true ? {
target: "e1kdzosf7"
} : 0)(baseItem, ";" + ( true ? "" : 0));
const CheckboxItem = /*#__PURE__*/createStyled($d08ef79370b62062$export$16ce288f89fa631c, true ? {
target: "e1kdzosf6"
} : 0)(baseItem, ";" + ( true ? "" : 0));
const RadioItem = /*#__PURE__*/createStyled($d08ef79370b62062$export$371ab307eab489c0, true ? {
target: "e1kdzosf5"
} : 0)(baseItem, ";" + ( true ? "" : 0));
const SubTrigger = /*#__PURE__*/createStyled($d08ef79370b62062$export$2ea8a7a591ac5eac, true ? {
target: "e1kdzosf4"
} : 0)(baseItem, " &[data-state='open']{background-color:", COLORS.gray[100], ";}" + ( true ? "" : 0));
const styles_Label = /*#__PURE__*/createStyled($d08ef79370b62062$export$b04be29aa201d4f5, true ? {
target: "e1kdzosf3"
} : 0)("box-sizing:border-box;display:flex;align-items:center;min-height:", space(8), ";padding:", space(2), " ", ITEM_PADDING_INLINE_END, " ", space(2), " ", ITEM_PREFIX_WIDTH, ";color:", COLORS.gray[700], ";font-size:11px;line-height:1.4;font-weight:500;text-transform:uppercase;" + ( true ? "" : 0));
const styles_Separator = /*#__PURE__*/createStyled($d08ef79370b62062$export$1ff3c3f08ae963c0, true ? {
target: "e1kdzosf2"
} : 0)("height:", config_values.borderWidth, ";background-color:", props => props.variant === 'toolbar' ? TOOLBAR_VARIANT_BORDER_COLOR : DEFAULT_BORDER_COLOR, ";margin:", space(2), " calc( -1 * ", CONTENT_WRAPPER_PADDING, " );" + ( true ? "" : 0));
const ItemIndicator = /*#__PURE__*/createStyled($d08ef79370b62062$export$c3468e2714d175fa, true ? {
target: "e1kdzosf1"
} : 0)( true ? {
name: "pl708y",
styles: "display:inline-flex;align-items:center;justify-content:center"
} : 0);
const SubmenuRtlChevronIcon = /*#__PURE__*/createStyled(build_module_icon, true ? {
target: "e1kdzosf0"
} : 0)(rtl({
transform: `scaleX(1) translateX(${space(2)})`
}, {
transform: `scaleX(-1) translateX(${space(2)})`
})(), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown-menu-v2/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Menu content's side padding + 4px
const SUB_MENU_OFFSET_SIDE = 16; // Opposite amount of the top padding of the menu item
const SUB_MENU_OFFSET_ALIGN = -8;
const DropdownMenuPrivateContext = (0,external_wp_element_namespaceObject.createContext)({
variant: undefined,
portalContainer: null
});
const dropdown_menu_v2_UnconnectedDropdownMenu = props => {
const {
// Root props
defaultOpen,
open,
onOpenChange,
modal = true,
// Content positioning props
side = 'bottom',
sideOffset = 0,
align = 'center',
alignOffset = 0,
// Render props
children,
trigger,
// From internal components context
variant
} = useContextSystem(props, 'DropdownMenu'); // Render the portal in the default slot used by the legacy Popover component.
const slot = useSlot(SLOT_NAME);
const portalContainer = slot.ref?.current;
const privateContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
variant,
portalContainer
}), [variant, portalContainer]);
return (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$be92b6f5f03c0fe9, {
defaultOpen: defaultOpen,
open: open,
onOpenChange: onOpenChange,
modal: modal,
dir: (0,external_wp_i18n_namespaceObject.isRTL)() ? 'rtl' : 'ltr'
}, (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$41fb9f06171c75f4, {
asChild: true
}, trigger), (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$602eac185826482c, {
container: portalContainer
}, (0,external_wp_element_namespaceObject.createElement)(dropdown_menu_v2_styles_Content, {
side: side,
align: align,
sideOffset: sideOffset,
alignOffset: alignOffset,
loop: true,
variant: variant
}, (0,external_wp_element_namespaceObject.createElement)(DropdownMenuPrivateContext.Provider, {
value: privateContextValue
}, children))));
};
/**
* `DropdownMenu` displays a menu to the user (such as a set of actions
* or functions) triggered by a button.
*/
const dropdown_menu_v2_DropdownMenu = contextConnectWithoutRef(dropdown_menu_v2_UnconnectedDropdownMenu, 'DropdownMenu');
const DropdownSubMenuTrigger = ({
prefix,
suffix = (0,external_wp_element_namespaceObject.createElement)(SubmenuRtlChevronIcon, {
icon: chevron_right_small,
size: 24
}),
children
}) => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, prefix && (0,external_wp_element_namespaceObject.createElement)(ItemPrefixWrapper, null, prefix), children, suffix && (0,external_wp_element_namespaceObject.createElement)(ItemSuffixWrapper, null, suffix));
};
const DropdownSubMenu = ({
// Sub props
defaultOpen,
open,
onOpenChange,
// Sub trigger props
disabled,
textValue,
// Render props
children,
trigger
}) => {
const {
variant,
portalContainer
} = (0,external_wp_element_namespaceObject.useContext)(DropdownMenuPrivateContext);
return (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$d7a01e11500dfb6f, {
defaultOpen: defaultOpen,
open: open,
onOpenChange: onOpenChange
}, (0,external_wp_element_namespaceObject.createElement)(SubTrigger, {
disabled: disabled,
textValue: textValue
}, trigger), (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$602eac185826482c, {
container: portalContainer
}, (0,external_wp_element_namespaceObject.createElement)(SubContent, {
loop: true,
sideOffset: SUB_MENU_OFFSET_SIDE,
alignOffset: SUB_MENU_OFFSET_ALIGN,
variant: variant
}, children)));
};
const DropdownMenuLabel = props => (0,external_wp_element_namespaceObject.createElement)(styles_Label, { ...props
});
const DropdownMenuGroup = props => (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$eb2fcfdbd7ba97d4, { ...props
});
const DropdownMenuItem = (0,external_wp_element_namespaceObject.forwardRef)(({
children,
prefix,
suffix,
...props
}, forwardedRef) => {
return (0,external_wp_element_namespaceObject.createElement)(styles_Item, { ...props,
ref: forwardedRef
}, prefix && (0,external_wp_element_namespaceObject.createElement)(ItemPrefixWrapper, null, prefix), children, suffix && (0,external_wp_element_namespaceObject.createElement)(ItemSuffixWrapper, null, suffix));
});
const DropdownMenuCheckboxItem = ({
children,
checked = false,
suffix,
...props
}) => {
return (0,external_wp_element_namespaceObject.createElement)(CheckboxItem, { ...props,
checked: checked
}, (0,external_wp_element_namespaceObject.createElement)(ItemPrefixWrapper, null, (0,external_wp_element_namespaceObject.createElement)(ItemIndicator, null, (checked === 'indeterminate' || checked === true) && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: checked === 'indeterminate' ? line_solid : library_check,
size: 24
}))), children, suffix && (0,external_wp_element_namespaceObject.createElement)(ItemSuffixWrapper, null, suffix));
};
const DropdownMenuRadioGroup = props => (0,external_wp_element_namespaceObject.createElement)($d08ef79370b62062$export$a98f0dcb43a68a25, { ...props
});
const radioDot = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Circle, {
cx: 12,
cy: 12,
r: 3,
fill: "currentColor"
}));
const DropdownMenuRadioItem = ({
children,
suffix,
...props
}) => {
return (0,external_wp_element_namespaceObject.createElement)(RadioItem, { ...props
}, (0,external_wp_element_namespaceObject.createElement)(ItemPrefixWrapper, null, (0,external_wp_element_namespaceObject.createElement)(ItemIndicator, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: radioDot,
size: 22
}))), children, suffix && (0,external_wp_element_namespaceObject.createElement)(ItemSuffixWrapper, null, suffix));
};
const DropdownMenuSeparator = props => {
const {
variant
} = (0,external_wp_element_namespaceObject.useContext)(DropdownMenuPrivateContext);
return (0,external_wp_element_namespaceObject.createElement)(styles_Separator, { ...props,
variant: variant
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/private-apis.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
lock,
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.', '@wordpress/components');
const privateApis = {};
lock(privateApis, {
CustomSelectControl: CustomSelectControl,
__experimentalPopoverLegacyPositionToPlacement: positionToPlacement,
createPrivateSlotFill: createPrivateSlotFill,
ComponentsContext: ComponentsContext,
DropdownMenuV2: dropdown_menu_v2_DropdownMenu,
DropdownMenuCheckboxItemV2: DropdownMenuCheckboxItem,
DropdownMenuGroupV2: DropdownMenuGroup,
DropdownMenuItemV2: DropdownMenuItem,
DropdownMenuLabelV2: DropdownMenuLabel,
DropdownMenuRadioGroupV2: DropdownMenuRadioGroup,
DropdownMenuRadioItemV2: DropdownMenuRadioItem,
DropdownMenuSeparatorV2: DropdownMenuSeparator,
DropdownSubMenuV2: DropdownSubMenu,
DropdownSubMenuTriggerV2: DropdownSubMenuTrigger
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/index.js
// Primitives.
// Components.
// Higher-Order Components.
// Private APIs.
}();
(window.wp = window.wp || {}).components = __webpack_exports__;
/******/ })()
;