) & 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/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'
;// 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 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(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 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 (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)
parse(characters, root, reference, reference, props, rulesets, length, points, children)
else
switch (atrule === 99 && Utility_charat(characters, 3) === 110 ? 100 : atrule) {
// d m s
case 100: case 109: case 115:
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:
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 === children[0]; // in nested rules comments become children of the "auto-inserted" rule
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? children[0].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;
};
/* harmony default export */ const emotion_cache_browser_esm = (createCache);
;// 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);
}
/* harmony default export */ const emotion_hash_esm = (murmur2);
;// CONCATENATED MODULE: ./node_modules/@emotion/unitless/dist/emotion-unitless.esm.js
var unitlessKeys = {
animationIterationCount: 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
};
/* harmony default export */ const emotion_unitless_esm = (unitlessKeys);
;// 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 (emotion_unitless_esm[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 = emotion_hash_esm(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 = (/* unused pure expression or super */ null && (useInsertionEffect || useLayoutEffect));
;// CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-element-6a883da9.browser.esm.js
var emotion_element_6a883da9_browser_esm_hasOwnProperty = {}.hasOwnProperty;
var EmotionCacheContext = /* #__PURE__ */(0,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__ */emotion_cache_browser_esm({
key: 'css'
}) : null);
if (false) {}
var CacheProvider = EmotionCacheContext.Provider;
var __unsafe_useEmotionCache = function useEmotionCache() {
return (0,external_React_.useContext)(EmotionCacheContext);
};
var emotion_element_6a883da9_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);
});
};
var emotion_element_6a883da9_browser_esm_ThemeContext = /* #__PURE__ */(0,external_React_.createContext)({});
if (false) {}
var useTheme = function useTheme() {
return useContext(emotion_element_6a883da9_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 = useContext(emotion_element_6a883da9_browser_esm_ThemeContext);
if (props.theme !== theme) {
theme = createCacheWithTheme(theme)(props.theme);
}
return /*#__PURE__*/createElement(emotion_element_6a883da9_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 = useContext(emotion_element_6a883da9_browser_esm_ThemeContext);
return /*#__PURE__*/createElement(Component, _extends({
theme: theme,
ref: ref
}, props));
}; // $FlowFixMe
var WithTheme = /*#__PURE__*/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_6a883da9_browser_esm_createEmotionProps = function createEmotionProps(type, props) {
if (false) {}
var newProps = {};
for (var key in props) {
if (emotion_element_6a883da9_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);
var rules = useInsertionEffectAlwaysWithSyncFallback(function () {
return insertStyles(cache, serialized, isStringTag);
});
return null;
};
var emotion_element_6a883da9_browser_esm_Emotion = /* #__PURE__ */(/* unused pure expression or super */ null && (emotion_element_6a883da9_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, useContext(emotion_element_6a883da9_browser_esm_ThemeContext));
if (false) { var labelFromStack; }
className += cache.key + "-" + serialized.name;
var newProps = {};
for (var key in props) {
if (emotion_element_6a883da9_browser_esm_hasOwnProperty.call(props, key) && key !== 'css' && key !== typePropName && ( true || 0)) {
newProps[key] = props[key];
}
}
newProps.ref = ref;
newProps.className = className;
return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof WrappedComponent === 'string'
}), /*#__PURE__*/createElement(WrappedComponent, newProps));
})));
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js
var 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
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 {
var maybeStyles = 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 = emotion_cache_browser_esm(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, 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 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;
};
/* harmony default export */ const emotion_css_create_instance_esm = (createEmotion);
;// CONCATENATED MODULE: ./node_modules/@emotion/css/dist/emotion-css.esm.js
var _createEmotion = emotion_css_create_instance_esm({
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,
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
// 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.
*
* ```jsx
* import { css } from '@emotion/react';
*
* const styles = css`
* color: red
* `;
*
* function RedText( { className, ...props } ) {
* const cx = useCx();
*
* const classes = cx(styles, className);
*
* return ;
* }
* ```
*/
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/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} The connected props.
*/
function useContextSystem(props, namespace) {
const contextSystemProps = useComponentsContext();
if (typeof namespace === 'undefined') {
true ? external_wp_warning_default()('useContextSystem: Please provide a namespace') : 0;
}
const contextProps = contextSystemProps?.[namespace] || {};
/* eslint-disable jsdoc/no-undefined-types */
/** @type {ConnectedProps
} */
// @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/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') {
true ? external_wp_warning_default()('contextConnect: Please provide a namespace') : 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/4f3a11243c365f94892e479bff0b922ccc4ccda3/packages/components/src/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);
var rules = 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_6a883da9_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 = (0,external_React_.useContext)(emotion_element_6a883da9_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__*/(0,external_React_.createElement)(external_React_.Fragment, null, /*#__PURE__*/(0,external_React_.createElement)(emotion_styled_base_browser_esm_Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof FinalTag === 'string'
}), /*#__PURE__*/(0,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;
};
};
/* harmony default export */ const emotion_styled_base_browser_esm = (createStyled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/view/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PolymorphicDiv = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "e19lxcc00"
} : 0)( true ? "" : 0);
function UnforwardedView({
as,
...restProps
}, ref) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(PolymorphicDiv, {
as: as,
ref: ref,
...restProps
});
}
/**
* `View` is a core component that renders everything in the library.
* It is the principle component in the entire library.
*
* ```jsx
* import { View } from `@wordpress/components`;
*
* function Example() {
* return (
*
* Code is Poetry
*
* );
* }
* ```
*/
const View = Object.assign((0,external_wp_element_namespaceObject.forwardRef)(UnforwardedView), {
selector: '.components-view'
});
/* harmony default export */ const 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
*
*
* );
* }
* ```
*/
const component_VisuallyHidden = contextConnect(UnconnectedVisuallyHidden, 'VisuallyHidden');
/* harmony default export */ const visually_hidden_component = (component_VisuallyHidden);
;// 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();
/**
* Normalizes and transforms an incoming value to better match the alignment values
*
* @param value An alignment value to parse.
*
* @return The parsed value.
*/
function normalize(value) {
const normalized = value === 'center' ? 'center center' : value;
// Strictly speaking, this could be `string | null | undefined`,
// but will be validated shortly, so we're typecasting to an
// `AlignmentMatrixControlValue` to keep TypeScript happy.
const transformed = normalized?.replace('-', ' ');
return ALIGNMENTS.includes(transformed) ? transformed : undefined;
}
/**
* 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 normalized = normalize(value);
if (!normalized) {
return;
}
const id = normalized.replace(' ', '-');
return `${prefixId}-${id}`;
}
/**
* Extracts an item value from its ID
*
* @param prefixId An ID prefix to remove
* @param id An item ID
* @return The item value
*/
function getItemValue(prefixId, id) {
const value = id?.replace(prefixId + '-', '');
return normalize(value);
}
/**
* Retrieves the alignment index from a value.
*
* @param alignment Value to check.
*
* @return The index of a matching alignment.
*/
function getAlignmentIndex(alignment = 'center') {
const normalized = normalize(alignment);
if (!normalized) {
return undefined;
}
const index = ALIGNMENTS.indexOf(normalized);
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__(1880);
;// CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-react.browser.esm.js
var pkg = {
name: "@emotion/react",
version: "11.10.6",
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"
},
"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"
},
"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"
},
"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"
},
"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": "./macro.js"
},
types: "types/index.d.ts",
files: [
"src",
"dist",
"jsx-runtime",
"jsx-dev-runtime",
"_isolated-hnrs",
"types/*.d.ts",
"macro.js",
"macro.d.ts",
"macro.js.flow"
],
sideEffects: false,
author: "Emotion Contributors",
license: "MIT",
scripts: {
"test:typescript": "dtslint types"
},
dependencies: {
"@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.10.6",
"@emotion/cache": "^11.10.5",
"@emotion/serialize": "^1.1.1",
"@emotion/use-insertion-effect-with-fallbacks": "^1.0.0",
"@emotion/utils": "^1.2.0",
"@emotion/weak-memoize": "^0.3.0",
"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.10.6",
"@emotion/css-prettifier": "1.1.1",
"@emotion/server": "11.10.0",
"@emotion/styled": "11.10.6",
"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": "./macro.js"
}
}
}
};
var jsx = function jsx(type, props) {
var args = arguments;
if (props == null || !hasOwnProperty.call(props, 'css')) {
// $FlowFixMe
return 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 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, useContext(ThemeContext));
// 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 = 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 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;
var rules = useInsertionEffectAlwaysWithSyncFallback(function () {
for (var i = 0; i < serializedArr.length; i++) {
var res = 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: useContext(ThemeContext)
};
var ele = props.children(content);
hasRendered = true;
return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/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/@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'
};
// Should match packages/components/src/utils/theme-variables.scss
const THEME = {
accent: `var(--wp-components-color-accent, var(--wp-admin-theme-color, #3858e9))`,
accentDarker10: `var(--wp-components-color-accent-darker-10, var(--wp-admin-theme-color-darker-10, #2145e6))`,
accentDarker20: `var(--wp-components-color-accent-darker-20, var(--wp-admin-theme-color-darker-20, #183ad6))`,
/** Used when placing text on the accent color. */
accentInverted: `var(--wp-components-color-accent-inverted, ${white})`,
background: `var(--wp-components-color-background, ${white})`,
foreground: `var(--wp-components-color-foreground, ${GRAY[900]})`,
/** Used when placing text on the foreground color. */
foregroundInverted: `var(--wp-components-color-foreground-inverted, ${white})`,
gray: {
/** @deprecated Use `COLORS.theme.foreground` instead. */
900: `var(--wp-components-color-foreground, ${GRAY[900]})`,
800: `var(--wp-components-color-gray-800, ${GRAY[800]})`,
700: `var(--wp-components-color-gray-700, ${GRAY[700]})`,
600: `var(--wp-components-color-gray-600, ${GRAY[600]})`,
400: `var(--wp-components-color-gray-400, ${GRAY[400]})`,
300: `var(--wp-components-color-gray-300, ${GRAY[300]})`,
200: `var(--wp-components-color-gray-200, ${GRAY[200]})`,
100: `var(--wp-components-color-gray-100, ${GRAY[100]})`
}
};
const UI = {
background: THEME.background,
backgroundDisabled: THEME.gray[100],
border: THEME.gray[600],
borderHover: THEME.gray[700],
borderFocus: THEME.accent,
borderDisabled: THEME.gray[400],
textDisabled: THEME.gray[600],
// Matches @wordpress/base-styles
darkGrayPlaceholder: `color-mix(in srgb, ${THEME.foreground}, transparent 38%)`,
lightGrayPlaceholder: `color-mix(in srgb, ${THEME.background}, transparent 35%)`
};
const COLORS = Object.freeze({
/**
* The main gray color object.
*
* @deprecated Use semantic aliases in `COLORS.ui` or theme-ready variables in `COLORS.theme.gray`.
*/
gray: GRAY,
// TODO: Stop exporting this when everything is migrated to `theme` or `ui`
white,
alert: ALERT,
/**
* Theme-ready variables with fallbacks.
*
* Prefer semantic aliases in `COLORS.ui` when applicable.
*/
theme: THEME,
/**
* Semantic aliases (prefer these over raw variables when applicable).
*/
ui: UI
});
/* harmony default export */ const colors_values = ((/* unused pure expression or super */ null && (COLORS)));
;// 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 = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "ecapk1j3"
} : 0)(rootBase, ";border:1px solid transparent;cursor:pointer;grid-template-columns:auto;", rootSize, ";" + ( true ? "" : 0));
const Row = /*#__PURE__*/emotion_styled_base_browser_esm("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.theme.accent;
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;@media not ( prefers-reduced-motion ){transition:all 120ms linear;}", pointActive(props), ";" + ( true ? "" : 0), true ? "" : 0);
};
const Point = /*#__PURE__*/emotion_styled_base_browser_esm("span", true ? {
target: "ecapk1j1"
} : 0)("height:6px;width:6px;", pointBase, ";" + ( true ? "" : 0));
const Cell = /*#__PURE__*/emotion_styled_base_browser_esm("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({
id,
isActive = false,
value,
...props
}) {
const tooltipText = ALIGNMENT_LABEL[value];
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(tooltip, {
text: tooltipText,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(CompositeItem, {
id: id,
render: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Cell, {
...props,
role: "gridcell"
}),
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(visually_hidden_component, {
children: value
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Point, {
isActive: isActive,
role: "presentation"
})]
})
});
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/Y6GYTNQ2.js
"use client";
// src/collection/collection-store.ts
function useCollectionStoreProps(store, update, props) {
useUpdateEffect(update, [props.store]);
useStoreProps(store, props, "items", "setItems");
return store;
}
function useCollectionStore(props = {}) {
const [store, update] = useStore(Core.createCollectionStore, props);
return useCollectionStoreProps(store, update, props);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/22K762VQ.js
"use client";
// src/collection/collection-store.ts
function isElementPreceding(a, b) {
return Boolean(
b.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_PRECEDING
);
}
function 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 (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 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 DLOEKDPY_getDocument(parentElement).body;
}
function getPrivateStore(store) {
return store == null ? void 0 : store.__unstablePrivateStore;
}
function createCollectionStore(props = {}) {
var _a;
throwOnConflictingProps(props, props.store);
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 syncPrivateStore = getPrivateStore(props.store);
const privateStore = createStore(
{ items, renderedItems: initialState.renderedItems },
syncPrivateStore
);
const collection = createStore(initialState, props.store);
const sortItems = (renderedItems) => {
const sortedItems = sortBasedOnDOMPosition(renderedItems);
privateStore.setState("renderedItems", sortedItems);
collection.setState("renderedItems", sortedItems);
};
setup(collection, () => init(privateStore));
setup(privateStore, () => {
return batch(privateStore, ["items"], (state) => {
collection.setState("items", state.items);
});
});
setup(privateStore, () => {
return batch(privateStore, ["renderedItems"], (state) => {
let firstRun = true;
let raf = requestAnimationFrame(() => {
const { renderedItems } = collection.getState();
if (state.renderedItems === renderedItems)
return;
sortItems(state.renderedItems);
});
if (typeof IntersectionObserver !== "function") {
return () => cancelAnimationFrame(raf);
}
const ioCallback = () => {
if (firstRun) {
firstRun = false;
return;
}
cancelAnimationFrame(raf);
raf = requestAnimationFrame(() => sortItems(state.renderedItems));
};
const root = getCommonParent(state.renderedItems);
const observer = new IntersectionObserver(ioCallback, { root });
for (const item of state.renderedItems) {
if (!item.element)
continue;
observer.observe(item.element);
}
return () => {
cancelAnimationFrame(raf);
observer.disconnect();
};
});
});
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_4R3V3JGP_spreadValues(_chunks_4R3V3JGP_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) => privateStore.setState("items", getItems),
true
);
return _chunks_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_spreadValues({}, collection), {
registerItem,
renderItem: (item) => 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;
},
// @ts-expect-error Internal
__unstablePrivateStore: privateStore
});
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/__chunks/7PRQYBBV.js
"use client";
// src/utils/array.ts
function 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/IERTEJ3A.js
"use client";
// src/composite/composite-store.ts
var IERTEJ3A_NULL_ITEM = { id: null };
function IERTEJ3A_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 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 IERTEJ3A_flipItems(items, activeId, shouldInsertNullItem = false) {
const index = items.findIndex((item) => item.id === activeId);
return [
...items.slice(index + 1),
...shouldInsertNullItem ? [IERTEJ3A_NULL_ITEM] : [],
...items.slice(0, index)
];
}
function IERTEJ3A_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 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 ? IERTEJ3A_findFirstEnabledItem(row) : row[i - 1];
row[i] = previousItem && activeId !== previousItem.id && focusShift ? previousItem : createEmptyItem(previousItem == null ? void 0 : previousItem.rowId);
}
}
}
return rows;
}
function verticalizeItems(items) {
const rows = IERTEJ3A_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_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_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_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_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);
setup(
composite,
() => sync(composite, ["renderedItems", "activeId"], (state) => {
composite.setState("activeId", (activeId2) => {
var _a2;
if (activeId2 !== void 0)
return activeId2;
return (_a2 = IERTEJ3A_findFirstEnabledItem(state.renderedItems)) == null ? void 0 : _a2.id;
});
})
);
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 = IERTEJ3A_findFirstEnabledItem(allItems)) == null ? void 0 : _a2.id;
}
const activeItem = allItems.find((item) => item.id === activeId2);
if (!activeItem) {
return (_b = IERTEJ3A_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 = 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 = IERTEJ3A_flipItems(loopItems, activeId2, hasNullItem);
const nextItem2 = IERTEJ3A_findFirstEnabledItem(sortedItems, activeId2);
return nextItem2 == null ? void 0 : nextItem2.id;
}
if (canWrap) {
const nextItem2 = IERTEJ3A_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 = IERTEJ3A_findFirstEnabledItem(nextItemsInRow, activeId2);
if (!nextItem && hasNullItem) {
return null;
}
return nextItem == null ? void 0 : nextItem.id;
};
return _chunks_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_spreadValues(_chunks_4R3V3JGP_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 = IERTEJ3A_findFirstEnabledItem(composite.getState().renderedItems)) == null ? void 0 : _a2.id;
},
last: () => {
var _a2;
return (_a2 = IERTEJ3A_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 = IERTEJ3A_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 = verticalizeItems(
flatten2DArray(
normalizeRows(IERTEJ3A_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 = verticalizeItems(
reverseArray(
flatten2DArray(
normalizeRows(
IERTEJ3A_groupItemsByRows(renderedItems),
activeId2,
shouldShift
)
)
)
);
const hasNullItem = includesBaseElement;
return getNextId(verticalItems, "vertical", hasNullItem, skip);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/7GBW5FLS.js
"use client";
// src/composite/composite-store.ts
function useCompositeStoreProps(store, update, props) {
store = useCollectionStoreProps(store, update, 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 [store, update] = EKQEJRUF_useStore(createCompositeStore, props);
return useCompositeStoreProps(store, update, props);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/7QTPYGNZ.js
"use client";
// src/composite/composite.tsx
function isGrid(items) {
return items.some((item) => !!item.rowId);
}
function isPrintableKey(event) {
const target = event.target;
if (target && !DLOEKDPY_isTextField(target))
return false;
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 useKeyboardEventProxy(store, onKeyboardEvent, previousElementRef) {
return useEvent((event) => {
var _a;
onKeyboardEvent == null ? void 0 : onKeyboardEvent(event);
if (event.defaultPrevented)
return;
if (event.isPropagationStopped())
return;
if (!isSelfTarget(event))
return;
if (isModifierKey(event))
return;
if (isPrintableKey(event))
return;
const state = store.getState();
const activeElement = (_a = getEnabledItem(store, state.activeId)) == null ? void 0 : _a.element;
if (!activeElement)
return;
const _b = event, { view } = _b, eventInit = __objRest(_b, ["view"]);
const previousElement = previousElementRef == null ? void 0 : previousElementRef.current;
if (activeElement !== previousElement) {
activeElement.focus();
}
if (!fireKeyboardEvent(activeElement, event.type, eventInit)) {
event.preventDefault();
}
if (event.currentTarget.contains(activeElement)) {
event.stopPropagation();
}
});
}
function findFirstEnabledItemInTheLastRow(items) {
return 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 useComposite = createHook(
(_a) => {
var _b = _a, {
store,
composite = true,
focusOnMove = composite,
moveOnKeyPress = true
} = _b, props = __objRest(_b, [
"store",
"composite",
"focusOnMove",
"moveOnKeyPress"
]);
const context = useCompositeProviderContext();
store = store || context;
invariant(
store,
false && 0
);
const previousElementRef = (0,external_React_.useRef)(null);
const scheduleFocus = useScheduleFocus(store);
const moves = store.useState("moves");
(0,external_React_.useEffect)(() => {
var _a2;
if (!store)
return;
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);
}, [store, moves, composite, focusOnMove]);
useSafeLayoutEffect(() => {
if (!store)
return;
if (!moves)
return;
if (!composite)
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) {
fireBlurEvent(previousElement, { relatedTarget: baseElement });
}
if (!hasFocus(baseElement)) {
baseElement.focus();
}
}, [store, moves, composite]);
const activeId = store.useState("activeId");
const virtualFocus = store.useState("virtualFocus");
useSafeLayoutEffect(() => {
var _a2;
if (!store)
return;
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 || getActiveElement(previousElement);
if (relatedTarget === previousElement)
return;
fireBlurEvent(previousElement, { relatedTarget });
}, [store, activeId, virtualFocus, composite]);
const onKeyDownCapture = useKeyboardEventProxy(
store,
props.onKeyDownCapture,
previousElementRef
);
const onKeyUpCapture = useKeyboardEventProxy(
store,
props.onKeyUpCapture,
previousElementRef
);
const onFocusCaptureProp = props.onFocusCapture;
const onFocusCapture = useEvent((event) => {
onFocusCaptureProp == null ? void 0 : onFocusCaptureProp(event);
if (event.defaultPrevented)
return;
if (!store)
return;
const { virtualFocus: virtualFocus2 } = store.getState();
if (!virtualFocus2)
return;
const previousActiveElement = event.relatedTarget;
const isSilentlyFocused = silentlyFocused(event.currentTarget);
if (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;
if (!store)
return;
const { relatedTarget } = event;
const { virtualFocus: virtualFocus2 } = store.getState();
if (virtualFocus2) {
if (isSelfTarget(event) && !isItem(store, relatedTarget)) {
queueMicrotask(scheduleFocus);
}
} else if (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;
if (!store)
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 = isItem(store, nextActiveElement);
const previousElement = previousElementRef.current;
previousElementRef.current = null;
if (isSelfTarget(event) && nextActiveElementIsItem) {
if (nextActiveElement === activeElement) {
if (previousElement && previousElement !== nextActiveElement) {
fireBlurEvent(previousElement, event);
}
} else if (activeElement) {
fireBlurEvent(activeElement, event);
} else if (previousElement) {
fireBlurEvent(previousElement, event);
}
event.stopPropagation();
} else {
const targetIsItem = isItem(store, event.target);
if (!targetIsItem && activeElement) {
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 (!store)
return;
if (!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 isHorizontalKey = event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === "Home" || event.key === "End";
if (isHorizontalKey && DLOEKDPY_isTextField(event.currentTarget))
return;
const up = () => {
if (grid) {
const item = items && findFirstEnabledItemInTheLastRow(items);
return item == null ? void 0 : item.id;
}
return store == null ? void 0 : 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,external_ReactJSXRuntime_namespaceObject.jsx)(CompositeContextProvider, { value: store, children: element }),
[store]
);
const activeDescendant = store.useState((state) => {
var _a2;
if (!store)
return;
if (!composite)
return;
if (!state.virtualFocus)
return;
return (_a2 = getEnabledItem(store, state.activeId)) == null ? void 0 : _a2.id;
});
props = _4R3V3JGP_spreadProps(_4R3V3JGP_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(_4R3V3JGP_spreadValues({ focusable }, props));
return props;
}
);
var Composite = createComponent((props) => {
const htmlProps = useComposite(props);
return _3ORBWXWF_createElement("div", htmlProps);
});
if (false) {}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/BNUFNEVY.js
"use client";
// src/composite/composite-row.tsx
var useCompositeRow = createHook(
(_a) => {
var _b = _a, {
store,
"aria-setsize": ariaSetSize,
"aria-posinset": ariaPosInSet
} = _b, props = __objRest(_b, [
"store",
"aria-setsize",
"aria-posinset"
]);
const context = useCompositeContext();
store = store || context;
invariant(
store,
false && 0
);
const id = useId(props.id);
const baseElement = store.useState(
(state) => state.baseElement || void 0
);
const providerValue = (0,external_React_.useMemo)(
() => ({ id, baseElement, ariaSetSize, ariaPosInSet }),
[id, baseElement, ariaSetSize, ariaPosInSet]
);
props = useWrapElement(
props,
(element) => /* @__PURE__ */ (0,external_ReactJSXRuntime_namespaceObject.jsx)(CompositeRowContext.Provider, { value: providerValue, children: element }),
[providerValue]
);
props = _4R3V3JGP_spreadValues({ id }, props);
return props;
}
);
var CompositeRow = createComponent((props) => {
const htmlProps = useCompositeRow(props);
return _3ORBWXWF_createElement("div", htmlProps);
});
if (false) {}
;// 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 = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "erowt52"
} : 0)( true ? {
name: "ogl07i",
styles: "box-sizing:border-box;padding:2px"
} : 0);
const alignment_matrix_control_icon_styles_Root = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 = dist_clsx('component-alignment-matrix-control-icon', className);
const styles = {
...style,
transform: `scale(${scale})`
};
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(alignment_matrix_control_icon_styles_Root, {
...props,
className: classes,
disablePointerEvents: disablePointerEvents,
role: "presentation",
style: styles,
children: ALIGNMENTS.map((align, index) => {
const isActive = alignIndex === index;
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(alignment_matrix_control_icon_styles_Cell, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(alignment_matrix_control_icon_styles_Point, {
isActive: isActive
})
}, align);
})
});
}
/* harmony default export */ const icon = (AlignmentMatrixControlIcon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
*
* 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 (
*
* );
* };
* ```
*/
function AlignmentMatrixControl({
className,
id,
label = (0,external_wp_i18n_namespaceObject.__)('Alignment Matrix Control'),
defaultValue = 'center center',
value,
onChange,
width = 92,
...props
}) {
const baseId = (0,external_wp_compose_namespaceObject.useInstanceId)(AlignmentMatrixControl, 'alignment-matrix-control', id);
const compositeStore = useCompositeStore({
defaultActiveId: getItemId(baseId, defaultValue),
activeId: getItemId(baseId, value),
setActiveId: nextActiveId => {
const nextValue = getItemValue(baseId, nextActiveId);
if (nextValue) {
onChange?.(nextValue);
}
},
rtl: (0,external_wp_i18n_namespaceObject.isRTL)()
});
const activeId = compositeStore.useState('activeId');
const classes = dist_clsx('component-alignment-matrix-control', className);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Composite, {
store: compositeStore,
render: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Root, {
...props,
"aria-label": label,
className: classes,
id: baseId,
role: "grid",
size: width
}),
children: GRID.map((cells, index) => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CompositeRow, {
render: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Row, {
role: "row"
}),
children: cells.map(cell => {
const cellId = getItemId(baseId, cell);
const isActive = cellId === activeId;
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(cell_Cell, {
id: cellId,
isActive: isActive,
value: cell
}, cell);
})
}, index))
});
}
AlignmentMatrixControl.Icon = icon;
/* harmony default export */ const 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 'components-animate__loading';
}
const {
type,
origin = getDefaultOrigin(type)
} = options;
if (type === 'appear') {
const [yAxis, xAxis = 'center'] = origin.split(' ');
return dist_clsx('components-animate__appear', {
['is-from-' + xAxis]: xAxis !== 'center',
['is-from-' + yAxis]: yAxis !== 'middle'
});
}
if (type === 'slide-in') {
return dist_clsx('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 = () => (
*
* { ( { className } ) => (
*
* Animation finished.
*
* ) }
*
* );
* ```
*/
function Animate({
type,
options = {},
children
}) {
return children({
className: getAnimateClassName({
type,
...options
})
});
}
/* harmony default export */ const animate = (Animate);
;// 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/is-browser.mjs
const is_browser_isBrowser = typeof document !== "undefined";
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs
const useIsomorphicLayoutEffect = is_browser_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/render/dom/utils/camel-to-dash.mjs
/**
* Convert camelCase to dash-case properties.
*/
const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase();
;// 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/GlobalConfig.mjs
const MotionGlobalConfig = {
skipAnimations: false,
useManualTiming: false,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/render-step.mjs
class Queue {
constructor() {
this.order = [];
this.scheduled = new Set();
}
add(process) {
if (!this.scheduled.has(process)) {
this.scheduled.add(process);
this.order.push(process);
return true;
}
}
remove(process) {
const index = this.order.indexOf(process);
if (index !== -1) {
this.order.splice(index, 1);
this.scheduled.delete(process);
}
}
clear() {
this.order.length = 0;
this.scheduled.clear();
}
}
function createRenderStep(runNextFrame) {
/**
* We create and reuse two queues, one to queue jobs for the current frame
* and one for the next. We reuse to avoid triggering GC after x frames.
*/
let thisFrame = new Queue();
let nextFrame = new Queue();
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 queue = addToCurrentFrame ? thisFrame : nextFrame;
if (keepAlive)
toKeepAlive.add(callback);
if (queue.add(callback) && addToCurrentFrame && isProcessing) {
// If we're adding it to the currently running queue, update its measured size
numToRun = thisFrame.order.length;
}
return callback;
},
/**
* Cancel the provided callback from running on the next frame.
*/
cancel: (callback) => {
nextFrame.remove(callback);
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;
[thisFrame, nextFrame] = [nextFrame, thisFrame];
// Clear the next frame queue
nextFrame.clear();
// Execute this frame
numToRun = thisFrame.order.length;
if (numToRun) {
for (let i = 0; i < numToRun; i++) {
const callback = thisFrame.order[i];
if (toKeepAlive.has(callback)) {
step.schedule(callback);
runNextFrame();
}
callback(frameData);
}
}
isProcessing = false;
if (flushNextFrame) {
flushNextFrame = false;
step.process(frameData);
}
},
};
return step;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/batcher.mjs
const stepsOrder = [
"read", // Read
"resolveKeyframes", // Write/Read/Write/Read
"update", // Compute
"preRender", // Compute
"render", // Write
"postRender", // Compute
];
const maxElapsed = 40;
function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
let runNextFrame = false;
let useDefaultElapsed = true;
const state = {
delta: 0,
timestamp: 0,
isProcessing: false,
};
const steps = stepsOrder.reduce((acc, key) => {
acc[key] = createRenderStep(() => (runNextFrame = true));
return acc;
}, {});
const processStep = (stepId) => {
steps[stepId].process(state);
};
const processBatch = () => {
const timestamp = MotionGlobalConfig.useManualTiming
? state.timestamp
: performance.now();
runNextFrame = false;
state.delta = useDefaultElapsed
? 1000 / 60
: Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
state.timestamp = timestamp;
state.isProcessing = true;
stepsOrder.forEach(processStep);
state.isProcessing = false;
if (runNextFrame && allowKeepAlive) {
useDefaultElapsed = false;
scheduleNextBatch(processBatch);
}
};
const wake = () => {
runNextFrame = true;
useDefaultElapsed = true;
if (!state.isProcessing) {
scheduleNextBatch(processBatch);
}
};
const schedule = stepsOrder.reduce((acc, key) => {
const step = steps[key];
acc[key] = (process, keepAlive = false, immediate = false) => {
if (!runNextFrame)
wake();
return step.schedule(process, keepAlive, immediate);
};
return acc;
}, {});
const cancel = (process) => stepsOrder.forEach((key) => steps[key].cancel(process));
return { schedule, cancel, state, steps };
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/microtask.mjs
const { schedule: microtask, cancel: cancelMicrotask } = createRenderBatcher(queueMicrotask, 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);
});
/**
* Cache this value as we want to know whether HandoffAppearAnimations
* was present on initial render - it will be deleted after this.
*/
const wantsHandoff = (0,external_React_.useRef)(Boolean(props[optimizedAppearDataAttribute] &&
!window.HandoffComplete));
useIsomorphicLayoutEffect(() => {
if (!visualElement)
return;
microtask.render(visualElement.render);
/**
* 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.
*/
if (wantsHandoff.current && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
});
(0,external_React_.useEffect)(() => {
if (!visualElement)
return;
visualElement.updateFeatures();
if (!wantsHandoff.current && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
if (wantsHandoff.current) {
wantsHandoff.current = false;
// This ensures all future calls to animateChanges() will run in useEffect
window.HandoffComplete = true;
}
});
return visualElement;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-ref-object.mjs
function isRefObject(ref) {
return (ref &&
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 (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 (v !== null &&
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/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);
const visualState = useVisualState(props, isStatic);
if (!isStatic && is_browser_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, initialLayoutGroupConfig);
}
}
/**
* The mount order and hierarchy is specific to ensure our element ref
* is hydrated by the time features fire their effects.
*/
return ((0,external_ReactJSXRuntime_namespaceObject.jsxs)(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? ((0,external_ReactJSXRuntime_namespaceObject.jsx)(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, 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
* })
*
* 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]/u.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 startsAsVariableToken = checkStringStartsWith("var(--");
const isCSSVariableToken = (value) => {
const startsWithToken = startsAsVariableToken(value);
if (!startsWithToken)
return false;
// Ensure any comments are stripped from the value as this can harm performance of the regex.
return singleCssVariableRegex.test(value.split("/*")[0].trim());
};
const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;
;// 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_clamp = (min, max, v) => {
if (v > max)
return max;
if (v < min)
return min;
return v;
};
;// 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_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+)?|\.\d+)/gu;
const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;
const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;
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,
backgroundPositionX: px,
backgroundPositionY: px,
// 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 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",
"custom",
"inherit",
"onBeforeLayoutMeasure",
"onAnimationStart",
"onAnimationComplete",
"onUpdate",
"onDragStart",
"onDrag",
"onDragEnd",
"onMeasureDragConstraints",
"onDirectionLock",
"onDragTransitionEnd",
"_dragX",
"_dragY",
"onHoverStart",
"onHoverEnd",
"onViewportEnter",
"onViewportLeave",
"globalTapTarget",
"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") ||
key.startsWith("onLayout") ||
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, attrScale, 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);
}
// Render attrX/attrY/attrScale as attributes
if (attrX !== undefined)
attrs.x = attrX;
if (attrY !== undefined)
attrs.y = attrY;
if (attrScale !== undefined)
attrs.scale = attrScale;
// 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, 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 = Component !== external_React_.Fragment
? { ...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]);
return (0,external_React_.createElement)(Component, {
...elementProps,
children: renderedChildren,
});
};
return useRender;
}
;// 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, visualElement) {
var _a;
const { style } = props;
const newValues = {};
for (const key in style) {
if (isMotionValue(style[key]) ||
(prevProps.style &&
isMotionValue(prevProps.style[key])) ||
isForcedMotionValue(key, props) ||
((_a = visualElement === null || visualElement === void 0 ? void 0 : visualElement.getValue(key)) === null || _a === void 0 ? void 0 : _a.liveStyle) !== undefined) {
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, visualElement) {
const newValues = scrapeMotionValuesFromProps(props, prevProps, visualElement);
for (const key in props) {
if (isMotionValue(props[key]) ||
isMotionValue(prevProps[key])) {
const targetKey = transformPropOrder.indexOf(key) !== -1
? "attr" + key.charAt(0).toUpperCase() + key.substring(1)
: key;
newValues[targetKey] = props[key];
}
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs
function getValueState(visualElement) {
const state = [{}, {}];
visualElement === null || visualElement === void 0 ? void 0 : visualElement.values.forEach((value, key) => {
state[0][key] = value.get();
state[1][key] = value.getVelocity();
});
return state;
}
function resolveVariantFromProps(props, definition, custom, visualElement) {
/**
* If the variant definition is a function, resolve.
*/
if (typeof definition === "function") {
const [current, velocity] = getValueState(visualElement);
definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
}
/**
* 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") {
const [current, velocity] = getValueState(visualElement);
definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
}
return definition;
}
;// 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/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/utils/noop.mjs
const noop_noop = (any) => any;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/frame.mjs
const { schedule: frame_frame, cancel: cancelFrame, state: frameData, steps, } = createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop_noop, true);
;// 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 }) => {
frame_frame.read(() => {
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,
};
}
});
frame_frame.render(() => {
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/gestures/hover.mjs
function addHoverEvent(node, isActive) {
const eventName = isActive ? "pointerenter" : "pointerleave";
const callbackName = isActive ? "onHoverStart" : "onHoverEnd";
const handleEvent = (event, info) => {
if (event.pointerType === "touch" || isDragActive())
return;
const props = node.getProps();
if (node.animationState && props.whileHover) {
node.animationState.setActive("whileHover", isActive);
}
const callback = props[callbackName];
if (callback) {
frame_frame.postRender(() => callback(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/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_noop;
this.removeEndListeners = noop_noop;
this.removeAccessibleListeners = noop_noop;
this.startPointerPress = (startEvent, startInfo) => {
if (this.isPressing)
return;
this.removeEndListeners();
const props = this.node.getProps();
const endPointerPress = (endEvent, endInfo) => {
if (!this.checkPressEnd())
return;
const { onTap, onTapCancel, globalTapTarget } = this.node.getProps();
/**
* We only count this as a tap gesture if the event.target is the same
* as, or a child of, this component's element
*/
const handler = !globalTapTarget &&
!isNodeOrChild(this.node.current, endEvent.target)
? onTapCancel
: onTap;
if (handler) {
frame_frame.update(() => handler(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) {
frame_frame.postRender(() => 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) {
frame_frame.postRender(() => 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) {
frame_frame.postRender(() => onTapCancel(event, info));
}
}
mount() {
const props = this.node.getProps();
const removePointerListener = addPointerEvent(props.globalTapTarget ? window : 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
function resolveVariant(visualElement, definition, custom) {
const props = visualElement.getProps();
return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement);
}
;// 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/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/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 getValueTransition(transition, key) {
return (transition[key] ||
transition["default"] ||
transition);
}
;// 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/animation/animators/waapi/utils/get-final-keyframe.mjs
const isNotNull = (value) => value !== null;
function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) {
const resolvedKeyframes = keyframes.filter(isNotNull);
const index = repeat && repeatType !== "loop" && repeat % 2 === 1
? 0
: resolvedKeyframes.length - 1;
return !index || finalKeyframe === undefined
? resolvedKeyframes[index]
: finalKeyframe;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/sync-time.mjs
let now;
function clearTime() {
now = undefined;
}
/**
* An eventloop-synchronous alternative to performance.now().
*
* Ensures that time measurements remain consistent within a synchronous context.
* Usually calling performance.now() twice within the same synchronous context
* will return different values which isn't useful for animations when we're usually
* trying to sync animations to the same frame.
*/
const time = {
now: () => {
if (now === undefined) {
time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming
? frameData.timestamp
: performance.now());
}
return now;
},
set: (newTime) => {
now = newTime;
queueMicrotask(clearTime);
},
};
;// 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]+$/u.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-none.mjs
function isNone(value) {
if (typeof value === "number") {
return value === 0;
}
else if (value !== null) {
return value === "none" || value === "0" || isZeroValueString(value);
}
else {
return true;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/errors.mjs
let warning = noop_noop;
let errors_invariant = noop_noop;
if (false) {}
;// 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+)?|\.\d+)$/u.test(v);
;// 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 splitCSSVariableRegex =
// eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words
/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;
function parseCSSVariable(current) {
const match = splitCSSVariableRegex.exec(current);
if (!match)
return [,];
const [, token1, token2, fallback] = match;
return [`--${token1 !== null && token1 !== void 0 ? token1 : token2}`, fallback];
}
const maxDepth = 4;
function getVariableValue(current, element, depth = 1) {
errors_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) {
const trimmed = resolved.trim();
return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
}
return isCSSVariableToken(fallback)
? getVariableValue(fallback, element, depth + 1)
: fallback;
}
;// 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",
"translateX",
"translateY",
]);
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\((.+)\)$/u);
if (matrix3d) {
return getPosFromMatrix(matrix3d[1], pos3);
}
else {
const matrix = transform.match(/^matrix\((.+)\)$/u);
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);
}
});
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),
};
// Alias translate longform names
positionalValues.translateX = positionalValues.x;
positionalValues.translateY = positionalValues.y;
;// 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/utils/KeyframesResolver.mjs
const toResolve = new Set();
let isScheduled = false;
let anyNeedsMeasurement = false;
function measureAllKeyframes() {
if (anyNeedsMeasurement) {
const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement);
const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element));
const transformsToRestore = new Map();
/**
* Write pass
* If we're measuring elements we want to remove bounding box-changing transforms.
*/
elementsToMeasure.forEach((element) => {
const removedTransforms = removeNonTranslationalTransform(element);
if (!removedTransforms.length)
return;
transformsToRestore.set(element, removedTransforms);
element.render();
});
// Read
resolversToMeasure.forEach((resolver) => resolver.measureInitialState());
// Write
elementsToMeasure.forEach((element) => {
element.render();
const restore = transformsToRestore.get(element);
if (restore) {
restore.forEach(([key, value]) => {
var _a;
(_a = element.getValue(key)) === null || _a === void 0 ? void 0 : _a.set(value);
});
}
});
// Read
resolversToMeasure.forEach((resolver) => resolver.measureEndState());
// Write
resolversToMeasure.forEach((resolver) => {
if (resolver.suspendedScrollY !== undefined) {
window.scrollTo(0, resolver.suspendedScrollY);
}
});
}
anyNeedsMeasurement = false;
isScheduled = false;
toResolve.forEach((resolver) => resolver.complete());
toResolve.clear();
}
function readAllKeyframes() {
toResolve.forEach((resolver) => {
resolver.readKeyframes();
if (resolver.needsMeasurement) {
anyNeedsMeasurement = true;
}
});
}
function flushKeyframeResolvers() {
readAllKeyframes();
measureAllKeyframes();
}
class KeyframeResolver {
constructor(unresolvedKeyframes, onComplete, name, motionValue, element, isAsync = false) {
/**
* Track whether this resolver has completed. Once complete, it never
* needs to attempt keyframe resolution again.
*/
this.isComplete = false;
/**
* Track whether this resolver is async. If it is, it'll be added to the
* resolver queue and flushed in the next frame. Resolvers that aren't going
* to trigger read/write thrashing don't need to be async.
*/
this.isAsync = false;
/**
* Track whether this resolver needs to perform a measurement
* to resolve its keyframes.
*/
this.needsMeasurement = false;
/**
* Track whether this resolver is currently scheduled to resolve
* to allow it to be cancelled and resumed externally.
*/
this.isScheduled = false;
this.unresolvedKeyframes = [...unresolvedKeyframes];
this.onComplete = onComplete;
this.name = name;
this.motionValue = motionValue;
this.element = element;
this.isAsync = isAsync;
}
scheduleResolve() {
this.isScheduled = true;
if (this.isAsync) {
toResolve.add(this);
if (!isScheduled) {
isScheduled = true;
frame_frame.read(readAllKeyframes);
frame_frame.resolveKeyframes(measureAllKeyframes);
}
}
else {
this.readKeyframes();
this.complete();
}
}
readKeyframes() {
const { unresolvedKeyframes, name, element, motionValue } = this;
/**
* If a keyframe is null, we hydrate it either by reading it from
* the instance, or propagating from previous keyframes.
*/
for (let i = 0; i < unresolvedKeyframes.length; i++) {
if (unresolvedKeyframes[i] === null) {
/**
* If the first keyframe is null, we need to find its value by sampling the element
*/
if (i === 0) {
const currentValue = motionValue === null || motionValue === void 0 ? void 0 : motionValue.get();
const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
if (currentValue !== undefined) {
unresolvedKeyframes[0] = currentValue;
}
else if (element && name) {
const valueAsRead = element.readValue(name, finalKeyframe);
if (valueAsRead !== undefined && valueAsRead !== null) {
unresolvedKeyframes[0] = valueAsRead;
}
}
if (unresolvedKeyframes[0] === undefined) {
unresolvedKeyframes[0] = finalKeyframe;
}
if (motionValue && currentValue === undefined) {
motionValue.set(unresolvedKeyframes[0]);
}
}
else {
unresolvedKeyframes[i] = unresolvedKeyframes[i - 1];
}
}
}
}
setFinalKeyframe() { }
measureInitialState() { }
renderEndStyles() { }
measureEndState() { }
complete() {
this.isComplete = true;
this.onComplete(this.unresolvedKeyframes, this.finalKeyframe);
toResolve.delete(this);
}
cancel() {
if (!this.isComplete) {
this.isScheduled = false;
toResolve.delete(this);
}
}
resume() {
if (!this.isComplete)
this.scheduleResolve();
}
}
;// 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_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/value/types/complex/index.mjs
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);
}
const NUMBER_TOKEN = "number";
const COLOR_TOKEN = "color";
const VAR_TOKEN = "var";
const VAR_FUNCTION_TOKEN = "var(";
const SPLIT_TOKEN = "${}";
// this regex consists of the `singleCssVariableRegex|rgbHSLValueRegex|digitRegex`
const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;
function analyseComplexValue(value) {
const originalValue = value.toString();
const values = [];
const indexes = {
color: [],
number: [],
var: [],
};
const types = [];
let i = 0;
const tokenised = originalValue.replace(complexRegex, (parsedValue) => {
if (color.test(parsedValue)) {
indexes.color.push(i);
types.push(COLOR_TOKEN);
values.push(color.parse(parsedValue));
}
else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) {
indexes.var.push(i);
types.push(VAR_TOKEN);
values.push(parsedValue);
}
else {
indexes.number.push(i);
types.push(NUMBER_TOKEN);
values.push(parseFloat(parsedValue));
}
++i;
return SPLIT_TOKEN;
});
const split = tokenised.split(SPLIT_TOKEN);
return { values, split, indexes, types };
}
function parseComplexValue(v) {
return analyseComplexValue(v).values;
}
function createTransformer(source) {
const { split, types } = analyseComplexValue(source);
const numSections = split.length;
return (v) => {
let output = "";
for (let i = 0; i < numSections; i++) {
output += split[i];
if (v[i] !== undefined) {
const type = types[i];
if (type === NUMBER_TOKEN) {
output += sanitize(v[i]);
}
else if (type === COLOR_TOKEN) {
output += color.transform(v[i]);
}
else {
output += v[i];
}
}
}
return output;
};
}
const convertNumbersToZero = (v) => typeof v === "number" ? 0 : v;
function getAnimatableNone(v) {
const parsed = parseComplexValue(v);
const transformer = createTransformer(v);
return transformer(parsed.map(convertNumbersToZero));
}
const complex = {
test,
parse: parseComplexValue,
createTransformer,
getAnimatableNone,
};
;// 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 = /\b([a-z-]*)\(.*?\)/gu;
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/render/html/utils/make-none-animatable.mjs
/**
* If we encounter keyframes like "none" or "0" and we also have keyframes like
* "#fff" or "200px 200px" we want to find a keyframe to serve as a template for
* the "none" keyframes. In this case "#fff" or "200px 200px" - then these get turned into
* zero equivalents, i.e. "#fff0" or "0px 0px".
*/
const invalidTemplates = new Set(["auto", "none", "0"]);
function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) {
let i = 0;
let animatableTemplate = undefined;
while (i < unresolvedKeyframes.length && !animatableTemplate) {
const keyframe = unresolvedKeyframes[i];
if (typeof keyframe === "string" &&
!invalidTemplates.has(keyframe) &&
analyseComplexValue(keyframe).values.length) {
animatableTemplate = unresolvedKeyframes[i];
}
i++;
}
if (animatableTemplate && name) {
for (const noneIndex of noneKeyframeIndexes) {
unresolvedKeyframes[noneIndex] = animatable_none_getAnimatableNone(name, animatableTemplate);
}
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/DOMKeyframesResolver.mjs
class DOMKeyframesResolver extends KeyframeResolver {
constructor(unresolvedKeyframes, onComplete, name, motionValue) {
super(unresolvedKeyframes, onComplete, name, motionValue, motionValue === null || motionValue === void 0 ? void 0 : motionValue.owner, true);
}
readKeyframes() {
const { unresolvedKeyframes, element, name } = this;
if (!element.current)
return;
super.readKeyframes();
/**
* If any keyframe is a CSS variable, we need to find its value by sampling the element
*/
for (let i = 0; i < unresolvedKeyframes.length; i++) {
const keyframe = unresolvedKeyframes[i];
if (typeof keyframe === "string" && isCSSVariableToken(keyframe)) {
const resolved = getVariableValue(keyframe, element.current);
if (resolved !== undefined) {
unresolvedKeyframes[i] = resolved;
}
if (i === unresolvedKeyframes.length - 1) {
this.finalKeyframe = keyframe;
}
}
}
/**
* Resolve "none" values. We do this potentially twice - once before and once after measuring keyframes.
* This could be seen as inefficient but it's a trade-off to avoid measurements in more situations, which
* have a far bigger performance impact.
*/
this.resolveNoneKeyframes();
/**
* Check to see if unit type has changed. If so schedule jobs that will
* temporarily set styles to the destination keyframes.
* Skip if we have more than two keyframes or this isn't a positional value.
* TODO: We can throw if there are multiple keyframes and the value type changes.
*/
if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) {
return;
}
const [origin, target] = unresolvedKeyframes;
const originType = findDimensionValueType(origin);
const targetType = findDimensionValueType(target);
/**
* Either we don't recognise these value types or we can animate between them.
*/
if (originType === targetType)
return;
/**
* If both values are numbers or pixels, we can animate between them by
* converting them to numbers.
*/
if (isNumOrPxType(originType) && isNumOrPxType(targetType)) {
for (let i = 0; i < unresolvedKeyframes.length; i++) {
const value = unresolvedKeyframes[i];
if (typeof value === "string") {
unresolvedKeyframes[i] = parseFloat(value);
}
}
}
else {
/**
* Else, the only way to resolve this is by measuring the element.
*/
this.needsMeasurement = true;
}
}
resolveNoneKeyframes() {
const { unresolvedKeyframes, name } = this;
const noneKeyframeIndexes = [];
for (let i = 0; i < unresolvedKeyframes.length; i++) {
if (isNone(unresolvedKeyframes[i])) {
noneKeyframeIndexes.push(i);
}
}
if (noneKeyframeIndexes.length) {
makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name);
}
}
measureInitialState() {
const { element, unresolvedKeyframes, name } = this;
if (!element.current)
return;
if (name === "height") {
this.suspendedScrollY = window.pageYOffset;
}
this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));
unresolvedKeyframes[0] = this.measuredOrigin;
// Set final key frame to measure after next render
const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
if (measureKeyframe !== undefined) {
element.getValue(name, measureKeyframe).jump(measureKeyframe, false);
}
}
measureEndState() {
var _a;
const { element, name, unresolvedKeyframes } = this;
if (!element.current)
return;
const value = element.getValue(name);
value && value.jump(this.measuredOrigin, false);
const finalKeyframeIndex = unresolvedKeyframes.length - 1;
const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex];
unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));
if (finalKeyframe !== null && this.finalKeyframe === undefined) {
this.finalKeyframe = finalKeyframe;
}
// If we removed transform values, reapply them before the next render
if ((_a = this.removedTransforms) === null || _a === void 0 ? void 0 : _a.length) {
this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
element
.getValue(unsetTransformName)
.set(unsetTransformValue);
});
}
this.resolveNoneKeyframes();
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/memo.mjs
function memo(callback) {
let result;
return () => {
if (result === undefined)
result = callback();
return result;
};
}
;// 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 = (value, name) => {
// If the list of keys tat might be non-animatable grows, replace with Set
if (name === "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) || value === "0") && // 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/animation/animators/utils/can-animate.mjs
function hasKeyframesChanged(keyframes) {
const current = keyframes[0];
if (keyframes.length === 1)
return true;
for (let i = 0; i < keyframes.length; i++) {
if (keyframes[i] !== current)
return true;
}
}
function canAnimate(keyframes, name, type, velocity) {
/**
* 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];
if (originKeyframe === null)
return false;
/**
* These aren't traditionally animatable but we do support them.
* In future we could look into making this more generic or replacing
* this function with mix() === mixImmediate
*/
if (name === "display" || name === "visibility")
return true;
const targetKeyframe = keyframes[keyframes.length - 1];
const isOriginAnimatable = isAnimatable(originKeyframe, name);
const isTargetAnimatable = isAnimatable(targetKeyframe, name);
warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} 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.`);
// Always skip if any of these are true
if (!isOriginAnimatable || !isTargetAnimatable) {
return false;
}
return hasKeyframesChanged(keyframes) || (type === "spring" && velocity);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/BaseAnimation.mjs
class BaseAnimation {
constructor({ autoplay = true, delay = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", ...options }) {
// Track whether the animation has been stopped. Stopped animations won't restart.
this.isStopped = false;
this.hasAttemptedResolve = false;
this.options = {
autoplay,
delay,
type,
repeat,
repeatDelay,
repeatType,
...options,
};
this.updateFinishedPromise();
}
/**
* A getter for resolved data. If keyframes are not yet resolved, accessing
* this.resolved will synchronously flush all pending keyframe resolvers.
* This is a deoptimisation, but at its worst still batches read/writes.
*/
get resolved() {
if (!this._resolved && !this.hasAttemptedResolve) {
flushKeyframeResolvers();
}
return this._resolved;
}
/**
* A method to be called when the keyframes resolver completes. This method
* will check if its possible to run the animation and, if not, skip it.
* Otherwise, it will call initPlayback on the implementing class.
*/
onKeyframesResolved(keyframes, finalKeyframe) {
this.hasAttemptedResolve = true;
const { name, type, velocity, delay, onComplete, onUpdate, isGenerator, } = this.options;
/**
* If we can't animate this value with the resolved keyframes
* then we should complete it immediately.
*/
if (!isGenerator && !canAnimate(keyframes, name, type, velocity)) {
// Finish immediately
if (instantAnimationState.current || !delay) {
onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(getFinalKeyframe(keyframes, this.options, finalKeyframe));
onComplete === null || onComplete === void 0 ? void 0 : onComplete();
this.resolveFinishedPromise();
return;
}
// Finish after a delay
else {
this.options.duration = 0;
}
}
const resolvedAnimation = this.initPlayback(keyframes, finalKeyframe);
if (resolvedAnimation === false)
return;
this._resolved = {
keyframes,
finalKeyframe,
...resolvedAnimation,
};
this.onPostResolved();
}
onPostResolved() { }
/**
* Allows the returned animation to be awaited or promise-chained. Currently
* resolves when the animation finishes at all but in a future update could/should
* reject if its cancels.
*/
then(resolve, reject) {
return this.currentFinishedPromise.then(resolve, reject);
}
updateFinishedPromise() {
this.currentFinishedPromise = new Promise((resolve) => {
this.resolveFinishedPromise = resolve;
});
}
}
;// 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_clamp(minDamping, maxDamping, dampingRatio);
duration = clamp_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,
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, duration, velocity, isResolvedFromDuration, } = getSpringOptions({
...options,
velocity: -millisecondsToSeconds(options.velocity || 0),
});
const initialVelocity = 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), // TODO: This should be passing * 1000
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/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_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(circIn);
;// 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_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
errors_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
errors_invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`);
return easingLookup[definition];
}
return definition;
};
;// 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/mix/number.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 mixNumber = (from, to, progress) => {
return from + (to - from) * progress;
};
;// 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;
const expo = v * (to * to - fromExpo) + fromExpo;
return expo < 0 ? 0 : Math.sqrt(expo);
};
const colorTypes = [hex, rgba, hsla];
const getColorType = (v) => colorTypes.find((type) => type.test(v));
function asRGBA(color) {
const type = getColorType(color);
errors_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 = mixNumber(fromRGBA.alpha, toRGBA.alpha, v);
return rgba.transform(blended);
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix/visibility.mjs
const invisibleValues = new Set(["none", "hidden"]);
/**
* Returns a function that, when provided a progress value between 0 and 1,
* will return the "none" or "hidden" string only when the progress is that of
* the origin or target.
*/
function mixVisibility(origin, target) {
if (invisibleValues.has(origin)) {
return (p) => (p <= 0 ? origin : target);
}
else {
return (p) => (p >= 1 ? target : origin);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix/complex.mjs
function mixImmediate(a, b) {
return (p) => (p > 0 ? b : a);
}
function complex_mixNumber(a, b) {
return (p) => mixNumber(a, b, p);
}
function getMixer(a) {
if (typeof a === "number") {
return complex_mixNumber;
}
else if (typeof a === "string") {
return isCSSVariableToken(a)
? mixImmediate
: color.test(a)
? mixColor
: mixComplex;
}
else if (Array.isArray(a)) {
return mixArray;
}
else if (typeof a === "object") {
return color.test(a) ? mixColor : mixObject;
}
return mixImmediate;
}
function mixArray(a, b) {
const output = [...a];
const numValues = output.length;
const blendValue = a.map((v, i) => getMixer(v)(v, b[i]));
return (p) => {
for (let i = 0; i < numValues; i++) {
output[i] = blendValue[i](p);
}
return output;
};
}
function mixObject(a, b) {
const output = { ...a, ...b };
const blendValue = {};
for (const key in output) {
if (a[key] !== undefined && b[key] !== undefined) {
blendValue[key] = getMixer(a[key])(a[key], b[key]);
}
}
return (v) => {
for (const key in blendValue) {
output[key] = blendValue[key](v);
}
return output;
};
}
function matchOrder(origin, target) {
var _a;
const orderedOrigin = [];
const pointers = { color: 0, var: 0, number: 0 };
for (let i = 0; i < target.values.length; i++) {
const type = target.types[i];
const originIndex = origin.indexes[type][pointers[type]];
const originValue = (_a = origin.values[originIndex]) !== null && _a !== void 0 ? _a : 0;
orderedOrigin[i] = originValue;
pointers[type]++;
}
return orderedOrigin;
}
const mixComplex = (origin, target) => {
const template = complex.createTransformer(target);
const originStats = analyseComplexValue(origin);
const targetStats = analyseComplexValue(target);
const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length &&
originStats.indexes.color.length === targetStats.indexes.color.length &&
originStats.indexes.number.length >= targetStats.indexes.number.length;
if (canInterpolate) {
if ((invisibleValues.has(origin) &&
!targetStats.values.length) ||
(invisibleValues.has(target) &&
!originStats.values.length)) {
return mixVisibility(origin, target);
}
return pipe(mixArray(matchOrder(originStats, targetStats), 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 mixImmediate(origin, target);
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix/index.mjs
function mix(from, to, p) {
if (typeof from === "number" &&
typeof to === "number" &&
typeof p === "number") {
return mixNumber(from, to, p);
}
const mixer = getMixer(from);
return mixer(from, to);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/interpolate.mjs
function createMixers(output, ease, customMixer) {
const mixers = [];
const mixerFactory = customMixer || mix;
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_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;
errors_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 (inputLength === 2 && input[0] === input[1])
return () => output[1];
// 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_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(mixNumber(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_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/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/drivers/driver-frameloop.mjs
const frameloopDriver = (update) => {
const passTimestamp = ({ timestamp }) => update(timestamp);
return {
start: () => frame_frame.update(passTimestamp, true),
stop: () => cancelFrame(passTimestamp),
/**
* If we're processing this frame we can use the
* framelocked timestamp to keep things in sync.
*/
now: () => (frameData.isProcessing ? frameData.timestamp : time.now()),
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/MainThreadAnimation.mjs
const generators = {
decay: inertia,
inertia: inertia,
tween: keyframes_keyframes,
keyframes: keyframes_keyframes,
spring: spring,
};
const percentToProgress = (percent) => percent / 100;
/**
* Animation that runs on the main thread. Designed to be WAAPI-spec in the subset of
* features we expose publically. Mostly the compatibility is to ensure visual identity
* between both WAAPI and main thread animations.
*/
class MainThreadAnimation extends BaseAnimation {
constructor({ KeyframeResolver: KeyframeResolver$1 = KeyframeResolver, ...options }) {
super(options);
/**
* The time at which the animation was paused.
*/
this.holdTime = null;
/**
* The time at which the animation was started.
*/
this.startTime = null;
/**
* The time at which the animation was cancelled.
*/
this.cancelTime = null;
/**
* The current time of the animation.
*/
this.currentTime = 0;
/**
* Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.
*/
this.playbackSpeed = 1;
/**
* The state of the animation to apply when the animation is resolved. This
* allows calls to the public API to control the animation before it is resolved,
* without us having to resolve it first.
*/
this.pendingPlayState = "running";
this.state = "idle";
/**
* This method is bound to the instance to fix a pattern where
* animation.stop is returned as a reference from a useEffect.
*/
this.stop = () => {
this.resolver.cancel();
this.isStopped = true;
if (this.state === "idle")
return;
this.teardown();
const { onStop } = this.options;
onStop && onStop();
};
const { name, motionValue, keyframes } = this.options;
const onResolved = (resolvedKeyframes, finalKeyframe) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe);
if (name && motionValue && motionValue.owner) {
this.resolver = motionValue.owner.resolveKeyframes(keyframes, onResolved, name, motionValue);
}
else {
this.resolver = new KeyframeResolver$1(keyframes, onResolved, name, motionValue);
}
this.resolver.scheduleResolve();
}
initPlayback(keyframes$1) {
const { type = "keyframes", repeat = 0, repeatDelay = 0, repeatType, velocity = 0, } = this.options;
const generatorFactory = generators[type] || keyframes_keyframes;
/**
* If our generator doesn't support mixing numbers, we need to replace keyframes with
* [0, 100] and then make a function that maps that to the actual keyframes.
*
* 100 is chosen instead of 1 as it works nicer with spring animations.
*/
let mapPercentToKeyframes;
let mirroredGenerator;
if (generatorFactory !== keyframes_keyframes &&
typeof keyframes$1[0] !== "number") {
if (false) {}
mapPercentToKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1]));
keyframes$1 = [0, 100];
}
const generator = generatorFactory({ ...this.options, keyframes: keyframes$1 });
/**
* If we have a mirror repeat type we need to create a second generator that outputs the
* mirrored (not reversed) animation and later ping pong between the two generators.
*/
if (repeatType === "mirror") {
mirroredGenerator = generatorFactory({
...this.options,
keyframes: [...keyframes$1].reverse(),
velocity: -velocity,
});
}
/**
* 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) {
generator.calculatedDuration = calcGeneratorDuration(generator);
}
const { calculatedDuration } = generator;
const resolvedDuration = calculatedDuration + repeatDelay;
const totalDuration = resolvedDuration * (repeat + 1) - repeatDelay;
return {
generator,
mirroredGenerator,
mapPercentToKeyframes,
calculatedDuration,
resolvedDuration,
totalDuration,
};
}
onPostResolved() {
const { autoplay = true } = this.options;
this.play();
if (this.pendingPlayState === "paused" || !autoplay) {
this.pause();
}
else {
this.state = this.pendingPlayState;
}
}
tick(timestamp, sample = false) {
const { resolved } = this;
// If the animations has failed to resolve, return the final keyframe.
if (!resolved) {
const { keyframes } = this.options;
return { done: true, value: keyframes[keyframes.length - 1] };
}
const { finalKeyframe, generator, mirroredGenerator, mapPercentToKeyframes, keyframes, calculatedDuration, totalDuration, resolvedDuration, } = resolved;
if (this.startTime === null)
return generator.next(0);
const { delay, repeat, repeatType, repeatDelay, onUpdate } = this.options;
/**
* 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 (this.speed > 0) {
this.startTime = Math.min(this.startTime, timestamp);
}
else if (this.speed < 0) {
this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);
}
// Update currentTime
if (sample) {
this.currentTime = timestamp;
}
else if (this.holdTime !== null) {
this.currentTime = this.holdTime;
}
else {
// Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
// 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
// example.
this.currentTime =
Math.round(timestamp - this.startTime) * this.speed;
}
// Rebase on delay
const timeWithoutDelay = this.currentTime - delay * (this.speed >= 0 ? 1 : -1);
const isInDelayPhase = this.speed >= 0
? timeWithoutDelay < 0
: timeWithoutDelay > totalDuration;
this.currentTime = Math.max(timeWithoutDelay, 0);
// If this animation has finished, set the current time to the total duration.
if (this.state === "finished" && this.holdTime === null) {
this.currentTime = totalDuration;
}
let elapsed = this.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 = Math.min(this.currentTime, totalDuration) / 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 isOddIteration = Boolean(currentIteration % 2);
if (isOddIteration) {
if (repeatType === "reverse") {
iterationProgress = 1 - iterationProgress;
if (repeatDelay) {
iterationProgress -= repeatDelay / resolvedDuration;
}
}
else if (repeatType === "mirror") {
frameGenerator = mirroredGenerator;
}
}
elapsed = clamp_clamp(0, 1, iterationProgress) * 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[0] }
: frameGenerator.next(elapsed);
if (mapPercentToKeyframes) {
state.value = mapPercentToKeyframes(state.value);
}
let { done } = state;
if (!isInDelayPhase && calculatedDuration !== null) {
done =
this.speed >= 0
? this.currentTime >= totalDuration
: this.currentTime <= 0;
}
const isAnimationFinished = this.holdTime === null &&
(this.state === "finished" || (this.state === "running" && done));
if (isAnimationFinished && finalKeyframe !== undefined) {
state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe);
}
if (onUpdate) {
onUpdate(state.value);
}
if (isAnimationFinished) {
this.finish();
}
return state;
}
get duration() {
const { resolved } = this;
return resolved ? millisecondsToSeconds(resolved.calculatedDuration) : 0;
}
get time() {
return millisecondsToSeconds(this.currentTime);
}
set time(newTime) {
newTime = secondsToMilliseconds(newTime);
this.currentTime = newTime;
if (this.holdTime !== null || this.speed === 0) {
this.holdTime = newTime;
}
else if (this.driver) {
this.startTime = this.driver.now() - newTime / this.speed;
}
}
get speed() {
return this.playbackSpeed;
}
set speed(newSpeed) {
const hasChanged = this.playbackSpeed !== newSpeed;
this.playbackSpeed = newSpeed;
if (hasChanged) {
this.time = millisecondsToSeconds(this.currentTime);
}
}
play() {
if (!this.resolver.isScheduled) {
this.resolver.resume();
}
if (!this._resolved) {
this.pendingPlayState = "running";
return;
}
if (this.isStopped)
return;
const { driver = frameloopDriver, onPlay } = this.options;
if (!this.driver) {
this.driver = driver((timestamp) => this.tick(timestamp));
}
onPlay && onPlay();
const now = this.driver.now();
if (this.holdTime !== null) {
this.startTime = now - this.holdTime;
}
else if (!this.startTime || this.state === "finished") {
this.startTime = now;
}
if (this.state === "finished") {
this.updateFinishedPromise();
}
this.cancelTime = this.startTime;
this.holdTime = null;
/**
* Set playState to running only after we've used it in
* the previous logic.
*/
this.state = "running";
this.driver.start();
}
pause() {
var _a;
if (!this._resolved) {
this.pendingPlayState = "paused";
return;
}
this.state = "paused";
this.holdTime = (_a = this.currentTime) !== null && _a !== void 0 ? _a : 0;
}
complete() {
if (this.state !== "running") {
this.play();
}
this.pendingPlayState = this.state = "finished";
this.holdTime = null;
}
finish() {
this.teardown();
this.state = "finished";
const { onComplete } = this.options;
onComplete && onComplete();
}
cancel() {
if (this.cancelTime !== null) {
this.tick(this.cancelTime);
}
this.teardown();
this.updateFinishedPromise();
}
teardown() {
this.state = "idle";
this.stopDriver();
this.resolveFinishedPromise();
this.updateFinishedPromise();
this.startTime = this.cancelTime = null;
this.resolver.cancel();
}
stopDriver() {
if (!this.driver)
return;
this.driver.stop();
this.driver = undefined;
}
sample(time) {
this.startTime = 0;
return this.tick(time, true);
}
}
// Legacy interface
function animateValue(options) {
return new MainThreadAnimation(options);
}
;// 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" && easing in supportedWaapiEasing) ||
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 mapEasingToNativeEasingWithDefault(easing) {
return (mapEasingToNativeEasing(easing) ||
supportedWaapiEasing.easeOut);
}
function mapEasingToNativeEasing(easing) {
if (!easing) {
return undefined;
}
else if (isBezierDefinition(easing)) {
return cubicBezierAsString(easing);
}
else if (Array.isArray(easing)) {
return easing.map(mapEasingToNativeEasingWithDefault);
}
else {
return supportedWaapiEasing[easing];
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animators/waapi/index.mjs
function animateStyle(element, valueName, keyframes, { delay = 0, duration = 300, 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/AcceleratedAnimation.mjs
const supportsWaapi = memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
/**
* A list of values that can be hardware-accelerated.
*/
const acceleratedValues = new Set([
"opacity",
"clipPath",
"filter",
"transform",
// TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved
// or until we implement support for linear() easing.
// "background-color"
]);
/**
* 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 AcceleratedAnimation_maxDuration = 20000;
/**
* Check if an animation can run natively via WAAPI or requires pregenerated keyframes.
* WAAPI doesn't support spring or function easings so we run these as JS animation before
* handing off.
*/
function requiresPregeneratedKeyframes(options) {
return (options.type === "spring" ||
options.name === "backgroundColor" ||
!isWaapiSupportedEasing(options.ease));
}
function pregenerateKeyframes(keyframes, options) {
/**
* Create a main-thread animation to pregenerate keyframes.
* We sample this at regular intervals to generate keyframes that we then
* linearly interpolate between.
*/
const sampleAnimation = new MainThreadAnimation({
...options,
keyframes,
repeat: 0,
delay: 0,
isGenerator: true,
});
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 < AcceleratedAnimation_maxDuration) {
state = sampleAnimation.sample(t);
pregeneratedKeyframes.push(state.value);
t += sampleDelta;
}
return {
times: undefined,
keyframes: pregeneratedKeyframes,
duration: t - sampleDelta,
ease: "linear",
};
}
class AcceleratedAnimation extends BaseAnimation {
constructor(options) {
super(options);
const { name, motionValue, keyframes } = this.options;
this.resolver = new DOMKeyframesResolver(keyframes, (resolvedKeyframes, finalKeyframe) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe), name, motionValue);
this.resolver.scheduleResolve();
}
initPlayback(keyframes, finalKeyframe) {
var _a;
let { duration = 300, times, ease, type, motionValue, name, } = this.options;
/**
* If element has since been unmounted, return false to indicate
* the animation failed to initialised.
*/
if (!((_a = motionValue.owner) === null || _a === void 0 ? void 0 : _a.current)) {
return false;
}
/**
* If this animation needs pre-generated keyframes then generate.
*/
if (requiresPregeneratedKeyframes(this.options)) {
const { onComplete, onUpdate, motionValue, ...options } = this.options;
const pregeneratedAnimation = pregenerateKeyframes(keyframes, options);
keyframes = pregeneratedAnimation.keyframes;
// If this is a very short animation, ensure we have
// at least two keyframes to animate between as older browsers
// can't animate between a single keyframe.
if (keyframes.length === 1) {
keyframes[1] = keyframes[0];
}
duration = pregeneratedAnimation.duration;
times = pregeneratedAnimation.times;
ease = pregeneratedAnimation.ease;
type = "keyframes";
}
const animation = animateStyle(motionValue.owner.current, name, keyframes, { ...this.options, duration, times, ease });
// Override the browser calculated startTime with one synchronised to other JS
// and WAAPI animations starting this event loop.
animation.startTime = time.now();
if (this.pendingTimeline) {
animation.timeline = this.pendingTimeline;
this.pendingTimeline = undefined;
}
else {
/**
* 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 = () => {
const { onComplete } = this.options;
motionValue.set(getFinalKeyframe(keyframes, this.options, finalKeyframe));
onComplete && onComplete();
this.cancel();
this.resolveFinishedPromise();
};
}
return {
animation,
duration,
times,
type,
ease,
keyframes: keyframes,
};
}
get duration() {
const { resolved } = this;
if (!resolved)
return 0;
const { duration } = resolved;
return millisecondsToSeconds(duration);
}
get time() {
const { resolved } = this;
if (!resolved)
return 0;
const { animation } = resolved;
return millisecondsToSeconds(animation.currentTime || 0);
}
set time(newTime) {
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
animation.currentTime = secondsToMilliseconds(newTime);
}
get speed() {
const { resolved } = this;
if (!resolved)
return 1;
const { animation } = resolved;
return animation.playbackRate;
}
set speed(newSpeed) {
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
animation.playbackRate = newSpeed;
}
get state() {
const { resolved } = this;
if (!resolved)
return "idle";
const { animation } = resolved;
return animation.playState;
}
/**
* Replace the default DocumentTimeline with another AnimationTimeline.
* Currently used for scroll animations.
*/
attachTimeline(timeline) {
if (!this._resolved) {
this.pendingTimeline = timeline;
}
else {
const { resolved } = this;
if (!resolved)
return noop_noop;
const { animation } = resolved;
animation.timeline = timeline;
animation.onfinish = null;
}
return noop_noop;
}
play() {
if (this.isStopped)
return;
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
if (animation.playState === "finished") {
this.updateFinishedPromise();
}
animation.play();
}
pause() {
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
animation.pause();
}
stop() {
this.resolver.cancel();
this.isStopped = true;
if (this.state === "idle")
return;
const { resolved } = this;
if (!resolved)
return;
const { animation, keyframes, duration, type, ease, times } = resolved;
if (animation.playState === "idle" ||
animation.playState === "finished") {
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.
*/
if (this.time) {
const { motionValue, onUpdate, onComplete, ...options } = this.options;
const sampleAnimation = new MainThreadAnimation({
...options,
keyframes,
duration,
type,
ease,
times,
isGenerator: true,
});
const sampleTime = secondsToMilliseconds(this.time);
motionValue.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta);
}
this.cancel();
}
complete() {
const { resolved } = this;
if (!resolved)
return;
resolved.animation.finish();
}
cancel() {
const { resolved } = this;
if (!resolved)
return;
resolved.animation.cancel();
}
static supports(options) {
const { motionValue, name, repeatDelay, repeatType, damping, type } = options;
return (supportsWaapi() &&
name &&
acceleratedValues.has(name) &&
motionValue &&
motionValue.owner &&
motionValue.owner.current instanceof HTMLElement &&
/**
* If we're outputting values to onUpdate then we can't use WAAPI as there's
* no way to read the value from WAAPI every frame.
*/
!motionValue.owner.getProps().onUpdate &&
!repeatDelay &&
repeatType !== "mirror" &&
damping !== 0 &&
type !== "inertia");
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs
const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {
const valueTransition = getValueTransition(transition, name) || {};
/**
* 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);
let options = {
keyframes: Array.isArray(target) ? target : [null, target],
ease: "easeOut",
velocity: value.getVelocity(),
...valueTransition,
delay: -elapsed,
onUpdate: (v) => {
value.set(v);
valueTransition.onUpdate && valueTransition.onUpdate(v);
},
onComplete: () => {
onComplete();
valueTransition.onComplete && valueTransition.onComplete();
},
name,
motionValue: value,
element: isHandoff ? undefined : element,
};
/**
* If there's no transition defined for this value, we can generate
* unqiue transition settings for this value.
*/
if (!isTransitionDefined(valueTransition)) {
options = {
...options,
...getDefaultTransition(name, 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 (options.from !== undefined) {
options.keyframes[0] = options.from;
}
let shouldSkip = false;
if (options.type === false ||
(options.duration === 0 && !options.repeatDelay)) {
options.duration = 0;
if (options.delay === 0) {
shouldSkip = true;
}
}
if (instantAnimationState.current ||
MotionGlobalConfig.skipAnimations) {
shouldSkip = true;
options.duration = 0;
options.delay = 0;
}
/**
* If we can or must skip creating the animation, and apply only
* the final keyframe, do so. We also check once keyframes are resolved but
* this early check prevents the need to create an animation at all.
*/
if (shouldSkip && !isHandoff && value.get() !== undefined) {
const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
if (finalKeyframe !== undefined) {
frame_frame.update(() => {
options.onUpdate(finalKeyframe);
options.onComplete();
});
return;
}
}
/**
* Animate via WAAPI if possible. If this is a handoff animation, the optimised animation will be running via
* WAAPI. Therefore, this animation must be JS to ensure it runs "under" the
* optimised animation.
*/
if (!isHandoff && AcceleratedAnimation.supports(options)) {
return new AcceleratedAnimation(options);
}
else {
return new MainThreadAnimation(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/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
/**
* Maximum time between the value of two frames, beyond which we
* assume the velocity has since been 0.
*/
const MAX_VELOCITY_DELTA = 30;
const isFloat = (value) => {
return !isNaN(parseFloat(value));
};
const collectMotionValues = {
current: undefined,
};
/**
* `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 = "11.2.6";
/**
* 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 = null;
/**
* An object containing a SubscriptionManager for each active event.
*/
this.events = {};
this.updateAndNotify = (v, render = true) => {
const currentTime = time.now();
/**
* If we're updating the value during another frame or eventloop
* than the previous frame, then the we set the previous frame value
* to current.
*/
if (this.updatedAt !== currentTime) {
this.setPrevFrameValue();
}
this.prev = this.current;
this.setCurrent(v);
// Update update subscribers
if (this.current !== this.prev && this.events.change) {
this.events.change.notify(this.current);
}
// Update render subscribers
if (render && this.events.renderRequest) {
this.events.renderRequest.notify(this.current);
}
};
this.hasAnimated = false;
this.setCurrent(init);
this.owner = options.owner;
}
setCurrent(current) {
this.current = current;
this.updatedAt = time.now();
if (this.canTrackVelocity === null && current !== undefined) {
this.canTrackVelocity = isFloat(this.current);
}
}
setPrevFrameValue(prevFrameValue = this.current) {
this.prevFrameValue = prevFrameValue;
this.prevUpdatedAt = this.updatedAt;
}
/**
* 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
* }
* ```
*
* @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.
*/
frame_frame.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 = undefined;
this.prevFrameValue = prev;
this.prevUpdatedAt = this.updatedAt - delta;
}
/**
* Set the state of the `MotionValue`, stopping any active animations,
* effects, and resets velocity to `0`.
*/
jump(v, endAnimation = true) {
this.updateAndNotify(v);
this.prev = v;
this.prevUpdatedAt = this.prevFrameValue = undefined;
endAnimation && this.stop();
if (this.stopPassiveEffect)
this.stopPassiveEffect();
}
/**
* Returns the latest state of `MotionValue`
*
* @returns - The latest state of `MotionValue`
*
* @public
*/
get() {
if (collectMotionValues.current) {
collectMotionValues.current.push(this);
}
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() {
const currentTime = time.now();
if (!this.canTrackVelocity ||
this.prevFrameValue === undefined ||
currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
return 0;
}
const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
// Casts because of parseFloat's poor typing
return velocityPerSecond(parseFloat(this.current) -
parseFloat(this.prevFrameValue), delta);
}
/**
* 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/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 || {};
target = { ...target, ...transitionEnd };
for (const key in target) {
const value = resolveFinalValueInKeyframes(target[key]);
setMotionValue(visualElement, key, value);
}
}
;// 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, targetAndTransition, { delay = 0, transitionOverride, type } = {}) {
var _a;
let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition;
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, (_a = visualElement.latestValues[key]) !== null && _a !== void 0 ? _a : null);
const valueTarget = target[key];
if (valueTarget === undefined ||
(animationTypeState &&
shouldBlockAnimation(animationTypeState, key))) {
continue;
}
const valueTransition = {
delay,
elapsed: 0,
...getValueTransition(transition || {}, key),
};
/**
* If this is the first time a value is being animated, check
* to see if we're handling off from an existing animation.
*/
let isHandoff = false;
if (window.HandoffAppearAnimations) {
const props = visualElement.getProps();
const appearId = props[optimizedAppearDataAttribute];
if (appearId) {
const elapsed = window.HandoffAppearAnimations(appearId, key, value, frame_frame);
if (elapsed !== null) {
valueTransition.elapsed = elapsed;
isHandoff = true;
}
}
}
value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && transformProps.has(key)
? { type: false }
: valueTransition, visualElement, isHandoff));
const animation = value.animation;
if (animation) {
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
animation.then(() => willChange.remove(key));
}
animations.push(animation);
}
}
if (transitionEnd) {
Promise.all(animations).then(() => {
frame_frame.update(() => {
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 = {}) {
var _a;
const resolved = resolveVariant(visualElement, variant, options.type === "exit"
? (_a = visualElement.presenceContext) === null || _a === void 0 ? void 0 : _a.custom
: undefined);
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(() => {
frame_frame.postRender(() => {
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 = (type) => (acc, definition) => {
var _a;
const resolved = resolveVariant(visualElement, definition, type === "exit"
? (_a = visualElement.presenceContext) === null || _a === void 0 ? void 0 : _a.custom
: undefined);
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(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);
let handledRemovedValues = false;
/**
* 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(type), {});
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;
if (removedKeys.has(key)) {
handledRemovedValues = true;
removedKeys.delete(key);
}
typeState.needsAnimating[key] = true;
const motionValue = visualElement.getValue(key);
if (motionValue)
motionValue.liveStyle = false;
};
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.
*/
let valueHasChanged = false;
if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
valueHasChanged = !shallowCompare(next, prev);
}
else {
valueHasChanged = next !== prev;
}
if (valueHasChanged) {
if (next !== undefined && next !== null) {
// 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
*/
if (shouldAnimateType && (!isInherited || handledRemovedValues)) {
animations.push(...definitionList.map((animation) => ({
animation: animation,
options: { type },
})));
}
}
/**
* 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);
const motionValue = visualElement.getValue(key);
if (motionValue)
motionValue.liveStyle = true;
// @ts-expect-error - @mattgperry to figure if we should do something here
fallbackAnimation[key] = fallbackTarget !== null && fallbackTarget !== void 0 ? fallbackTarget : null;
});
animations.push({ animation: fallbackAnimation });
}
let shouldAnimate = Boolean(animations.length);
if (isInitialRender &&
(props.initial === false || props.initial === props.animate) &&
!visualElement.manuallyAnimateOnMount) {
shouldAnimate = false;
}
isInitialRender = false;
return shouldAnimate ? animate(animations) : Promise.resolve();
}
/**
* Change whether a certain animation type is active.
*/
function setActive(type, isActive) {
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(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 id = 0;
class ExitAnimationFeature extends Feature {
constructor() {
super(...arguments);
this.id = id++;
}
update() {
if (!this.node.presenceContext)
return;
const { isPresent, onExitComplete } = this.node.presenceContext;
const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};
if (!this.node.animationState || isPresent === prevIsPresent) {
return;
}
const exitAnimation = this.node.animationState.setActive("exit", !isPresent);
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, contextWindow, dragSnapToOrigin = false } = {}) {
/**
* @internal
*/
this.startEvent = null;
/**
* @internal
*/
this.lastMoveEvent = null;
/**
* @internal
*/
this.lastMoveEventInfo = null;
/**
* @internal
*/
this.handlers = {};
/**
* @internal
*/
this.contextWindow = window;
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
frame_frame.update(this.updatePoint, true);
};
this.handlePointerUp = (event, info) => {
this.end();
const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;
if (this.dragSnapToOrigin)
resumeAnimation && resumeAnimation();
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
return;
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.dragSnapToOrigin = dragSnapToOrigin;
this.handlers = handlers;
this.transformPagePoint = transformPagePoint;
this.contextWindow = contextWindow || window;
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(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp));
}
updateHandlers(handlers) {
this.handlers = handlers;
}
end() {
this.removeListeners && this.removeListeners();
cancelFrame(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: getVelocity(history, 0.1),
};
}
function startDevicePoint(history) {
return history[0];
}
function lastDevicePoint(history) {
return history[history.length - 1];
}
function 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 = mixNumber(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 =
mixNumber(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
? mixNumber(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
? mixNumber(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_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 ||
values.skewX ||
values.skewY);
}
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 = mixNumber(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/utils/get-context-window.mjs
// Fixes https://github.com/framer/motion/issues/2270
const getContextWindow = ({ current }) => {
return current ? current.ownerDocument.defaultView : null;
};
;// 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) => {
const { dragSnapToOrigin } = this.getProps();
// Stop or pause any animations on both axis values immediately. This allows the user to throw and catch
// the component.
dragSnapToOrigin ? this.pauseAnimation() : 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) {
frame_frame.postRender(() => 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);
const resumeAnimation = () => eachAxis((axis) => {
var _a;
return this.getAnimationState(axis) === "paused" &&
((_a = this.getAxisMotionValue(axis).animation) === null || _a === void 0 ? void 0 : _a.play());
});
const { dragSnapToOrigin } = this.getProps();
this.panSession = new PanSession(originEvent, {
onSessionStart,
onStart,
onMove,
onSessionEnd,
resumeAnimation,
}, {
transformPagePoint: this.visualElement.getTransformPagePoint(),
dragSnapToOrigin,
contextWindow: getContextWindow(this.visualElement),
});
}
stop(event, info) {
const isDragging = this.isDragging;
this.cancel();
if (!isDragging)
return;
const { velocity } = info;
this.startAnimation(velocity);
const { onDragEnd } = this.getProps();
if (onDragEnd) {
frame_frame.postRender(() => 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() {
var _a;
const { dragConstraints, dragElastic } = this.getProps();
const layout = this.visualElement.projection &&
!this.visualElement.projection.layout
? this.visualElement.projection.measure(false)
: (_a = this.visualElement.projection) === null || _a === void 0 ? void 0 : _a.layout;
const prevConstraints = this.constraints;
if (dragConstraints && 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.constraints !== false &&
this.getAxisMotionValue(axis)) {
this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]);
}
});
}
}
resolveRefConstraints() {
const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();
if (!constraints || !isRefObject(constraints))
return false;
const constraintsElement = constraints.current;
errors_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, this.visualElement));
}
stopAnimation() {
eachAxis((axis) => this.getAxisMotionValue(axis).stop());
}
pauseAnimation() {
eachAxis((axis) => { var _a; return (_a = this.getAxisMotionValue(axis).animation) === null || _a === void 0 ? void 0 : _a.pause(); });
}
getAnimationState(axis) {
var _a;
return (_a = this.getAxisMotionValue(axis).animation) === null || _a === void 0 ? void 0 : _a.state;
}
/**
* 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] - mixNumber(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 (!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 && this.constraints !== false) {
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(mixNumber(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 (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_noop;
this.removeListeners = noop_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_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) {
frame_frame.postRender(() => handler(event, info));
}
};
class PanGesture extends Feature {
constructor() {
super(...arguments);
this.removePointerDownListener = noop_noop;
}
onPointerDown(pointerDownEvent) {
this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), {
transformPagePoint: this.node.getTransformPagePoint(),
contextWindow: getContextWindow(this.node),
});
}
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) {
frame_frame.postRender(() => 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
* }
* ```
*
* 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
* }
* ```
*
* @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/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/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/projection/styles/scale-box-shadow.mjs
const correctBoxShadow = {
correct: (latest, { treeScale, projectionDelta }) => {
const original = latest;
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 = mixNumber(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;
return template(shadow);
},
};
;// 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.
*/
frame_frame.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();
microtask.postRender(() => {
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 ((0,external_ReactJSXRuntime_namespaceObject.jsx)(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 = mixNumber(0,
// TODO Reinstate this if only child
lead.opacity !== undefined ? lead.opacity : 1, easeCrossfadeIn(progress));
target.opacityExit = mixNumber(follow.opacity !== undefined ? follow.opacity : 1, 0, easeCrossfadeOut(progress));
}
else if (isOnlyMember) {
target.opacity = mixNumber(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(mixNumber(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 = mixNumber(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_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 = mixNumber(sourceAxis.min, sourceAxis.max, translate / 100);
translate = relativeProgress - sourceAxis.min;
}
if (typeof translate !== "number")
return;
let originPoint = mixNumber(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 boxEqualsRounded(a, b) {
return (Math.round(a.x.min) === Math.round(b.x.min) &&
Math.round(a.x.max) === Math.round(b.x.max) &&
Math.round(a.y.min) === Math.round(b.y.min) &&
Math.round(a.y.max) === Math.round(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;
const zTranslate = (latestTransform === null || latestTransform === void 0 ? void 0 : latestTransform.z) || 0;
if (xTranslate || yTranslate || zTranslate) {
transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `;
}
/**
* 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 { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform;
if (transformPerspective)
transform = `perspective(${transformPerspective}px) ${transform}`;
if (rotate)
transform += `rotate(${rotate}deg) `;
if (rotateX)
transform += `rotateX(${rotateX}deg) `;
if (rotateY)
transform += `rotateY(${rotateY}deg) `;
if (skewX)
transform += `skewX(${skewX}deg) `;
if (skewY)
transform += `skewY(${skewY}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 = time.now();
const checkElapsed = ({ timestamp }) => {
const elapsed = timestamp - start;
if (elapsed >= timeout) {
cancelFrame(checkElapsed);
callback(elapsed - timeout);
}
};
frame_frame.read(checkElapsed, true);
return () => cancelFrame(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"];
const hiddenVisibility = { visibility: "hidden" };
/**
* 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 resetDistortingTransform(key, visualElement, values, sharedAnimationValues) {
const { latestValues } = visualElement;
// Record the distorting transform and then temporarily set it to 0
if (latestValues[key]) {
values[key] = latestValues[key];
visualElement.setStaticValue(key, 0);
if (sharedAnimationValues) {
sharedAnimationValues[key] = 0;
}
}
}
function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
return class ProjectionNode {
constructor(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();
this.hasTreeAnimated = false;
// Note: Currently only running on root node
this.updateScheduled = false;
this.projectionUpdateScheduled = false;
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 = () => {
this.projectionUpdateScheduled = false;
/**
* 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.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;
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);
}
/**
* Lifecycles
*/
mount(instance, isLayoutDirty = this.root.hasTreeAnimated) {
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);
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 ||
!boxEqualsRounded(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) {
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;
cancelFrame(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;
/**
* If we're running optimised appear animations then these must be
* cancelled before measuring the DOM. This is so we can measure
* the true layout of the element rather than the WAAPI animation
* which will be unaffected by the resetSkewAndRotate step.
*/
if (window.HandoffCancelAllAnimations) {
window.HandoffCancelAllAnimations();
}
this.nodes && this.nodes.forEach(resetSkewAndRotation);
this.animationId++;
}
getTransformTemplate() {
const { visualElement } = this.options;
return visualElement && visualElement.getProps().transformTemplate;
}
willUpdate(shouldNotifyListeners = true) {
this.root.hasTreeAnimated = 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");
}
update() {
this.updateScheduled = false;
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) {
this.nodes.forEach(clearIsLayoutDirty);
}
this.isUpdating = false;
/**
* 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();
/**
* Manually flush any pending updates. Ideally
* we could leave this to the following requestAnimationFrame but this seems
* to leave a flash of incorrectly styled content.
*/
const now = time.now();
frameData.delta = clamp_clamp(0, 1000 / 60, now - frameData.timestamp);
frameData.timestamp = now;
frameData.isProcessing = true;
steps.update.process(frameData);
steps.preRender.process(frameData);
steps.render.process(frameData);
frameData.isProcessing = false;
}
didUpdate() {
if (!this.updateScheduled) {
this.updateScheduled = true;
microtask.read(() => this.update());
}
}
clearAllSnapshots() {
this.nodes.forEach(clearSnapshot);
this.sharedNodes.forEach(removeLeadSnapshots);
}
scheduleUpdateProjection() {
if (!this.projectionUpdateScheduled) {
this.projectionUpdateScheduled = true;
frame_frame.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.
*/
frame_frame.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.
*/
if (!this.targetDelta && !this.relativeTarget) {
const relativeParent = this.getClosestProjectingParent();
if (relativeParent &&
relativeParent.layout &&
this.animationProgress !== 1) {
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.animationProgress !== 1) {
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);
/**
* Record previous tree scales before updating.
*/
const prevTreeScaleX = this.treeScale.x;
const prevTreeScaleY = this.treeScale.y;
/**
* 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);
/**
* If this layer needs to perform scale correction but doesn't have a target,
* use the layout as the target.
*/
if (lead.layout &&
!lead.target &&
(this.treeScale.x !== 1 || this.treeScale.y !== 1)) {
lead.target = lead.layout.layoutBox;
lead.targetWithTransforms = createBox();
}
const { target } = lead;
if (!target) {
/**
* If we don't have a target to project into, but we were previously
* projecting, we want to remove the stored transform and schedule
* a render to ensure the elements reflect the removed transform.
*/
if (this.projectionTransform) {
this.projectionDelta = createDelta();
this.projectionTransform = "none";
this.scheduleRender();
}
return;
}
if (!this.projectionDelta) {
this.projectionDelta = createDelta();
this.projectionDeltaWithTransform = createDelta();
}
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) {
cancelFrame(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 = frame_frame.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;
}
}
resetSkewAndRotation() {
const { visualElement } = this.options;
if (!visualElement)
return;
// If there's no detected skew or rotation values, we can early return without a forced render.
let hasDistortingTransform = 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.z ||
latestValues.rotate ||
latestValues.rotateX ||
latestValues.rotateY ||
latestValues.rotateZ ||
latestValues.skewX ||
latestValues.skewY) {
hasDistortingTransform = true;
}
// If there's no distorting values, we don't need to do any more.
if (!hasDistortingTransform)
return;
const resetValues = {};
if (latestValues.z) {
resetDistortingTransform("z", visualElement, resetValues, this.animationValues);
}
// Check the skew and rotate value of all axes and reset to 0
for (let i = 0; i < transformAxes.length; i++) {
resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
}
// Force a render of this element to apply the transform with all skews and rotations
// set to 0.
visualElement.render();
// Put back all the values we reset
for (const key in resetValues) {
visualElement.setStaticValue(key, resetValues[key]);
if (this.animationValues) {
this.animationValues[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;
if (!this.instance || this.isSVG)
return undefined;
if (!this.isVisible) {
return hiddenVisibility;
}
const styles = {
visibility: "",
};
const transformTemplate = this.getTransformTemplate();
if (this.needsReset) {
this.needsReset = false;
styles.opacity = "";
styles.pointerEvents =
resolveMotionValue(styleProp === null || styleProp === void 0 ? void 0 : 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 === null || styleProp === void 0 ? void 0 : 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 === null || styleProp === void 0 ? void 0 : 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 (!boxEqualsRounded(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 clearIsLayoutDirty(node) {
node.isLayoutDirty = false;
}
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;
node.isProjectionDirty = true;
}
function resolveTargetDelta(node) {
node.resolveTargetDelta();
}
function calcProjection(node) {
node.calcProjection();
}
function resetSkewAndRotation(node) {
node.resetSkewAndRotation();
}
function removeLeadSnapshots(stack) {
stack.removeLeadSnapshot();
}
function mixAxisDelta(output, delta, p) {
output.translate = mixNumber(delta.translate, 0, p);
output.scale = mixNumber(delta.scale, 1, p);
output.origin = delta.origin;
output.originPoint = delta.originPoint;
}
function mixAxis(output, from, to, p) {
output.min = mixNumber(from.min, to.min, p);
output.max = mixNumber(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],
};
const userAgentContains = (string) => typeof navigator !== "undefined" &&
navigator.userAgent &&
navigator.userAgent.toLowerCase().includes(string);
/**
* Measured bounding boxes must be rounded in Safari and
* left untouched in Chrome, otherwise non-integer layouts within scaled-up elements
* can appear to jump.
*/
const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/")
? Math.round
: noop_noop;
function roundAxis(axis) {
// Round to the nearest .5 pixels to support subpixel layouts
axis.min = roundPoint(axis.min);
axis.max = roundPoint(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({});
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/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 (!is_browser_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/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);
if (existingValue.liveStyle === true) {
existingValue.jump(nextValue);
}
else if (!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/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/VisualElement.mjs
const featureNames = Object.keys(featureDefinitions);
const numFeatures = featureNames.length;
const propEventHandlers = [
"AnimationStart",
"AnimationComplete",
"Update",
"BeforeLayoutMeasure",
"LayoutMeasure",
"LayoutAnimationStart",
"LayoutAnimationComplete",
];
const numVariantProps = variantProps.length;
function getClosestProjectingNode(visualElement) {
if (!visualElement)
return undefined;
return visualElement.options.allowProjection !== false
? visualElement.projection
: getClosestProjectingNode(visualElement.parent);
}
/**
* A VisualElement is an imperative abstraction around UI elements such as
* HTMLElement, SVGElement, Three.Object3D etc.
*/
class VisualElement {
/**
* 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, _visualElement) {
return {};
}
constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) {
this.resolveKeyframes = (keyframes,
// We use an onComplete callback here rather than a Promise as a Promise
// resolution is a microtask and we want to retain the ability to force
// the resolution of keyframes synchronously.
onComplete, name, value) => {
return new this.KeyframeResolver(keyframes, onComplete, name, value, this);
};
/**
* 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();
this.KeyframeResolver = KeyframeResolver;
/**
* 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 = () => frame_frame.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.blockInitialAnimation = Boolean(blockInitialAnimation);
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, {}, this);
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);
}
}
}
}
mount(instance) {
this.current = instance;
visualElementStore.set(instance, this);
if (this.projection && !this.projection.instance) {
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() {
var _a;
visualElementStore.delete(this.current);
this.projection && this.projection.unmount();
cancelFrame(this.notifyUpdate);
cancelFrame(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) {
(_a = this.features[key]) === null || _a === void 0 ? void 0 : _a.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 && frame_frame.preRender(this.notifyUpdate);
if (valueIsTransform && this.projection) {
this.projection.isTransformDirty = true;
}
});
const removeOnRenderRequest = value.on("renderRequest", this.scheduleRender);
this.valueSubscriptions.set(key, () => {
removeOnChange();
removeOnRenderRequest();
if (value.owner)
value.stop();
});
}
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, 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.type === "html" || this.type === "svg") &&
!this.projection &&
ProjectionNodeConstructor) {
const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, } = renderedProps;
this.projection = new ProjectionNodeConstructor(this.latestValues, renderedProps["data-framer-portal-id"]
? undefined
: getClosestProjectingNode(this.parent));
this.projection.setOptions({
layoutId,
layout,
alwaysMeasureLayout: Boolean(drag) ||
(dragConstraints && 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();
}
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;
}
/**
* 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 listenerName = ("on" + key);
const listener = props[listenerName];
if (listener) {
this.propEventSubscriptions[key] = this.on(key, listener);
}
}
this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), 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
const existingValue = this.values.get(key);
if (value !== existingValue) {
if (existingValue)
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 === null ? undefined : 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, target) {
var _a;
let value = this.latestValues[key] !== undefined || !this.current
? this.latestValues[key]
: (_a = this.getBaseTargetFromProps(this.props, key)) !== null && _a !== void 0 ? _a : this.readValueFromInstance(this.current, key, this.options);
if (value !== undefined && value !== null) {
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(target)) {
value = animatable_none_getAnimatableNone(key, target);
}
this.setBaseTarget(key, isMotionValue(value) ? value.get() : value);
}
return isMotionValue(value) ? value.get() : value;
}
/**
* 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;
let valueFromInitial;
if (typeof initial === "string" || typeof initial === "object") {
const variant = resolveVariantFromProps(this.props, initial, (_a = this.presenceContext) === null || _a === void 0 ? void 0 : _a.custom);
if (variant) {
valueFromInitial = variant[key];
}
}
/**
* 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 {
constructor() {
super(...arguments);
this.KeyframeResolver = DOMKeyframesResolver;
}
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];
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs
function HTMLVisualElement_getComputedStyle(element) {
return window.getComputedStyle(element);
}
class HTMLVisualElement extends DOMVisualElement {
constructor() {
super(...arguments);
this.type = "html";
}
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, visualElement) {
return scrapeMotionValuesFromProps(props, prevProps, visualElement);
}
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.type = "svg";
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, visualElement) {
return scrape_motion_values_scrapeMotionValuesFromProps(props, prevProps, visualElement);
}
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, {
allowProjection: Component !== external_React_.Fragment,
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/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)(() => frame_frame.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,
});
const { nonce } = (0,external_React_.useContext)(MotionConfigContext);
/**
* 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");
if (nonce)
style.nonce = nonce;
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 ((0,external_ReactJSXRuntime_namespaceObject.jsx)(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: 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 ? [Math.random()] : [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 = (0,external_ReactJSXRuntime_namespaceObject.jsx)(PopChild, { isPresent: isPresent, children: children });
}
return ((0,external_ReactJSXRuntime_namespaceObject.jsx)(PresenceContext_PresenceContext.Provider, { value: context, children: 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 }) => (
*
* {items.map(item => (
*
* ))}
*
* )
* ```
*
* 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", }) => {
errors_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.
const forceRender = (0,external_React_.useContext)(LayoutGroupContext).forceRender || use_force_update_useForceUpdate()[0];
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 exitingChildren = (0,external_React_.useRef)(new Map()).current;
// 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();
exitingChildren.clear();
});
if (isInitialRender.current) {
return ((0,external_ReactJSXRuntime_namespaceObject.jsx)(external_ReactJSXRuntime_namespaceObject.Fragment, { children: childrenToRender.map((child) => ((0,external_ReactJSXRuntime_namespaceObject.jsx)(PresenceChild, { isPresent: true, initial: initial ? undefined : false, presenceAffectsLayout: presenceAffectsLayout, mode: mode, children: child }, getChildKey(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 && !exitingChildren.has(key)) {
exitingChildren.set(key, undefined);
}
}
// 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" && exitingChildren.size) {
childrenToRender = [];
}
// Loop through all currently exiting components and clone them to overwrite `animate`
// with any `exit` prop they might have defined.
exitingChildren.forEach((component, 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);
let exitingComponent = component;
if (!exitingComponent) {
const onExit = () => {
// clean up the exiting children map
exitingChildren.delete(key);
// compute the keys of children that were rendered once but are no longer present
// this could happen in case of too many fast consequent renderings
// @link https://github.com/framer/motion/issues/2023
const leftOverKeys = Array.from(allChildren.keys()).filter((childKey) => !targetKeys.includes(childKey));
// clean up the all children map
leftOverKeys.forEach((leftOverKey) => allChildren.delete(leftOverKey));
// make sure to render only the children that are actually visible
presentChildren.current = filteredChildren.filter((presentChild) => {
const presentChildKey = getChildKey(presentChild);
return (
// filter out the node exiting
presentChildKey === key ||
// filter out the leftover children
leftOverKeys.includes(presentChildKey));
});
// Defer re-rendering until all exiting children have indeed left
if (!exitingChildren.size) {
if (isMounted.current === false)
return;
forceRender();
onExitComplete && onExitComplete();
}
};
exitingComponent = ((0,external_ReactJSXRuntime_namespaceObject.jsx)(PresenceChild, { isPresent: false, onExitComplete: onExit, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, children: child }, getChildKey(child)));
exitingChildren.set(key, exitingComponent);
}
childrenToRender.splice(insertionIndex, 0, exitingComponent);
});
// 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 exitingChildren.has(key) ? (child) : ((0,external_ReactJSXRuntime_namespaceObject.jsx)(PresenceChild, { isPresent: true, presenceAffectsLayout: presenceAffectsLayout, mode: mode, children: child }, getChildKey(child)));
});
if (false) {}
return ((0,external_ReactJSXRuntime_namespaceObject.jsx)(external_ReactJSXRuntime_namespaceObject.Fragment, { children: exitingChildren.size
? childrenToRender
: childrenToRender.map((child) => (0,external_React_.cloneElement)(child)) }));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/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/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/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/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function 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(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/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/flex/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlex(props, forwardedRef) {
const {
children,
isColumn,
...otherProps
} = useFlex(props);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(FlexContext.Provider, {
value: {
flexItemDisplay: isColumn ? 'block' : undefined
},
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component, {
...otherProps,
ref: forwardedRef,
children: 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 (
*
*
* Code
*
*
* Poetry
*
*
* );
* }
* ```
*/
const component_Flex = contextConnect(UnconnectedFlex, 'Flex');
/* harmony default export */ const flex_component = (component_Flex);
;// 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
* ...
*
* );
* }
* ```
*/
const FlexBlock = contextConnect(UnconnectedFlexBlock, 'FlexBlock');
/* harmony default export */ const flex_block_component = (FlexBlock);
;// 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, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(ltrStyles, true ? "" : 0, 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, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(ltrStyles, true ? "" : 0, 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
*
* WordPress.org
*
*
* Code is Poetry
*
*
* );
* }
* ```
*/
const Spacer = contextConnect(UnconnectedSpacer, 'Spacer');
/* harmony default export */ const spacer_component = (Spacer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z"
})
});
/* harmony default export */ const library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/reset.js
/**
* WordPress dependencies
*/
const reset_reset = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "M7 11.5h10V13H7z"
})
});
/* harmony default export */ const library_reset = (reset_reset);
;// 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
* ...
*
* );
* }
* ```
*/
const FlexItem = contextConnect(UnconnectedFlexItem, 'FlexItem');
/* harmony default export */ const 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} 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} 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;
}
/**
* Converts a string to a number.
*
* @param {string} value
* @return {number} String as a number.
*/
const stringToNumber = value => {
return parseFloat(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;
};
;// 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();
let childrenAsText;
if (typeof children === 'string') {
childrenAsText = children;
} else if (typeof children === 'number') {
childrenAsText = children.toString();
}
const truncatedContent = childrenAsText ? truncateContent(childrenAsText, {
ellipsis,
ellipsizeMode,
limit,
numberOfLines
}) : children;
const shouldTruncate = !!childrenAsText && ellipsizeMode === TRUNCATE_TYPE.auto;
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
// The `word-break: break-all` property first makes sure a text line
// breaks even when it contains 'unbreakable' content such as long URLs.
// See https://github.com/WordPress/gutenberg/issues/60860.
const truncateLines = /*#__PURE__*/emotion_react_browser_esm_css(numberOfLines === 1 ? 'word-break: break-all;' : '', " -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/colord/index.mjs
var colord_r={grad:.9,turn:360,rad:360/(2*Math.PI)},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},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)}},i=/^#([0-9a-f]{3,8})$/i,s=function(r){var t=r.toString(16);return t.length<2?"0"+t:t},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}},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}},g=function(r){return{h:u(r.h),s:colord_e(r.s,0,100),l:colord_e(r.l,0,100),a:colord_e(r.a)}},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)}},f=function(r){return 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},c=function(r){return{h:(t=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},l=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,p=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,m=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,y={string:[[function(r){var t=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=v.exec(r)||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=l.exec(t)||p.exec(t);if(!n)return null;var e,u,a=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 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 t(n)&&t(e)&&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(!t(n)||!t(e)||!t(u))return null;var i=g({h:Number(n),s:Number(e),l:Number(u),a:Number(o)});return 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(!t(n)||!t(a)||!t(o))return null;var h=function(r){return{h: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 b(h)},"hsv"]]},N=function(r,t){for(var n=0;n=.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?s(colord_n(255*a)):"","#"+s(t)+s(e)+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 d(c(this.rgba))},r.prototype.toHslString=function(){return r=d(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=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 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),w(M(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,-r))},r.prototype.grayscale=function(){return w(M(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),w($(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),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?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=c(this.rgba);return"number"==typeof r?w({h:r,s:t.s,l:t.l,a:t.a}):colord_n(t.h)},r.prototype.isEqual=function(r){return this.toHex()===w(r).toHex()},r}(),w=function(r){return r instanceof j?r:new j(r)},S=[],k=function(r){r.forEach(function(r){S.indexOf(r)<0&&(r(j,y),S.push(r))})},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['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} [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['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['style']} [unhighlightStyle] Style to apply to unhighlighted text.
*/
/**
* Maps props to lowercase names.
*
* @param object Props to map.
* @return The mapped props.
*/
const lowercaseProps = object => {
const mapped = {};
for (const key in object) {
mapped[key.toLowerCase()] = object[key];
}
return mapped;
};
const memoizedLowercaseProps = memize(lowercaseProps);
/**
* @param options
* @param options.activeClassName
* @param options.activeIndex
* @param options.activeStyle
* @param options.autoEscape
* @param options.caseSensitive
* @param options.children
* @param options.findChunks
* @param options.highlightClassName
* @param options.highlightStyle
* @param options.highlightTag
* @param options.sanitize
* @param options.searchWords
* @param options.unhighlightClassName
* @param options.unhighlightStyle
*/
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;
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/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
*/
var hook_ref = true ? {
name: "50zrmy",
styles: "text-transform:uppercase"
} : 0;
/**
* @param {import('../context').WordPressComponentProps} props
*/
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');
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,
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),
fontWeight: weight,
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]);
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 `` 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 props
* @param forwardedRef
*/
function UnconnectedText(props, forwardedRef) {
const textProps = useText(props);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 Code is Poetry;
* }
* ```
*/
const component_Text = contextConnect(UnconnectedText, 'Text');
/* harmony default export */ const text_component = (component_Text);
;// 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
*/
/**
* Internal dependencies
*/
const Prefix = /*#__PURE__*/emotion_styled_base_browser_esm("span", true ? {
target: "em5sgkm7"
} : 0)( true ? {
name: "pvvbxf",
styles: "box-sizing:border-box;display:block"
} : 0);
const Suffix = /*#__PURE__*/emotion_styled_base_browser_esm("span", true ? {
target: "em5sgkm6"
} : 0)( true ? {
name: "jgf79h",
styles: "align-items:center;align-self:stretch;box-sizing:border-box;display:flex"
} : 0);
const backdropBorderColor = ({
disabled,
isBorderless
}) => {
if (isBorderless) {
return 'transparent';
}
if (disabled) {
return COLORS.ui.borderDisabled;
}
return COLORS.ui.border;
};
const BackdropUI = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "em5sgkm5"
} : 0)("&&&{box-sizing:border-box;border-color:", backdropBorderColor, ";border-radius:inherit;border-style:solid;border-width:1px;bottom:0;left:0;margin:0;padding:0;pointer-events:none;position:absolute;right:0;top:0;", rtl({
paddingLeft: 2
}), ";}" + ( true ? "" : 0));
const input_control_styles_Root = /*#__PURE__*/emotion_styled_base_browser_esm(flex_component, true ? {
target: "em5sgkm4"
} : 0)("box-sizing:border-box;position:relative;border-radius:2px;padding-top:0;&:focus-within:not( :has( :is( ", Prefix, ", ", Suffix, " ):focus-within ) ){", BackdropUI, "{border-color:", COLORS.ui.borderFocus, ";box-shadow:", config_values.controlBoxShadowFocus, ";outline:2px solid transparent;outline-offset:-2px;}}" + ( 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 = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "em5sgkm3"
} : 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',
compact: '13px',
'__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,
__next40pxDefaultSize
}) => {
// Paddings may be overridden by the custom paddings props.
const sizes = {
default: {
height: 40,
lineHeight: 1,
minHeight: 40,
paddingLeft: space(4),
paddingRight: space(4)
},
small: {
height: 24,
lineHeight: 1,
minHeight: 24,
paddingLeft: space(2),
paddingRight: space(2)
},
compact: {
height: 32,
lineHeight: 1,
minHeight: 32,
paddingLeft: space(2),
paddingRight: space(2)
},
'__unstable-large': {
height: 40,
lineHeight: 1,
minHeight: 40,
paddingLeft: space(4),
paddingRight: space(4)
}
};
if (!__next40pxDefaultSize) {
sizes.default = sizes.compact;
}
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 = /*#__PURE__*/emotion_styled_base_browser_esm("input", true ? {
target: "em5sgkm2"
} : 0)("&&&{background-color:transparent;box-sizing:border-box;border:none;box-shadow:none!important;color:", COLORS.theme.foreground, ";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__*/emotion_styled_base_browser_esm(text_component, true ? {
target: "em5sgkm1"
} : 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 => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(BaseLabel, {
...props,
as: "label"
});
const LabelWrapper = /*#__PURE__*/emotion_styled_base_browser_esm(flex_item_component, true ? {
target: "em5sgkm0"
} : 0)( true ? {
name: "1b6uupn",
styles: "max-width:calc( 100% - 10px )"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/backdrop.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Backdrop({
disabled = false,
isBorderless = false
}) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(BackdropUI, {
"aria-hidden": "true",
className: "components-input-control__backdrop",
disabled: disabled,
isBorderless: isBorderless
});
}
const MemoizedBackdrop = (0,external_wp_element_namespaceObject.memo)(Backdrop);
/* harmony default export */ const 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(visually_hidden_component, {
as: "label",
htmlFor: htmlFor,
children: children
});
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(LabelWrapper, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Label, {
htmlFor: htmlFor,
...props,
children: children
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/use-deprecated-props.js
function useDeprecated36pxDefaultSizeProp(props) {
const {
__next36pxDefaultSize,
__next40pxDefaultSize,
...otherProps
} = props;
return {
...otherProps,
__next40pxDefaultSize: __next40pxDefaultSize !== null && __next40pxDefaultSize !== void 0 ? __next40pxDefaultSize : __next36pxDefaultSize
};
}
;// 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(props, ref) {
const {
__next40pxDefaultSize,
__unstableInputWidth,
children,
className,
disabled = false,
hideLabelFromVision = false,
labelPosition,
id: idProp,
isBorderless = false,
label,
prefix,
size = 'default',
suffix,
...restProps
} = useDeprecated36pxDefaultSizeProp(useContextSystem(props, 'InputBase'));
const id = useUniqueId(idProp);
const hideLabel = hideLabelFromVision || !label;
const {
paddingLeft,
paddingRight
} = getSizeConfig({
inputSize: size,
__next40pxDefaultSize
});
const prefixSuffixContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => {
return {
InputControlPrefixWrapper: {
paddingLeft
},
InputControlSuffixWrapper: {
paddingRight
}
};
}, [paddingLeft, paddingRight]);
return (
/*#__PURE__*/
// @ts-expect-error The `direction` prop from Flex (FlexDirection) conflicts with legacy SVGAttributes `direction` (string) that come from React intrinsic prop definitions.
(0,external_ReactJSXRuntime_namespaceObject.jsxs)(input_control_styles_Root, {
...restProps,
...getUIFlexProps(labelPosition),
className: className,
gap: 2,
ref: ref,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(label_Label, {
className: "components-input-control__label",
hideLabelFromVision: hideLabelFromVision,
labelPosition: labelPosition,
htmlFor: id,
children: label
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(Container, {
__unstableInputWidth: __unstableInputWidth,
className: "components-input-control__container",
disabled: disabled,
hideLabel: hideLabel,
labelPosition: labelPosition,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(ContextSystemProvider, {
value: prefixSuffixContextValue,
children: [prefix && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Prefix, {
className: "components-input-control__prefix",
children: prefix
}), children, suffix && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Suffix, {
className: "components-input-control__suffix",
children: suffix
})]
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(backdrop, {
disabled: disabled,
isBorderless: isBorderless
})]
})]
})
);
}
/**
* `InputBase` is an internal component used to style the standard borders for an input,
* as well as handle the layout for prefix/suffix elements.
*/
/* harmony default export */ const input_base = (contextConnect(InputBase, '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 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-fe213e88.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 _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 ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
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 || (_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_fe213e88_esm_noop() {}
function actions_fe213e88_esm_chain(...fns) {
if (fns.length === 0) return actions_fe213e88_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);
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 = V.sub(state.offset, previousOffset);
this.computeMovement();
if (gestureIsActive && (!state.last || dt > BEFORE_LAST_KINEMATICS_DELAY)) {
state.delta = V.sub(state.offset, previousOffset);
const absoluteDelta = state.delta.map(Math.abs);
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(_objectSpread2(_objectSpread2(_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);
_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 = V.add(this.state.lastOffset, this.state.movement);
}
computeMovement() {
this.state.movement = 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 actions_fe213e88_esm_identity = v => v;
const DEFAULT_RUBBERBAND = 0.15;
const commonConfigResolver = {
enabled(value = true) {
return value;
},
eventOptions(value, _k, config) {
return _objectSpread2(_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 V.toVector(value);
}
},
from(value) {
if (typeof value === 'function') return value;
if (value != null) return V.toVector(value);
},
transform(value, _k, config) {
const transform = value || config.shared.transform;
this.hasCustomTransform = !!transform;
if (false) {}
return transform || actions_fe213e88_esm_identity;
},
threshold(value) {
return V.toVector(value, 0);
}
};
if (false) {}
const DEFAULT_AXIS_THRESHOLD = 0;
const coordinatesConfigResolver = _objectSpread2(_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);
_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 = V.sub(_values, state._values);
this.computeValues(_values);
}
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;
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_fe213e88_esm_isBrowser = typeof window !== 'undefined' && window.document && window.document.createElement;
function supportsTouchEvents() {
return actions_fe213e88_esm_isBrowser && 'ontouchstart' in window;
}
function isTouchScreen() {
return supportsTouchEvents() || actions_fe213e88_esm_isBrowser && window.navigator.maxTouchPoints > 1;
}
function supportsPointerEvents() {
return actions_fe213e88_esm_isBrowser && 'onpointerdown' in window;
}
function supportsPointerLock() {
return actions_fe213e88_esm_isBrowser && 'exitPointerLock' in window.document;
}
function supportsGestureEvents() {
try {
return 'constructor' in GestureEvent;
} catch (e) {
return false;
}
}
const SUPPORT = {
isBrowser: actions_fe213e88_esm_isBrowser,
gesture: supportsGestureEvents(),
touch: supportsTouchEvents(),
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 = _objectSpread2(_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 = 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(V.toVector(velocity)),
distance: this.transform(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 _objectSpread2(_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);
_defineProperty(this, "ingKey", 'pinching');
_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 = 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 = 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 && (Array.isArray(modifierKey) ? !modifierKey.find(k => event[k]) : !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];
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 = _objectSpread2(_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 = 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);
_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 = V.sub(values, state._values);
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 = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, {
mouseOnly: (value = true) => value
});
class ScrollEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
_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 = V.sub(values, state._values);
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);
_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);
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);
_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 = 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 = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, {
mouseOnly: (value = true) => value
});
const actions_fe213e88_esm_EngineMap = new Map();
const ConfigResolverMap = new Map();
function actions_fe213e88_esm_registerAction(action) {
actions_fe213e88_esm_EngineMap.set(action.key, action.engine);
ConfigResolverMap.set(action.key, action.resolver);
}
const actions_fe213e88_esm_dragAction = {
key: 'drag',
engine: DragEngine,
resolver: dragConfigResolver
};
const actions_fe213e88_esm_hoverAction = {
key: 'hover',
engine: HoverEngine,
resolver: hoverConfigResolver
};
const actions_fe213e88_esm_moveAction = {
key: 'move',
engine: MoveEngine,
resolver: moveConfigResolver
};
const actions_fe213e88_esm_pinchAction = {
key: 'pinch',
engine: PinchEngine,
resolver: pinchConfigResolver
};
const actions_fe213e88_esm_scrollAction = {
key: 'scroll',
engine: ScrollEngine,
resolver: scrollConfigResolver
};
const actions_fe213e88_esm_wheelAction = {
key: 'wheel',
engine: WheelEngine,
resolver: wheelConfigResolver
};
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/use-gesture-core.esm.js
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 _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _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(_objectSpread2({
shared: _config.shared
}, rest), resolver);
} else {
for (const key in rest) {
const resolver = ConfigResolverMap.get(key);
if (resolver) {
_config[key] = resolveWith(_objectSpread2({
shared: _config.shared
}, rest[key]), resolver);
} else if (false) {}
}
}
return _config;
}
class EventStore {
constructor(ctrl, gestureKey) {
_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 = _objectSpread2(_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() {
_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) {
_defineProperty(this, "gestures", new Set());
_defineProperty(this, "_targetEventStore", new EventStore(this));
_defineProperty(this, "gestureEventStores", {});
_defineProperty(this, "gestureTimeoutStores", {});
_defineProperty(this, "handlers", {});
_defineProperty(this, "config", {});
_defineProperty(this, "pointerIds", new Set());
_defineProperty(this, "touchIds", new Set());
_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_fe213e88_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](_objectSpread2(_objectSpread2({}, this.state.shared), {}, {
event,
args
})), undefined, true);
}
}
for (const handlerProp in props) {
props[handlerProp] = actions_fe213e88_esm_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_fe213e88_esm_registerAction(actions_fe213e88_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) {
registerAction(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/utils/with-ignore-ime-events.js
/**
* A higher-order function that wraps a keydown event handler to ensure it is not an IME event.
*
* In CJK languages, an IME (Input Method Editor) is used to input complex characters.
* During an IME composition, keydown events (e.g. Enter or Escape) can be fired
* which are intended to control the IME and not the application.
* These events should be ignored by any application logic.
*
* @param keydownHandler The keydown event handler to execute after ensuring it was not an IME event.
*
* @return A wrapped version of the given event handler that ignores IME events.
*/
function withIgnoreIMEEvents(keydownHandler) {
return event => {
const {
isComposing
} = 'nativeEvent' in event ? event.nativeEvent : event;
if (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;
}
keydownHandler(event);
};
}
;// 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,
isPressEnterToChange = false,
onBlur = input_field_noop,
onChange = input_field_noop,
onDrag = input_field_noop,
onDragEnd = input_field_noop,
onDragStart = input_field_noop,
onKeyDown = input_field_noop,
onValidate = input_field_noop,
size = 'default',
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);
/**
* If isPressEnterToChange is set, this commits the value to
* the onChange callback.
*/
if (isDirty || !event.target.validity.valid) {
wasDirtyOnBlur.current = true;
handleOnCommit(event);
}
};
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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Input, {
...props,
...dragProps,
className: "components-input-control__input",
disabled: disabled,
dragCursor: dragCursor,
isDragging: isDragging,
id: id,
onBlur: handleOnBlur,
onChange: handleOnChange,
onKeyDown: withIgnoreIMEEvents(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 */ const input_field = (ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/font-values.js
/* harmony default export */ const 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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 (
*
*
*
* );
* );
* ```
*/
const UnconnectedBaseControl = props => {
const {
__nextHasNoMarginBottom = false,
id,
label,
hideLabelFromVision = false,
help,
className,
children
} = useContextSystem(props, 'BaseControl');
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(base_control_styles_Wrapper, {
className: className,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(StyledField, {
className: "components-base-control__field"
// TODO: Official deprecation for this should start after all internal usages have been migrated
,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
children: [label && id && (hideLabelFromVision ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(visually_hidden_component, {
as: "label",
htmlFor: id,
children: label
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(StyledLabel, {
className: "components-base-control__label",
htmlFor: id,
children: label
})), label && !id && (hideLabelFromVision ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(visually_hidden_component, {
as: "label",
children: label
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(VisualLabel, {
children: label
})), children]
}), !!help && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(StyledHelp, {
id: id ? id + '__help' : undefined,
className: "components-base-control__help",
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
children: 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 = () => (
*
* Author
*
*
* );
*/
const VisualLabel = ({
className,
children,
...props
}) => {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(StyledVisualLabel, {
...props,
className: dist_clsx('components-base-control__label', className),
children: children
});
};
const BaseControl = Object.assign(contextConnectWithoutRef(UnconnectedBaseControl, 'BaseControl'), {
VisualLabel
});
/* harmony default export */ const 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(props, ref) {
const {
__next40pxDefaultSize,
__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,
...restProps
} = useDeprecated36pxDefaultSizeProp(props);
const id = input_control_useUniqueId(idProp);
const classes = dist_clsx('components-input-control', className);
const draftHookProps = useDraft({
value,
onBlur: restProps.onBlur,
onChange
});
const helpProp = !!help ? {
'aria-describedby': `${id}__help`
} : {};
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(base_control, {
className: classes,
help: help,
id: id,
__nextHasNoMarginBottom: true,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(input_base, {
__next40pxDefaultSize: __next40pxDefaultSize,
__unstableInputWidth: __unstableInputWidth,
disabled: disabled,
gap: 3,
hideLabelFromVision: hideLabelFromVision,
id: id,
justify: "left",
label: label,
labelPosition: labelPosition,
prefix: prefix,
size: size,
style: style,
suffix: suffix,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(input_field, {
...restProps,
...helpProp,
__next40pxDefaultSize: __next40pxDefaultSize,
className: "components-input-control__input",
disabled: disabled,
id: id,
isPressEnterToChange: isPressEnterToChange,
onKeyDown: onKeyDown,
onValidate: onValidate,
paddingInlineStart: prefix ? space(2) : undefined,
paddingInlineEnd: suffix ? space(2) : undefined,
ref: ref,
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 'react';
*
* const Example = () => {
* const [ value, setValue ] = useState( '' );
*
* return (
* setValue( nextValue ?? '' ) }
* />
* );
* };
* ```
*/
const InputControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedInputControl);
/* harmony default export */ const input_control = (InputControl);
;// 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: iconClass,
style: styles,
...extraProps
});
}
/* harmony default export */ const 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const build_module_icon = (Icon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const disabledEventsOnDisabledButton = ['onMouseDown', 'onClick'];
function button_useDeprecatedProps({
isDefault,
isPrimary,
isSecondary,
isTertiary,
isLink,
isPressed,
isSmall,
size,
variant,
...otherProps
}) {
let computedSize = size;
let computedVariant = variant;
const newProps = {
// @todo Mark `isPressed` as deprecated
'aria-pressed': isPressed
};
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()('wp.components.Button `isDefault` prop', {
since: '5.4',
alternative: 'variant="secondary"'
});
(_computedVariant4 = computedVariant) !== null && _computedVariant4 !== void 0 ? _computedVariant4 : computedVariant = 'secondary';
}
if (isLink) {
var _computedVariant5;
(_computedVariant5 = computedVariant) !== null && _computedVariant5 !== void 0 ? _computedVariant5 : computedVariant = 'link';
}
return {
...newProps,
...otherProps,
size: computedSize,
variant: computedVariant
};
}
function UnforwardedButton(props, ref) {
const {
__next40pxDefaultSize,
isBusy,
isDestructive,
className,
disabled,
icon,
iconPosition = 'left',
iconSize,
showTooltip,
tooltipPosition,
shortcut,
label,
children,
size = 'default',
text,
variant,
__experimentalIsFocusable: isFocusable,
describedBy,
...buttonOrAnchorProps
} = button_useDeprecatedProps(props);
const {
href,
target,
'aria-checked': ariaChecked,
'aria-pressed': ariaPressed,
'aria-selected': ariaSelected,
...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 truthyAriaPressedValues = [true, 'true', 'mixed'];
const classes = dist_clsx('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': truthyAriaPressedValues.includes(ariaPressed),
'is-pressed-mixed': ariaPressed === 'mixed',
'is-busy': isBusy,
'is-link': variant === 'link',
'is-destructive': isDestructive,
'has-text': !!icon && (hasChildren || text),
'has-icon': !!icon
});
const trulyDisabled = disabled && !isFocusable;
const Tag = href !== undefined && !trulyDisabled ? 'a' : 'button';
const buttonProps = Tag === 'button' ? {
type: 'button',
disabled: trulyDisabled,
'aria-checked': ariaChecked,
'aria-pressed': ariaPressed,
'aria-selected': ariaSelected
} : {};
const anchorProps = Tag === 'a' ? {
href,
target
} : {};
const disableEventProps = {};
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) {
disableEventProps[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 = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [icon && iconPosition === 'left' && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(build_module_icon, {
icon: icon,
size: iconSize
}), text && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: text
}), children, icon && iconPosition === 'right' && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(build_module_icon, {
icon: icon,
size: iconSize
})]
});
const element = Tag === 'a' ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("a", {
...anchorProps,
...additionalProps,
...disableEventProps,
...commonProps,
children: elementChildren
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("button", {
...buttonProps,
...additionalProps,
...disableEventProps,
...commonProps,
children: elementChildren
});
// In order to avoid some React reconciliation issues, we are always rendering
// the `Tooltip` component even when `shouldShowTooltip` is `false`.
// In order to make sure that the tooltip doesn't show when it shouldn't,
// we don't pass the props to the `Tooltip` component.
const tooltipProps = shouldShowTooltip ? {
text: children?.length && describedBy ? describedBy : label,
shortcut,
placement: tooltipPosition &&
// Convert legacy `position` values to be used with the new `placement` prop
positionToPlacement(tooltipPosition)
} : {};
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(tooltip, {
...tooltipProps,
children: element
}), describedBy && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(visually_hidden_component, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
id: descriptionId,
children: describedBy
})
})]
});
}
/**
* Lets users take actions and make choices with a single click or tap.
*
* ```jsx
* import { Button } from '@wordpress/components';
* const Mybutton = () => (
*
* );
* ```
*/
const Button = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedButton);
/* harmony default export */ const build_module_button = (Button);
;// 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__*/emotion_styled_base_browser_esm(input_control, true ? {
target: "ep09it41"
} : 0)(htmlArrowStyles, ";" + ( true ? "" : 0));
const SpinButton = /*#__PURE__*/emotion_styled_base_browser_esm(build_module_button, true ? {
target: "ep09it40"
} : 0)("&&&&&{color:", COLORS.theme.accent, ";}" + ( 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} 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} 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;
}
;// 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/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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(flex_item_component, {
isBlock: true,
...childElement.props
}, _key);
}
return child;
});
const propsForFlex = {
children: clonedChildren,
direction,
justify: 'center',
...align,
...otherProps,
gap: spacing
};
// Omit `isColumn` because it's not used in HStack.
const {
isColumn,
...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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
* Code
* is
* Poetry
*
* );
* }
* ```
*/
const HStack = contextConnect(UnconnectedHStack, 'HStack');
/* harmony default export */ const 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(props, forwardedRef) {
const {
__unstableStateReducer: stateReducerProp,
className,
dragDirection = 'n',
hideHTMLArrows = false,
spinControls = hideHTMLArrows ? 'none' : 'native',
isDragEnabled = true,
isShiftStepEnabled = true,
label,
max = Infinity,
min = -Infinity,
required = false,
shiftStep = 10,
step = 1,
spinFactor = 1,
type: typeProp = 'number',
value: valueProp,
size = 'default',
suffix,
onChange = number_control_noop,
...restProps
} = useDeprecated36pxDefaultSizeProp(props);
if (hideHTMLArrows) {
external_wp_deprecated_default()('wp.components.NumberControl hideHTMLArrows prop ', {
alternative: 'spinControls="none"',
since: '6.2',
version: '6.3'
});
}
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 baseSpin = ensureNumber(spinFactor) * baseStep;
const baseValue = roundClamp(0, min, max, baseStep);
const constrainValue = (value, stepOverride) => {
// When step is "any" clamp the value, otherwise round and clamp it.
// Use '' + to convert to string for use in input value attribute.
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 = dist_clsx('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) * baseSpin : baseSpin;
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) {
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) * baseSpin : baseSpin;
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;
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 === '';
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 so that consumers can use
// e.g. event.target.validity.
event: {
...event,
target: inputRef.current
}
});
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(number_control_styles_Input, {
autoComplete: autoComplete,
inputMode: "numeric",
...restProps,
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' ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [suffix, /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(spacer_component, {
marginBottom: 0,
marginRight: 2,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(h_stack_component, {
spacing: 1,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(SpinButton, {
className: spinButtonClasses,
icon: library_plus,
size: "small",
label: (0,external_wp_i18n_namespaceObject.__)('Increment'),
onClick: buildSpinButtonClickHandler('up')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(SpinButton, {
className: spinButtonClasses,
icon: library_reset,
size: "small",
label: (0,external_wp_i18n_namespaceObject.__)('Decrement'),
onClick: buildSpinButtonClickHandler('down')
})]
})
})]
}) : suffix,
onChange: onChange
});
}
const NumberControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedNumberControl);
/* harmony default export */ const 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 CircleRoot = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("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 = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "eln3bjz1"
} : 0)("background:", COLORS.theme.accent, ";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__*/emotion_styled_base_browser_esm(text_component, true ? {
target: "eln3bjz0"
} : 0)("color:", COLORS.theme.accent, ";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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CircleRoot, {
ref: angleCircleRef,
onMouseDown: startDrag,
className: "components-angle-picker-control__angle-circle",
...props,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CircleIndicatorWrapper, {
style: value ? {
transform: `rotate(${value}deg)`
} : undefined,
className: "components-angle-picker-control__angle-circle-indicator-wrapper",
tabIndex: -1,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const 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 {
className,
label = (0,external_wp_i18n_namespaceObject.__)('Angle'),
onChange,
value,
...restProps
} = props;
const handleOnNumberChange = unprocessedValue => {
if (onChange === undefined) {
return;
}
const inputValue = unprocessedValue !== undefined && unprocessedValue !== '' ? parseInt(unprocessedValue, 10) : 0;
onChange(inputValue);
};
const classes = dist_clsx('components-angle-picker-control', className);
const unitText = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(UnitText, {
children: "\xB0"
});
const [prefixedUnitText, suffixedUnitText] = (0,external_wp_i18n_namespaceObject.isRTL)() ? [unitText, null] : [null, unitText];
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(flex_component, {
...restProps,
ref: ref,
className: classes,
gap: 2,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(flex_block_component, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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
})
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(spacer_component, {
marginBottom: "1",
marginTop: "auto",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
* );
* }
* ```
*/
const AnglePickerControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedAnglePickerControl);
/* harmony default export */ const angle_picker_control = (AnglePickerControl);
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(9681);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// CONCATENATED MODULE: external ["wp","richText"]
const external_wp_richText_namespaceObject = window["wp"]["richText"];
;// CONCATENATED MODULE: external ["wp","a11y"]
const external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: external ["wp","keycodes"]
const external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/strings.js
/**
* External dependencies
*/
/**
* All unicode characters that we consider "dash-like":
* - `\u007e`: ~ (tilde)
* - `\u00ad`: (soft hyphen)
* - `\u2053`: ⁓ (swung dash)
* - `\u207b`: ⁻ (superscript minus)
* - `\u208b`: ₋ (subscript minus)
* - `\u2212`: − (minus sign)
* - `\\p{Pd}`: any other Unicode dash character
*/
const ALL_UNICODE_DASH_CHARACTERS = new RegExp(/[\u007e\u00ad\u2053\u207b\u208b\u2212\p{Pd}]/gu);
const normalizeTextString = value => {
return remove_accents_default()(value).toLocaleLowerCase().replace(ALL_UNICODE_DASH_CHARACTERS, '-');
};
/**
* Converts any string to kebab case.
* Backwards compatible with Lodash's `_.kebabCase()`.
* Backwards compatible with `_wp_to_kebab_case()`.
*
* @see https://lodash.com/docs/4.17.15#kebabCase
* @see https://developer.wordpress.org/reference/functions/_wp_to_kebab_case/
*
* @param str String to convert.
* @return Kebab-cased string
*/
function kebabCase(str) {
var _str$toString;
let input = (_str$toString = str?.toString?.()) !== null && _str$toString !== void 0 ? _str$toString : '';
// See https://github.com/lodash/lodash/blob/b185fcee26b2133bd071f4aaca14b455c2ed1008/lodash.js#L4970
input = input.replace(/['\u2019]/, '');
return paramCase(input, {
splitRegexp: [/(?!(?:1ST|2ND|3RD|[4-9]TH)(?![a-z]))([a-z0-9])([A-Z])/g,
// fooBar => foo-bar, 3Bar => 3-bar
/(?!(?:1st|2nd|3rd|[4-9]th)(?![a-z]))([0-9])([a-z])/g,
// 3bar => 3-bar
/([A-Za-z])([0-9])/g,
// Foo3 => foo-3, foo3 => foo-3
/([A-Z])([A-Z][a-z])/g // FOOBar => foo-bar
]
});
}
/**
* Escapes the RegExp special characters.
*
* @param string Input string.
*
* @return 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/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs
/**
* Provides data to position an inner element of the floating element so that it
* appears 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_arrow = options => {
function isRef(value) {
return {}.hasOwnProperty.call(value, 'current');
}
return {
name: 'arrow',
options,
fn(state) {
const {
element,
padding
} = typeof options === 'function' ? options(state) : options;
if (element && isRef(element)) {
if (element.current != null) {
return floating_ui_dom_arrow({
element: element.current,
padding
}).fn(state);
}
return {};
}
if (element) {
return floating_ui_dom_arrow({
element,
padding
}).fn(state);
}
return {};
}
};
};
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;
let i;
let 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 (!{}.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;
}
// biome-ignore lint/suspicious/noSelfCompare: in source
return a !== a && b !== b;
}
function getDPR(element) {
if (typeof window === 'undefined') {
return 1;
}
const win = element.ownerDocument.defaultView || window;
return win.devicePixelRatio || 1;
}
function floating_ui_react_dom_roundByDPR(element, value) {
const dpr = getDPR(element);
return Math.round(value * dpr) / dpr;
}
function useLatestRef(value) {
const ref = external_React_.useRef(value);
index(() => {
ref.current = value;
});
return ref;
}
/**
* Provides data to position a floating element.
* @see https://floating-ui.com/docs/useFloating
*/
function useFloating(options) {
if (options === void 0) {
options = {};
}
const {
placement = 'bottom',
strategy = 'absolute',
middleware = [],
platform,
elements: {
reference: externalReference,
floating: externalFloating
} = {},
transform = true,
whileElementsMounted,
open
} = options;
const [data, setData] = external_React_.useState({
x: 0,
y: 0,
strategy,
placement,
middlewareData: {},
isPositioned: false
});
const [latestMiddleware, setLatestMiddleware] = external_React_.useState(middleware);
if (!deepEqual(latestMiddleware, middleware)) {
setLatestMiddleware(middleware);
}
const [_reference, _setReference] = external_React_.useState(null);
const [_floating, _setFloating] = external_React_.useState(null);
const setReference = external_React_.useCallback(node => {
if (node !== referenceRef.current) {
referenceRef.current = node;
_setReference(node);
}
}, []);
const setFloating = external_React_.useCallback(node => {
if (node !== floatingRef.current) {
floatingRef.current = node;
_setFloating(node);
}
}, []);
const referenceEl = externalReference || _reference;
const floatingEl = externalFloating || _floating;
const referenceRef = external_React_.useRef(null);
const floatingRef = external_React_.useRef(null);
const dataRef = external_React_.useRef(data);
const hasWhileElementsMounted = whileElementsMounted != null;
const whileElementsMountedRef = useLatestRef(whileElementsMounted);
const platformRef = useLatestRef(platform);
const update = external_React_.useCallback(() => {
if (!referenceRef.current || !floatingRef.current) {
return;
}
const config = {
placement,
strategy,
middleware: latestMiddleware
};
if (platformRef.current) {
config.platform = platformRef.current;
}
floating_ui_dom_computePosition(referenceRef.current, floatingRef.current, config).then(data => {
const fullData = {
...data,
isPositioned: true
};
if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
dataRef.current = fullData;
external_ReactDOM_namespaceObject.flushSync(() => {
setData(fullData);
});
}
});
}, [latestMiddleware, placement, strategy, platformRef]);
index(() => {
if (open === false && dataRef.current.isPositioned) {
dataRef.current.isPositioned = false;
setData(data => ({
...data,
isPositioned: false
}));
}
}, [open]);
const isMountedRef = external_React_.useRef(false);
index(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
// biome-ignore lint/correctness/useExhaustiveDependencies: `hasWhileElementsMounted` is intentionally included.
index(() => {
if (referenceEl) referenceRef.current = referenceEl;
if (floatingEl) floatingRef.current = floatingEl;
if (referenceEl && floatingEl) {
if (whileElementsMountedRef.current) {
return whileElementsMountedRef.current(referenceEl, floatingEl, update);
}
update();
}
}, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);
const refs = external_React_.useMemo(() => ({
reference: referenceRef,
floating: floatingRef,
setReference,
setFloating
}), [setReference, setFloating]);
const elements = external_React_.useMemo(() => ({
reference: referenceEl,
floating: floatingEl
}), [referenceEl, floatingEl]);
const floatingStyles = external_React_.useMemo(() => {
const initialStyles = {
position: strategy,
left: 0,
top: 0
};
if (!elements.floating) {
return initialStyles;
}
const x = floating_ui_react_dom_roundByDPR(elements.floating, data.x);
const y = floating_ui_react_dom_roundByDPR(elements.floating, data.y);
if (transform) {
return {
...initialStyles,
transform: "translate(" + x + "px, " + y + "px)",
...(getDPR(elements.floating) >= 1.5 && {
willChange: 'transform'
})
};
}
return {
position: strategy,
left: x,
top: y
};
}, [strategy, transform, elements.floating, data.x, data.y]);
return external_React_.useMemo(() => ({
...data,
update,
refs,
elements,
floatingStyles
}), [data, update, refs, elements, floatingStyles]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
const close_close = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const library_close = (close_close);
;// 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 (
*
*
* { isScrollLocked &&
}
*
* Scroll locked:
* { isScrollLocked ? 'Yes' : 'No' }
*
*
* );
* };
* ```
*/
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 */ const scroll_lock = (ScrollLock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot-fill-context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const initialContextValue = {
slots: (0,external_wp_compose_namespaceObject.observableMap)(),
fills: (0,external_wp_compose_namespaceObject.observableMap)(),
registerSlot: () => {
true ? external_wp_warning_default()('Components must be wrapped within `SlotFillProvider`. ' + 'See https://developer.wordpress.org/block-editor/components/slot-fill/') : 0;
},
updateSlot: () => {},
unregisterSlot: () => {},
registerFill: () => {},
unregisterFill: () => {},
// This helps the provider know if it's using the default context value or not.
isDefault: true
};
const SlotFillContext = (0,external_wp_element_namespaceObject.createContext)(initialContextValue);
/* harmony default export */ const slot_fill_context = (SlotFillContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/use-slot.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSlot(name) {
const registry = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const slot = (0,external_wp_compose_namespaceObject.useObservableValue)(registry.slots, 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
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const initialValue = {
registerSlot: () => {},
unregisterSlot: () => {},
registerFill: () => {},
unregisterFill: () => {},
getSlot: () => undefined,
getFills: () => [],
subscribe: () => () => {}
};
const context_SlotFillContext = (0,external_wp_element_namespaceObject.createContext)(initialValue);
/* harmony default export */ const context = (context_SlotFillContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/use-slot.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* React hook returning the active slot given a name.
*
* @param name Slot name.
* @return 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 */ const use_slot = (use_slot_useSlot);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/fill.js
/**
* 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
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Whether the argument is a function.
*
* @param maybeFunc The argument to check.
* @return 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(props) {
super(props);
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, this);
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;
}
let childKey = childIndex;
if (typeof child === 'object' && 'key' in child && child?.key) {
childKey = child.key;
}
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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: isFunction(children) ? children(fills) : fills
});
}
}
const Slot = props => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(context.Consumer, {
children: ({
registerSlot,
unregisterSlot,
getFills
}) => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(SlotComponent, {
...props,
registerSlot: registerSlot,
unregisterSlot: unregisterSlot,
getFills: getFills
})
});
/* harmony default export */ const slot = (Slot);
;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/native.js
const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
/* harmony default export */ const esm_browser_native = ({
randomUUID
});
;// CONCATENATED MODULE: ./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()).
let getRandomValues;
const 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.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
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/uuid/dist/esm-browser/stringify.js
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 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
return 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]];
}
function stringify_stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset); // 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 (!validate(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
/* harmony default export */ const esm_browser_stringify = ((/* unused pure expression or super */ null && (stringify_stringify)));
;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
if (esm_browser_native.randomUUID && !buf && !options) {
return esm_browser_native.randomUUID();
}
options = options || {};
const 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 (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
/* harmony default export */ const esm_browser_v4 = (v4);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/style-provider/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const uuidCache = new Set();
// Use a weak map so that when the container is detached it's automatically
// dereferenced to avoid memory leak.
const containerCacheMap = new WeakMap();
const memoizedCreateCacheWithContainer = container => {
if (containerCacheMap.has(container)) {
return containerCacheMap.get(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);
const cache = emotion_cache_browser_esm({
container,
key
});
containerCacheMap.set(container, cache);
return cache;
};
function StyleProvider(props) {
const {
children,
document
} = props;
if (!document) {
return null;
}
const cache = memoizedCreateCacheWithContainer(document.head);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CacheProvider, {
value: cache,
children: children
});
}
/* harmony default export */ const style_provider = (StyleProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/fill.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function fill_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(props) {
var _slot$fillProps;
const {
name,
children
} = props;
const {
registerFill,
unregisterFill,
...slot
} = useSlot(name);
const rerender = fill_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;
}
// 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 = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(style_provider, {
document: slot.ref.current.ownerDocument,
children: typeof children === 'function' ? children((_slot$fillProps = slot.fillProps) !== null && _slot$fillProps !== void 0 ? _slot$fillProps : {}) : 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
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function slot_Slot(props, forwardedRef) {
const {
name,
fillProps = {},
as,
// `children` is not allowed. However, if it is passed,
// it will be displayed as is, so remove `children`.
// @ts-ignore
children,
...restProps
} = props;
const {
registerSlot,
unregisterSlot,
...registry
} = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const ref = (0,external_wp_element_namespaceObject.useRef)(null);
(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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component, {
as: as,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([forwardedRef, ref]),
...restProps
});
}
/* harmony default export */ const bubbles_virtually_slot = ((0,external_wp_element_namespaceObject.forwardRef)(slot_Slot));
;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
const 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
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function createSlotRegistry() {
const slots = (0,external_wp_compose_namespaceObject.observableMap)();
const fills = (0,external_wp_compose_namespaceObject.observableMap)();
const registerSlot = (name, ref, fillProps) => {
const slot = slots.get(name);
slots.set(name, {
...slot,
ref: ref || slot?.ref,
fillProps: fillProps || slot?.fillProps || {}
});
};
const 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);
}
};
const 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.forEach(fill => fill.current.rerender());
}
};
const registerFill = (name, ref) => {
fills.set(name, [...(fills.get(name) || []), ref]);
};
const unregisterFill = (name, ref) => {
const fillsForName = fills.get(name);
if (!fillsForName) {
return;
}
fills.set(name, 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(slot_fill_context.Provider, {
value: registry,
children: children
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/provider.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function provider_createSlotRegistry() {
const slots = {};
const fills = {};
let listeners = [];
function registerSlot(name, slot) {
const previousSlot = slots[name];
slots[name] = slot;
triggerListeners();
// Sometimes the fills are registered after the initial render of slot
// But before the registerSlot call, we need to rerender the slot.
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();
}
}
function registerFill(name, instance) {
fills[name] = [...(fills[name] || []), instance];
forceUpdateSlot(name);
}
function 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 (slots[name] !== instance) {
return;
}
delete slots[name];
triggerListeners();
}
function unregisterFill(name, instance) {
var _fills$name$filter;
fills[name] = (_fills$name$filter = fills[name]?.filter(fill => fill !== instance)) !== null && _fills$name$filter !== void 0 ? _fills$name$filter : [];
forceUpdateSlot(name);
}
function getSlot(name) {
return slots[name];
}
function getFills(name, slotInstance) {
// Fills should only be returned for the current instance of the slot
// in which they occupy.
if (slots[name] !== slotInstance) {
return [];
}
return fills[name];
}
function forceUpdateSlot(name) {
const slot = getSlot(name);
if (slot) {
slot.forceUpdate();
}
}
function triggerListeners() {
listeners.forEach(listener => listener());
}
function subscribe(listener) {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
};
}
return {
registerSlot,
unregisterSlot,
registerFill,
unregisterFill,
getSlot,
getFills,
subscribe
};
}
function provider_SlotFillProvider({
children
}) {
const [contextValue] = (0,external_wp_element_namespaceObject.useState)(provider_createSlotRegistry);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(context.Provider, {
value: contextValue,
children: children
});
}
/* harmony default export */ const provider = (provider_SlotFillProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/index.js
/**
* External dependencies
*/
/**
* 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Fill, {
...props
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(fill_Fill, {
...props
})]
});
}
function UnforwardedSlot(props, ref) {
const {
bubblesVirtually,
...restProps
} = props;
if (bubblesVirtually) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(bubbles_virtually_slot, {
...restProps,
ref: ref
});
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(slot, {
...restProps
});
}
const slot_fill_Slot = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSlot);
function Provider({
children,
passthrough = false
}) {
const parent = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
if (!parent.isDefault && passthrough) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: children
});
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(provider, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(SlotFillProvider, {
children: children
})
});
}
function createSlotFill(key) {
const baseName = typeof key === 'symbol' ? key.description : key;
const FillComponent = props => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(slot_fill_Fill, {
name: key,
...props
});
FillComponent.displayName = `${baseName}Fill`;
const SlotComponent = props => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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/overlay-middlewares.js
/**
* External dependencies
*/
function overlayMiddlewares() {
return [{
name: 'overlay',
fn({
rects
}) {
return rects.reference;
}
}, floating_ui_dom_size({
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
// 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 = () => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 100 100",
className: "components-popover__triangle",
role: "presentation",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
className: "components-popover__triangle-bg",
d: "M 0 0 L 50 50 L 100 0"
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 slotNameContext = (0,external_wp_element_namespaceObject.createContext)(undefined);
const fallbackContainerClassname = 'components-popover__fallback-container';
const getPopoverFallbackContainer = () => {
let container = document.body.querySelector('.' + fallbackContainerClassname);
if (!container) {
container = document.createElement('div');
container.className = fallbackContainerClassname;
document.body.append(container);
}
return container;
};
const UnforwardedPopover = (props, forwardedRef) => {
const {
animate = true,
headerTitle,
constrainTabbing,
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,
inline = false,
variant,
// Deprecated props
__unstableForcePosition,
anchorRef,
anchorRect,
getAnchorRect,
isAlternate,
// Rest
...contentProps
} = useContextSystem(props, 'Popover');
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 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;
const middleware = [...(placementProp === 'overlay' ? overlayMiddlewares() : []), offset(offsetProp), computedFlipProp && floating_ui_dom_flip(), computedResizeProp && floating_ui_dom_size({
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'
});
}
}), shift && floating_ui_dom_shift({
crossAxis: true,
limiter: floating_ui_dom_limitShift(),
padding: 1 // Necessary to avoid flickering at the edge of the viewport.
}), floating_ui_react_dom_arrow({
element: arrowRef
})];
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)({
constrainTabbing,
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,
// 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) => autoUpdate(referenceParam, floatingParam, updateParam, {
layoutShift: false,
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 resultingReferenceElement = getReferenceElement({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement
});
refs.setReference(resultingReferenceElement);
}, [anchor, anchorRef, anchorRefTop, anchorRefBottom, anchorRefStartContainer, anchorRefCurrent, anchorRect, getAnchorRect, fallbackReferenceElement, refs]);
const mergedFloatingRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([refs.setFloating, dialogRef, forwardedRef]);
const 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.
x: computePopoverPosition(x),
y: computePopoverPosition(y)
};
const shouldReduceMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
const shouldAnimate = animate && !isExpanded && !shouldReduceMotion;
const [animationFinished, setAnimationFinished] = (0,external_wp_element_namespaceObject.useState)(false);
const {
style: motionInlineStyles,
...otherMotionProps
} = (0,external_wp_element_namespaceObject.useMemo)(() => placementToMotionAnimationProps(computedPlacement), [computedPlacement]);
const animationProps = shouldAnimate ? {
style: {
...motionInlineStyles,
...style
},
onAnimationComplete: () => setAnimationFinished(true),
...otherMotionProps
} : {
animate: false,
style
};
// When Floating UI has finished positioning and Framer Motion has finished animating
// the popover, add the `is-positioned` class to signal that all transitions have finished.
const isPositioned = (!shouldAnimate || animationFinished) && x !== null && y !== null;
let content = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(motion.div, {
className: dist_clsx(className, {
'is-expanded': isExpanded,
'is-positioned': isPositioned,
// Use the 'alternate' classname for 'toolbar' variant for back compat.
[`is-${computedVariant === 'toolbar' ? 'alternate' : computedVariant}`]: computedVariant
}),
...animationProps,
...contentProps,
ref: mergedFloatingRef,
...dialogProps,
tabIndex: -1,
children: [isExpanded && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(scroll_lock, {}), isExpanded && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
className: "components-popover__header",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "components-popover__header-title",
children: headerTitle
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(build_module_button, {
className: "components-popover__close",
icon: library_close,
onClick: onClose
})]
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("div", {
className: "components-popover__content",
children: children
}), hasArrow && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("div", {
ref: arrowCallbackRef,
className: ['components-popover__arrow', `is-${computedPlacement.split('-')[0]}`].join(' '),
style: {
left: typeof arrowData?.x !== 'undefined' && Number.isFinite(arrowData.x) ? `${arrowData.x}px` : '',
top: typeof arrowData?.y !== 'undefined' && Number.isFinite(arrowData.y) ? `${arrowData.y}px` : ''
},
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ArrowTriangle, {})
})]
});
const shouldRenderWithinSlot = slot.ref && !inline;
const hasAnchor = anchorRef || anchorRect || anchor;
if (shouldRenderWithinSlot) {
content = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(slot_fill_Fill, {
name: slotName,
children: content
});
} else if (!inline) {
content = (0,external_wp_element_namespaceObject.createPortal)( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(StyleProvider, {
document: document,
children: content
}), getPopoverFallbackContainer());
}
if (hasAnchor) {
return content;
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("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 (
*
* );
* };
* ```
*
*/
const popover_Popover = contextConnect(UnforwardedPopover, 'Popover');
function PopoverSlot({
name = SLOT_NAME
}, ref) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(slot_fill_Slot, {
bubblesVirtually: true,
name: name,
className: "popover-slot",
ref: ref
});
}
// @ts-expect-error For Legacy Reasons
popover_Popover.Slot = (0,external_wp_element_namespaceObject.forwardRef)(PopoverSlot);
// @ts-expect-error For Legacy Reasons
popover_Popover.__unstableSlotNameProvider = slotNameContext.Provider;
/* harmony default export */ const popover = (popover_Popover);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/autocompleter-ui.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ListBox({
items,
onSelect,
selectedIndex,
instanceId,
listBoxId,
className,
Component = 'div'
}) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Component, {
id: listBoxId,
role: "listbox",
className: "components-autocomplete__results",
children: items.map((option, index) => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(build_module_button, {
id: `components-autocomplete-item-${instanceId}-${option.key}`,
role: "option",
"aria-selected": index === selectedIndex,
disabled: option.isDisabled,
className: dist_clsx('components-autocomplete__result', className, {
'is-selected': index === selectedIndex
}),
onClick: () => onSelect(option),
children: option.label
}, option.key))
});
}
function getAutoCompleterUI(autocompleter) {
var _autocompleter$useIte;
const useItems = (_autocompleter$useIte = autocompleter.useItems) !== null && _autocompleter$useIte !== void 0 ? _autocompleter$useIte : 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 aria-* 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;
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(popover, {
focusOnMount: false,
onClose: onReset,
placement: "top-start",
className: "components-autocomplete__popover",
anchor: popoverAnchor,
ref: popoverRefs,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ListBox, {
items: items,
onSelect: onSelect,
selectedIndex: selectedIndex,
instanceId: instanceId,
listBoxId: listBoxId,
className: className
})
}), contentRef.current && needsA11yCompat && (0,external_ReactDOM_namespaceObject.createPortal)( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ListBox, {
items: items,
onSelect: onSelect,
selectedIndex: selectedIndex,
instanceId: instanceId,
listBoxId: listBoxId,
className: className,
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 getNodeText = node => {
if (node === null) {
return '';
}
switch (typeof node) {
case 'string':
case 'number':
return node.toString();
break;
case 'boolean':
return '';
break;
case 'object':
{
if (node instanceof Array) {
return node.map(getNodeText).join('');
}
if ('props' in node) {
return getNodeText(node.props.children);
}
break;
}
default:
return '';
}
return '';
};
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) {
return;
}
switch (event.key) {
case 'ArrowUp':
{
const newIndex = (selectedIndex === 0 ? filteredOptions.length : selectedIndex) - 1;
setSelectedIndex(newIndex);
// See the related PR as to why this is necessary: https://github.com/WordPress/gutenberg/pull/54902.
if ((0,external_wp_keycodes_namespaceObject.isAppleOS)()) {
(0,external_wp_a11y_namespaceObject.speak)(getNodeText(filteredOptions[newIndex].label), 'assertive');
}
break;
}
case 'ArrowDown':
{
const newIndex = (selectedIndex + 1) % filteredOptions.length;
setSelectedIndex(newIndex);
if ((0,external_wp_keycodes_namespaceObject.isAppleOS)()) {
(0,external_wp_a11y_namespaceObject.speak)(getNodeText(filteredOptions[newIndex].label), 'assertive');
}
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;
}
// Find the completer with the highest triggerPrefix index in the
// textContent.
const completer = completers.reduce((lastTrigger, currentCompleter) => {
const triggerIndex = textContent.lastIndexOf(currentCompleter.triggerPrefix);
const lastTriggerIndex = lastTrigger !== null ? textContent.lastIndexOf(lastTrigger.triggerPrefix) : -1;
return triggerIndex > lastTriggerIndex ? currentCompleter : lastTrigger;
}, null);
if (!completer) {
if (autocompleter) {
reset();
}
return;
}
const {
allowContext,
triggerPrefix
} = completer;
const triggerIndex = textContent.lastIndexOf(triggerPrefix);
const textWithoutTrigger = textContent.slice(triggerIndex + 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;
}
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 && wordsFromTrigger.length <= 3;
if (mismatch && !(matchingWhileBackspacing || hasOneTriggerWord)) {
if (autocompleter) {
reset();
}
return;
}
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, triggerIndex), textAfterSelection)) {
if (autocompleter) {
reset();
}
return;
}
if (/^\s/.test(textWithoutTrigger) || /\s\s+$/.test(textWithoutTrigger)) {
if (autocompleter) {
reset();
}
return;
}
if (!/[\u0000-\uFFFF]*$/.test(textWithoutTrigger)) {
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: withIgnoreIMEEvents(handleKeyDown),
popover: hasSelection && AutocompleterUI && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [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);
return {
baseControlProps: {
id: uniqueId,
help,
...restProps
},
controlProps: {
id: uniqueId,
...(!!help ? {
'aria-describedby': `${uniqueId}__help`
} : {})
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link.js
/**
* WordPress dependencies
*/
const link_link = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const library_link = (link_link);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link-off.js
/**
* WordPress dependencies
*/
const linkOff = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(tooltip, {
text: label,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component, {
className: className,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(build_module_button, {
...buttonProps,
size: "small",
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label,
ref: forwardedRef
})
})
});
};
const ConnectedBorderBoxControlLinkedButton = contextConnect(BorderBoxControlLinkedButton, 'BorderBoxControlLinkedButton');
/* harmony default export */ const 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component, {
...otherProps,
ref: forwardedRef
});
};
const ConnectedBorderBoxControlVisualizer = contextConnect(BorderBoxControlVisualizer, 'BorderBoxControlVisualizer');
/* harmony default export */ const border_box_control_visualizer_component = (ConnectedBorderBoxControlVisualizer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-solid.js
/**
* WordPress dependencies
*/
const lineSolid = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "M5 11.25h14v1.5H5z"
})
});
/* harmony default export */ const line_solid = (lineSolid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-dashed.js
/**
* WordPress dependencies
*/
const lineDashed = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const line_dashed = (lineDashed);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-dotted.js
/**
* WordPress dependencies
*/
const lineDotted = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const line_dotted = (lineDotted);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/DeprecatedLayoutGroupContext.mjs
/**
* Note: Still used by components generated by old versions of Framer
*
* @deprecated
*/
const DeprecatedLayoutGroupContext = (0,external_React_.createContext)(null);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/group.mjs
const notify = (node) => !node.isLayoutDirty && node.willUpdate(false);
function nodeGroup() {
const nodes = new Set();
const subscriptions = new WeakMap();
const dirtyAll = () => nodes.forEach(notify);
return {
add: (node) => {
nodes.add(node);
subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll));
},
remove: (node) => {
nodes.delete(node);
const unsubscribe = subscriptions.get(node);
if (unsubscribe) {
unsubscribe();
subscriptions.delete(node);
}
dirtyAll();
},
dirty: dirtyAll,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/LayoutGroup/index.mjs
const shouldInheritGroup = (inherit) => inherit === true;
const shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === "id";
const LayoutGroup = ({ children, id, inherit = true }) => {
const layoutGroupContext = (0,external_React_.useContext)(LayoutGroupContext);
const deprecatedLayoutGroupContext = (0,external_React_.useContext)(DeprecatedLayoutGroupContext);
const [forceRender, key] = use_force_update_useForceUpdate();
const context = (0,external_React_.useRef)(null);
const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext;
if (context.current === null) {
if (shouldInheritId(inherit) && upstreamId) {
id = id ? upstreamId + "-" + id : upstreamId;
}
context.current = {
id,
group: shouldInheritGroup(inherit)
? layoutGroupContext.group || nodeGroup()
: nodeGroup(),
};
}
const memoizedContext = (0,external_React_.useMemo)(() => ({ ...context.current, forceRender }), [key]);
return ((0,external_ReactJSXRuntime_namespaceObject.jsx)(LayoutGroupContext.Provider, { value: memoizedContext, children: children }));
};
;// 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;position:relative;", 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);
};
var styles_ref = true ? {
name: "1aqh2c7",
styles: "min-height:40px;padding:3px"
} : 0;
var _ref2 = true ? {
name: "1ndywgm",
styles: "min-height:36px;padding:2px"
} : 0;
const toggleGroupControlSize = size => {
const styles = {
default: _ref2,
'__unstable-large': styles_ref
};
return styles[size];
};
const toggle_group_control_styles_block = true ? {
name: "7whenc",
styles: "display:flex;width:100%"
} : 0;
const VisualLabelWrapper = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "eakva830"
} : 0)( true ? {
name: "zjik7",
styles: "display:flex"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@ariakit/core/esm/radio/radio-store.js
"use client";
// src/radio/radio-store.ts
function createRadioStore(_a = {}) {
var props = _4R3V3JGP_objRest(_a, []);
var _a2;
const syncState = (_a2 = props.store) == null ? void 0 : _a2.getState();
const composite = createCompositeStore(_chunks_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_spreadValues({}, props), {
focusLoop: defaultValue(props.focusLoop, syncState == null ? void 0 : syncState.focusLoop, true)
}));
const initialState = _chunks_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_spreadValues({}, composite.getState()), {
value: defaultValue(
props.value,
syncState == null ? void 0 : syncState.value,
props.defaultValue,
null
)
});
const radio = createStore(initialState, composite, props.store);
return _chunks_4R3V3JGP_spreadProps(_chunks_4R3V3JGP_spreadValues(_chunks_4R3V3JGP_spreadValues({}, composite), radio), {
setValue: (value) => radio.setState("value", value)
});
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/LEIRFLRL.js
"use client";
// src/radio/radio-store.ts
function useRadioStoreProps(store, update, props) {
store = useCompositeStoreProps(store, update, props);
useStoreProps(store, props, "value", "setValue");
return store;
}
function useRadioStore(props = {}) {
const [store, update] = EKQEJRUF_useStore(createRadioStore, props);
return useRadioStoreProps(store, update, props);
}
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/XEV62JUQ.js
"use client";
// src/radio/radio-context.tsx
var XEV62JUQ_ctx = createStoreContext(
[CompositeContextProvider],
[CompositeScopedContextProvider]
);
var useRadioContext = XEV62JUQ_ctx.useContext;
var useRadioScopedContext = XEV62JUQ_ctx.useScopedContext;
var useRadioProviderContext = XEV62JUQ_ctx.useProviderContext;
var RadioContextProvider = XEV62JUQ_ctx.ContextProvider;
var RadioScopedContextProvider = XEV62JUQ_ctx.ScopedContextProvider;
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/radio/radio-group.js
"use client";
// src/radio/radio-group.tsx
var useRadioGroup = createHook(
(_a) => {
var _b = _a, { store } = _b, props = __objRest(_b, ["store"]);
const context = useRadioProviderContext();
store = store || context;
invariant(
store,
false && 0
);
props = useWrapElement(
props,
(element) => /* @__PURE__ */ (0,external_ReactJSXRuntime_namespaceObject.jsx)(RadioScopedContextProvider, { value: store, children: element }),
[store]
);
props = _4R3V3JGP_spreadValues({
role: "radiogroup"
}, props);
props = useComposite(_4R3V3JGP_spreadValues({ store }, props));
return props;
}
);
var RadioGroup = createComponent((props) => {
const htmlProps = useRadioGroup(props);
return _3ORBWXWF_createElement("div", htmlProps);
});
if (false) {}
;// 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 */ const toggle_group_control_context = (ToggleGroupControlContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Used to determine, via an internal heuristics, whether an `undefined` value
* received for the `value` prop should be interpreted as the component being
* used in uncontrolled mode, or as an "empty" value for controlled mode.
*
* @param valueProp The received `value`
*/
function useComputeControlledOrUncontrolledValue(valueProp) {
const isInitialRender = (0,external_wp_element_namespaceObject.useRef)(true);
const prevValueProp = (0,external_wp_compose_namespaceObject.usePrevious)(valueProp);
const prevIsControlled = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isInitialRender.current) {
isInitialRender.current = false;
}
}, []);
// Assume the component is being used in controlled mode on the first re-render
// that has a different `valueProp` from the previous render.
const isControlled = prevIsControlled.current || !isInitialRender.current && prevValueProp !== valueProp;
(0,external_wp_element_namespaceObject.useEffect)(() => {
prevIsControlled.current = isControlled;
}, [isControlled]);
if (isControlled) {
// When in controlled mode, use `''` instead of `undefined`
return {
value: valueProp !== null && valueProp !== void 0 ? valueProp : '',
defaultValue: undefined
};
}
// When in uncontrolled mode, the `value` should be intended as the initial value
return {
value: undefined,
defaultValue: valueProp
};
}
;// 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: onChangeProp,
size,
value: valueProp,
id: idProp,
...otherProps
}, forwardedRef) {
const generatedId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlAsRadioGroup, 'toggle-group-control-as-radio-group');
const baseId = idProp || generatedId;
// Use a heuristic to understand if the component is being used in controlled
// or uncontrolled mode, and consequently:
// - when controlled, convert `undefined` values to `''` (ie. "no value")
// - use the `value` prop as the `defaultValue` when uncontrolled
const {
value,
defaultValue
} = useComputeControlledOrUncontrolledValue(valueProp);
// `useRadioStore`'s `setValue` prop can be called with `null`, while
// the component's `onChange` prop only expects `undefined`
const wrappedOnChangeProp = onChangeProp ? v => {
onChangeProp(v !== null && v !== void 0 ? v : undefined);
} : undefined;
const radio = useRadioStore({
defaultValue,
value,
setValue: wrappedOnChangeProp
});
const selectedValue = radio.useState('value');
const setValue = radio.setValue;
const groupContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
baseId,
isBlock: !isAdaptiveWidth,
size,
value: selectedValue,
setValue
}), [baseId, isAdaptiveWidth, size, selectedValue, setValue]);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(toggle_group_control_context.Provider, {
value: groupContextValue,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(RadioGroup, {
store: radio,
"aria-label": label,
render: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component, {}),
...otherProps,
id: baseId,
ref: forwardedRef,
children: children
})
});
}
const ToggleGroupControlAsRadioGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlAsRadioGroup);
;// 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/toggle-group-control/toggle-group-control/as-button-group.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlAsButtonGroup({
children,
isAdaptiveWidth,
label,
onChange,
size,
value: valueProp,
id: idProp,
...otherProps
}, forwardedRef) {
const generatedId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlAsButtonGroup, 'toggle-group-control-as-button-group');
const baseId = idProp || generatedId;
// Use a heuristic to understand if the component is being used in controlled
// or uncontrolled mode, and consequently:
// - when controlled, convert `undefined` values to `''` (ie. "no value")
// - use the `value` prop as the `defaultValue` when uncontrolled
const {
value,
defaultValue
} = useComputeControlledOrUncontrolledValue(valueProp);
const [selectedValue, setSelectedValue] = useControlledValue({
defaultValue,
value,
onChange
});
const groupContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
baseId,
value: selectedValue,
setValue: setSelectedValue,
isBlock: !isAdaptiveWidth,
isDeselectable: true,
size
}), [baseId, selectedValue, setSelectedValue, isAdaptiveWidth, size]);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(toggle_group_control_context.Provider, {
value: groupContextValue,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component, {
"aria-label": label,
...otherProps,
ref: forwardedRef,
role: "group",
children: 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
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedToggleGroupControl(props, forwardedRef) {
const {
__nextHasNoMarginBottom = false,
__next40pxDefaultSize = false,
className,
isAdaptiveWidth = false,
isBlock = false,
isDeselectable = false,
label,
hideLabelFromVision = false,
help,
onChange,
size = 'default',
value,
children,
...otherProps
} = useContextSystem(props, 'ToggleGroupControl');
const baseId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControl, 'toggle-group-control');
const normalizedSize = __next40pxDefaultSize && size === 'default' ? '__unstable-large' : size;
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(toggleGroupControl({
isBlock,
isDeselectable,
size: normalizedSize
}), isBlock && toggle_group_control_styles_block, className), [className, cx, isBlock, isDeselectable, normalizedSize]);
const MainControl = isDeselectable ? ToggleGroupControlAsButtonGroup : ToggleGroupControlAsRadioGroup;
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(base_control, {
help: help,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
children: [!hideLabelFromVision && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(VisualLabelWrapper, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(base_control.VisualLabel, {
children: label
})
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(MainControl, {
...otherProps,
className: classes,
isAdaptiveWidth: isAdaptiveWidth,
label: label,
onChange: onChange,
ref: forwardedRef,
size: normalizedSize,
value: value,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(LayoutGroup, {
id: baseId,
children: children
})
})]
});
}
/**
* `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 (
*
*
*
*
* );
* }
* ```
*/
const ToggleGroupControl = contextConnect(UnconnectedToggleGroupControl, 'ToggleGroupControl');
/* harmony default export */ const toggle_group_control_component = (ToggleGroupControl);
;// CONCATENATED MODULE: ./node_modules/@ariakit/react-core/esm/__chunks/JL6IRDFK.js
"use client";
// src/radio/radio.ts
function getIsChecked(value, storeValue) {
if (storeValue === void 0)
return;
if (value != null && storeValue != null) {
return storeValue === value;
}
return !!storeValue;
}
function isNativeRadio(tagName, type) {
return tagName === "input" && (!type || type === "radio");
}
var useRadio = createHook(
(_a) => {
var _b = _a, { store, name, value, checked } = _b, props = __objRest(_b, ["store", "name", "value", "checked"]);
const context = useRadioContext();
store = store || context;
const id = useId(props.id);
const ref = (0,external_React_.useRef)(null);
const isChecked = useStoreState(
store,
(state) => checked != null ? checked : getIsChecked(value, state == null ? void 0 : state.value)
);
(0,external_React_.useEffect)(() => {
if (!id)
return;
if (!isChecked)
return;
const isActiveItem = (store == null ? void 0 : store.getState().activeId) === id;
if (isActiveItem)
return;
store == null ? void 0 : store.setActiveId(id);
}, [store, isChecked, id]);
const onChangeProp = props.onChange;
const tagName = useTagName(ref, props.as || "input");
const nativeRadio = isNativeRadio(tagName, props.type);
const disabled = disabledFromProps(props);
const [propertyUpdated, schedulePropertyUpdate] = useForceUpdate();
(0,external_React_.useEffect)(() => {
const element = ref.current;
if (!element)
return;
if (nativeRadio)
return;
if (isChecked !== void 0) {
element.checked = isChecked;
}
if (name !== void 0) {
element.name = name;
}
if (value !== void 0) {
element.value = `${value}`;
}
}, [propertyUpdated, nativeRadio, isChecked, name, value]);
const onChange = useEvent((event) => {
if (disabled) {
event.preventDefault();
event.stopPropagation();
return;
}
if (!nativeRadio) {
event.currentTarget.checked = true;
schedulePropertyUpdate();
}
onChangeProp == null ? void 0 : onChangeProp(event);
if (event.defaultPrevented)
return;
store == null ? void 0 : store.setValue(value);
});
const onClickProp = props.onClick;
const onClick = useEvent((event) => {
onClickProp == null ? void 0 : onClickProp(event);
if (event.defaultPrevented)
return;
if (nativeRadio)
return;
onChange(event);
});
const onFocusProp = props.onFocus;
const onFocus = useEvent((event) => {
onFocusProp == null ? void 0 : onFocusProp(event);
if (event.defaultPrevented)
return;
if (!nativeRadio)
return;
if (!store)
return;
const { moves, activeId } = store.getState();
if (!moves)
return;
if (id && activeId !== id)
return;
onChange(event);
});
props = _4R3V3JGP_spreadProps(_4R3V3JGP_spreadValues({
id,
role: !nativeRadio ? "radio" : void 0,
type: nativeRadio ? "radio" : void 0,
"aria-checked": isChecked
}, props), {
ref: useMergeRefs(ref, props.ref),
onChange,
onClick,
onFocus
});
props = useCompositeItem(_4R3V3JGP_spreadValues({ store, clickOnEnter: !nativeRadio }, props));
return _4R3V3JGP_spreadValues({
name: nativeRadio ? name : void 0,
value: nativeRadio ? value : void 0,
checked: isChecked
}, props);
}
);
var Radio = createMemoComponent((props) => {
const htmlProps = useRadio(props);
return _3ORBWXWF_createElement("input", htmlProps);
});
if (false) {}
;// 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 = /*#__PURE__*/emotion_styled_base_browser_esm("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;@media not ( prefers-reduced-motion ){transition:background ", config_values.transitionDurationFast, " linear,color ", config_values.transitionDurationFast, " linear,font-weight 60ms linear;}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.theme.accent, ";outline:2px solid transparent;}" + ( true ? "" : 0), true ? "" : 0);
const ButtonContentView = /*#__PURE__*/emotion_styled_base_browser_esm("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': '32px'
};
return /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";height:", iconButtonSizes[size], ";aspect-ratio:1;padding-left:0;padding-right:0;" + ( true ? "" : 0), true ? "" : 0);
};
const backdropView = /*#__PURE__*/emotion_react_browser_esm_css("background:", COLORS.gray[900], ";border-radius:", config_values.controlBorderRadius, ";position:absolute;inset:0;z-index:1;outline:2px solid transparent;outline-offset:-3px;" + ( 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
// 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 REDUCED_MOTION_TRANSITION_CONFIG = {
duration: 0
};
const LAYOUT_ID = 'toggle-group-backdrop-shared-layout-id';
const WithToolTip = ({
showTooltip,
text,
children
}) => {
if (showTooltip && text) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(tooltip, {
text: text,
placement: "top",
children: children
});
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: children
});
};
function ToggleGroupControlOptionBase(props, forwardedRef) {
const shouldReduceMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
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'
} = toggleGroupControlContext;
const {
className,
isIcon = false,
value,
children,
showTooltip = false,
onFocus: onFocusProp,
...otherButtonProps
} = buttonProps;
const isPressed = toggleGroupControlContext.value === value;
const cx = useCx();
const labelViewClasses = (0,external_wp_element_namespaceObject.useMemo)(() => cx(isBlock && labelBlock), [cx, isBlock]);
const itemClasses = (0,external_wp_element_namespaceObject.useMemo)(() => cx(buttonView({
isDeselectable,
isIcon,
isPressed,
size
}), className), [cx, isDeselectable, isIcon, isPressed, size, className]);
const backdropClasses = (0,external_wp_element_namespaceObject.useMemo)(() => cx(backdropView), [cx]);
const buttonOnClick = () => {
if (isDeselectable && isPressed) {
toggleGroupControlContext.setValue(undefined);
} else {
toggleGroupControlContext.setValue(value);
}
};
const commonProps = {
...otherButtonProps,
className: itemClasses,
'data-value': value,
ref: forwardedRef
};
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(component_LabelView, {
className: labelViewClasses,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(WithToolTip, {
showTooltip: showTooltip,
text: otherButtonProps['aria-label'],
children: isDeselectable ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("button", {
...commonProps,
onFocus: onFocusProp,
"aria-pressed": isPressed,
type: "button",
onClick: buttonOnClick,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component_ButtonContentView, {
children: children
})
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Radio, {
render: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("button", {
type: "button",
...commonProps,
onFocus: event => {
onFocusProp?.(event);
if (event.defaultPrevented) {
return;
}
toggleGroupControlContext.setValue(value);
}
}),
value: value,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(component_ButtonContentView, {
children: children
})
})
}), isPressed ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(motion.div, {
layout: true,
layoutRoot: true,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(motion.div, {
className: backdropClasses,
transition: shouldReduceMotion ? REDUCED_MOTION_TRANSITION_CONFIG : undefined,
role: "presentation",
layoutId: LAYOUT_ID
})
}) : null]
});
}
/**
* `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 (
*
*
*
*
* );
* }
* ```
*/
const ConnectedToggleGroupControlOptionBase = contextConnect(ToggleGroupControlOptionBase, 'ToggleGroupControlOptionBase');
/* harmony default export */ const toggle_group_control_option_base_component = (ConnectedToggleGroupControlOptionBase);
;// 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(toggle_group_control_option_base_component, {
...restProps,
isIcon: true,
"aria-label": label,
showTooltip: true,
ref: ref,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 (
*
*
*
*
* );
* }
* ```
*/
const ToggleGroupControlOptionIcon = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlOptionIcon);
/* harmony default export */ const toggle_group_control_option_icon_component = (ToggleGroupControlOptionIcon);
;// 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'
}];
function UnconnectedBorderControlStylePicker({
onChange,
...restProps
}, forwardedRef) {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(toggle_group_control_component, {
__nextHasNoMarginBottom: true,
__next40pxDefaultSize: true,
ref: forwardedRef,
isDeselectable: true,
onChange: value => {
onChange?.(value);
},
...restProps,
children: BORDER_STYLES.map(borderStyle => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(toggle_group_control_option_icon_component, {
value: borderStyle.value,
icon: borderStyle.icon,
label: borderStyle.label
}, borderStyle.value))
});
}
const BorderControlStylePicker = contextConnect(UnconnectedBorderControlStylePicker, 'BorderControlStylePicker');
/* harmony default export */ const border_control_style_picker_component = (BorderControlStylePicker);
;// 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: dist_clsx('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 = () => ;
* ```
*/
const ColorIndicator = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedColorIndicator);
/* harmony default export */ const 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
*/
const UnconnectedDropdown = (props, forwardedRef) => {
const {
renderContent,
renderToggle,
className,
contentClassName,
expandOnMobile,
headerTitle,
focusOnMount,
popoverProps,
onClose,
onToggle,
style,
open,
defaultOpen,
// 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] = useControlledValue({
defaultValue: defaultOpen,
value: open,
onChange: onToggle
});
/**
* 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() {
onClose?.();
setIsOpen(false);
}
const args = {
isOpen: !!isOpen,
onToggle: () => setIsOpen(!isOpen),
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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("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,
children: [renderToggle(args), isOpen && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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: dist_clsx('components-dropdown__content', popoverProps?.className, contentClassName),
children: renderContent(args)
})]
});
};
/**
* Renders a button that opens a floating content modal when clicked.
*
* ```jsx
* import { Button, Dropdown } from '@wordpress/components';
*
* const MyDropdown = () => (
* (
*
* ) }
* renderContent={ () => This is the content of the dropdown.
}
* />
* );
* ```
*/
const Dropdown = contextConnect(UnconnectedDropdown, 'Dropdown');
/* harmony default export */ const 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 /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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';
*
* %}
* />
* ```
*/
const InputControlSuffixWrapper = contextConnect(UnconnectedInputControlSuffixWrapper, 'InputControlSuffixWrapper');
/* harmony default export */ const 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_sizeStyles = ({
__next40pxDefaultSize,
multiple,
selectSize = 'default'
}) => {
if (multiple) {
// When `multiple`, just use the native browser styles
// without setting explicit height.
return;
}
const sizes = {
default: {
height: 40,
minHeight: 40,
paddingTop: 0,
paddingBottom: 0
},
small: {
height: 24,
minHeight: 24,
paddingTop: 0,
paddingBottom: 0
},
compact: {
height: 32,
minHeight: 32,
paddingTop: 0,
paddingBottom: 0
},
'__unstable-large': {
height: 40,
minHeight: 40,
paddingTop: 0,
paddingBottom: 0
}
};
if (!__next40pxDefaultSize) {
sizes.default = sizes.compact;
}
const style = sizes[selectSize] || sizes.default;
return /*#__PURE__*/emotion_react_browser_esm_css(style, true ? "" : 0, true ? "" : 0);
};
const chevronIconSize = 18;
const sizePaddings = ({
__next40pxDefaultSize,
multiple,
selectSize = 'default'
}) => {
const padding = {
default: 16,
small: 8,
compact: 8,
'__unstable-large': 16
};
if (!__next40pxDefaultSize) {
padding.default = padding.compact;
}
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 = /*#__PURE__*/emotion_styled_base_browser_esm("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, ";", fontSizeStyles, ";", select_control_styles_sizeStyles, ";", sizePaddings, ";", overflowStyles, ";}" + ( true ? "" : 0));
const DownArrowWrapper = /*#__PURE__*/emotion_styled_base_browser_esm("div", true ? {
target: "e1mv6sxx1"
} : 0)("margin-inline-end:", space(-1), ";line-height:0;" + ( true ? "" : 0));
const InputControlSuffixWrapperWithClickThrough = /*#__PURE__*/emotion_styled_base_browser_esm(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
* @param {import('react').ForwardedRef} ref The forwarded ref to the SVG element.
*
* @return {JSX.Element} Icon component
*/
function icon_Icon({
icon,
size = 24,
...props
}, ref) {
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
width: size,
height: size,
...props,
ref
});
}
/* harmony default export */ const icons_build_module_icon = ((0,external_wp_element_namespaceObject.forwardRef)(icon_Icon));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-down.js
/**
* WordPress dependencies
*/
const chevronDown = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(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 */ const chevron_down = (chevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/chevron-down.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SelectControlChevronDown = () => {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(InputControlSuffixWrapperWithClickThrough, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(DownArrowWrapper, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(icons_build_module_icon, {
icon: chevron_down,
size: chevronIconSize
})
})
});
};
/* harmony default export */ const select_control_chevron_down = (SelectControlChevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
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,
onChange,
options = [],
size = 'default',
value: valueProp,
labelPosition = 'top',
children,
prefix,
suffix,
__next40pxDefaultSize = false,
__nextHasNoMarginBottom = false,
...restProps
} = useDeprecated36pxDefaultSizeProp(props);
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 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 = dist_clsx('components-select-control', className);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(base_control, {
help: help,
id: id,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(input_base, {
className: classes,
disabled: disabled,
hideLabelFromVision: hideLabelFromVision,
id: id,
label: label,
size: size,
suffix: suffix || !multiple && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(select_control_chevron_down, {}),
prefix: prefix,
labelPosition: labelPosition,
__next40pxDefaultSize: __next40pxDefaultSize,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Select, {
...restProps,
__next40pxDefaultSize: __next40pxDefaultSize,
"aria-describedby": helpId,
className: "components-select-control__input",
disabled: disabled,
id: id,
multiple: multiple,
onChange: handleOnChange,
ref: ref,
selectSize: size,
value: valueProp,
children: children || options.map((option, index) => {
const key = option.id || `${option.label}-${option.value}-${index}`;
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("option", {
value: option.value,
disabled: option.disabled,
hidden: option.hidden,
children: option.label
}, key);
})
})
})
});
}
/**
* `SelectControl` allows users to select from a single or multiple option menu.
* It functions as a wrapper around the browser's native `